Audit — PR #727 helios: gate PCIe peer-access graphs and fix teardown, AsyncTransfer, and startup drain races @ c9df77b
Partitioned into 3 disjoint slices (execution/threaded.rs; runtime_core/* + 2 docs; async_transfer/* + server/metrics.rs + verification/*), each audited with the full 4-part protocol, then I re-verified every headline finding myself against the head sources (quotes below are from read_file at c9df77b, not from the sub-reports).
Verdict: 2 Major correctness defects, 1 Major state-loss defect (TLA-modeled invariant is violated in the model's own premise but the real bug is the queued_sqes/flushed desync), 3 Minor. The teardown barrier, the widened peer-access gate, the RankWedgeWatchdog activity bookkeeping, the EINTR bound, and the metrics rank labels are all verified correct.
Finding 1 — Major: best_effort_drain_peers treats a peer's error reply as thread exit and then join()s it with no deadline, defeating the shared deadline and the whole point of the fix
Diff site helios/src/execution/threaded.rs:1317-1340 (verified verbatim):
let mut exited = false;
loop {
match peer.receiver.try_recv() {
Ok(Ok(Reply::Drained))
| Ok(Err(_))
| Err(mpsc::TryRecvError::Disconnected) => {
exited = true;
break;
}
Ok(Ok(_)) => {
made_progress = true;
continue;
}
Err(mpsc::TryRecvError::Empty) => break,
}
}
if exited {
if let Some(thread) = peer.thread.take() {
let _ = thread.join();
Callee resolution — Ok(Err(_)) does not imply the peer thread is exiting. On the peer side (threaded.rs:1543-1555) the rank sends its error and only then drains outstanding frames for up to TIMEOUT (120 s) inside executor.poll() (cuStreamQuery/cuStreamSynchronize — precisely where a wedged GPU blocks, i.e. the #722 failure mode):
let _ = replies.send(Err(error.clone()));
ring.mark_peer_exited();
let _ = drain_outstanding_frames(
executor, |exec| exec.outstanding(), |exec| exec.poll(),
&mut started, TIMEOUT,
|completion| { let _ = send(Reply::Complete(completion)); },
);
The thread only reaches its exit path afterwards. The single shared deadline is at threaded.rs:1309 (let deadline = Instant::now() + timeout;) and the join() at 1335 is outside it; after the join the for loop continues to the next peer, so remaining is only re-checked at 1348, i.e. after an unbounded join.
Concrete counterexample (SM120 PCIe TP4, ranks 1..3): every peer fails validate_submission on epoch e → each sends Err, then blocks up to 120 s in drain_outstanding_frames. Coordinator: close_peers times out (120 s) → best_effort_drain_peers(120s) reads Ok(Err(_)) from peer 1 at t0 and join()s it, blocking ~120 s; peer 2 and 3 are never even polled before the deadline expires at 1348, so they are left unconfirmed and the local.close()/watchdog path fires (CloseStalled → std::process::abort()). Worst case per close is 120 + N·120 s instead of one shared 120 s — the new watchdog then converts that into exactly the process abort the drain handshake was added to remove.
Fix: only Reply::Drained or TryRecvError::Disconnected may set exited; an Err reply must be recorded and treated as progress, never joined:
Ok(Ok(Reply::Drained)) | Err(mpsc::TryRecvError::Disconnected) => { exited = true; break; }
Ok(Err(e)) => { peer.reported_error = Some(e); made_progress = true; continue; }
and only join when Disconnected was observed (or hand handles to a detached joiner so the sweep stays within deadline).
Finding 2 — Major: flushed_now is inferred from two counters that do not count the same SQEs; cancel SQEs corrupt queued_sqes, so reads are marked flushed that the kernel never submitted (and vice versa)
Diff site helios/src/async_transfer/worker.rs:1222-1229 and 1236-1244 (verified verbatim):
if res.is_ok() {
submitted_io = true;
let flushed_now = scheduler
.unflushed_io_count()
.saturating_sub(args.io_backend.pending_submissions());
if flushed_now > 0 {
scheduler.mark_io_flushed(flushed_now);
}
if submitted_io || args.io_backend.pending_submissions() > 0 {
let flush_result = args.io_backend.flush();
let flushed_now = scheduler
.unflushed_io_count()
.saturating_sub(args.io_backend.pending_submissions());
Callee resolution: pending_submissions() is self.queued_sqes (io_backend.rs:195-197), which is incremented only in push_read_sqe (io_backend.rs:136) but is decremented by the total submission count on paths that also submit cancel SQEs (io_backend.rs:224-236 and :252-255):
for op_id in pending_ids {
let cancel = opcode::AsyncCancel::new(op_id).build().user_data(0);
if self.ring.submission().is_full() {
if let Ok(submitted) = self.ring.submit() {
self.queued_sqes = self.queued_sqes.saturating_sub(submitted);
}
}
let _ = unsafe { self.ring.submission().push(&cancel) };
}
if let Ok(submitted) = self.ring.submit() {
self.queued_sqes = self.queued_sqes.saturating_sub(submitted);
}
submit_with_args(1, &args) (io_backend.rs:252) submits everything staged, cancels included, and its return is subtracted from queued_sqes. So the identity "queued_sqes == number of staged SQEs belonging to unflushed ops" is false.
Concrete counterexample: 2 reads staged & unflushed, expected holds 4 ops → 4 cancel SQEs pushed, queued_sqes still 2; submit_with_args submits 6 and returns 6 → queued_sqes = 2.saturating_sub(6) = 0. The worker then computes flushed_now = 2 - 0 = 2 and calls mark_io_flushed(2) on reads with no guarantee of kernel submission. Mirror direction: any orphan SQE makes unflushed_io_count() - pending_submissions() equal the true count while a genuinely submitted read is never marked; its CQE is then silently dropped by the new complete_io guard (scheduler.rs:580-582, if ok && !self.inflight_io[pos].flushed { return None; }) at the harvest site worker.rs:993-997, inflight_io never empties, finish_drain (scheduler.rs:816) never reaches Stopped, and FailedDrain pins all host memory + CUDA handles until process exit. saturating_sub hides the accounting corruption in both directions.
Fix: count read SQEs explicitly — increment queued_read_sqes in push_read_sqe, return the number of read SQEs actually accepted from flush(), and drive mark_io_flushed from that delta; give cancel SQEs a distinct user_data so poll_completions's op_id == 0 filter (io_backend.rs:203-206) stays sound.
Finding 3 — Major: the cuEventQuery-fault path can never advance the mapped-host completion mirror; host waiters block to their own timeout on a transfer that completed
Diff site helios/src/async_transfer/worker.rs:1039-1044 (verified verbatim):
untracked_faulted_dmas.push(UntrackedFaultedDma {
op_id: done.op_id,
pending_notice: None,
hardware_signaled: done.hardware_signaled,
host_mirror_on_drain: None,
});
Callee resolution: the drain branch that is supposed to advance the mirror is worker.rs:1053-1059: if let Some((slot, val)) = item.host_mirror_on_drain { update_host_comp(slot, val); }. host_mirror_on_drain is hard-None on this path, and PendingEventDma (worker.rs:315-321) carries completion_action but the fault construction drops it — only the cuEventRecord-failure path populates host_mirror_on_drain (worker.rs:1180-1185).
Concrete counterexample: DMA with cuStreamWriteValue64_v2 already enqueued (hardware_signaled = true, worker.rs:1143-1149) whose cuEventQuery then returns a sticky error. mark_dma_faulted(.., true) correctly suppresses the error sentinel (scheduler.rs:724-728), complete_dma releases the bounce slot on clean drain — but update_host_comp is never called, so a host consumer polling that completion slot never observes the success cookie and spins to its own timeout (or mis-times the transfer) even though the DMA finished.
Fix: retain completion_action in PendingEventDma and compute host_mirror_on_drain at fault time with the same match used at worker.rs:1180-1185.
Finding 4 — Minor: all_nvlink_p2p collapses three fabric states into two, so "cannot tell" silently widens the gate to peer_access_graphs
helios/src/runtime_core/model.rs:135-172 (per source read): Nvml::load(), device_by_pci_bus_id and device_p2p_status failures all return false, which copy_gate_policy reads as "not all-pairs NVLink" → gate enabled on peer_access_graphs. Counterexample: 4× H100 NVSwitch host in a container without libnvidia-ml.so; copy_gate_policy(4,false,false,true) == (true,true) → every peer-access graph serializes behind prefix-cache offload batches and can fail with ExecutionError::Drain after PEER_GRAPH_GATE_TIMEOUT (120 s) for no reason. Fails safe (gates more), hence Minor. Fix: return a tri-state and, for Unknown, keep today's narrower peer_copy_graphs predicate plus a one-time load-time diagnostic. The predicate itself is correct: it queries (i,j) and (j,i) for P2P_CAPS_INDEX_NVLINK, so asymmetric NVLink correctly reads as "not all NVLink".
Finding 5 — Minor: cleanup_failed_startup join()s with no deadline and the watchdog is spawned only after a successful startup
helios/src/execution/threaded.rs:1437-1444: match thread.join() { Ok(shutdown) if shutdown.drained => {} ... } — peer.receive() is TIMEOUT-bounded but join() is not, and the RankWedgeWatchdog is created at 1012-1028, after startup succeeds. A peer stuck in GraphExecutor::close() (synchronize(), engram.drain(), unbounded) hangs ThreadedExecutor::new forever. Fix: spawn the watchdog before the startup closure, or poll JoinHandle::is_finished() against TIMEOUT.
Finding 6 — Minor: two hot-path costs and one dropped-CQE silence
worker.rs:1199-1233+1238-1243: every submit doesunflushed_io_count()(O(n) scan,scheduler.rs:226-228) andmark_io_flushed(O(n),scheduler.rs:231-243), twice per iteration;complete_ionow does an orderedVec::remove(O(n),scheduler.rs:585) instead ofswap_remove— fine atDEFAULT_MAX_TOTAL_IO = 32(worker.rs:46) but the bound is not enforced:TransferScheduler::newaccepts anymax_total_io(scheduler.rs:162-169). Keep anunflushedcounter instead of rescanning.complete_io'sNone(unflushed-okguard) is discarded at both harvest sites (worker.rs:993-997,:1294-1295): a dropped CQE yields no counter, nolast_error, and leaves the op pinned with zero diagnostics.threaded.rs:1326-1329:made_progress = true; continue;skips the loop's only sleep (1354-1356), so a peer streaming non-terminal replies busy-spins all peers.
Verified correct (explicitly checked, no defect)
- Three-phase teardown barrier (
model.rs:1277-1340): phases strictly drain-all →engram.clear()+offload.reset()(whileMappedHoststaging buffers and CUDA contexts are live;Layer::dropengram.rs:584-592joins the reader thread,Transfers::Dropoffload/transfer.rs:843-854joins every offload thread) → destroy-all → reverse-rank context release.teardown_model_ranksaccumulatesall_drained &= drainedover every rank before skipping phases 2–3, so N=4 with rank 2 failing drain frees nothing → the cross-rank UAF cannot recur.stop_rank_workers(mod.rs:2033-2040) genuinely removes the||short-circuit (both&self, idempotent stops). peer_access_graphsvspeer_copy_graphsseparation (mod.rs:297-327,1482-1483,1612-1618;serving.rs:54-59): both vectors pushed in the samecore.graphsiteration ⇒ aligned withself.executables;Node::Copy(Memory::Peer)sets both, local copy neither,Memset/Kernelset access only viapeer_refs,Empty/EventWaitneither.validate_async_transfer_peer_copy_compatibility(model.rs:191-207) keeps onlyhas_any_peer_copy_graphs⇒ NVLink/kernel-P2P cores are no longer falsely rejected — the intended decoupling.- Peer-referencing closure ordering:
collect_peer_referencing_allocationsruns afterload_payloadhas populatedpeer_table_allocationsand before the module-global scan (mod.rs:995-1043), stored inself.peer_refs(1091), consumed withtake()+ recompute fallback (1119-1125); monotone fixpoint (252-267).prepare_kernelsis called unconditionally per rank beforeprepare_graphs(model.rs:912-930, joined at1183-1214), so the gate can never see a half-filled vector. - Payload 8-byte scan boundaries (
mod.rs:201-232,payload.rs:257,378-387):chunks_exact(8)on analloc_offset-derivedskipcatches a pointer in the last 8-byte word; emptypeer_intervalsshort-circuits before any scan; search is O(words · log m) viapartition_point, not O(n·m). Only residual doubt:format.rsacceptsalignment == 1, under which an unaligned pointer table could be missed — unreachable for the exported cores examined, but worth hardening toalignment >= 8for payload-bound allocations. RankWedgeWatchdog: resets only whencurrent != last_activity(no off-by-one/never-reset);wake.wait_whilere-checks busy/closing/peer_exited/stopped under the lock with every notify-holder takingwake_lockfirst ⇒ no lost wakeup, zero idle CPU; the closing branch dominatespeer_exitedso a healthy teardown arms no 30 s grace; dropped insideclose()beforeself.shutdownis recorded.flush_queued_sqes(io_backend.rs:146-170): EINTR bounded to 16 consecutive retries,Ok(0)breaks without spinning, non-EINTR errors propagate withqueued_sqespreserved — unit-tested at:461-471.hardware_signaledsentinel suppression acrossInflightDma/PendingEventDma/UntrackedFaultedDma:mark_dma_faulted(hw=true)returnscompletion_slot: None(scheduler.rs:724-728) and every publish site passes!hardware_signaled/false, sosignal_completion_slotis unreachable for already-signaled DMAs;host_compstill advances monotonically.- Metrics rank labels (
metrics.rs:1535-1567):s.rankis the true global rank (ChannelConfig.rank = global_rank,runtime_core/mod.rs:1849-1852, fromcluster_rank.unwrap_or(idx)), channel names are unique per rank ⇒ no duplicate(channel, rank)series; the newVecof snapshots is one extra POD allocation per scrape on a path that already cloned aStringper channel. - TLA+/
.cfg/check.pywiring is real, not vacuous:FlushIois inStep(AsyncTransfer.tla:186) and kind 12 inActionMatches(:320) hence reachable fromNext;UnflushedIoBounded/HwSignaledFaultedSafeare defined (:247-255), wrapped intoObservedSafe(:267-268) and listed inAsyncTransfer.cfg:22-23; projection width 16 matcheslifecycle_tests.rs:24; both new TLA mutations and both new Rust mutations match the shipped text verbatim (count(needle) == 1enforced atcheck.py:273-274).
Limits: source-reading only — no execution of the live SM120 TP4 run, the TLA+ suite, or the crate tests was possible here; Findings 1–3 are established by code reading and need a partial-submit/EINTR + wedged-peer workload to reproduce live.