PR #736: fix(helios): zero reclaimed VMM-aliased snapshot KV pages before reuse to prevent SM103 FP8 V-cache tail NaNs

Raw Markdown for agents: https://autobot.eidonix.com/api/v1/cases/769e7b40-cfb1-4f9a-87ce-d881eab03c88

Opened by a workflow run, Dec 4, 2026 8:41 PM EST. decide malicious: all_clear (100%): No malicious content found

explore

Author: ebfio (FIRST_TIME_CONTRIBUTOR; SM103/GB300 operator, 0 merged PRs, 4 open, 1 superseded; Discord ebfio) Motivation: Continuation snapshots share physical GPU memory with KV cache pages, and evicting a snapshot returns those pages to the free list without clearing them, leaving stale BF16 bytes that FP8 attention on SM103 reads as NaN and turns into 0.0 * NaN = NaN in P·V, failing requests with device errors. This PR zeroes those pages before anything can reuse or restore into them. Scale: +601 / −25 lines in 11 files Proposal:

Full report · Notes

Value Proposition

Value Proposition — PR #736 (zero reclaimed VMM-aliased snapshot KV pages)

Charter alignment — in scope, but the "right place" test is live. SM103 is a named Goals target, and the change adds no per-model branch, no flag, and no API or on-disk format change, so already-exported cores keep working (the dossier's stated advantage over the kernel route). Against that: #202 recorded the decision as kernel-side ("Flare does not need to enforce finite bytes in unused slots for this path"), #181's triage called page clearing a "broad page-clearing workaround," and #736 re-enters that class at the Helios cache layer while reversing #181's deliberate choice to clear at first commit rather than at release — with only a zero-before-store.fetch barrier as compensation. The PR never links #116.

Novelty and status — genuinely additive. Not obsolete: no commit in the last 60 days clears released snapshot pages. Not superseded: #181 is closed unmerged (2026-11-15) for staleness, not refuted, and #659/#674/#729 are adjacent rather than overlapping. It is additive but disconnected: #116 (open, P1) reports this exact root cause with a 143/143-prompt A/B on released-alias-page zeroing, and its prototype explicitly "doesn't cover the multi-process tensor-parallel executor" that this PR wires up.

Value vs. maintenance cost — real defect, uneven evidence, heavy footprint. The bug is in the supported matrix: the PR's SM103 matrix shows B_v_nan at 100% NaN across every backend/mode/window/seq_len, and all of #201/#202 state "SM121 and SM103 were not exercised." Evidence is partly solid — four CPU tests verified in-repo, including the ["zero","fetch"] ordering test — but there is no GPU test for the memset path (contrast #181), the soaks are single-machine and per the author "not re-run," and the ~27 µs is arithmetic. Cost is disproportionate: 601 lines across 11 files; rank protocol tags added with no version bump (a patched rank zero with an unpatched peer fails at "unexpected rank command"); an always-on CU_STREAM_NON_BLOCKING per executor; synchronous TP zeroing with a 120 s deadline; out-of-range page IDs being fatal to the whole executor; and pool-tier restores via the same HostStore left without a dedicated barrier. The six new flush points sit in server/runtime.rs, which open #705 rewrites.

Verdict: Worth it with changes. Conditions: link and close against #116; address #202's recorded remedy and say why no SM103 masking fix is in flight; add a hardware test for enqueue_zero_cache_pages; version the rank tags; cover the pool-tier restore path; make the extra stream opt-in to alias-using cores and downgrade bookkeeping mismatches from fatal.

Full report Decide Value: yes (99%): This change is worth reviewing: it provides value to the project in line with its charter.

Classify intake

Selected: triage:review, priority:P1, bug, performance, area:caching, area:memory

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

Applied: +triage:review, +priority:P1, +bug, +performance, +area:caching, +area:memory

Subtraction and simplicity

Subtraction & Simplicity audit — PR #736 (zero reclaimed VMM-aliased snapshot KV pages)

Scope: the 11 changed files (+601/−25). Good news first: the PR adds no CLI flag, no config key, no metric, no env var, no on-disk format change and no model-specific branch, so the usual "knob creep" category is empty. scheduler.rs (+2) and ranks.rs (+14, pure 3-arm dispatch) are as lean as they can be. The subtraction debt is concentrated in two places: the number of flush call sites in Worker and the enqueue/sync/context-wrapping plumbing around the memset.


1. (Highest value) Six of the eight zero_reclaimed_kv_pages flush sites are not load-bearing

The helper is three lines (helios/src/server/runtime.rs:1788-1794) but it is called from seven places in Worker, and the same three lines are inlined an eighth time:

The PR body itself states the required ordering: zeroing must complete "before any kernel submission or host-to-GPU prefix-cache DMA restore". Every GPU path that can read or write a freshly allocated KV page goes through exactly two places: executor.submit (runtime.rs:3271) and store.fetch (runtime.rs:4005). publish/service_store/complete/plan only read pages that were allocated by an earlier admission and already zeroed by :3220.

So the invariant can be maintained by two barriers (:3220 and :3998) instead of eight. The six remaining sites are ~15 lines of loop noise plus a whole helper that must be re-audited whenever the loop is reordered — and server/runtime.rs:1609-1630 is precisely the loop body open PR #705 rewrites, so fewer touch points is also less conflict surface. Worth the author stating explicitly in the doc comment why each site is needed, or deleting the ones that are not.

Related, smaller: :1858 is before the admission loop that allocates the pages, so it clears a queue that cannot yet contain anything new from this pass, and :2165 and :1626 both fire around the same self.plan()? call (:1625-1626 and :2164-2166) — at minimum one of those pair is pure duplication.

2. Stream::with_context should be folded into synchronize/memset_d8_async, not exported to callers

helios/src/cuda.rs:1128-1131 adds a public-in-crate wrapper:

pub(crate) fn with_context<T>(&self, operation: impl FnOnce() -> Result<T>) -> Result<T> {
    // SAFETY: `self.context` is the CUDA context bound when this stream was opened and outlives it.
    unsafe { self.driver.with_context(self.context, operation) }
}

…and then every call site re-wraps a method of the same stream in a closure:

The file already establishes the correct convention: Stream::destroy (cuda.rs:1145) and Drop for Stream (cuda.rs:1464) call self.driver.with_context(self.context, …) inside themselves. Doing the same in synchronize (cuda.rs:1133) and memset_d8_async (cuda.rs:1223) deletes the new wrapper plus four closure call sites and removes the footgun that a future caller forgets to wrap (which would silently memset the wrong context's stream — memset_d8_async is unsafe only for the buffer range, not the context). That is ~4 lines added to two existing methods against ~10 lines and 4 wrappers deleted, and it makes the safety argument local instead of contractual.

3. The enqueue / sync split and its Result<bool> exist only to serve one caller — collapse to one function

helios/src/execution/transport.rs:1357-1391 is three functions:

pub(super) fn enqueue_zero_kv_pages(&mut self, pages: &[u32]) -> Result<bool> { ... Ok(!cache.planes.is_empty()) }
pub(super) fn sync_zero_kv_pages(&self) -> Result<()> { ... }
pub(crate) fn zero_kv_pages(&mut self, pages: &[u32]) -> Result<()> {
    if self.enqueue_zero_kv_pages(pages)? { self.sync_zero_kv_pages()?; }
    Ok(())
}

The bool means "something was issued", but enqueue_zero_cache_pages already encodes exactly that at transport.rs:1474: if runs.is_empty() || cache.planes.is_empty() { return Ok(()); }. The split exists so ThreadedExecutor::zero_kv_pages can overlap local with peers, and it does so with two different emptiness tests for the same condition:

let local_enqueued = self.local.enqueue_zero_kv_pages(pages)?;      // threaded.rs:1234
...
if local_enqueued { self.local.sync_zero_kv_pages()?; }             // :1238-1240
for (cache, stream) in &self.peer_zeros {
    if !cache.planes.is_empty() { stream.with_context(|| stream.synchronize())?; }   // :1241-1245
}

i.e. the peer loop re-tests cache.planes.is_empty() after enqueue_zero_cache_pages already tested it. Simplification: make enqueue_zero_cache_pages return bool, drop sync_zero_kv_pages from the executor API, keep only zero_kv_pages for non-threaded callers, and let ThreadedExecutor do let issued = enqueue(...); …; if issued { synchronize() } on one uniform flag. Removes one pub(super) function, one Result<bool> contract, and one redundant predicate.

While there: let peer_runs = self.peer_zeros.iter().map(|(cache, _)| coalesce_page_runs(pages, cache.page_capacity)).collect::<Result<Vec<_>>>()?; (threaded.rs:1229-1233) re-coalesces the same id list once per peer. The scheduler is rank-zero-global (helios/src/execution/rendezvous.rs:239-241 (not opened): "Every rank must hold the same rows and pages: rank zero's scheduler addresses all of them"), so page_capacity is agreed across ranks and one coalesce_page_runs against any rank's capacity is enough; the Vec<_> + zip (:1235) collapses to a single slice.

4. The zero stream is opened unconditionally, including for executors with no KV cache at all

helios/src/execution/transport.rs:573 adds zero: Stream to Resources and :626 opens it on every construction:

let zero = Stream::open(manifest.context, manifest.device)?;

enqueue_zero_kv_pages (:1368-1370) then immediately returns Ok(false) when self.manifest.cache is None, and enqueue_zero_cache_pages returns early when cache.planes.is_empty(). But the stream is still created for every GraphExecutor — including non-cache cores and each rank thread — and that cost is not local: it must be synchronized at transport.rs:1403 (let zero = resources.zero.synchronize().map_err(Error::drain);), folded into the drained conjunction (:1416-1417), and into the error chain (:1421). Five lines of teardown plumbing and one CUDA stream per executor for a feature that is inert without a cache. Making it Option<Stream> gated on manifest.cache.as_ref().is_some_and(|c| !c.planes.is_empty()) (and having enqueue_zero_kv_pages return Ok(false) when it is None) deletes the close/synchronize plumbing for the common case. This also matches what the PR description claims in spirit — "runs only when a VMM-aliased continuation snapshot is evicted".

5. zero_error side-channel + nested Option<&mut RankExecutor> guards

helios/src/server/runtime.rs:1939-1951:

let mut zero_error = None;
let admission = if let Some(store) = ... {
    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(())
    };

…re-raised at :1985-1987:

if let Some(error) = zero_error { return Err(error); }

The side channel exists only because admit_with_host_store maps all errors the same way at the call site (:1999-2002, incoming.reject_admission(error)), and a zeroing failure must instead be fatal. The error is cloned, stashed, returned through the closure, and then re-raised — three representations of one fact. Collapsing to a single error path (e.g. have the closure return an Error variant the caller matches on: Err(Error::Execution(_)) => return Err(error)) removes the Option<Error>, its clone, and the "did we already return this?" second if let.

The Option<&mut RankExecutor> itself (:1801-1804) exists only for the #[cfg(test)] shim at :1796-1799, and it forces three if let Some(executor) = executor.as_deref_mut() guards (:1857, :1944, :2164). Given that §1 removes most of those flush points, this shrinks on its own; if any remain, passing the zeroing closure unconditionally (tests pass |_| Ok(())) makes the invalid None-in-production state unrepresentable and drops the #[cfg(test)] admit wrapper.

6. wire::encode_page_ids / decode_page_ids hand-roll what number/Reader already provide

helios/src/execution/parallel/wire.rs:502-524 adds 23 lines of bespoke framing:

let mut bytes = Vec::with_capacity(byte_len);
for &page in pages { bytes.extend_from_slice(&page.to_le_bytes()); }
...
if !bytes.len().is_multiple_of(size_of::<u32>()) {
    return Err(invalid("truncated zero_kv_pages control packet"));
}
for chunk in bytes.chunks_exact(size_of::<u32>()) { pages.push(u32::from_le_bytes(chunk.try_into().unwrap())); }

The same module already has pub(super) fn number(bytes: &mut Vec<u8>, value: usize) (wire.rs:136) and Reader::number()/Reader::bytes()/Reader::end() (:155-165), which every other packet in the file uses and which give trailing-byte and truncation rejection for free. Encoding number(bytes, pages.len()) followed by the u32 blob, and decoding with let count = reader.number()?; let data = reader.bytes(count * 4)?; reader.end()?; is roughly half the code, removes a bespoke error string, and keeps the packet style uniform. (It also makes the MAX_PACKET check at :505-507 unnecessary for the id payload, since the count is now validated against the frame length.)

7. The release_snapshot decrement loop now has a third copy in the same file

The new push lands inside an existing loop (helios/src/scheduler/cache_memory.rs:824-834):

for page in range.clone() {
    let count = &mut self.page_snapshot_refs[page as usize];
    *count = count.checked_sub(1).expect("snapshot alias ownership");
    if *count == 0 {
        self.stats.snapshot_backing_pages -= 1;
        assert!(self.free_pages.insert(PageId(page)));
        self.reclaimed_snapshot_pages.push(page);   // <- new
    }
}

The reference model in the same file has the same loop again (cache_memory.rs:1466-1476):

for page in range.clone() {
    refs[page as usize] -= 1;
    if refs[page as usize] == 0 { free_pages.insert(PageId(page)); }
}

The diff now makes the real implementation and its in-file model diverge by one statement — exactly the kind of drift that silently invalidates a planner test later. Extracting the shared body ("release every page in this snapshot range, returning the ones that dropped to zero") into one helper used by both is a net deletion and makes the new reclaimed_snapshot_pages.push live in exactly one place.

8. The new ordering test re-implements a decorator the file already has

helios/src/server/runtime/phase_tests.rs:12256-12287 adds a 30-line RecordingStore whose only purpose is to push "fetch" into an Rc<RefCell<Vec<&'static str>>>; six of its eight trait methods are one-line pass-throughs (lookup, store, poll, stats, close). The same file already has OrderStore (phase_tests.rs:2707-2727) doing precisely this with an mpsc::Sender<(&'static str, PrefixKey)> ordered log, and the new test already collects order from a second source (the zero closure). Sending "zero" from the closure and "fetch" from the store onto one mpsc channel (the pattern at :2730-2742) gives the same ["zero", "fetch"] assertion with no decorator and no Rc<RefCell<…>> double-wrap. FakeStore already records fetched: Vec<(HostHit, InboundTicket)> (:2071), so the store.inner.fetched assertions keep working.

9. Minor / not worth a round trip


Bottom line

The mechanism is right-sized (one field, one accessor, one coalescing helper, one wire pair). The subtraction wins, in order of value, are: (1) cut the flush sites from 8 to the 2 that actually order against GPU work, (2) move with_context inside Stream::synchronize/memset_d8_async and delete four closure call sites, (3) collapse the enqueue/sync/Result<bool> trio and the duplicate planes.is_empty() tests, (4) gate the always-on zero stream on cache presence. Together those are roughly 45-55 lines and three redundant contracts removed without changing behaviour; items 5-8 are smaller but each removes a duplicated concept (zero_error, bespoke wire framing, a third copy of the snapshot-release loop, a test decorator).

Full report

Gates and contracts

Contracts, Charter & Verification Gates Audit — PR #736 (500b774)

Scope of this lens: the four hard gates only. Consistent with the calibration rules, I do not flag the missing GitHub Actions checks (my tools cannot observe them, and neither the description nor the dossier reports a CI failure), and I do not flag docs/TODO.txt bookkeeping.

Prior-round check: the PR has zero comments, zero reviews, zero labels, and the ## Case File History contains an explore pass and a Value Proposition pass — neither reports a TLA+ run, a --release run, a GPU test, or an A/B benchmark. So no gate is satisfied by earlier-round evidence.

Gate 2 — Vendored upstream dependencies & cross-PR conflicts: PASS

The diff touches no vendored upstream file (helios/native/* untouched), no Cargo.toml, no Cargo.lock, no recipe, no dependency pin. Nothing depends on an unmerged external PR. File overlap with the closed #181 is textual (10 of 11 files) and carried by an in-repo predecessor, not an external dependency — Info only.

Gate 1 — Signed core-format / wire / captured-graph / public contract boundaries: ONE MAJOR

The PR adds no Protobuf enum, no core-format field, no captured-graph operation, and no per-model branch, so the approval-required surfaces (design-review.md:22-26) are untouched. However it does add two new rank-control wire kinds on a shipped default with no version bump and no doc change:

Secondary, non-blocking note (Info): the PR adds a second zeroing pass over alias pages while the documented invariant remains the single first-commit pass — helios/src/runtime_core/cache_memory.rs:2110 ("Zero each physical byte once, before any graph or transfer can read an alias") and the implementation at :2111-2125. No normative doc is contradicted (docs/runtime-core-design.md:950 — "GPU tests preserve snapshot bytes while released KV pages are overwritten" — is a qualification statement and remains true), but the new release-time lifetime rule is undocumented in docs/runtime-core-design.md:970-995, which is where snapshot/backing ownership is specified.

Gate 3 — Mandatory verification evidence: BLOCKER (three distinct misses)

3a. TLA+ lifecycle conformance not run for covered code (blocking per the checklist's own words). docs/design-review.md:212-215 requires python3 verification/helios-lifecycle/check.py whenever changing "admission, fences, generations, cancellation, speculation accounting, cache compaction, snapshot aliases, response buffering or ownership, offload aggregation, readiness, or rank coordination." This PR changes snapshot aliases (scheduler/cache_memory.rs:828-846: new reclaimed_snapshot_pages push on the 1 -> 0 refcount edge, new take_reclaimed_snapshot_pages), admission (runtime.rs:3856-4001: admit_with_host_store gains a zero_kv_pages closure param and a new barrier strictly before store.fetch; Worker::admit becomes #[cfg(test)]-only and is replaced by admit_with_executor), and rank coordination (parallel.rs:99-146, 288-328, 744-752; threaded.rs:1217-1262, 1270-1306). docs/design-review.md:234-240 says touching such code without running the applicable models "is a blocking design failure, regardless of whether CPU unit tests pass," and :247-251 says a disclosed limitation does not excuse the omission. The description's verification section mentions only cargo check (three feature combinations) and a filtered cargo test ... --lib -- cuda:: scheduler:: execution:: server::runtime::. No check.py invocation appears anywhere in the description, and no verification/ file is in the diff. Affected suite names are enumerated in verification/helios-lifecycle/check.py:22-36 (CacheOwnership, CheckpointReservation, RankProtocol, DispatchRing, Lifecycle) — all in the touched area. This alone is a blocker.

3b. Cross-rank test + live multi-GPU evidence missing for a TP dispatch/transport change. docs/design-review.md:189-194: changes to helios/src/execution/{threaded,parallel,roce}* "require a multi-thread CPU test with a blocking cross-rank barrier coupling rank-zero local submission with peer commit handlers." docs/design-review.md:252-259: "Replacing or reordering cross-rank launch, commit, cancellation, or drain paths … requires an explicit before/after cross-rank happens-before analysis and live multi-GPU execution of real collective graphs … Disclosing busy or unavailable GPUs does not waive this." This PR does reorder cross-rank paths: TensorParallelExecutor::poll now funnels READY/COMPLETE through the extracted apply_peer_message (parallel.rs:99-146, used at :415-420 and inside the new waiting loop at :316); it adds a blocking rank-zero zero_kv_pages that services peer READY/COMPLETE while waiting on a 120 s deadline (parallel.rs:288-328); and it adds peer zero streams plus new drain/teardown ordering in ThreadedExecutor (threaded.rs:1217-1256, :1270-1306, including mem::forget of peer streams on poisoned teardown). The only new coordination test is zero_kv_pages_wire_roundtrip_and_truncation (parallel/tests.rs:837-854), which is a two-endpoint channel roundtrip through rank_stream::test_pair(), not a blocking cross-rank barrier through coordinate_step/commit_and_launch. No happens-before analysis is in the description, and the soak numbers are one GB300 with no stated multi-rank run. This is a second independent mandatory-gate miss.

3c. No test at all executes the new CUDA/VMM path. The change's entire effect is cuMemsetD8Async over coalesced runs across cache planes (transport.rs:1442-1505), on new streams (transport.rs:626 Resources.zero, threaded.rs:1203 peer_zeros). All four added tests are CPU-only and run with CUDA_VISIBLE_DEVICES="": cache_memory.rs:2856-2883, transport.rs:2163-2180 (coalesce_page_runs only), parallel/tests.rs:837-854 (wire codec only), phase_tests.rs:12250-12396 (closure ordering with a fake store). enqueue_zero_cache_pages, Stream::with_context switching (cuda.rs:1128-1132), the per-peer path and the TP zero round-trip are executed by nothing in the repository. Contrast the predecessor #181, which shipped a hardware VMM-alias CUDA test. docs/design-review.md:106-115 (principle 12) requires exercising affected shapes, tails, cache boundaries and allocation stability; AGENTS.md:194-199 rejects validation that does not exercise the affected contract. The SM103 isolation matrix and the 75/75 / 152/152 GB300 soaks are the author's own off-repo runs from one machine and, per the description itself, "were not re-run for this submission."

3d. Profile requirement (Minor within this gate). Layer 1 asks for cargo test --locked --release on affected crates (docs/design-review.md:180-187). The reported runs are debug-profile and filtered; cargo check is explicitly called out as non-substituting.

Attributable failing tests: not a finding. The 6 full-suite failures are disclosed, pre-existing, caused by an absent generated fixture (FLARE_TEST_TEMPLATE_DIR → tests/frontend/prepare_templates.py (not opened), per helios/README.md:170-171 (not opened) and .github/workflows/native-serving.yml:31 (not opened),59), and lie outside the touched files.

Gate 4 — Material scope / claim contradictions: ONE MAJOR (needs author confirmation), ONE MINOR

Undeclared behaviour worth recording (Info, not blockers)

Bottom line

The three Gate-3 items are fixable by running the existing checks and adding the barriers/tests the checklist already specifies — no owner approval is needed for the design itself, and the charter's "right place" question (cache-layer clearing vs kernel masking, #202) is a design question for the Code Correctness/Value lenses, not a governance violation of the four gates I audit.

Full report

Code correctness

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)

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.

Full report Merge Risk: medium_high (100%): Medium or high merge risk (core runtime/scheduler/GPU/CUDA/VMM/RoCE/multi-rank/contracts/ABI, large multi-crate changes, or Blocker/Major findings) — route to Super Agent.

Final review

Recommendation: Changes Requested

The core mechanism—recording VMM-aliased KV pages on the 1 -> 0 page_snapshot_refs transition in release_snapshot and zeroing coalesced contiguous runs via cuMemsetD8Async across all KV planes before kernel submission or store.fetch—is technically sound, correctly fence-ordered across all verified release_snapshot call sites, and covers both local and pooled host-cache restores. However, the PR cannot merge as-is because it omits mandatory verification gates (verification/helios-lifecycle/check.py, a GPU test exercising enqueue_zero_cache_pages, --release crate tests, and multi-GPU TP verification for the new cross-rank coordination and drain paths), extends the rank-control wire protocol without bumping its handshake version, and omits poisoning GraphExecutor on zeroing failures.

Merge Risk

Level: Medium

Walkthrough

Pre-merge Checks

Blockers

  1. Mandatory TLA+ lifecycle conformance (verification/helios-lifecycle/check.py) was not run (docs/design-review.md:211-215, 234-251).

    • This PR modifies snapshot alias ownership (helios/src/scheduler.rs:669,772, helios/src/scheduler/cache_memory.rs:828-846), admission (helios/src/server/runtime.rs:1788-2166, 3856-4001), and rank coordination (helios/src/execution/parallel.rs:99-147, 288-328, 418-429, 747-751; helios/src/execution/threaded.rs:873-885, 1217-1258, 1273-1308).
    • docs/design-review.md:211-215 and :234-251 make python3 verification/helios-lifecycle/check.py a non-waivable CPU gate whenever modifying snapshot aliases, admission, or rank coordination ("blocking design failure, regardless of whether CPU unit tests pass"; disclosure does not waive runnable CPU checks).
    • Fix: Run python3 verification/helios-lifecycle/check.py (with --tlc-jar) against this branch and report the full pass results in the PR description.
  2. Zero automated or current-submission verification of the new CUDA memset path and multi-GPU TP coordination/drain paths (docs/design-review.md:106-115, 180-187, 252-259; AGENTS.md:194-199).

    • All four added tests run under CUDA_VISIBLE_DEVICES="" and exercise only CPU helpers/wire codec/closure ordering. Nothing in the test suite executes enqueue_zero_cache_pages (helios/src/execution/transport.rs:1469-1508), Stream::with_context (helios/src/cuda.rs:1128-1131), ThreadedExecutor::zero_kv_pages (helios/src/execution/threaded.rs:1217-1258), or TensorParallelExecutor::zero_kv_pages / serve_rank handling of ZERO_KV_PAGES interleaved with in-flight READY/COMPLETE messages (helios/src/execution/parallel.rs:288-328, 747-751).
    • In addition, the reported GB300 soak runs were single-GPU and, per Validation limits, not re-run for this submission; the reported cargo test run was debug-profile and filtered rather than --release (docs/design-review.md:180-187); and docs/design-review.md:252-259 requires an explicit before/after happens-before analysis plus live multi-GPU collective execution for changes altering cross-rank coordination and drain paths in parallel.rs / threaded.rs (new blocking ZERO_KV_PAGES RPC with apply_peer_message consumption, cross-context peer zero streams, and ThreadedExecutor::close() drain/poison teardown).
    • Fix:
      1. Add an #[ignore] CUDA test (matching the existing GPU test pattern in helios/src/cuda.rs / helios/src/runtime_core/cache_memory.rs and predecessor #181) that writes non-zero (0x7F/0xFF) bytes through a VMM-aliased snapshot row, runs enqueue_zero_cache_pages / zero_kv_pages, and verifies reclaimed pages are zeroed across all planes while live aliased pages remain byte-identical.
      2. Add a CPU test exercising TensorParallelExecutor::zero_kv_pages + serve_rank (or apply_peer_message + ZEROED_KV_PAGES loop) with interleaved READY/COMPLETE messages before ZEROED_KV_PAGES.
      3. Run cargo test --locked --release on helios (--features runtime-core,server), provide the cross-rank happens-before analysis for ZERO_KV_PAGES and ThreadedExecutor::close(), and run live multi-GPU TP verification (or, if TP scope is unnecessary/untestable on available hardware, explicitly coordinate scope with maintainers rather than shipping unverified TP code).

Should Fix

  1. Bump the rank-control handshake protocol version for the new wire tags (helios/src/execution/parallel/wire.rs:27-28, 185-196, helios/src/execution/parallel.rs:179-189, 747-752, docs/multi-host.md:24-26).

    • Adding ZERO_KV_PAGES = 14 and ZEROED_KV_PAGES = 15 without incrementing wire::layout()'s leading protocol version (6 at wire.rs:188, asserted at helios/src/execution/parallel/tests.rs:229) allows a patched rank zero and an unpatched peer to pass HELLO handshake (parallel.rs:185) and then fail mid-serving on the first snapshot eviction with "unexpected rank command" (parallel.rs:752), contradicting docs/multi-host.md:24-26 ("Serving builds must agree on the rank control protocol version").
    • Fix: Bump the leading protocol version in wire::layout() (wire.rs:188) from 6 to 7 (matching predecessor #181), update parallel/tests.rs:229, and verify incompatible builds are rejected during HELLO.
  2. Poison GraphExecutor when KV page zeroing fails (helios/src/execution/transport.rs:1357-1391).

    • TensorParallelExecutor::zero_kv_pages (parallel.rs:324-326) and ThreadedExecutor::zero_kv_pages (threaded.rs:1253-1255) both record self.poison = Some(error.clone()) on error, matching GraphExecutor::submit (transport.rs:1158) and GraphExecutor::poll (transport.rs:1187-1296). In contrast, GraphExecutor::enqueue_zero_kv_pages (transport.rs:1357-1377) and GraphExecutor::zero_kv_pages (transport.rs:1386-1391) check self.poison on entry (:1361) but never set self.poison if coalesce_page_runs, cuMemsetD8Async, or cuStreamSynchronize fails. On single-GPU (RankExecutorInner::Local), a partial async memset failure or sync error leaves GraphExecutor un-poisoned, allowing subsequent calls to proceed and dropping the root error from Shutdown.error in close() (transport.rs:1424).
    • Fix: Record self.poison = Some(error.clone()) on failure in enqueue_zero_kv_pages and zero_kv_pages (changing sync_zero_kv_pages to &mut self or poisoning around the call in zero_kv_pages).

Subtract / Simplify

  1. Consolidate the 8 zero_reclaimed_kv_pages flush sites in helios/src/server/runtime.rs (:1618, :1622, :1624, :1626, :1858, :2165, :3220, :3998-4001) down to the 2 actual GPU-ordering barriers.
    • Every GPU read/write of a newly allocated KV page goes through either store.fetch (runtime.rs:4005) or executor.submit (runtime.rs:3271). Removing the 6 intermediate flushes (:1618, :1622, :1624, :1626, :1858, :2165) reduces loop noise and merge conflict surface with #705, eliminates the Option<&mut RankExecutor> plumbing in admit_with_executor (:1796-1804, :1857, :2164) by passing only the zeroing closure, and avoids issuing up to 6 separate synchronous cross-rank ZERO_KV_PAGES network round-trips + cuStreamSynchronize calls within a single worker tick when multiple events release snapshots before one submission.
  2. Gate the dedicated zero CUDA stream on cache/alias presence (helios/src/execution/transport.rs:573,626,1403, helios/src/execution/threaded.rs:875-880).
    • Currently Stream::open creates an extra CU_STREAM_NON_BLOCKING stream on every GraphExecutor and every cache-owning peer even when manifest.cache is None or cache.snapshot_pages.is_empty() (where reclaimed_snapshot_pages is never populated). Storing Option<Stream> gated on cache.is_some_and(|c| !c.planes.is_empty() && !c.snapshot_pages.is_empty()) avoids allocating and draining unused streams on non-aliasing cores.
  3. Deduplicate coalesce_page_runs and unify the enqueue/sync predicate in ThreadedExecutor::zero_kv_pages (helios/src/execution/threaded.rs:1229-1245, helios/src/execution/transport.rs:1357-1391,1469-1476).
    • ThreadedExecutor::zero_kv_pages currently sorts and allocates pages.to_vec() once per peer plus once for local (ranks + 1 times) and uses two different emptiness guards (local_enqueued vs !cache.planes.is_empty()). Coalesce once, validate the max page against each rank's page_capacity, and return Result<bool> from enqueue_zero_cache_pages so local and peer sync paths share one uniform predicate.

Nits

Dropped on verification

Full report

Classify triage

Selected: triage:review

Threshold: 65%

Triage

Apply labels

No label changes Decision to Test: no (99%): Testing will not add significant value as the code stands today. The code is either not yet ready to merge, or adequate testing has already been done to validate the contents of the code, or the available hardware is not suitable to test with.