Subtraction and simplicity report · NVIDIA/hyperflare-inference #727

Raw Markdown for agents: https://autobot.eidonix.com/p/bea2607a-ac47-451e-9757-ccdba8c47d2a.md

Subtraction & Simplicity audit — PR #727 (head 224fb40)

Scope read at head: runtime_core/{mod,model,payload,serving}.rs, async_transfer/{io_backend,worker,scheduler}.rs, execution/threaded.rs, server/metrics.rs (full diffs + targeted reads). Caveat: the local main is stale, so worker.rs/io_backend.rs/scheduler.rs show as "new files" in the raw diff; I scoped against real head line numbers, not the diff offsets.

The PR is mostly the right shape for a concurrency fix — phases documented in prose, pure policy function, testable seams. But it carries four genuinely free deletions and four wrapper/duplication clusters that add no behaviour.


High value — delete outright

1. stop_rank_workers is a test-only wrapper around two let statements

helios/src/runtime_core/mod.rs:2035-2042:

fn stop_rank_workers(
    stop_persistent_worker: impl FnOnce() -> Result<()>,
    stop_async_transfers: impl FnOnce() -> Result<()>,
) -> bool {
    let worker_ok = stop_persistent_worker().is_ok();
    let transfers_ok = stop_async_transfers().is_ok();
    worker_ok && transfers_ok
}

Its single production caller (mod.rs:2055-2058) is inside a &mut self method, so the two-closure signature buys nothing over inline code:

let worker_ok = self.stop_persistent_worker().is_ok();
let transfers_ok = self.stop_async_transfers().is_ok();
if !(worker_ok && transfers_ok) { ... }

Deleting it also deletes the 27-line unit test stop_rank_workers_evaluates_both_stops_without_short_circuiting (mod.rs:2541-2567), which only exercises the wrapper. The real invariant (non-short-circuit evaluation) is better asserted through drain_execution_context, where a failure actually matters.

2. RankWedgeWatchdog::stop_and_join is a byte-for-byte duplicate of its Drop

helios/src/execution/threaded.rs:738-753:

    fn stop_and_join(mut self) {
        self.state.stop();
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

impl Drop for RankWedgeWatchdog {
    fn drop(&mut self) {
        self.state.stop();
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

stop_and_join(self) sets thread = None, then self is dropped and Drop::drop runs the same body as a no-op. stop_and_join is pure redundancy: self.watchdog.take() (the existing call site at threaded.rs:1231-1233) already drops and joins. Delete the method and the 3 test calls (threaded.rs:4045, 4074, 4103 region) become drop(watchdog).

3. WatchdogCallGuard::enter's keep_busy argument is dead at both call sites

helios/src/execution/threaded.rs:611-619:

impl WatchdogCallGuard {
    fn enter(state: &Arc<WatchdogState>, keep_busy: bool) -> Self {

Both callers immediately overwrite the field:

Drop the parameter (enter(state)); the Drop impl already defaults to clearing busy. Six lines and one borrow-checker-sensitive argument go away.

4. Four dead public accessors on AsyncTransferRuntime

helios/src/async_transfer/worker.rs:484-507 defines name(), rank(), state(), host_pool_bytes(), device_pool_bytes(). Grep across helios/src shows:

AsyncTransferSnapshot (worker.rs:108-127) already carries name, rank, device_pool_bytes, host_pool_bytes, state, so the accessors are pure duplication of the snapshot surface. Delete name/rank/device_pool_bytes, keep at most state if tests need it.


High value — collapse duplicated logic

5. The async_transfers ↔ peer-copy rejection exists twice, with the same message

Load time, helios/src/runtime_core/model.rs:181-197:

fn validate_async_transfer_peer_copy_compatibility(
    has_peer_copy_nodes: bool,
    cores: &[Core],
) -> Result<()> {
    ...
    if has_peer_copy_nodes && has_async_transfers {
        return Err(invalid(
            "Execution.async_transfers cannot accompany graphs with Copy Engine peer-to-peer copy nodes; \
             in-graph demand waits cannot serialize behind CopyEngineGate without deadlocking the Copy Engine",
        ));

And again, reachable only if the load-time check didn't exist, mod.rs:1750-1755:

        if self.has_any_peer_copy_graphs() {
            return Err(invalid(
                "Execution.async_transfers cannot accompany graphs with Copy Engine peer-to-peer copy nodes; \
                 in-graph demand waits cannot serialize behind CopyEngineGate without deadlocking the Copy Engine",
            ));
        }

Since #727 moved validation to load time (model.rs:921-925, before prepare_offload/prepare_async_transfers), the mod.rs copy is unreachable for any core that reaches it — a dead branch carrying a duplicated 2-line string literal (the same text appears a third time in helios/manifest.md:206 (not opened)). Delete mod.rs:1750-1755 and the whole error text lives in exactly one place.

6. Two Vec<bool> + a mode flag + four accessors where one Vec<bool> + two bools suffice

helios/src/runtime_core/mod.rs:115-134 stores peer_copy_graphs: Vec<bool>, peer_access_graphs: Vec<bool>, gate_peer_access: bool, plus peer_table_allocations/peer_modules. The accessor cluster mod.rs:1588-1614 is:

    pub(super) fn has_any_peer_copy_graphs(&self) -> bool { self.peer_copy_graphs.iter().any(|&has_peer| has_peer) }
    pub(super) fn has_any_peer_access_graphs(&self) -> bool { self.peer_access_graphs.iter().any(|&has_peer| has_peer) }
    pub(super) fn set_gate_peer_access(&mut self, gate: bool) { self.gate_peer_access = gate; }
    pub(super) fn graph_uses_copy_gate(&self, index: usize) -> bool {
        if self.gate_peer_access {
            self.peer_access_graphs.get(index).copied().unwrap_or(false)
        } else {
            self.peer_copy_graphs.get(index).copied().unwrap_or(false)
        }
    }

But peer_access_graphs[i] implies peer_copy_graphs[i] by construction — node_peer_usage (mod.rs:303-307) computes let access_peer = copy_peer || .... And peer_copy_graphs is only ever consumed as "any" (model.rs:924, mod.rs:1750). So the minimal state is:

peer_access_graphs: Vec<bool>,
has_peer_copy: bool,      // set during prepare_graphs
gate_peer_access: bool,
graph_uses_copy_gate(i) = if gate_peer_access { access[i] } else { access[i] && is_copy[i] }

— which still needs per-graph strictness… if the strict answer must stay per-graph, keep one Vec<u8> of bitflags (COPY=1, ACCESS=2) and drop one Vec<bool> + one accessor. Either way set_gate_peer_access (a one-field setter broadcast from model.rs:936-939) is unnecessary: pass the boolean down as a parameter of prepare_graphs, or store it once on NativeModel (which already holds copy_gate) instead of replicating it into every NativeResources.

7. node_peer_usage's allocations parameter and is_direct_peer closure are derivable

helios/src/runtime_core/mod.rs:278-296:

fn node_peer_usage(
    node: &Node,
    function_modules: &HashMap<usize, &str>,
    allocations: &HashMap<String, Storage>,
    peer_refs: &HashSet<String>,
    peer_ref_intervals: &[(u64, u64)],
    peer_modules: &HashSet<String>,
) -> (bool, bool) {
    let is_direct_peer = |reference: &Reference| {
        allocations
            .get(&reference.allocation)
            .is_some_and(|storage| matches!(storage.memory, Memory::Peer))
    };

collect_peer_referencing_allocations (mod.rs:232-236) already builds exactly this direct-peer set as the seed of peer_refs:

    let mut peer_refs: HashSet<String> = allocations
        .iter()
        .filter(|(_, storage)| matches!(storage.memory, Memory::Peer))
        .map(|(name, _)| name.clone())
        .collect();

Returning that seed alongside the closure result gives is_direct_peer(x) ≡ direct_peers.contains(&x.allocation). Six parameters → five, one closure and one HashMap<String, Storage> dependency removed from the graph-walking hot loop (called once per node across 135 graphs/rank).

8. Identical interval-collection closure written twice

helios/src/runtime_core/mod.rs:160-174:

fn peer_address_intervals(allocations: &HashMap<String, Storage>) -> Vec<(u64, u64)> {
    let intervals = allocations
        .values()
        .filter(|storage| matches!(storage.memory, Memory::Peer) && storage.nbytes > 0)
        .filter_map(|storage| {
            storage
                .address
                .checked_add(storage.nbytes as u64)
                .map(|end| (storage.address, end))
        })
        .collect();
    merge_sorted_intervals(intervals)
}

and mod.rs:258-269, which repeats the identical filter(nbytes > 0).filter_map(checked_add → (address, end)) chain over peer_refs. One helper fn intervals<'a>(it: impl Iterator<Item = &'a Storage>) -> Vec<(u64,u64)> serves both; peer_address_intervals becomes a one-line caller.

9. collect_peer_referencing_allocations runs the same work twice per rank

mod.rs:994-998 (end of prepare_kernels) and mod.rs:1117-1121 (start of prepare_graphs) both call it with byte-identical arguments — (core, &self.allocations, &self.peer_table_allocations) — each time re-running the transitive-relocation fixpoint (mod.rs:242-257) and the interval merge over every peer allocation. Compute once (after load_payload finishes writing peer_table_allocations, at mod.rs:934) and store the pair on self. On the SM120 TP4 core this is 1.92 GiB of peer views re-scanned per rank per phase.


Medium value — generic wrapper that isn't generic

10. teardown_model_ranks — one instantiation, five parameters, four closures

helios/src/runtime_core/model.rs:1275-1303:

fn teardown_model_ranks<R>(
    ranks: &mut Vec<R>,
    mut drain_rank: impl FnMut(&mut R) -> bool,
    release_host_subsystems: impl FnOnce(),
    mut destroy_rank: impl FnMut(&mut R) -> bool,
    mut release_rank_context: impl FnMut(R),
) -> bool {

It is called exactly once, with R = NativeResources (model.rs:1309-1320), and the only reason for R + the four closures is to dodge the borrow checker so engram/offload can be captured — which is why Drop needs the awkward preamble at model.rs:1307-1308:

        let engram = &mut self.engram;
        let offload = &mut self.offload;

The three phase bodies are three plain loops (&mut ranks.iter_mut().rev() ×2, while let Some(rank) = ranks.pop()); as an inherent method fn teardown(&mut self) -> bool on NativeModel the closures, the R generic, the impl Fn* signatures and the borrow-dodge preamble all disappear, and the ordering — the actual content of the fix — stays visible as straight-line code between two comments. The dedicated 40-line teardown_model_ranks_enforces_three_phase_cross_rank_barrier test (model.rs tests, ~line 1700 region) then tests the real method instead of a reified event log of a mock.

11. payload.rs: two Chunk fields that encode data already present

helios/src/runtime_core/payload.rs:212-213 adds

    alloc_index: usize,
    alloc_offset: usize,

threaded through all three Chunk construction sites (payload.rs:278-279, 301-302, plus the test at 509-510) solely so the reader thread can call contains_interval_address(bytes, peer_intervals, Some(chunk.alloc_offset)) and flag peer_flagged[chunk.alloc_index] (payload.rs:378-387). But alloc_offset is just offset + start relative to allocation.address, and destination already equals allocation.address + offset + start — i.e. both fields are recoverable as destination - allocation.address and the owning allocation. A single peer alloc base/Option<usize> per chunk (or storing Option<(usize /*alloc*/, usize /*offset*/)> as one Option so the "scanned" state is unrepresentable when there is no peer interval) achieves the same with one added field. Related: peer_flagged: Vec<AtomicBool> (payload.rs:310-314) is a full-length atomic array for at most a handful of hits; the reader threads already share a Mutex (available), so a small Mutex<HashSet<usize>> (or Vec<AtomicBool> only when !peer_intervals.is_empty(), which is the common case today) is simpler to reason about.

12. queued_sqes bookkeeping repeated four times in one function

helios/src/async_transfer/io_backend.rs:243-281 (cancel_and_drain) repeats

                        self.queued_sqes = self.queued_sqes.saturating_sub(submitted);

at four sites around self.ring.submit() / submit_with_args. A private fn submit_now(&mut self) -> io::Result<usize> that submits and decrements once collapses the loop and removes the risk of a fifth site forgetting the decrement — the very class of bug this PR is fixing.


Already lean — no action

Worth a second look (not verified enough to assert)

Net: the four free deletions (§1–§4, ≈80 lines + 27 lines of wrapper test) and the two duplication collapses (§5 duplicated rejection, §8 duplicated interval closure) are pure wins with no behavioural change; §6/§7/§10 remove the state/indirection that a reviewer has to hold in their head to check the #722 fix, which is the part of this PR most at risk of being mis-reviewed.