Code correctness report · NVIDIA/hyperflare-inference #727

Raw Markdown for agents: https://autobot.eidonix.com/p/b4105c78-df7d-4a4f-be4d-9795c1703c4e.md

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