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:
helios/src/runtime_core/host.rs:62-70—ranges.sort_unstable(); let mut merged: Vec<(u64, u64)> = Vec::new(); for (start, end) in ranges { if let Some(last) = merged.last_mut().filter(|last| start <= last.1) { last.1 = last.1.max(end); } else { merged.push((start, end)); } }helios/src/runtime_core/archive.rs:300-313—fn merge_ranges(...), same fold over(offset, nbytes).
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:
:226-230if self.ring.submission().is_full() { if let Ok(submitted) = self.ring.submit() { self.queued_sqes = self.queued_sqes.saturating_sub(submitted); } }:234-236the same three lines after the cancel loop:262-264the same inside theErr(_)arm ofsubmit_with_args:252-255Ok(submitted) => { self.queued_sqes = self.queued_sqes.saturating_sub(submitted); }
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
helios/src/server/metrics.rs:1530-1537:render_async_transfer_metricsexists only to mapchannelsto snapshots and delegate; its single caller (:999) could inlinerender_async_transfer_snapshots(&mut text, &channels.iter().map(|c| c.snapshot()).collect::<Vec<_>>()). The split buys testability (:1599-1630), so this is a justified wrapper — flagging only so it is a conscious choice.helios/src/async_transfer/scheduler.rs:217-223(hw_signaled_faulted_dma_count) and:245-250(is_io_flushed) arepubbut used only by tests (scheduler.rs:1076/1122/1124,lifecycle_tests.rs:47/111/277). They are legitimate TLA+ projection fields (lifecycle_tests.rs:46-47), but they do not need to be public API;#[cfg(test)]orpub(crate)avoids growing the crate surface with test observability.helios/src/execution/threaded.rs:375-377fn drain_requested(&self)has exactly one use — the watchdog's log string at:1022-1024. Fine to keep, but it is diagnostic-only surface.helios/src/runtime_core/model.rs:1074-1077:let cluster_rank = self.cluster.as_ref().map(|cluster| cluster.rank); … let global_rank = cluster_rank.unwrap_or(idx);—unwrap_or(idx)silently restores the flat-local-index semantics that the metrics fix is removing; ifclusteris everNoneon a multi-rank topology the metric goes back to being wrong with no diagnostic. Prefer an explicit rank source or an assertion instead of a silent fallback.helios/src/execution/threaded.rstest-onlyPeerExitGuardconstruction now requireswatchdog: Arc::new(WatchdogState::new())at five sites (:2142,:2209,:3350,:3427,:3492, plus the new startup test) purely to satisfy the field. APeerExitGuard::new(ring)that leaveswatchdog: Nonedeletes that boilerplate (the struct is internal).
D. Where the diff is already lean (no action)
helios/src/async_transfer/io_backend.rs:146-170flush_queued_sqes(&mut usize, impl FnMut) -> io::Result<usize>: the&mutcounter + injected submit closure is the minimum needed to unit-test boundedEINTRand partial submits; do not "simplify" it into a method.helios/src/async_transfer/worker.rs:1222-1250:if submitted_io || args.io_backend.pending_submissions() > 0plus theunflushed_io_count().saturating_sub(pending_submissions())derivation is repeated three times (:1224-1229,:1238-1244,:1287-1292) — afn sync_flushed(scheduler, backend)helper would remove ~9 duplicated lines, but the three sites have genuinely differentdid_work/last_errorside effects, so the duplication is shallow; borderline, list only if you want one more.helios/src/execution/threaded.rs:629-760watchdog: three explicitOption<Instant>since-fields (stall_since,peer_exit_since,close_since) and the three-branch body are the readable form of an inherently stateful monitor; therecord_progress()call sites are already the minimum needed for progress-awareness.helios/src/runtime_core/payload.rs:alloc_index/alloc_offsetonChunkplus theVec<AtomicBool>flag vector are the cheapest possible way to flag peer-pointer tables during the read (buffers are transient, so a post-load scan is not available); keep. The((CHUNK / ranks) & !7).max(8)chunk alignment is the right one-line fix.- No new CLI flags, config knobs, or feature gates were added anywhere in the 17 files; the one new public config field (
ChannelConfig.rank,worker.rs:94) is required data, not speculative generality.
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.