Deep Code Correctness / Invariants / Hot-Path Audit — PR #736 (head 500b774)
Scope decision: 11 files, all inside the single helios crate (helios/src/cuda.rs, helios/src/execution/{parallel,parallel/tests,parallel/wire,ranks,threaded,transport}.rs, helios/src/scheduler.rs, helios/src/scheduler/cache_memory.rs, helios/src/server/{runtime,runtime/phase_tests}.rs). ~430 added lines, one top-level crate → per the partitioning rule I audited directly with batched reads rather than spawning crate sub-agents, and pulled in the cross-crate callees (selene/src/geometry.rs, helios/src/runtime_core/cache_memory.rs, helios/src/execution/manifest.rs (not opened)) where the diff depends on them.
Bottom line
I found no Blocker and no Major defect in the changed code. The core invariant this PR rests on — a page is queued for zeroing exactly when its last snapshot alias drops and it re-enters free_pages, and the memset is synchronized before the next kernel submission or host-to-GPU restore that can touch it — holds up under callee-level and ordering tracing, and I verified the batch-safety argument that makes concurrent peer-stream memsets safe. The findings below are all Minor (one dead guard, one silent-drop path on a test-only entry point, and three small hot-path/allocation nits), plus one explicitly-labelled open risk I could not close within my turn budget.
Findings
1. Minor — Dead deadline guard: the deadline is re-armed on every loop iteration, so it can never expire
helios/src/execution/parallel.rs:288-325 (new TensorParallelExecutor::zero_kv_pages):
for (index, peer) in self.peers.iter_mut().enumerate() {
let deadline = std::time::Instant::now() + TIMEOUT; // <-- re-created each peer
loop {
let (tag, bytes) = peer.channel.wait(false)?;
if tag == ZEROED_KV_PAGES {
if !bytes.is_empty() {
return Err(invalid("unexpected zero_kv_pages reply payload"));
}
break;
}
apply_peer_message(&mut self.pending, manifest, index, tag, bytes)?;
if std::time::Instant::now() >= deadline { // <-- always false
return Err(invalid("rank zero_kv_pages deadline expired"));
}
}
}
Counterexample: a peer that streams an unbounded sequence of READY/COMPLETE packets (e.g. a mis-versioned or wedged peer re-sending frames) keeps the loop alive forever, because deadline is recomputed as now + 120s before the loop and each wait(false) resets its own 120 s socket timeout (wire.rs:118-123, Channel::wait → idle(false)). The Instant::now() >= deadline check is therefore unconditionally dead code, and the intended "rank zero_kv_pages deadline" never fires.
Fix: hoist let deadline = Instant::now() + TIMEOUT; above loop { (i.e. one deadline per peer, or one per call), so the guard is live.
Note the same loop is otherwise sound: consuming READY/COMPLETE through the new apply_peer_message (parallel.rs:99-147) preserves in-flight peer message ordering, and completing frames are only record_peer_completion'd into already-committed slots (frames are committed solely in poll_ranks, parallel.rs:430-453), so no window state is corrupted.
2. Minor — Reclaimed pages are silently discarded when zero_kv_pages is a no-op closure
helios/src/server/runtime.rs:1994-2001 (inside admit_with_host_store) drains the queue and then calls the injected closure:
let reclaimed = scheduler.take_reclaimed_snapshot_pages();
if !reclaimed.is_empty() {
zero_kv_pages(&reclaimed)?;
}
and the closure at helios/src/server/runtime.rs:1943-1951:
let mut zero_pages = |pages: &[u32]| {
if let Some(executor) = executor.as_deref_mut()
&& let Err(error) = executor.zero_kv_pages(pages)
{ zero_error = Some(error.clone()); return Err(error); }
Ok(())
};
take_reclaimed_snapshot_pages() has already mem::taken the vector, so when executor is None the pages are dropped without being zeroed and there is no way for a caller to observe it. This is currently reachable only through the #[cfg(test)] fn admit(&mut self) wrapper (runtime.rs:1796-1799, which passes None), i.e. it is a test-only hole today; but it is exactly the shape of bug that becomes real the moment another caller passes None/a partial executor. Also note the type-level hazard: the signature impl FnMut(&[u32]) -> Result<()> cannot express "not zeroed", so a future Local-only executor cannot report that peer planes were skipped.
Fix: make the closure return Result<bool> ("zeroed at least one cache-owning rank") or have zero_reclaimed_kv_pages/admit_with_host_store assert executor.is_some() when reclaimed is non-empty (does not change production behaviour, closes the trap).
3. Minor — coalesce_page_runs re-sorts and re-allocates the same page list once per rank (fan-out × ranks) on the eviction path
helios/src/execution/threaded.rs:1229-1237:
let peer_runs = self
.peer_zeros
.iter()
.map(|(cache, _)| super::transport::coalesce_page_runs(pages, cache.page_capacity))
.collect::<Result<Vec<_>>>()?;
let local_enqueued = self.local.enqueue_zero_kv_pages(pages)?;
with helios/src/execution/transport.rs:1442-1467 doing let mut sorted = pages.to_vec(); sorted.sort_unstable(); sorted.dedup(); per call — so one eviction of an N-page snapshot costs (ranks + 1) × O(N log N) plus (ranks + 1) heap Vecs of N u32. At the PR's own cited peak (3,008 / 3,184 snapshot-backing pages, up to 16 ranks: MAX_RANKS, threaded.rs:846), that is up to 17 sorts of ~3 k elements ≈ 17×3 k×12 comparisons plus 17 allocations (~200 kB transient) per eviction — inside the worker's admission/submit loop. Only the bound differs between ranks (cache.page_capacity, which same_layout explicitly allows to differ, geometry.rs:100-111), so the merged-run computation could be shared and only the bounds check repeated. Not a scaling blocker (eviction-path only, not per-step), but the redundancy is avoidable: sort/dedup once, then validate per-rank capacity.
4. Minor — Unnecessary full-stream synchronizations when a peer enqueued nothing
helios/src/execution/threaded.rs:1241-1245:
for (cache, stream) in &self.peer_zeros {
if !cache.planes.is_empty() {
stream.with_context(|| stream.synchronize())?;
}
}
The guard tests cache.planes but the actual enqueue was a no-op whenever runs.is_empty() (transport.rs:1474-1476) — i.e. a peer whose coalesce_page_runs produced no runs still pays a blocking cuStreamSynchronize. In practice pages non-empty ⇒ runs non-empty, so this is dead-guard-shaped rather than a measured regression; it should nonetheless mirror the enqueue condition (local_enqueued && !runs.is_empty()) to keep the "sync only what you enqueued" invariant explicit.
5. Minor — Over-zeroing on never-populated snapshots
helios/src/scheduler/cache_memory.rs:822-835 queues every page whose refcount drops to 0, including snapshots that were reserved and released without ever capturing (scheduler.rs:3100-3103 refund path, scheduler.rs:3134-3137 swap-out path, scheduler.rs:2053-2063 fail_ticket). Those pages provably never held non-FP8 snapshot bytes, so the memset + full-stream sync (~27 µs per the PR text; on the admission path it is serialized before store.fetch, runtime.rs:3998-4005) is paid for a no-op. Correct but pessimistic; a captured: bool on the snapshot reservation would remove the cost from cancel/abort-heavy workloads. Not a correctness issue.
What I verified as correct (so the report is not one-sided)
- Queue/refcount correspondence.
release_snapshot(cache_memory.rs:822-835) decrementspage_snapshot_refs[page]and pushes toreclaimed_snapshot_pagesonly insideif *count == 0, in the same block that doesstats.snapshot_backing_pages -= 1andfree_pages.insert(PageId(page)). So the queue is exactly the set of pages that re-enter the free list, with no double-queue (a page already at 0 can only be pushed after a freshreserve_snapshot_idincrements it,cache_memory.rs:302-313) and no missed page. Overlapping alias ranges (share_snapshot_pages(&[8..12, 10..14])) hold refcount ≥ 2 and are correctly not queued until the last alias releases. - Zero-before-kernel ordering on the submit path.
Worker::submitcallsreserve_and_packthenzero_reclaimed_kv_pagesthenexecutor.submit(runtime.rs:3218-3221, kernel submission atruntime.rs:3271), and bothGraphExecutor::zero_kv_pages(transport.rs:1386-1391) andThreadedExecutor::zero_kv_pages(threaded.rs:1238-1245)cuStreamSynchronizethe dedicatedzerostream before returning. Sincereserve_and_packis the only page allocation feeding a kernel, page reuse always observescuMemsetD8Asynccompletion first. - Zero-before-host-DMA ordering. The drain sits strictly before
store.fetch(hit, ticket)(runtime.rs:3998-4005) and the new test asserts the["zero","fetch"]order and suppressed fetch on error (phase_tests.rs:12349-12399). - Bounds/overflow discipline in
enqueue_zero_cache_pages(transport.rs:1469-1508):start * unit_bytes,address + offset,count * unit_bytesare allchecked_*,usize::try_fromis guarded, andstart + count <= page_capacityis established bycoalesce_page_runs'page >= capacityrejection (transport.rs:1450-1457). The plane allocation ispadded_bytes(page_capacity * unit_bytes)-aligned and never shorter (runtime_core/cache_memory.rs:219-224), so a capacity-bounded memset cannot run off the end of a plane. - Batch safety of concurrent peer-stream memsets. Freeing a snapshot happens in
advance_retirement(fence)(scheduler.rs:3076-3079,scheduler.rs:3228-3249), andfenceis the merged all-rank completion the coordinator popped atparallel.rs:454-468/threaded.rs:1200-1214; the peer zero streams therefore only memset pages whose last GPU read on every rank is already retired.Stream::with_context(cuda.rs:1128-1131→cuda.rs:358-376) correctly saves/restores the previous current context and no-ops when it already matches, which is what makes driving peer contexts from the coordinator thread safe. - Wire encoding.
encode_page_ids/decode_page_ids(parallel.rs/wire.rs:500-522(not opened)) enforceMAX_PACKETon encode and reject non-multiple-of-4 without panicking;sendrejects oversize independently (wire.rs:71-76). Round-trip + truncation is tested (parallel/tests.rs:837-853).
Open risk I could not close (stated as a question, not a finding)
helios/src/scheduler.rs:3412 (if let Some(guard) = request.anchor_guard.take() { self.release_snapshot(guard); }) is on the cancel path, reached from Worker::admit_with_executor at runtime.rs:1853 (self.scheduler.cancel(active.request)?) while that request may still have submissions outstanding on the model stream. If RequestScheduler::cancel frees the anchor snapshot's pages immediately rather than deferring them through self.retired/advance_retirement until their fence retires, then the drain at runtime.rs:1857-1859 would memset pages a still-in-flight batched step is reading for the other, live lanes in that same submission — a silent cross-request attention corruption rather than a cancelled-request-only artifact. The release_snapshot calls I traced all sit inside advance_retirement/apply_completion (fence-gated) or checkpoint_copy_allowed refunds, which is consistent with the safe design, but I did not get to read RequestScheduler::cancel/retire to confirm the deferral. Recommend the author confirm that cancel → anchor_guard release is fence-deferred; that single check is the only thing standing between this PR and a "no findings" verdict.