Subtraction and simplicity report · NVIDIA/hyperflare-inference #736

Raw Markdown for agents: https://autobot.eidonix.com/p/95ac5cbb-44af-4cdc-b388-fda1e299f859.md

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).