PR #727: helios: gate PCIe peer-access graphs and fix teardown, AsyncTransfer, and startup drain races

Raw Markdown for agents: https://autobot.eidonix.com/api/v1/cases/84232bb3-2db8-42d1-8a54-6057a9f401c7

Opened by a workflow run, Dec 4, 2026 12:28 PM EST. decide malicious: all_clear (100%): No malicious content found

explore

Author: lukealonso (COLLABORATOR, charter-named priority contributor, 51 merged PRs in 180 days; de-facto sole owner of the AsyncTransfer / teardown / CopyEngineGate area); Discord lukealonso Motivation: On 4-GPU PCIe boxes, serving with the prefix cache's host offload enabled deadlocks: the Copy Engine gate only recognises graphs with explicit peer copies, so kernel-based peer-to-peer graphs slip past it and transfers collide with them, hanging the GPUs at 100 % with no error. This PR widens that detection, and also repairs three further latent defects in model teardown, asynchronous extent transfers, and startup error handling. Scale: +1973 / −221 lines in 16 files Proposal:

Full report · Notes

Value Proposition

Value Proposition — PR #727 (helios: gate PCIe peer-access graphs…)

Charter alignment. The motivating report, #722, is a reproducible priority:P1 deadlock in shipped flare 0.5.3 on 4× SM120 PCIe under --prefix-cache-memory — squarely inside "What gets merged" (reproducible bug) and inside the charter's target hardware (captured-graph serving on SM120/SM121). The gate is topology-derived (copy_gate_policy, NVML P2P_CAPS_INDEX_NVLINK) rather than a per-model branch, and it explicitly preserves NVLink SM-P2P, which respects "keep the runtime small and model-agnostic." Two tensions are real: RankWedgeWatchdog ends in std::process::abort() after TIMEOUT + 30 s (threaded.rs:1027), a mitigation above #722's root cause that sits awkwardly with "fix the root cause"; and the PR concedes SM103/SM121 hardware and multi-host RoCE were never run, against the charter's supported-matrix expectation.

Novelty & status. Neither obsolete nor superseded. #722 is still open and latent since #628; no competing PR claims it; siblings #723/#726 don't cover it. But this is a same-day self-follow-up: it re-fixes defects #721 introduced hours earlier (SQE flush, DMA fault sentinel, the .enumerate() rank label at pr/721 metrics.rs:1557) and replaces #721's two-phase teardown. Useful, but two passes over the same code in 24 h by the author of the code being fixed, with zero independent review, is genuine maintenance churn.

Value vs cost. Beneficiaries are concrete: PCIe multi-rank operators exposed on 0.5.3 today, where the runtime currently hangs past its own 120 s deadlines. Evidence is uneven, though. The #722 fix is backed by tests of a pure function over synthetic booleans plus one live run that is not the reproduction (13k tokens/20-way/4G/135 graphs vs 32k/c4/256G/177 graphs), with no patched-vs-unpatched comparison. Clusters 2–4 have no external report at all. Operator-visible changes — rank label semantics, deliberate resource retention until exit, a ~150 s abort — are absent from the description, and the load-time scan over every 8-byte word is unquantified.

Needed: split the #722 cluster from the three self-found clusters; a patched run on #722's workload; document the abort, the leak, and the metrics-label change; quantify scan cost. Per #229, spell this out rather than closing.

Verdict: Worth it with changes — land the #722 gate promptly (release exposure), with the above conditions.

Full report Decide Value: yes (100%): This change is worth reviewing: it provides value to the project in line with its charter.

Classify intake

Selected: triage:review, priority:P1, bug, performance

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

Applied: +triage:review, +priority:P1, +bug, +performance

Subtraction and simplicity

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.

Full report

Gates and contracts

Contracts, Charter & Verification Gates Audit — PR #727

Verdict: No contract, vendored-file, or mandatory verification gate blockers.

Four hard gates checked against docs/design-review.md (incl. the Layer 1–3 testing hierarchy and Mandatory Enforcement section), AGENTS.md, docs/verification.md, docs/core-format-design.md, docs/scheduling-theory.md, docs/scheduling-runtime-design.md, and the head diff.


Gate 1 — Signed core-format / wire / captured-graph / public contract boundaries: PASS

Gate 2 — Vendored upstream dependencies and cross-PR conflicts: PASS

Gate 3 — Mandatory verification evidence and failing tests: PASS

This change touches all three gate-requiring surfaces: scheduler/cache/worker lifecycle, GPU/VMM teardown paths, and cross-rank dispatch. Each applicable layer is satisfied and was reported in this round's evidence, with the formal artifacts present in the diff:

Gate 4 — Material scope / claim contradictions: PASS


Summary of what I would record, by severity

Severity Finding
Blocker None.
Major None.
Info / Nit (1) RankWedgeWatchdog ends in std::process::abort() after ≈150 s; the description says "bounds wedged-rank hangs" without stating the process terminates — worth one clarifying sentence in the description. (2) docs/api.md:403-415 should state that the flare_async_transfer_* rank label is the global rank ID, since its meaning changed. (3) #726/#723 overlap on prepare_async_transfers/release_execution_resources; serialize if #726 lands first.
Note The 6 frontend template tests failing on HTTP 403 from the gated meta-models/Muse-Spark-Open-816B-A42B-NVFP4 repo are disclosed in the "1,920 passed" run and are environmental; they do not block. Kani correctly not re-run (no applicable validator changed).

No contract or verification gate blockers.

Full report

Code correctness

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):

  1. pop_next_io ×3 → inflight_io = [A, B, C], all unflushed, queued_sqes = 3.
  2. mark_io_flushed(1) marks A; pending_submissions() == 2.
  3. A's read fails → complete_io(A, false) → swap_remove(0) → C moves to index 0 → [C, B].
  4. Kernel accepts 1 of 2 pending → flushed_now = 2 - 1 = 1 → marks C, not B.
  5. 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.


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)


Explicitly verified as CORRECT (so the report does not raise false alarms)


Limitations of this audit

Full report Merge Risk: medium_high (100%): Medium or high merge risk (core runtime/scheduler/GPU/CUDA/VMM/RoCE/multi-rank/contracts/ABI, large multi-crate changes, or Blocker/Major findings) — route to Super Agent.

Final review

Recommendation: Changes Requested

The core fixes for #722's PCIe kernel-P2P CopyEngineGate detection, the three-phase cross-rank teardown barrier, the Reply::Started(Result<()>) startup drain handshake, and the global-rank Prometheus metrics label are sound and well-structured. However, verification at 224fb40 confirmed one Blocker in AsyncTransfer's new unflushed-IO tracking (where swap_remove desynchronizes inflight_io order from io_uring SQ FIFO order after a partial submit, causing complete_io to permanently drop a real kernel completion) and two Should Fix defects in ThreadedExecutor (RankWedgeWatchdog::CloseStalled aborting progressing/multi-stage teardowns and best_effort_drain_peers skipping already-drained peers after a wedged peer exhausts the shared deadline).

Merge Risk

Level: High

Walkthrough

Pre-merge Checks

Blockers

  1. mark_io_flushed + complete_io swap_remove desynchronizes inflight_io from io_uring SQ FIFO order and permanently drops real kernel completions (helios/src/async_transfer/scheduler.rs:231-243, 578-583; helios/src/async_transfer/worker.rs:994-1001, 1226-1248)
    • Verified behavior: pop_next_io() pushes new InflightIo entries to the back of self.inflight_io (scheduler.rs:566), and worker.rs:1228-1248 computes flushed_now = scheduler.unflushed_io_count().saturating_sub(args.io_backend.pending_submissions()) and passes it to scheduler.mark_io_flushed(flushed_now), which marks the first count unflushed entries in Vec index order (scheduler.rs:233-241). However, complete_io() removes finished entries via self.inflight_io.swap_remove(pos) (scheduler.rs:583), swapping the last element into pos and scrambling submission order relative to the kernel io_uring SQ FIFO.
    • Concrete failure trace:
      1. Stage reads A, B, C -> inflight_io = [A(unflushed), B(unflushed), C(unflushed)], io_uring SQ FIFO = [A, B, C], queued_sqes = 3.
      2. Partial flush submits 1 SQE (A) (Ok(1) then EBUSY/Ok(0)): queued_sqes = 2, flushed_now = 1 -> mark_io_flushed(1) marks A.
      3. A completes (normal ok = true or ok = false) -> complete_io(A, _) executes swap_remove(0) -> inflight_io becomes [C(unflushed), B(unflushed)], while the io_uring SQ still holds [B, C].
      4. Next partial flush submits 1 SQE (B): queued_sqes = 1, flushed_now = 1 -> mark_io_flushed(1) marks C (inflight_io[0]) as flushed = true while leaving B as flushed = false.
      5. poll_completions() (io_backend.rs:198-201) reaps B's CQE (IoCompletion { op_id: B, ok: true }) and removes B from IoUringBackend.expected; worker.rs:998 calls scheduler.complete_io(B, true).
      6. scheduler.rs:580-582 executes if ok && !self.inflight_io[pos].flushed { return None; } and silently discards B's completion without removing B from inflight_io.
    • Impact: B's CQE is permanently lost. Any GPU demand wait on B's completion slot hangs forever, any bounce slot held by B leaks permanently, and shutdown finish_drain() (scheduler.rs:814) permanently fails into ChannelState::FailedDrain, leaking pinned pools and CUDA handles until process exit.
    • Fix: Preserve submission order in inflight_io by replacing swap_remove(pos) with remove(pos) at scheduler.rs:583 (max_total_io is 32, so ordered removal is O(32) and preserves exact SQ FIFO order), or track a monotonic dispatch sequence number on InflightIo and have mark_io_flushed mark the count unflushed entries with the lowest dispatch sequence. Add a regression test exercising partial flush -> completion of first op -> second partial flush -> complete_io(B, true).

Should Fix

  1. RankWedgeWatchdog CloseStalled fires std::process::abort() during legitimate slow or multi-stage teardowns (helios/src/execution/threaded.rs:594-598, 679-687, 1015-1029, 1211-1233)

    • Verified behavior: begin_close() sets closing = true (one-way) and increments activity, but the closing arm of the watchdog loop (679-687) never reads activity and never resets close_since. It applies a single fixed 150 s wall-clock deadline (TIMEOUT + WATCHDOG_GRACE) across all stages of ThreadedExecutor::close(): draining self.pending via self.poll()? (up to TIMEOUT = 120 s per frame), close_peers(..., TIMEOUT = 120 s), fallback best_effort_drain_peers(..., TIMEOUT = 120 s) whenever poll() or close_peers fails, and self.local.close(). As a result, a poisoned teardown where poll() or close_peers hits its 120 s deadline only gets 30 s inside best_effort_drain_peers before the watchdog calls std::process::abort(), and a healthy slow teardown draining frames plus peers in >150 s while actively progressing also aborts.
    • Fix: Track activity in the closing branch (resetting close_since = Some(now) whenever activity advances, matching the busy branch at 703-707), and call self.watchdog_state.record_progress() across close() stage transitions (after pending drains, as each peer joins in close_peers/best_effort_drain_peers, and before self.local.close()).
  2. best_effort_drain_peers shared deadline skips later peers without checking already-queued Reply::Drained, leaving finished threads detached (helios/src/execution/threaded.rs:1278-1316)

    • Verified behavior: Hoisting let deadline = Instant::now() + timeout; outside the for peer in peers.iter_mut() loop (1292) means that if an earlier peer is wedged and consumes the 120 s budget, deadline.checked_duration_since(Instant::now()) returns None for all subsequent peers (1298). The while body never executes even once, so peers that already exited cleanly and queued Reply::Drained in peer.receiver are never polled, exited stays false, and their JoinHandles are dropped without join().
    • Fix: Even when deadline has expired, run a non-blocking try_recv() loop on every remaining peer so peers that already sent Reply::Drained/Err(_)/Disconnected are still joined (or poll remaining peers round-robin against the shared deadline so a wedged peer at index 0 cannot starve peers 1..N-1). Do not join peers that have not confirmed exit.

Subtract / Simplify

Nits

Dropped on verification

Full report

Classify triage

Selected: triage:review

Threshold: 65%

Triage

Apply labels

No label changes decide malicious: all_clear (100%): No malicious content found

explore

Author: lukealonso (COLLABORATOR; charter-named priority contributor, 51 merged PRs/180d, de-facto sole owner of AsyncTransfer/teardown/CopyEngineGate; Discord lukealonso) Motivation: A P1 external bug report (#722) shows a 4-GPU PCIe SM120 server deadlocking under --prefix-cache-memory: most captured graphs were never gated against Copy Engine traffic and nothing bounds a wedged rank. The PR widens that gate and hardens the surrounding teardown, AsyncTransfer and startup-drain code — some of which it had just merged hours earlier as #721. Scale: +2234 / −253 lines in 17 files Proposal:

Full report · Notes

Classify intake

Selected: triage:review, priority:P1, bug, performance

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

No label changes

Gates and contracts

Contracts, Charter & Verification Gates Audit — PR #727 @ c9df77bd

Verdict: no hard contract or vendored-file gate violations; one genuine mandatory-verification gap (Gate 3, live multi-GPU execution of the reordered peer-drain path at the current head). Everything else in all four gates passes; I deliberately did not escalate process preferences (PR splitting, unrun SM103/SM121, workload-differs-from-#722, unobservable CI) into findings.

Scope verified at head: 17 files, none under .github/, no .proto/core-format/schema file, nothing under helios/native/ (pr_files). The earlier .github/ hunks were base drift, now confirmed absent.


Gate 1 — Signed core-format / wire / captured-graph / public-contract boundaries: PASS

Gate 2 — Vendored upstream dependencies & cross-PR conflicts: PASS

Gate 3 — Mandatory verification evidence & failing tests: one gap

What is satisfied (verified at head, not taken on faith). This PR touches async_transfer scheduler/lifecycle state and rank coordination, so check.py + mutations are mandatory (docs/design-review.md:209-240); the artifacts exist, not just the claim:

The gap (Gate 3, live multi-GPU prong). docs/design-review.md:252-259 is explicit:

"Replacing or reordering cross-rank launch, commit, cancellation, or drain paths in helios/src/execution/{threaded,parallel,roce}* requires ... live multi-GPU execution of real collective graphs (for example, serving a multi-GPU exported core through flare run), not only independent per-rank synthetic graphs. Disclosing busy or unavailable GPUs does not waive this requirement for changes to TP execution paths."

best_effort_drain_peers — a peer drain path — was reordered in exactly this push, from per-peer sequential receive() with an individual deadline to a round-robin, non-blocking try_recv() sweep against one shared deadline (helios/src/execution/threaded.rs:1294-1358), with close_peers/best_effort_drain_peers gaining WatchdogState::record_progress() calls (threaded.rs:1281-1283, :1337-1339). The PR's own evidence places the multi-GPU live run before that change:

So the reordered drain path has no live multi-GPU run at the head, and the rule says the disclosure of that gap does not waive it. The CPU side is covered (a mock-transport multi-peer test exists: best_effort_drain_peers_joins_healthy_peers_even_when_earlier_peer_is_wedged, threaded.rs:4175), which is why I am recording this as a gap to close by re-running the existing TP4 flare run sequence on c9df77bd — one command, not a design change — rather than as an architectural objection.

Gate 4 — Material scope / claim contradictions: PASS


Findings by severity

Severity Finding
Blocker None.
Major (gate) Live multi-GPU execution is missing for the reordered peer-drain path at the head. best_effort_drain_peers was reordered (round-robin try_recv, one shared deadline) in c9df77bd (helios/src/execution/threaded.rs:1294-1358), and the only multi-GPU live run is dated 224fb403; the head's live test is single-device. docs/design-review.md:252-259 names drain paths explicitly and says disclosure does not waive live multi-GPU execution. Remedy: re-run the same SM120 PCIe TP4 flare run sequence (serve the exported 4-rank core, exercise SIGTERM teardown) on c9df77bd and report it.
Info / Nit (1) std::process::abort() as the watchdog remedy (threaded.rs:1017-1028) has no docs/ entry, though it is now stated in the PR description; the charter's "don't just swallow/retry an unexplained error" tension is a disclosed design choice, not an omission. (2) docs/api.md:403-405 gives the new meaning of the rank label but not the migration fact that it was previously a flat per-process channel index. (3) #726/#723 overlap on prepare_async_transfers/release_execution_resources; serialise if #726 lands first.
Note 6 frontend template tests failing on HTTP 403 from the gated HF repo are environmental and disclosed; Kani correctly not re-run because no validator it covers changed (CI covers it); the .github/ hunks seen in earlier rounds remain confirmed base drift, not this PR's.

No contract or vendored-file gate blockers. One mandatory verification prong (Gate 3, live multi-GPU drain) needs a re-run at c9df77bd to clear.

Full report · Notes

Subtraction and simplicity

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.

Full report

Code correctness

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.


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


Verified correct (explicitly checked, no defect)

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.

Full report Merge Risk: medium_high (100%): Medium or high merge risk (core runtime/scheduler/GPU/CUDA/VMM/RoCE/multi-rank/contracts/ABI, large multi-crate changes, or Blocker/Major findings) — route to Super Agent.

Re-review

Recommendation: Changes Requested

All Round 1 findings are cleanly resolved at c9df77b — complete_io now preserves io_uring SQ FIFO order via remove(pos) with a regression test, RankWedgeWatchdog::CloseStalled now tracks activity across close() stages, best_effort_drain_peers sweeps peers round-robin against a shared deadline, and all 3 simplifications and 4 nits were addressed. However, verification at c9df77b identified two concrete edge-case code defects — one in the rewritten best_effort_drain_peers loop (where Ok(Err(_)) triggers an unbounded thread.join() while a peer is still inside drain_outstanding_frames) and one in AsyncTransfer's cuEventQuery-fault path (which drops host_mirror_on_drain instead of propagating HostOnly completions on clean stream drain) — plus the mandatory live multi-GPU re-run for modified threaded.rs drain paths (docs/design-review.md:252-259). Fixing both small defects and re-running the existing SM120 PCIe TP4 flare run + SIGTERM check on the final commit will make this ready to merge.

Merge Risk

Level: Medium

Walkthrough

Pre-merge Checks

Blockers

None.

Should Fix

  1. best_effort_drain_peers treats Ok(Err(_)) as thread exit and calls unbounded thread.join() while a peer may still be inside drain_outstanding_frames (helios/src/execution/threaded.rs:1319-1340, 1540-1555, 913-919)

    • Verified behavior: When a peer fails validate_submission (threaded.rs:1540-1555), it sends replies.send(Err(error.clone())) at 1543 before calling drain_outstanding_frames(..., TIMEOUT) at 1545-1554 (which can block up to 120 s or wedge inside executor.poll()). In best_effort_drain_peers (1319-1336), Ok(Err(_)) sets exited = true and immediately calls thread.join() without a deadline — starving subsequent healthy peers from being polled/joined within the shared deadline and allowing CloseStalled to abort the process. By contrast, every real error-exit path (901, 916) returns immediately and drops replies, producing Err(mpsc::TryRecvError::Disconnected), and clean drain sends Reply::Drained only after executor.close() returns (1375-1382).
    • Fix: Only treat Ok(Ok(Reply::Drained)) | Err(mpsc::TryRecvError::Disconnected) as exited = true. Move Ok(Err(_)) into the Ok(Ok(_)) | Ok(Err(_)) => { made_progress = true; continue; } arm so a peer that already exited after sending Err immediately hits Disconnected on the next try_recv() iteration and joins, while a peer still draining in drain_outstanding_frames does not block the round-robin sweep. Add a regression test where peer 0 sends Err(...) while remaining blocked and peer 1 sends Reply::Drained.
  2. cuEventQuery-fault path hardcodes host_mirror_on_drain: None, leaving host_comp stale after clean stream drain (helios/src/async_transfer/worker.rs:1031-1066, 1143-1149, 1164-1192)

    • Verified behavior: When args.use_write_value64 && args.config.device_completions_base != 0, a hardware-signaled DMA stores completion_action: EventCompletionAction::HostOnly(slot, dma.signal_value) in PendingEventDma (1143-1149, 1164-1174). On cuEventRecord failure (1180-1192), worker_main extracts host_mirror_on_drain from completion_action so update_host_comp(slot, val) advances the mapped-host mirror when cuStreamQuery(copy_stream) == 0 (1057-1059). However, on cuEventQuery failure (1039-1044), UntrackedFaultedDma is constructed with host_mirror_on_drain: None, dropping done.completion_action so host-side readers polling host_comp[slot] never observe completion even after copy_stream drains cleanly.
    • Fix: Compute host_mirror_on_drain from done.completion_action at worker.rs:1039-1044 using the same EventCompletionAction::HostOnly(slot, val) if done.hardware_signaled => Some((slot, val)) match (or a small helper shared with 1180-1185).
  3. Re-run live SM120 PCIe TP4 serving + SIGTERM verification on the final commit (docs/design-review.md:252-259)

    • Verified behavior: docs/design-review.md:252-259 requires live multi-GPU execution of real collective graphs (e.g., serving a multi-GPU exported core via flare run) when replacing or reordering drain paths in helios/src/execution/threaded.rs. The PR's live TP4 run is from 224fb403, prior to c9df77bd's changes to best_effort_drain_peers and close_peers.
    • Fix: After applying fixes (1) and (2) above, re-run the existing SM120 PCIe TP4 flare run + SIGTERM check on the final head and record the commit hash and result in the PR description.

Subtract / Simplify

Nits

None.

Dropped on verification

Full report

Classify triage

Selected: triage:review

Threshold: 65%

Triage

Apply labels

No label changes Decision to Test: no (97%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with.