Code correctness report · NVIDIA/hyperflare-inference #737

Raw Markdown for agents: https://autobot.eidonix.com/p/80fcb112-23a5-41ac-966f-01883b8c7b0c.md

Audit report — PR #737 @ 46e6a3b (async_transfer: DevToHost, dual-stream H2D, DEFER_TASKRUN, host-wide RAM pool)

Method. 16 files / ~2,080 changed lines across three subsystems, so the diff was partitioned into three disjoint slices (async_transfer ring/scheduler/TLA; worker.rs+io_backend.rs+driver.rs; runtime_core memory/model + selene) audited in parallel under the four-part protocol (callee/enum resolution, same-loop state-order tracing, adversarial small-N/boundary, hot-path big-O), then synthesized and cross-checked for contradictions. All findings quote files read at head 46e6a3b.

Blocker

B1. stream_comp_max is a permanent, submit-time high-water mark → reused completion slot silently stops publishing completions

helios/src/async_transfer/worker.rs:977-990 (declaration/gates), consumed at :1000-1002, :1024-1026, :1421-1475, :1543; recorded at :1013, :1033, :1459, :1571.

let stream_comp_max: Vec<std::cell::Cell<u64>> =
    vec![std::cell::Cell::new(0); args.config.completion_slots as usize];
let should_write_stream_comp = |slot: u32, value: u64| -> bool {
    value >= stream_comp_max[slot as usize].get()
};
let record_stream_comp = |slot: u32, value: u64| {
    let cell = &stream_comp_max[slot as usize];
    if value > cell.get() { cell.set(value); }
};

The cell is written at submission (:1459), before the transfer runs, and is never cleared for the channel's lifetime — only record_stream_comp's monotone max ever writes it. It is a cumulative maximum over every signal_value ever submitted on that slot, not an in-flight check like the neighbouring wait_other_streams_on_slot (:964-975), which correctly scans only pending queues. Any later legal command on the same slot carrying a smaller signal_value is dropped wholesale: no cuStreamWaitEvent, no cuStreamWriteValue64_v2, and — because completion_action stays EventCompletionAction::None — not even the host-mirror update_host_comp (:1210-1223, :1283-1296). validate_command imposes no monotonicity on signal_value (only the bit-63 exclusion, ring.rs:497-508), so this is a legal command stream.

Counterexample (completion ring of 32): slot 3 with signal_value = 9000 for request A (record_stream_comp → 9000, word written, consumer advances). New epoch, same slot, request B with signal_value = 1000 → 1_000 >= 9_000 false → nothing written; B's event completes → complete_dma(op, true) → publish_notice(notice, false, …) (:1224-1231) → no device word and no host mirror. last_error stays Ok and completed_cmds increments, so telemetry is healthy while the captured graph spins forever on device_completions[3] == 1000. Same swallow for signal_completion_slot used by DiskToHost/CancelEpoch/error notices (:999-1002): host mirror advances, device word skipped, observability diverges. The PR's live test only uses increasing values per slot (6006, 7007→7008, 7009/7010, 7011, :2090-2235), so it cannot catch this.

Fix. Derive "may I write this slot?" from the in-flight set exactly as wait_other_streams_on_slot does — scan pending_dem_dma_events/pending_bg_dma_events/pending_d2h_events for completion_slot == Some(slot) and compare against only those entries' signal_value (≤18 entries; the scan is already being done for the wait, so free). If a high-water mark is kept, reset stream_comp_max[slot] when the slot's last pending entry is harvested/drained (:1201-1205, :1278, begin_drain/finish_drain) and record at completion, not submission. Keep an unconditional device-word write for the HostAndDevice fallback.

Major

M1. Shared CUDA event pool is drained by the H2D loop first → DevToHost starves exactly when VRAM pressure needs it

helios/src/async_transfer/worker.rs:874-891 (pool size), :1384 (H2D loop), :1520 (D2H loop).

let event_pool_cap = DEFAULT_MAX_TOTAL_DMA + DEFAULT_MAX_D2H;   // 16 + 2 = 18
let mut free_events: Vec<Handle> = Vec::with_capacity(event_pool_cap);
...
while !has_faulted_h2d && !free_events.is_empty() {      // up to 16
...
while !has_faulted_d2h && !free_events.is_empty() {      // leftovers

One pool, three streams; H2D runs first with concurrency cap DEFAULT_MAX_TOTAL_DMA = 16 out of 18 events. With 16 H2D in flight, step 5b returns immediately and no DevToHost can ever be dispatched — while D2H is precisely what frees the VRAM those H2Ds need (motivation #1). Counterexample: 16 demand HostToDev + 2 DevToHost demotions → demotions wait forever with d2h_stream idle, and pop_next_d2h's gate (scheduler.rs:920-928) adds a second starvation axis. Fix: dedicated free_d2h_events deque of DEFAULT_MAX_D2H handles that the H2D loop cannot consume.

M2. pop_next_d2h is priority-blind and its demand-yield gating keys off H2D only → demand DevToHost head-of-line blocked behind background demotions

helios/src/async_transfer/scheduler.rs:920-934 (new); with_max_d2h at :229-232, dem_dma_inflight at :351-356, fields at :177/:183, default DEFAULT_MAX_D2H = 2 at worker.rs:52 applied at worker.rs:929.

pub fn pop_next_d2h(&mut self) -> Option<InflightD2h> {
    if self.state != ChannelState::Running || self.inflight_d2h.len() >= self.max_d2h {
        return None;
    }
    let dem_dma_active = self.dem_dma_inflight() > 0;
    for prio in [Priority::Demand, Priority::Prefetch, Priority::Warm] {
        if prio.is_background() && dem_dma_active { continue; }
pub fn dem_dma_inflight(&self) -> usize {
    self.inflight_dma.iter().filter(|op| !op.priority.is_background()).count()
}

(a) dem_dma_inflight() counts only inflight_dma (H2D), so the new "background yields to demand" rule never fires for a background DevToHost; (b) the capacity gate is priority-blind, so once max_d2h background D2H ops are in flight a queued Demand D2H is refused although it is the only queued D2H op — and even when admitted it is appended to the single FIFO d2h_stream (worker.rs:1529), so it cannot preempt, unlike H2D which the PR split into two streams.

Counterexample (max_d2h = 1, the configuration the PR's own harness uses, lifecycle_tests.rs:82): enqueue(DevToHost{Priority::Warm}); pop_next_d2h() → Some, inflight_d2h.len() == 1; enqueue(DevToHost{Priority::Demand}); pop_next_d2h() → None because 1 >= max_d2h. At production depth 2, two Warm demotions block a Demand demotion for two full PCIe copies. Not a deadlock or memory-safety bug (ready_retention/can_release_memory stay correct), but a real inversion against the PR's stated invariant.

Fix:

let dem_d2h_pending = !self.d2h_queues[Priority::Demand.index()].is_empty()
    || self.inflight_d2h.iter().any(|op| !op.priority.is_background());
...
if prio.is_background()
    && (dem_dma_active || dem_d2h_pending || self.inflight_d2h.len() + 1 >= self.max_d2h)
{ continue; }

plus a max_d2h = 2 test: one Warm D2H in flight + one Demand D2H queued ⇒ the background arm must not take the last slot.

M3. Background completions are written on the high-priority stream, so device_completions correctness depends entirely on B1's permanent latch

helios/src/async_transfer/worker.rs:1209-1239 (bg-queue harvest) and :992-1043 (signal_completion_slot always writes on copy_stream).

EventCompletionAction::HostAndDevice(slot, val) => {
    signal_completion_slot(slot, val, &pending_bg_dma_events, &pending_d2h_events);
}

A bg bg_copy_stream transfer whose inline write could not be issued is later written by the worker onto copy_stream at harvest. Counterexample: demand 7010 queued on copy_stream, then a late bg 7009 write appended to the same stream's tail → device_completions[slot] regresses to 7009. The permanent latch in B1 is the only thing masking this, so B1 and M3 must be fixed together: an in-flight-set comparison alone re-opens the regression unless the bg harvest path writes on bg_copy_stream after a cuStreamWaitEvent on the demand stream's event for that slot, or gates on the actual last write the worker issued to that slot.

M4. Concurrent startup makes NEXT_WORKER_ORDINAL → rank mapping racy, removing determinism of the cross-rank storage stagger

helios/src/runtime_core/model.rs:1086-1092; assignment helios/src/async_transfer/worker.rs:948; consumer worker.rs:1149-1155.

let handles = self.async_transfer_handles();
let mut first_err: Option<crate::Error> = None;
std::thread::scope(|scope| {
    let joins: Vec<_> = handles.iter().map(|ch| scope.spawn(move || ch.start())).collect();
let worker_ordinal = NEXT_WORKER_ORDINAL.fetch_add(1, Ordering::Relaxed);
...
rotate_storage_runs(&mut drained_cmds, worker_ordinal);

Pre-PR, start_async_transfers() ran in strict rank order (runtime_core/mod.rs:1987-1992), so rank k deterministically got ordinal k and rotate_storage_runs staggered rank k by k against the striped RAID-0 set. Now eight scope.spawned threads race into worker_main. Counterexample with run length len = 3: pre-PR maps rank 0→0, 1→1, 2→2, 3→0…; a racy run can map 0→5, 1→2, 2→7, so which physical drive each rank's demand reads hit changes boot to boot with no ordinal % len separation. This makes the PR's 1,202 ms stall-spread result non-reproducible. Fix: thread the ordinal through WorkerThreadArgs (worker.rs:610-628, add one field) computed from (rank, channel index) in prepare_async_transfers, or reserve it in start() before spawning (worker.rs:567-639, per-channel mutex).

Minor

Verified clean (explicit negative results)

Not verifiable here: cargo-kani not run (B1/M2 are runtime logic, unaffected); the io-uring 0.7 builder surface (setup_no_sqarray, sq.taskrun(), sq.cq_overflow()) was read, not compiled, so a builder/return-type mismatch would not have surfaced; the new io_backend.rs:663-713 test asserts data correctness only and would pass through the plain-Read path, so it does not prove the ReadFixed/DEFER_TASKRUN claims.