Deep Code Correctness, Invariants & Hot-Path Audit — PR #727 @ 224fb40
Partitioning applied: PR touches 16 files / ~2,100 changed lines across 3 distinct helios subsystems (async_transfer, runtime_core, execution) plus verification, so per the large-PR rule I partitioned into 3 disjoint slices and launched all three sub-agents concurrently in Turn 1. All three completed with the full 4-part protocol applied (callee/enum resolution, same-loop state-order tracing, adversarial small-N, hot-path big-O). I verified the callee citations and quotes below against the reports; findings are all read-verified at 224fb40 (no execution was possible — see limitations).
Verdict: 6 verified defects (2 Blocker-adjacent Major, 4 Major, plus Minors). The PR's headline fixes (three-phase teardown barrier, Reply::Started(Result), metrics rank label) are genuinely correct, but three of its own new mechanisms introduce worse regressions than the bugs they replace.
BLOCKER-1 / MAJOR — CloseStalled watchdog aborts a progressing teardown (regression over pre-PR behaviour)
Diff site: helios/src/execution/threaded.rs:679-687; threshold threaded.rs:1015-1020; constants threaded.rs:23-25.
Calves it must cover (opened): threaded.rs:1211-1225 (close() pending-drain loop + close_peers), threaded.rs:1256-1258 (per-peer receive(..., timeout)), threaded.rs:1278-1316 (best_effort_drain_peers), threaded.rs:594-598 (begin_close), threaded.rs:1157-1167 (frame deadline).
// threaded.rs:679-687
if closing {
let since = *close_since.get_or_insert(now);
let elapsed = now.saturating_duration_since(since);
if elapsed >= stall_timeout {
if let Some(fire) = on_wedge.take() {
fire(WedgeReason::CloseStalled { elapsed });
}
break;
}
} else {
close_since = None; // <-- reset ONLY on the non-closing branch
// threaded.rs:594-598 — begin_close is one-way, bumps activity exactly once
fn begin_close(&self) {
self.closing.0.store(true, Ordering::Release);
self.activity.0.fetch_add(1, Ordering::Release); // never read on this path again
self.wake();
}
Defect. The closing branch is a plain wall-clock timer from begin_close(). It never samples activity, and close_since is reset only in the else arm — but closing never returns to false. So the coordinator gets exactly 150 s (TIMEOUT 120 s + WATCHDOG_GRACE 30 s) of total teardown time, while its own callees legitimately permit ≈ 120 × (peers + 2) s. This is not the "zero idle CPU" criterion the PR description claims for this branch (it is only true for the busy path at threaded.rs:702-716, which does read activity).
Concrete counterexample (TP3, started == true, graceful SIGTERM). Coordinator drains two frames for 60 s (both well under the 120 s frame deadline); peer 0 takes 90 s inside drain_rank (threaded.rs:1318-1342, under its 120 s Peer::receive deadline); peer 1 takes 30 s. Total 180 s > 150 s → watchdog fires CloseStalled → std::process::abort() at threaded.rs:1027 while every stage was inside its sanctioned deadline. This is a hard abort on a legitimate-but-slow teardown and is strictly worse than the pre-PR behaviour (which simply waited).
Fix. Drive close_since off the heartbeat: sample activity on the closing branch, reset close_since whenever it changed, and record_progress() after each close() stage (after the pending-drain loop at 1216, and per peer inside close_peers at 1261). Also size the close-path timeout as TIMEOUT * (peers + 2) + WATCHDOG_GRACE, or make CloseStalled a bounded eprintln! rather than abort().
BLOCKER-2 / MAJOR — Unflushed-OK complete_io silently drops a real completion → permanent inflight_io leak and permanent FailedDrain
Diff site: helios/src/async_transfer/scheduler.rs:578-583. Callees (opened): scheduler.rs:231-243 (mark_io_flushed), :226-228 (unflushed_io_count), :259-273 (bg_*_inflight), :583/:746 (swap_remove), worker.rs:993-1001 (poll_completions → complete_io), worker.rs:1228-1233/:1242-1246 (flushed_now = unflushed_io_count() - pending_submissions()), worker.rs:814 (finish_drain requires inflight_io.is_empty()).
// scheduler.rs:578
pub fn complete_io(&mut self, op_id: OpId, ok: bool) -> Option<CompletionNotice> {
let pos = self.inflight_io.iter().position(|op| op.op_id == op_id)?;
if ok && !self.inflight_io[pos].flushed {
return None; // consumes nothing, but the backend already reaped it
}
let op = self.inflight_io.swap_remove(pos);
// scheduler.rs:231 — marks the first `count` entries in *Vec* order
pub fn mark_io_flushed(&mut self, count: usize) -> usize {
let mut marked = 0;
for op in &mut self.inflight_io {
if marked >= count { break; }
if !op.flushed { op.flushed = true; marked += 1; }
}
Defect. mark_io_flushed assumes Vec order == SQE submission order, but complete_io (:583) and complete_dma (:746) both use swap_remove, which moves the last element into the freed index — so Vec order permanently diverges from submission order after the very first completion. worker.rs:1228-1233 infers "accepted by the kernel" as unflushed_io_count() - pending_submissions() and feeds that count to mark_io_flushed, which then marks the wrong ops whenever the kernel accepts only a prefix of the staged SQEs — the exact partial-submit case this PR exists to fix. The return None then permanently strands the op because its IoCompletion was already drained from the backend.
Concrete counterexample (defaults MAX_TOTAL_IO = 32, BOUNCE_SLOTS = 16):
pop_next_io×3 →inflight_io = [A, B, C], all unflushed,queued_sqes = 3.mark_io_flushed(1)marks A;pending_submissions() == 2.- A's read fails →
complete_io(A, false)→swap_remove(0)→ C moves to index 0 →[C, B]. - Kernel accepts 1 of 2 pending →
flushed_now = 2 - 1 = 1→ marks C, not B. - B's completion harvested →
complete_io(B, true)→ok && !flushed→return None. B is never removed and no future iteration can complete it.
Observable state: B is stuck in inflight_io forever → can_release_memory() permanently false, finish_drain returns Err → ChannelState::FailedDrain → AsyncTransferRuntime::stop() (worker.rs:670-686) retains the pinned host pool, bounce pool, CUDA context and stream until process exit. Repeated across channels: a slow pinned-memory leak plus guaranteed drain failure on a healthy channel.
Fix (both needed): (a) store a monotonic seq on InflightIo at pop_next_io and have mark_io_flushed mark the count unflushed entries with the lowest seq, not the first in Vec order; (b) never discard an ok completion — complete it normally (setting flushed = true) instead of return None.
Test that encodes the bug as correct: helios/src/async_transfer/lifecycle_tests.rs:
if ok && !is_flushed {
assert!(
notice.is_none() && n.inflight_io_count() == before_count,
"unflushed IO must not complete with ok=true before kernel submission"
);
continue;
check.py's mutation ("unflushed io completed ok before flush", "if ok && !self.inflight_io[pos].flushed {", ...) only proves the early-return exists, not that the dropped completion is ever recovered. AsyncTransfer.tla's CompleteIo cannot represent this state at all (its wasUnflushed arm always decrements inDemIo + inBgIo), so the model is structurally blind to the leak.
MAJOR-3 — best_effort_drain_peers shared deadline starves later peers and leaves their threads detached
Diff site: helios/src/execution/threaded.rs:1292 (the let deadline line was moved out of the loop by this PR); caller threaded.rs:1223-1225; short-circuit at threaded.rs:1207-1210.
let deadline = Instant::now() + timeout; // threaded.rs:1292 — one budget for all peers
for peer in peers.iter_mut() {
if peer.thread.is_none() { continue; }
let mut exited = false;
while let Some(remaining) = deadline.checked_duration_since(Instant::now()) {
match receive(&peer.receiver, Some(remaining)) { ... }
}
if exited {
if let Some(thread) = peer.thread.take() { let _ = thread.join(); }
}
}
Defect. When the shared budget is exhausted, checked_duration_since returns None and the while body never executes — no receive, no exited = true, no thread.take(), no join(). The function returns (), and Drop for ThreadedExecutor → close() short-circuits at threaded.rs:1208, so there is no second attempt: the Peer is dropped with thread: Some(JoinHandle) — a detached thread, precisely what the comment at 1223-1224 says is prevented.
Concrete counterexample. started == false, 4 ranks, peer 0 answers immediately, peer 1 wedged in drain_rank for the full 120 s. At t=120 s the budget is gone; peers 2 and 3 are skipped without a single receive even if they would answer Drained in 1 ms, and their threads are never joined. The PR description advertises this change as an improvement; the previous per-peer deadline had neither starvation nor unjoined threads.
Fix. Always take()+join(), and use deadline.checked_duration_since(Instant::now()).unwrap_or(Duration::ZERO).min(MIN_PER_PEER) so no peer is ever skipped; or revert to the original per-peer deadline.
MAJOR-4 — CopyEngineGate can be silently None while the widened peer-access predicate is installed
Diff site: helios/src/runtime_core/model.rs:921-942; predicate mod.rs:1591-1614; consumer serving.rs:49-59; policy model.rs:166-175; lease user offload/copy_gate.rs:267-275.
let (gate_peer_access, enable_copy_gate) = copy_gate_policy(
model.ranks.len(), all_nvlink_p2p(&pci_bus_ids), has_peer_copy_nodes, has_peer_access_graphs);
if gate_peer_access { for rank in &mut model.ranks { rank.set_gate_peer_access(true); } }
model.copy_gate = enable_copy_gate.then(|| Arc::new(crate::offload::CopyEngineGate::new()));
Defect. copy_gate_policy computes enable_gate = has_peer_copy_nodes || (gate_peer_access && has_peer_access_graphs), but set_gate_peer_access(true) is applied to every rank whenever gate_peer_access is true. When gate_peer_access == true and enable_copy_gate == false — the case the PR's own unit test asserts (copy_gate_policy(4, false, false, false) == (true, false), model.rs:1659-1660) — every rank routes through the widened peer_access_graphs (mod.rs:1608, published as peer_copy_graphs in serving.rs:59) while model.copy_gate is None. PeerGraphLeases::new(None, peer_copy_graphs) then holds all-false entries, so no graph gates and offload batches never pause — the #722 deadlock shape, restored by a policy inconsistency.
Fix. Make the two decisions consistent: enable_gate = gate_peer_access (gate exists whenever the widened predicate is installed), or do not set_gate_peer_access(true) when no peer-access graph was found.
MAJOR-5 — all_nvlink_p2p queries only one direction per pair → asymmetric NVLink disables the gate
Diff site: helios/src/runtime_core/model.rs:135-162; callee nvml.rs:358-369; constant nvml.rs:21-23.
for i in 0..handles.len() {
for j in (i + 1)..handles.len() {
if nvml.device_p2p_status(handles[i], handles[j], crate::nvml::P2P_CAPS_INDEX_NVLINK)
!= Some(Ok(crate::nvml::P2P_STATUS_OK))
{ return false; }
}
}
nvmlDeviceGetP2PStatus(d1, d2, ...) is directional (can d1 access d2). The loop never queries (j, i), so a topology where status(i→j) == OK but status(j→i) != OK (asymmetric NVLink, partially bridged or mis-reporting board) makes all_nvlink_p2p return true → gate_peer_access = false → the widened classification is not installed and no gate is created, even though graphs touch Memory::Peer. Per the policy's own test, copy_gate_policy(4, true, false, true) == (false, false) (model.rs:1662). Note the None (missing NVML symbol) case is safe — it falls toward gating.
Fix. Query both directions and require both Some(Ok(P2P_STATUS_OK)).
Related classification gap (Major-5b, mod.rs:227-270, 291-296): collect_peer_referencing_allocations closes only over recorded relocations plus payload-scanned bytes. A rank_data-style table that is zero at load and written with a peer address by a kernel at runtime never enters peer_table_allocations, so graphs reading it are classified non-peer-access. Counterexample: single-host PCIe TP2 core + rank_data (Memory::Device, stored_bytes() == 0), graph A's kernel writes the peer VA into it, graphs B/C take rank_data as an argument → node_peer_usage returns (false,false) for all of them. That is exactly the "indirect peer-pointer tables such as rank_data" case the PR description claims to cover; it is only covered when the table is populated during load.
MAJOR-6 — flush_queued_sqes retries EINTR with no bound; stop() joins with no timeout → teardown can hang forever
Diff site: helios/src/async_transfer/io_backend.rs flush_queued_sqes (added by this PR); callers IoUringBackend::flush, cancel_and_drain, worker.rs:1241/:1249, and worker.rs:654-661 (stop() → handle.join()).
while *queued_sqes > 0 {
match submit() {
Ok(0) => break,
Ok(submitted) => { *queued_sqes = queued_sqes.saturating_sub(submitted); }
Err(err) if err.raw_os_error() == Some(libc::EINTR) => continue, // unbounded
Err(err) => return Err(err),
}
}
Defect. No attempt counter and no deadline, unlike every other wait in this module (cancel_and_drain, the shutdown stream-drain loop at worker.rs:1302-1314 all take an Instant deadline). A signal storm delivered to the worker thread (profiler SIGPROF, SIGURG, SIGCHLD with a process-wide handler) makes io_uring_submit return EINTR on every attempt → infinite spin. AsyncTransferRuntime::stop() computes drained from handle.join() with no timeout (DRAIN_TIMEOUT is only enforced inside the worker, after the main loop exits), so a stuck flush() wedges stop() permanently — which turns clean SIGTERM into a hang and stalls teardown_model_ranks phase 1, i.e. the cross-rank hazard this PR exists to remove.
Fix. Bound the retries (MAX_FLUSH_ATTEMPTS, then Err(io::ErrorKind::Interrupted); the worker already only stores last_error and cancel_and_drain ignores the result), and give stop() a bounded join (handle.is_finished() polled against DRAIN_TIMEOUT, else FailedDrain). The added test uses a finite VecDeque scripted closure, so it structurally cannot detect the unbounded case.
MINOR findings (verified, lower impact)
poll_completionscollapses four outcomes intook == false(io_backend.rs):expected.remove(&op_id); result >= 0 && result as u64 == want. Short read is correctly failed, but-EINTRand-ECANCELED(fromcancel_and_drain) are published as a stickyCOMPLETION_ERROR_BITsentinel into the caller's slot andupdate_host_completionisfetch_max, so it is unrecoverable — while the rest of the module treats both as retryable. Fix: three-valuedIoCompletion(Ok/Interrupted/Failed).op_id == 0collision is NOT a bug —next_op_idstarts at 1 andwrapping_add(1).max(1)skips 0 (resolved per protocol item 1).peer_exit_grace= 30 s < the recovery window (threaded.rs:1019, branch690-698):mark_peer_exitedis set by the first peer to finish draining; if rank 0 is inside a legitimate 40 scuGraphLaunch, the nextpeer_exited()check at 40 s > 30 s firesstd::process::abort()instead of the gracefulon_peer_exit()error. Should be ≥TIMEOUT.chunk_bytes = ((CHUNK / ranks) & !7).max(8)(payload.rs:257): not a multiple ofBLOCK = 4096wheneverranksdoesn't divide 4 MiB in 4096 units (e.g.ranks = 3→ 1398104).read_range(payload.rs:216-241) still produces aligned reads but now re-reads up to 2 × 4096 bytes per chunk (~460 chunks × ≤8 KiB extra I/O for 1.92 GiB).ranks > CHUNKyieldschunk_bytes = 8whileStaging::newallocates 4096-byte buffers → 512× read amplification.ranks = 0panics on division by zero. Fix:((CHUNK / ranks.max(1)) & !(BLOCK - 1)).max(BLOCK).- Load-path scan cost / duplicated work (
payload.rs:257,378-387;mod.rs:191-222,242-257,994-998,1117-1121,291-296):contains_interval_addressruns inside the direct-I/O read closure, so every byte of the 1.92 GiB peer view (2.58 × 10⁸ words, each apartition_pointbinary search) lengthens staging-slot occupancy and sits on thecuMemcpyHtoDAsynccritical path; andcollect_peer_referencing_allocations(HashSet of all peer-referencing names + sorted interval vec + fixed-point closure) is recomputed twice per rank (prepare_kernelsandprepare_graphs) although it is final after the first. Fix: scan after the read, cache(peer_refs, peer_ref_intervals)onNativeResources, and skip allocations withstored_bytes() == 0. - Teardown failure path double-leaks the
driverArc (model.rs:1275-1328vsmod.rs:2051-2079,2197-2205):drain_execution_contextdoesmem::forget(self.driver.clone()); self.context = null_mut();on the sync-failure path, andteardown_model_ranksthenmem::forgets the wholeVec<NativeResources>— soDrop for NativeResourcesnever runs and the explicit clone leak is redundant. Leak-only (no UAF); the retained ranks also have a permanently nullcontext, which is currently unreachable becauseself.ranksismem::taken first. bg_io_inflight/bg_dma_inflightare O(n) scans (scheduler.rs:259-273) called per dispatch attempt inside a loop bounded byfree_events (16) × inflight_dma (16)= ≤256 cheap scans. Bounded; not a real perf defect, reported for completeness only. No per-poll heap allocation exists on the completion path (io_completionsreused viaclear()/drain(..),pending_dma_eventsreused).
Explicitly verified as CORRECT (so the report does not raise false alarms)
- Three-phase teardown barrier (
model.rs:1275-1328,mod.rs:2035-2042):stop_rank_workersevaluates both stops without short-circuit;all_drained &= drainedaccumulates over all ranks before theif !all_drainedcheck, so a rank-2 failure still drains ranks 3,1,0 and nothing is freed while a peer holds it. Phase 2 runsengram.clear()+offload.reset()beforedestroy_execution_resources;Layer::drop(engram.rs:584-592) joins the background threads. Phase 3 pops in reverse rank order. The stated UAF is genuinely closed. Reply::Started(Result<()>)is updated at every construction (threaded.rs:1431,1435) and every destructure (1355,1356-1358,1359-1361,cleanup_failed_startup:1385) in the whole crate; the coordinator does propagateErr(1356-1358). The failed-finish_startuppeer stays alive, loops toreceive(commands, None)(1429-1441), andcleanup_failed_startup:1376-1379sendsCommand::Drainto every peer unconditionally → no deadlock, and thestd::process::abort()path is genuinely removed.Condvarwatchdog usage: every state a waiter reads is written under awake()that takeswake_lockfirst (579-582,584-588,594-598,600-603,759-763); both waits holdwake_lockbefore re-checking → no lost wakeup;wait_whilepredicate matches the pre-wait predicate.Instantarithmetic uses saturating/checked forms. Watchdog is joined viastop_and_join(738-743) from1231-1233, plusDrop(746-752) → noSIGTERMhang from the watchdog.WatchdogCallGuard::enteris oneswap+ at most onewake()on the false→true edge → allocation-free per step.server/metrics.rsrank label is genuinely the GLOBAL rank — no defect.ChannelConfig.rank/AsyncTransferSnapshot.rankarepub rank: usize(worker.rs:94,111),snapshot()copiesself.config.rank(worker.rs:714-718), set toglobal_rank = cluster_rank.unwrap_or(idx)(model.rs:1064-1069,mod.rs:1851-1853); single-host hascluster == Nonesoidxis global; multi-host selects exactly one local rank (model.rs:421-426).render_async_transfer_snapshots(metrics.rs:1566-1592) usess.rank; the old flat.enumerate()bug is fixed and the new test (metrics.rs:1599-1640) exercises 3 snapshots → ranks 0,0,3. Series cardinality unchanged at 10/channel; the oneStringalloc per channel is inrender()(per scrape), not per transfer.AsyncTransfer.tlaUnflushedIoBounded/HwSignaledFaultedSafefaithfully model the Rust predicates (unflushed_io_count,hw_signaled_faulted_dma_count=faulted && hardware_signaled, a genuine subset), the width-16 projection agrees withDecode/project(), andcheck.py:247-265mutations requireoriginal.count(needle) == 1and the expected assertion text in the failing output, so they are real assertions.
Limitations of this audit
- Sub-agents were read-only: no
cargo test,check.py, or TLC execution. Every finding above is from reading files at224fb40; no finding depends on runtime observation. In particular the PR's claim ofcheck.pyexit 0 / 431 transitions and 1,920 passing lib tests is unconfirmed by me. - Multi-host RoCE, SM103/SM121, and Kani (no
cargo-kani) were out of scope, matching the PR's own limitation list.ring.rs::validate_commandwas read only for its constants, so no claim is made about slot range checks. - I could not observe a live SM120 run, so Major-1's 150 s threshold and Major-5's asymmetric-NVML case are constructed from the code's own deadlines and the NVML API contract, not from hardware.