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
find_fixed_buflinear scan per submitted read —io_backend.rs:157-167, called frompush_read_sqe(:177) for every read atworker.rs:1635-1643; withFIXED_BUF_CHUNK_BYTES = 1 << 30(:283-291) a large--pool-ram-memoryrank has hundreds of spans, and cost grows with pool size on the submit path. Spans are ascending/non-overlapping: usebinary_search_byonb_start, or computeidx = span_start + (dst - pool_base) / chunk_bytesin O(1) and verifyend <= span_end.- 50 ms
ACTIVE_SPIN_WINDOWpegs a core per rank —worker.rs:43,:1674-1698;last_activerefreshes on anydid_work, so one command every 40 ms keepsspin_loop()forever (8 pegged cores on TP8),BUSY_SPIN_LIMIT = 512becomes unreachable, and:1686redundantly re-readslast_active.elapsed()inside a branch already guarded at:1685. Cache the predicate once per iteration; extend the window only on a burst. - Stale
has_faulted_d2hinside the dispatch loop —worker.rs:1517-1537(mirrored:1381-1384/:1496-1512):event_recordfailurebreaks but thecuMemcpyDtoHAsync_v2rejection pathcontinues without setting a fault flag, re-issuing a failing copy each iteration (three streams now amplify it). Addd2h_poisoned = trueto the guard. MemoryLimit::Reserveduplicated, not shared —memory.rs:118-129vsPoolMemoryLimit::cap_bytes(limits.rs:174-180); the RAM arm also subtracts aggregatehost_bounce, so--pool-vram-memory -8G --pool-ram-memory -8Ggives VRAMavailable − 8 GiBbut RAMavailable − 8·512 MiB − 8 GiB, and a futurecap_bytesedit changes only one tier. Addcap_bytes_less(available, total, extra_pinned)used by all threeReservesites.- Startup pinning still serial —
model.rs:1077-1083vs:1086-1109: the ~27 GiBcuMemHostRegister_v2per rank (worker.rs:419-435→:145-182) dominatesPrepare async transfersand stays 8× serial; the parallel section only coversbind_worker_thread/best-effortregister_buffers. Motivation #5 is thus addressed only for fixed-buffer registration. - TLA+/mutation model does not encode the two new scheduler predicates —
AsyncTransfer.tla:158-186,:76-110,MaxD2h = 1atAsyncTransfer.cfg:6, mutations atcheck.py:816-819:DispatchD2hmodels a priority-free FIFO andDispatchIo/DispatchDmacarry no demand-in-flight component, soscheduler.rs:636,:791,:926are unconstrained (conformance is Rust→model only) — exactly why M2 passes TLC.MaxD2h = 1withMaxQueue = 2makes production depth 2 and any slot reservation unreachable; the only gating mutation sets the whole term toif falseand is never applied topop_next_io;Spec == Init /\ [][Next]_state(:394) has no fairness, so no anti-starvation property is checked despite the preemption claim.
Verified clean (explicit negative results)
Opcode::DevToHost = 5bounds roles are correct, not swapped —ring.rs:497-517:host_offsetvalidated againsthost_pool_bytes(HostRangeOutOfBounds),device_offsetagainstdevice_pool_bytes(DeviceRangeOutOfBounds), identical toHostToDev(:438-457) and matchingcuMemcpyDtoHAsync_v2(host dst, device src atworker.rs:1526-1530).fits_rangeuseschecked_add(:369-374) soptr + lennearu64::MAXerrors instead of wrapping;nbytes == 0→LengthMismatch; bit-63COMPLETION_ERROR_BITexcluded by the shared check (:405-407); opcodes 6/0/255 →InvalidOpcode(:69-78).kani_proofs.rs:199-218matches the implementation and is not vacuous (only reached viavalidate_transfer_header, which guarantees alignment/power-of-two).- All four new CUDA bindings have correct signatures/argument order (
driver.rs:301,325,326,338):cuCtxGetStreamPriorityRange(least, greatest)called with&mut least_prio, &mut greatest_prio, usinggreatest_prio(numerically smallest = highest priority) inmake_stream(worker.rs:446-464) with a correctgreatest_prio < least_priono-range guard;cuStreamCreateWithPriority(out, CU_STREAM_NON_BLOCKING, prio);cuStreamWaitEvent(target_stream, pending.event, 0). - Cross-stream slot synchronization ordered correctly — the wait is always issued on the target stream before its write edge, against an event owned by a different stream (
worker.rs:964-975,:1003,:1027,:1424-1437,:1544-1549); no site lets two streams touch a slot without a wait. - Faulted-DMA retention/drain correct for all three streams (
worker.rs:1325-1378,:1401-1409,:1742-1762;scheduler.rs:410-415,:1051-1054,:1072-1076,:704): bounce slots retained until drain,host_mirror_on_drainpreserved,DevToHostowns no bounce slot (bounce_slot()→None,scheduler.rs:92-97),mark_d2h_faulted/complete_d2hmirror H2D semantics with no duplicate drain notice, andcan_release_memory/epoch/drain all includeinflight_d2h. bounce_pool_geometry(worker.rs:78-96) cannot exceed the 512 MiB ceiling for anyslot_bytes ∈ (0, 32 MiB];ReadFixedfallback (io_backend.rs:158-167,:177-209,:298-322) never issuesReadFixedwith an unregistered index, including after partial registration failure, andqueued_sqesaccounting stays exact;update_host_completionusesfetch_max.- Host-wide
--pool-ram-memoryarithmetic sound (memory.rs:118-158,selene/src/offload.rs:945-994): no bounce double-count, aggregate identity holds in bothReserveandNonearms,discrete_ranks = 0unreachable (:1359-1363,local_ranks.max(1)),--pool-ram-memory 400Gon 251 GiB still clamps per rank,pinned.saturating_mul(ranks).div_ceil(512)cannot overflow and is charged once, integrated/unified-DRAM andhost_futuregenuinely unchanged,discrete_ranks = 1bit-identical to pre-PR except the intended− bouncereserve fix. Thestd::thread::scope(model.rs:1086-1109) is sound: allResults and panics propagated (:1099-1106), no shared mutable state crossed unlocked,O(channels)threads. - No hot-path allocation regression in the scheduler:
d2h_queuesareVecDequewithpop_front/push_back,complete_d2husesswap_remove,InflightD2hisCopy,queue_shape_key(scheduler.rs:419-434) distinguishes priority/bounce classes, and the BFS harness (lifecycle_tests.rs:94-190, assertions:308-319,:390-415,:466-501) genuinely reaches the D2H fault/drain branches.
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.