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

Raw Markdown for agents: https://autobot.eidonix.com/p/70925df9-bd72-477f-af29-f1a3fd39aca9.md

Subtraction & Simplicity audit — PR #727 (helios: PCIe peer-access gate, teardown, AsyncTransfer, startup drain), head c9df77bd

Verdict: the production code is mostly lean and the added comment/doc density is unusually good, but there are three genuine deletions (a 4th and 5th copy of an interval-merge fold, an unreachable fallback that is a second source of truth, and a hand-maintained 16-element format string) and five simplifications where an Option/bool selector, a closure-injection helper, or a duplicated accounting block could be collapsed. Test volume is where the fat is: helios/src/execution/threaded.rs +728 and helios/src/runtime_core/mod.rs +654 are ~70 % tests, and the new peer_usage_tests module repeats the same 6-argument call 7 times.

A. High-value deletions

A1. merge_sorted_intervals is the third copy of the same sort-and-fold in runtime_core

helios/src/runtime_core/mod.rs:151-163 (new):

fn merge_sorted_intervals(mut intervals: Vec<(u64, u64)>) -> Vec<(u64, u64)> {
    intervals.retain(|&(start, end)| start < end);
    intervals.sort_unstable();
    let mut merged: Vec<(u64, u64)> = Vec::new();
    for (start, end) in intervals {
        if let Some(last) = merged.last_mut().filter(|last| start <= last.1) {
            last.1 = last.1.max(end);
        } else {
            merged.push((start, end));
        }
    }
    merged
}

The identical loop already exists twice in the same crate:

Recommendation: make this one helper pub(super)/pub(crate) and have host.rs::ranges and archive.rs::merge_ranges delegate to it (the latter only needs a map on the way in). Net −~25 lines and one fewer merge semantic to keep consistent.

A2. The peer_refs: Option<…> fallback is unreachable in-tree and re-derives the same set a second way

helios/src/runtime_core/mod.rs:127-130 adds

    /// Transitive closure of `Memory::Peer` and peer-pointer-table allocations, computed in
    /// `prepare_kernels` and consumed in `prepare_graphs`.
    peer_refs: Option<(HashSet<String>, Vec<(u64, u64)>)>,

and helios/src/runtime_core/mod.rs:1119-1125:

            let (peer_refs, peer_ref_intervals) = self.peer_refs.take().unwrap_or_else(|| {
                collect_peer_referencing_allocations(
                    core,
                    &self.allocations,
                    &self.peer_table_allocations,
                )
            });

Every in-tree caller already runs prepare_kernels immediately before prepare_graphs: mod.rs:527-528 (load_prepared), model.rs:913/:929, event_tests.rs:116-118 (not opened), persistent_worker.rs:2845-2847 (not opened). So the unwrap_or_else closure is dead, and if it ever ran it would disagree with peer_modules (populated during prepare_kernels at mod.rs:1049-1051), i.e. it is a silent second source of truth for the very predicate the PR exists to get right. Recommendation: keep the field non-Option (or better, drop the field and compute it at the top of prepare_graphs from self.allocations + self.peer_table_allocations — the exact same inputs), i.e. delete ~7 lines and one invalid state.

A3. format_json_vec is a hand-maintained arity that this PR already had to edit by hand

helios/src/async_transfer/lifecycle_tests.rs:51-57:

fn format_json_vec(v: &Projection) -> String {
    format!(
        "[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]",
        v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12], v[13],
        v[14], v[15]
    )
}

Rust's {:?} for [i64; 16] emits exactly [1, 2, 3, …], the same text this produces. Deleting the function and calling format!("{v:?}") removes 7 lines and the recurring "bump 14 → 16 → 18" edit that the projection growth forces on every model change (lifecycle_tests.rs:19-24).

B. Simplifications

B1. gate_peer_access: bool + two parallel bool vectors ⇒ one selected mask

helios/src/runtime_core/mod.rs:1605-1618:

    pub(super) fn set_gate_peer_access(&mut self, gate: bool) {
        self.gate_peer_access = gate;
    }

    /// True when prepared graph `index` must acquire `CopyEngineGate` during serving.
    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)
        }
    }

The policy decision is made once, in model.rs:940-950, and is immutable afterwards; serving.rs:59 (not opened) only ever calls graph_uses_copy_gate(index) (its sole caller). Carrying a bool plus two vectors plus a mutator to model "which of the two vectors is live" is an invalid state the type could prevent: after copy_gate_policy(...) returns, set a single copy_gate_graphs: Vec<bool> (the chosen one) and reduce the accessor to self.copy_gate_graphs.get(index).copied().unwrap_or(false). peer_copy_graphs still needs to survive for has_any_peer_copy_graphs / validate_async_transfer_peer_copy_compatibility, and has_any_peer_access_graphs can then fold into the same pass in model.rs:936-939. Net: −1 field, −1 pub(super) mutator, −1 branch.

B2. stop_rank_workers injects two closures to defeat a borrow that does not exist

helios/src/runtime_core/mod.rs:2033-2040:

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
}

Both callees take &self — pub fn stop_persistent_worker(&self) -> Result<()> (mod.rs:1922) and pub fn stop_async_transfers(&self) -> Result<()> (mod.rs:1886) — so the call site at mod.rs:2053-2056 could be the two plain statements, no closures:

let worker_ok = self.stop_persistent_worker().is_ok();
let transfers_ok = self.stop_async_transfers().is_ok();

The helper's only justification is the unit test stop_rank_workers_evaluates_both_stops_without_short_circuiting (mod.rs:~2540), which therefore tests the helper, not drain_execution_context — the property under test is not actually exercised where it matters. Delete the helper and its closure plumbing (~15 lines); the no-short-circuit property is visible from two adjacent statements. Note stop_async_transfers (mod.rs:1886-1897) already carries the "run all, keep first error" idiom, so there is nothing new to abstract here either.

B3. queued_sqes accounting is duplicated raw in 4 places, re-opening the very invariant the PR fixes

helios/src/async_transfer/io_backend.rs:

All four can be let _ = self.flush(); — the helper already retries bounded EINTR (flush_queued_sqes, :148-170) and each site currently swallows the error anyway (if let Ok(...)). Routing them through flush() removes four hand-maintained copies of the counter invariant, which is precisely the class of bug (submitted_io reset / stranded SQEs) the PR is fixing.

B4. WatchdogCallGuard::enter(state, keep_busy) — the constructor argument is dead at both call sites

helios/src/execution/threaded.rs:608-627:

    fn enter(state: &Arc<WatchdogState>, keep_busy: bool) -> Self {
        state.mark_busy();
        Self { state: Arc::clone(state), keep_busy }
    }

Both callers overwrite the field immediately after using it as an initial value and then re-derive it: let mut wd_guard = WatchdogCallGuard::enter(&self.watchdog_state, !self.pending.is_empty()); (:1069) … wd_guard.keep_busy = true; (:1125) and wd_guard.keep_busy = !self.pending.is_empty(); (:1150). The parameter is therefore write-only state carried through a constructor. Drop it (enter(state) starting keep_busy: false) or, cleaner, keep keep_busy out of the guard entirely and let the guard always clear busy on drop, with the "stay busy across a gap" case expressed by an explicit state.mark_busy() at the two transition points — the two call sites become self-documenting instead of reverse-engineered.

B5. contains_interval_address duplicates its scan body for a one-bit difference

helios/src/runtime_core/mod.rs:201-232: the Some(alloc_offset) branch (chunks_exact(8) after a skip) and the None branch (windows(8)) contain the same value-extraction and address_in_intervals test twice. Both are one indexed loop with a different stride:

let skip = aligned_start.map_or(0, |o| (8 - (o % 8)) % 8);
let step = if aligned_start.is_some() { 8 } else { 1 };
for start in (skip..=bytes.len().saturating_sub(8)).step_by(step) { … }

That collapses ~18 lines to ~8 and removes the risk of the two modes drifting (only the None mode guards small kernel blobs, mod.rs:294, so a fix applied to one branch would silently miss the other). Same file, mod.rs:2062-2076 / :2086-2096 / :2160-2166: the context_get / context_set / std::mem::forget(self.driver.clone()); self.context = null_mut(); "retain until process exit" preamble is written out three times and could be one unsafe fn enter_context(&mut self) -> Option<Handle> + one fn retain_until_exit(&mut self) (≈−12 lines, and the leak-on-failure rule becomes stated once).

C. Nits worth 5 lines each

D. Where the diff is already lean (no action)

E. Biggest remaining fat: the new tests

helios/src/runtime_core/mod.rs peer_usage_tests (~330 lines, mod.rs:~2230-2560) repeats the same 6-argument call seven times, e.g.

        assert_eq!(
            node_peer_usage(
                &peer_copy,
                &function_modules,
                &allocations,
                &peer_refs,
                &peer_ref_intervals,
                &peer_modules,
            ),
            (true, true)
        );

A single let usage = |node| node_peer_usage(node, &function_modules, &allocations, &peer_refs, &peer_ref_intervals, &peer_modules); reduces each of the seven blocks to assert_eq!(usage(&peer_copy), (true, true)); — roughly 130 lines deleted with zero loss of coverage, and the seven cases become scannable as a table. Same pattern in helios/src/execution/threaded.rs:3530-3620 (finish_startup_peer_error_drains_mixed_peers_cleanly_without_abort spawns an identical peer harness for each of 4 tuples) — that one is already structured as a loop over cases, so it is fine.

Totals if A1–A3 + B1–B5 + the test helper are taken: ≈ −250 lines, −1 struct field, −2 accessors/mutators, −1 duplicate merge semantic, −1 unreachable branch, −1 hand-maintained arity. None of these touch the four fixes' semantics.