Deep Code Correctness, Invariants & Hot-Path Performance Audit — PR #711 @ 6916f22
Partitioning. The PR spans 57 files / ~7.4k lines across 4 subsystems, so I split it into 3 disjoint slices and ran them concurrently (helios/src/async_transfer/**, heliopause/** + TLA+, ignition/** + flare-cli/flare config). The heliopause sub-agent died without producing a report, so I audited that entire slice myself, plus the helios/src/runtime_core/{mod,memory,protobuf,model}.rs wiring that no sub-agent owned. I independently re-read and confirmed every finding below; I dropped sub-agent claims I could not prove (listed at the end).
Result: 3 Major, 4 Minor. No Blocker. The ABI layout, ring/directory bounds validation, pool-size arithmetic, DEVICE_POOL mapping, and extent authentication are sound; the real defects are in the completion-signal contract, the shutdown drain, and bounce-pool sizing.
MAJOR 1 — HOST_TO_DEV never publishes a completion word: the host word is skipped on success and the device word is skipped on failure
Diff site: helios/src/async_transfer/worker.rs:786-792 (step 4) and worker.rs:822-871 (step 5).
Callee/contract: worker.rs:673-699 (publish_notice(notice, write_slot)), worker.rs:650-671 (signal_completion_slot), Proto contract helios/proto/runtime_core.proto:855-857, host-word offset helios/src/async_transfer/ring.rs:242-249 (host_completions_offset).
// worker.rs:786-792 (step 4: DMA completion harvested)
let ok = status == 0;
if let Some((slot, val)) = done.signal_host_slot {
signal_completion_slot(slot, val);
}
if let Some(notice) = scheduler.complete_dma(done.op_id, ok) {
publish_notice(notice, false); // <-- write_slot == false
}
// worker.rs:822-853 (step 5: submit)
if copy_status == 0 {
if let Some(slot) = dma.completion_slot {
if args.use_write_value64 {
let target_addr = if args.config.device_completions_base != 0 {
args.config.device_completions_base + u64::from(slot) * 8
} else { /* cuMemHostGetDevicePointer on the host word */ };
if target_addr != 0 { /* cuStreamWriteValue64_v2 → device word only */ }
else { signal_host_on_event = Some((slot, dma.signal_value)); }
} else { signal_host_on_event = Some((slot, dma.signal_value)); }
}
}
...
if copy_status == 0 && signal_status == 0 && rec_status == 0 { /* push pending_dma_events */ }
else { free_events.push(ev);
if let Some(notice) = scheduler.complete_dma(dma.op_id, false) {
publish_notice(notice, true); } } // <-- host word only, never the device word
On the success path with device_completions configured and attribute 122 supported (exactly the PR's own CUDA-test configuration), signal_host_on_event stays None, and step 4 calls publish_notice(..., false), so neither the host word (host_completions_offset) nor the device word for that slot is ever written beyond the cuStreamWriteValue64 device write. On the failure path the complement holds: the host word is written, the device word never is.
Concrete counterexample: the PR's own test at worker.rs:1223-1238 publishes HostToDev{completion_slot: 1, signal_value: 2002} and waits on the device word, so it passes. Change it to wait on the host word — wait_host_comp(ctrl_ptr, 1, 2002), defined at worker.rs:1129-1140 and used at line 1219/1220 — and it times out and panics: the success path never calls signal_completion_slot(1, 2002). Symmetrically, make cuMemcpyHtoDAsync fail (copy_status != 0) with a graph blocked on device word 1: word 1 stays 0 forever. Because CompletionNotice still carries completion_slot: Some(1) (scheduler.rs:638-651), one of the two consumer types starves on every transfer, and the doc sentence "written in stream order … after Copy Engine DMA completes" (manifest.md:178-182) holds for neither consumer in the general case.
Fix: make every path publish both sides, e.g. on success publish_notice(notice, true) after complete_dma (the second host store is idempotent; guard the cuStreamWriteValue64 so it is not issued twice), or restructure signal_completion_slot to always write the host word and, when device_completions_base != 0, to record the same value to the device word on signal_stream on the event/failure paths too.
MAJOR 2 — Shutdown drain reports success with storage reads still in flight; finish_drain is never called
Diff sites: helios/src/async_transfer/worker.rs:936-944 and worker.rs:974.
Callee/contract: helios/src/async_transfer/scheduler.rs:687-710 (finish_drain), scheduler.rs:262-268 (can_release_memory), helios/src/async_transfer/io_backend.rs:182-211 (cancel_and_drain), consumer helios/src/runtime_core/mod.rs:1628-1639 → worker.rs:499-509.
// worker.rs:936-944
let io_drained = args.io_backend.cancel_and_drain(DRAIN_TIMEOUT);
if io_drained {
// Clear scheduler inflight IO accounting now that backend confirmed zero pending reads.
io_completions.clear();
let _ = args.io_backend.poll_completions(&mut io_completions);
for c in io_completions.drain(..) { let _ = scheduler.complete_io(c.op_id, c.ok); }
}
// worker.rs:974
let ok = io_drained && stream_drained && scheduler.inflight_dma_count() == 0;
// io_backend.rs:197-210 — cancellation CQEs are consumed and thrown away
let deadline = Instant::now() + timeout;
let mut discarded = Vec::new();
while !self.expected.is_empty() {
discarded.clear();
let _ = self.poll_completions(&mut discarded); // removes from `expected`, result DROPPED
if self.expected.is_empty() { break; }
...
}
true
scheduler.finish_drain(...) — the only code that enforces inflight_io.is_empty() && inflight_dma.is_empty() and that can raise FailedDrain for the I/O side (scheduler.rs:695-701) — is never called by the worker (verified: the only call sites are lifecycle_tests.rs:270 and scheduler.rs:835,853). cancel_and_drain harvests each cancellation CQE into discarded and drops it, so the follow-up poll_completions at worker.rs:940 yields nothing and scheduler.inflight_io is never cleared. /verify/ run() — the lifecycle model's FinishDrainFail/FinishDrainOk actions (AsyncTransfer.tla:132-141) therefore have no counterpart in the worker.
Concrete counterexample: queue one DISK_TO_HOST of a 64 KiB extent (ring_capacity = 16, completion_slots = 8) against a slow device, then stop the server while it is in flight. cancel_and_drain pushes AsyncCancel for that op_id, harvests -ECANCELED into discarded, expected empties → returns true; the worker's poll sees nothing; scheduler.inflight_io_count() == 1; ok is computed without that term → true; stop() (worker.rs:499-509) sets ChannelState::Stopped, writes Stopped into ControlHeader.worker_state, and release_owned_resources_locked destroys the streams and unregisters/munmaps the pinned host + bounce pools while an I/O operation still targets that memory. This violates the invariants the PR adds to check: StoppedHasZeroInflight and CanReleaseExact (AsyncTransfer.tla:178-183, 200-201) and the Rust harness assertion at lifecycle_tests.rs:118-127 (Stopped ⇒ inflight == 0 && free_bounce == bounce_slots && can_release_memory()). The laundering point is that the worker writes the scheduler's Stopped claim into the exported control header, advertising Stopped to captured graphs that may publish more commands.
Fix: after the I/O drain, finish through the state machine and only release on confirmation:
let ok = io_drained && stream_drained && scheduler.inflight_io_count() == 0
&& scheduler.inflight_dma_count() == 0
&& scheduler.finish_drain(stream_drained).is_ok();
and make cancel_and_drain return the harvested IoCompletions (or leave them for the caller) so complete_io frees bounce slots and inflight_io; otherwise force FailedDrain and retain pinned memory as the doc claims.
MAJOR 3 — Bounce-slot size is rounded up after the 32 MiB cap, so a legal alignment inflates pinned host RAM 16× beyond the VRAM that was reserved for it
Diff site: helios/src/async_transfer/worker.rs:249-258; cap constants worker.rs:47-50; reserve computation helios/src/runtime_core/memory.rs:64-103; validation of alignment ring.rs:280-282 and heliopause/src/export/binding.rs:633-637.
// worker.rs:249-257
let max_extent = config.extents.iter().map(|e| e.nbytes).max().unwrap_or(0);
let (bounce_slots, bounce_slot_bytes) = if max_extent > 0 {
let align = u64::from(config.alignment);
let slot_bytes = max_extent.min(MAX_BOUNCE_SLOT_BYTES).div_ceil(align) * align;
(DEFAULT_BOUNCE_SLOTS, slot_bytes)
} else { (0, 0) };
let bounce_total = usize::try_from(bounce_slot_bytes.saturating_mul(bounce_slots as u64))
// memory.rs:94-101 (the reserve that exists to make startup safe)
pinned = pinned.saturating_add(host_pool)
.saturating_add(crate::async_transfer::worker::MAX_BOUNCE_POOL_BYTES);
...
let page_tables = pinned.div_ceil(512);
alignment is only constrained to be a power of two ≥ 4096 (ring.rs:280-282; binding.rs:633-637 allows up to u32::MAX), and div_ceil(align) * align is applied after the min(MAX_BOUNCE_SLOT_BYTES) clamp, so the cap is not a cap.
Concrete counterexample: a channel with alignment = 1 GiB and a single 4 KiB extent. max_extent = 4096 → slot_bytes = 4096.min(32 MiB).div_ceil(1 GiB) * 1 GiB = 1 GiB → bounce_total = 16 GiB of map_host + cuMemHostRegister_v2 (and map_host prefaults, so this is not overcommit-cheap). The reserve charged in memory.rs:96-98 is MAX_BOUNCE_POOL_BYTES / 512 = 1 MiB of VRAM page tables, i.e. 16 384× less than the real 16 GiB registration cost. prepare_async_transfers then fails in PinnedHostRegion::allocate (worker.rs:247-267) or exhausts host RAM after allocate_caches has already committed DEVICE_POOL and the KV cache — the exact failure this reserve was added to prevent. With alignment = 64 MiB the inflation is 16 × 64 MiB = 1 GiB per channel.
Fix: clamp after rounding and make the charger use the same function:
let slot_bytes = max_extent.div_ceil(align).checked_mul(align)?;
if slot_bytes > MAX_BOUNCE_SLOT_BYTES { /* disable bounce staging: slots = 0 */ }
and call that helper from async_transfer_device_reserve so reserved VRAM always equals registered pinned bytes.
MINOR 4 — Dead break in the I/O dispatch loop starves Demand/older-epoch reads behind a bounce-blocked background op
helios/src/async_transfer/scheduler.rs:437-457:
for prio in [Priority::Demand, Priority::Prefetch, Priority::Warm] {
...
let queue = &mut self.io_queues[prio.index()];
while let Some(front) = queue.front().copied() {
...
if needs_bounce && self.free_bounce_slots.is_empty() { break; }
break exits only the inner while, then the for advances to the next priority — so it is not the "stop dispatching" it reads as, but it also never re-examines the same queue: for prio = Warm it exits the loop entirely. Combined with the single global pop_next_io/pop_next_dma per iteration, a WARM-priority bounce-backed DISK_TO_DEV at the head of the Warm queue blocks a Demand non-bounce read behind it only when slots are exhausted — the "DEMAND > PREFETCH > WARM" preemption claim in manifest.md:190-192 then does not hold under bounce exhaustion. Counterexample: 16 bounce slots held by in-flight Warm ops, one Warm DISK_TO_DEV queued, then a Demand DISK_TO_HOST queued: the Warm op is skipped but the loop exits that queue, and the Demand read is dispatched — correct — yet the same structure lets the Warm head keep the bounce slot it will never get while pop_next_io returns None once all priorities are bounce-blocked, with no back-pressure signal to the producer. Fix: use break 'outer semantics or continue 'next_priority explicitly, and record ErrorCode/telemetry when dispatch is bounce-blocked.
MINOR 5 — Ring overrun by the producer is undetected
helios/src/async_transfer/worker.rs:734-739:
let tail = header.cmd_tail.load(Ordering::Acquire);
while head < tail {
let slot_idx = (head & ring_mask) as usize;
let cmd = unsafe { std::ptr::read_volatile(ring_base.add(slot_idx)) };
head = head.wrapping_add(1);
ring_capacity is a validated power of two (ring.rs:271-276), so & ring_mask is exact, but nothing checks tail - head <= ring_capacity. A captured graph that publishes more than ring_capacity outstanding commands (ring_capacity = 16) overwrites unconsumed slots and the worker silently executes overwritten commands instead of raising ErrorCode. Fix: before the loop, if tail.wrapping_sub(head) > u64::from(args.config.ring_capacity) { header.last_error.store(ErrorCode::RingOverrun as u32, Release); header.cmd_head.store(tail, Release); break; } (new error code).
MINOR 6 — The worker busy-spins a full core for the whole duration of every in-flight transfer
helios/src/async_transfer/worker.rs:913-925:
if did_work {
sync_telemetry(&scheduler);
idle_spins = 0;
} else if scheduler.inflight_io_count() == 0 && scheduler.inflight_dma_count() == 0 {
idle_spins = idlespins.saturating_add(1);
if idle_spins < IDLE_SPIN_LIMIT { std::hint::spin_loop(); }
else { thread::sleep(IDLE_PARK_INTERVAL); }
} else {
std::hint::spin_loop();
}
The park path is unreachable while work is in flight, so each channel's thread spins at 100 % CPU for the entire duration of a multi-GiB pinned-RAM→VRAM copy or a cold O_DIRECT read; N channels cost N cores and contend with the thread that must submit the next DMA. Fix: after a bounded number of unproductive polls with work in flight, thread::yield_now() then a short sleep (the 200 µs IDLE_PARK_INTERVAL is already defined) or wait on the DMA event with a timeout.
MINOR 7 — _seed_library_device_caches relies on an ambient pool it never enters, then latches permanently
ignition/preparation/capture.py:123-146 (new function):
# CoreStorage.__enter__ keeps warmup_storage.pool active outside transient(),
# so allocations here land directly in persistent exported storage.
with torch.cuda.device(index):
for fn in (...):
if fn is not None and hasattr(fn, "cache_clear"): fn.cache_clear()
...
warmup_storage._seeded_library_caches = True
Unlike its sibling _seed_auxiliary_workspaces (capture.py:89-91), which explicitly does torch.cuda.use_mem_pool(graph_pool), this function never enters warmup_storage.pool; it is correct only if the caller happens to be inside with CoreStorage(...): (the scope created at core_storage.py:118 and entered by __enter__). capture_forwards is a public entry point (capture.py:155) whose only in-repo caller contract is that the caller holds the storage. Counterexample: any second capture_forwards call after CoreStorage.__exit__ has popped the scope, or a duck-typed storage (the new test itself uses SimpleNamespace(pool=object()), tests/preparation/test_transient_retention.py:219): the seed tensors allocate from PyTorch's default pool, _seeded_library_caches = True at line 146 makes that permanent, and capture records default-pool pointers — the illegal-access failure this change exists to remove. Fix: mirror the sibling — pool_ctx = torch.cuda.use_mem_pool(warmup_storage.pool) inside the with — or assert the storage scope is active and raise instead of silently seeding into the wrong pool.
I also drop two sub-agent claims I could not prove or judged out of bar: (a) PoolMemoryLimit "0.0" → Display → "0" round-trip asymmetry (limits.rs:167-168, 201) — real but semantically identical at runtime (cap_bytes returns 0 for both), so it is an identity-string nit, not a serving defect; (b) AsyncTransferChannel.device_pool not validated in ignition/preparation/execution.py:317-331 — an unknown name is rejected at export by heliopause/src/export/binding.rs ("device_pool allocation not found"), so it is a diagnostics nit, not a bug.
Checked and verified correct (no finding)
- ABI/layout:
ControlHeader#[repr(C, align(64))]is exactly 256 B withcmd_tailat 64,cmd_headat 128, telemetry at 192 (ring.rs:152-187);TransferCommandis exactly 64 B with no implicit padding (ring.rs:190-203);required_control_bytes = 256 + 64*ring_capacity + 8*completion_slotswith checked arithmetic (ring.rs:244-261) matches both the export check (binding.rs:638-657) and the worker's pointer math (worker.rs:616-620). - 24-byte extent directory:
decode_extent_directoryreads[u32 seg][u32 reserved][u64 rel][u64 nbytes]little-endian, rejects nonzeroreserved, missing segment, misaligned relative and absolute offset, andrel + nbytes > segment_nbyteswith overflow checks (ring.rs:469-523). The heliopause export path calls it with the real segment lengths (capture.rsnew block) and the runtime re-validates (runtime_core/mod.rs:1519-1538), so a forged table cannot reach the I/O backend. Authentication is complete: segments and directory are added torequired_payloads(core/reader.rs:225-230), checked against payload roles (core/schema.rs:643-676), reachability-marked (reachability.rs:105-113), and resolved to authenticated spans at load (protobuf.rs:1512-1530). DEVICE_POOL:map_device_poolmaps fixed VA with zero initial backing, sizes only when the sizing capacity is2, is excluded from KV planes, and resizes 1-D/2-D buffer views consistently (runtime_core/mod.rs:1412-1458,memory.rs:1140-1209,memory.rs:1546-1563);agreed_bytes= min across ranks prevents rank divergence.- Pool/limit arithmetic:
resolve_pool_bytesaligns down, returns 0 foralignment == 0/non-power-of-two/max == 0(ring.rs:318-338);PoolMemoryLimit::cap_bytesusessaturating_subfor reserves andfloor().max(0.0)for fractions withvalidate()bounding[0,1](limits.rs:140-156), so no underflow, divide-by-zero, or NaN cast is reachable;pool_vram_limitis applied toavailable - min_kv_reserve(memory.rs:1168-1177), so even a1.0fraction cannot starve KV/state. prepare_async_transfersordering:allocate_caches→prepare_offload→prepare_async_transfers→start_async_transfers, all before tuning graphs (model.rs:921-948), matching manifest.md:193-196; teardown order is async-transfer stop → context sync → unmap (mod.rs:1780-1789).- Scheduler accounting (non-drain):
pop_next_io/pop_next_dmare-read the background count once and dispatch at most one op per call, sobg_usedcannot go stale;advance_epoch,begin_drain, andpop_next_dmareturn bounce slots for every dropped op (scheduler.rs:291-317, 657-685, 586-592);complete_iopromotes a fusedDISK_TO_DEVread into the DMA queue with its bounce slot transferred (scheduler.rs:518-556), so no completion word is signalled before stage 2. - Verification harness quality:
AsyncTransfer.tlainvariants are non-vacuous —check.py:705-722asserts four mutation-sensitive checks (unconfirmed drain →Stopped, background DMA cap, leaked bounce slot on drain,FailedDrainreleasing memory) againsthelios/src/async_transfer/scheduler.rs;DrainingHasEmptyQueuesis non-trivially falsified becauseCANCEL_EPOCHcan add toqDmawhileDRAINING(tla:100). The Kani oracles (kani_proofs.rs:17-59, 91-217) re-derive expectations inu128independently of the implementation and are not tautological. The model does not cover the worker's drain path (Major 2) or the two-sided completion contract (Major 1), which is why both escaped the harnesses. flare-cli/flareconfig path: CLI-vs-config precedence viaserving.pool_vram_memory.is_none()is correct and applied once (config.rs:81-98); flag forwarding to every rank (cli.rs:1170-1176) is guarded by the new parse test; the newdebian_man_page_documents_every_visible_subcommandtest matchespackaging/debian/flare.1's.SH COMMANDSorder against clap's visible subcommand declaration order and should pass. No per-step allocation was added on any hot path (load_optionscopies already-parsedOption<PoolMemoryLimit>;RuntimeSettings::applyparses once per model load).