From 500b7746f7f514adce221d32bf9995a658632973 Mon Sep 17 00:00:00 2001 From: ebfio Date: Fri, 4 Dec 2026 20:33:05 -0500 Subject: [PATCH 1/8] fix(helios): zero reclaimed VMM-aliased snapshot KV pages before reuse Why. Continuation snapshot rows share physical pages with KV cache rows through CUDA VMM aliasing (share_snapshot_pages). Before this change, evicting a snapshot returned those pages to free_pages without clearing them, so a request that later allocated one inherited the evicted snapshot's bytes wherever the KV write kernels did not reach, meaning any tail beyond seq_len % page_size. On SM103 those bytes are read as FP8 E4M3FN, where 0x7F and 0xFF both decode as NaN, and TRT-LLM FP8 FMHA BMM2 multiplies zero attention weights by them (0.0 * NaN), so one stale tail poisons the attention output and sampling fails with INVALID_DISTRIBUTION (device error 1). Zeroing at reclaim was chosen over zeroing at allocation because reclaim is the one point every cache scheme passes through and it keeps the cost off the allocation fast path. What changed. RequestScheduler now records pages whose page_snapshot_refs falls 1 -> 0 and zeroes them with coalesced cuMemsetD8Async on a dedicated CU_STREAM_NON_BLOCKING stream, strictly before any kernel submission or host-to-GPU prefix-cache DMA restore (store.fetch) can observe them. The same reclaim path is wired through the local, threaded-TP and multi-process TP executors, plus the page-id wire encoding exchanged between ranks. Eleven files: cuda.rs, execution/{parallel,parallel/tests,parallel/wire,ranks,threaded, transport}.rs, scheduler.rs, scheduler/cache_memory.rs, server/runtime.rs and server/runtime/phase_tests.rs. Benefit. Expected: removes a class of nondeterministic sampling failure on SM103 long-context continuation snapshots, at the cost of one asynchronous memset per reclaimed page. Measured: the four new regression tests pass and the targeted suite moves from 798 to 802 passing tests with zero failures. Evidence. cargo check exits 0 for the default, runtime-core and server,runtime-core feature sets with warning counts identical to clean HEAD (5 / 7 / 2), so the change adds no warnings. The targeted lib suite reports "802 passed; 0 failed; 10 ignored". The PR carries the GPU isolation evidence from a GB300: a poisoned v_cache tail yields 100% NaN while a poisoned k_cache tail yields none, and evicted BF16 bytes produced 8.2M NaN against 0 in the control. Limitations. The full lib suite is not green on the authoring host: 6 failures both before and after the patch, all from a missing fixture (FLARE_TEST_TEMPLATE_DIR), none in touched files. The GPU measurements come from one GB300 and were not re-run for this submission. Signed-off-by: ebfio Design-Signed-Off-By: Iris (deepseek-v4.1-unlimited via litellm); design-review=2e5b --- helios/src/cuda.rs | 5 + helios/src/execution/parallel.rs | 121 ++++++++++++++---- helios/src/execution/parallel/tests.rs | 19 +++ helios/src/execution/parallel/wire.rs | 27 ++++ helios/src/execution/ranks.rs | 14 +++ helios/src/execution/threaded.rs | 68 ++++++++++- helios/src/execution/transport.rs | 129 +++++++++++++++++++- helios/src/scheduler.rs | 2 + helios/src/scheduler/cache_memory.rs | 42 +++++++ helios/src/server/runtime.rs | 50 +++++++- helios/src/server/runtime/phase_tests.rs | 149 +++++++++++++++++++++++ 11 files changed, 601 insertions(+), 25 deletions(-) diff --git a/helios/src/cuda.rs b/helios/src/cuda.rs index b63cb2842..cdb808fe3 100644 --- a/helios/src/cuda.rs +++ b/helios/src/cuda.rs @@ -1125,6 +1125,11 @@ impl Stream { }) } + pub(crate) fn with_context(&self, operation: impl FnOnce() -> Result) -> Result { + // SAFETY: `self.context` is the CUDA context bound when this stream was opened and outlives it. + unsafe { self.driver.with_context(self.context, operation) } + } + pub(crate) fn synchronize(&self) -> Result<()> { self.driver.check("cuStreamSynchronize", unsafe { (self.driver.stream_synchronize)(self.handle as Handle) diff --git a/helios/src/execution/parallel.rs b/helios/src/execution/parallel.rs index 2ae858244..738b35170 100644 --- a/helios/src/execution/parallel.rs +++ b/helios/src/execution/parallel.rs @@ -96,6 +96,56 @@ fn read_identity(bytes: &[u8]) -> Result<(Fence, usize)> { Ok(value) } +fn apply_peer_message( + pending: &mut VecDeque, + manifest: &ExecutionManifest, + index: usize, + tag: u8, + bytes: Vec, +) -> Result<()> { + if tag == READY { + let (fence, graph) = read_identity(&bytes)?; + ready_frame(pending, index, fence, graph)?; + } else if tag == COMPLETE { + let mut reader = Reader(&bytes); + let fence = Fence(reader.number()? as u64); + let graph = reader.number()?; + let timing = wire::timing(&mut reader)?; + let proposal_confidence = wire::proposal_confidence( + &mut reader, + manifest.request_capacity(), + manifest.completion_token_capacity, + )?; + let speculative_survival = wire::speculative_survival( + &mut reader, + manifest.request_capacity(), + manifest.completion_token_capacity, + )?; + if reader.0.len() != manifest.completion_bytes() { + return Err(invalid("rank completion size differs from its ABI")); + } + let completion = FrameCompletion { + logprobs: None, + prompt_logprobs: None, + proposal_confidence, + speculative_survival, + fence, + graph_index: graph, + timing, + records: super::transport::decode_records( + reader.0, + fence, + manifest.request_capacity(), + manifest.completion_fields(), + )?, + }; + protocol::record_peer_completion(pending, index, completion)?; + } else { + return Err(invalid("unexpected rank message")); + } + Ok(()) +} + /// Rank zero owns request scheduling; peer processes execute identical graph steps. /// Two frame slots include preparation and unconsumed all-rank completions. pub struct TensorParallelExecutor { @@ -234,6 +284,49 @@ impl TensorParallelExecutor { && self.local.can_submit(grammar) } + #[cfg(feature = "server")] + pub(crate) fn zero_kv_pages(&mut self, pages: &[u32]) -> Result<()> { + if pages.is_empty() { + return Ok(()); + } + if let Some(error) = &self.poison { + return Err(error.clone()); + } + if self.shutdown.is_some() { + return Err(invalid("tensor-parallel executor is closed")); + } + let result = (|| -> Result<()> { + let payload = wire::encode_page_ids(pages)?; + for peer in &mut self.peers { + peer.channel.nonblocking(false)?; + peer.channel.send(ZERO_KV_PAGES, &payload)?; + } + self.local.zero_kv_pages(pages)?; + let manifest = self.local.manifest(); + for (index, peer) in self.peers.iter_mut().enumerate() { + let deadline = std::time::Instant::now() + TIMEOUT; + 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 { + return Err(invalid("rank zero_kv_pages deadline expired")); + } + } + } + Ok(()) + })(); + if let Err(error) = &result { + self.poison = Some(error.clone()); + } + result + } + pub fn next_fence(&self) -> Result { if let Some(error) = &self.poison { return Err(error.clone()); @@ -322,31 +415,12 @@ impl TensorParallelExecutor { if let Some(completion) = self.local.poll()? { protocol::record_local_completion(&mut self.pending, completion)?; } + let manifest = self.local.manifest(); for (index, peer) in self.peers.iter_mut().enumerate() { peer.channel.nonblocking(true)?; let result = (|| -> Result<()> { while let Some((tag, bytes)) = peer.channel.poll()? { - if tag == READY { - let (fence, graph) = read_identity(&bytes)?; - ready_frame(&mut self.pending, index, fence, graph)?; - } else if tag == COMPLETE { - let mut reader = Reader(&bytes); - let fence = Fence(reader.number()? as u64); - let graph = reader.number()?; - let timing = wire::timing(&mut reader)?; - let proposal_confidence = wire::proposal_confidence(&mut reader, self.local.manifest().request_capacity(), self.local.manifest().completion_token_capacity)?; - let speculative_survival = wire::speculative_survival(&mut reader, self.local.manifest().request_capacity(), self.local.manifest().completion_token_capacity)?; - if reader.0.len() != self.local.manifest().completion_bytes() { - return Err(invalid("rank completion size differs from its ABI")); - } - let completion = FrameCompletion { - logprobs: None, prompt_logprobs: None, proposal_confidence, speculative_survival, - fence, graph_index: graph, timing, - records: super::transport::decode_records(reader.0, fence, - self.local.manifest().request_capacity(), self.local.manifest().completion_fields())?, - }; - protocol::record_peer_completion(&mut self.pending, index, completion)?; - } else { return Err(invalid("unexpected rank message")); } + apply_peer_message(&mut self.pending, manifest, index, tag, bytes)?; } Ok(()) })(); @@ -670,6 +744,11 @@ pub unsafe fn serve_rank( leases.track(Some(fence), guard); started.push_back(Instant::now()); } + ZERO_KV_PAGES => { + let pages = wire::decode_page_ids(&bytes)?; + executor.zero_kv_pages(&pages)?; + channel.send(ZEROED_KV_PAGES, &[])?; + } _ => return Err(invalid("unexpected rank command")), } } diff --git a/helios/src/execution/parallel/tests.rs b/helios/src/execution/parallel/tests.rs index 62a8066a7..86cec70c2 100644 --- a/helios/src/execution/parallel/tests.rs +++ b/helios/src/execution/parallel/tests.rs @@ -833,3 +833,22 @@ fn speculative_agreement_applies_to_speculative_and_speculative_mixed_graphs() { manifest.graphs[0].token_capacity = 1; assert!(uses_speculative_agreement(&manifest.graphs[0])); } + +#[test] +fn zero_kv_pages_wire_roundtrip_and_truncation() { + let pages = [7u32, 0, 42, 1024, u32::MAX]; + let encoded = wire::encode_page_ids(&pages).unwrap(); + assert_eq!(wire::decode_page_ids(&encoded).unwrap(), pages); + assert_eq!(wire::decode_page_ids(&[]).unwrap(), Vec::::new()); + assert!(wire::decode_page_ids(&[1, 2, 3]).is_err()); + + let (client, server) = crate::execution::rank_stream::test_pair().unwrap(); + let mut tx = Channel::new(client).unwrap(); + let mut rx = Channel::new(server).unwrap(); + tx.send(ZERO_KV_PAGES, &encoded).unwrap(); + let (tag, body) = rx.wait(false).unwrap(); + assert_eq!(tag, ZERO_KV_PAGES); + assert_eq!(wire::decode_page_ids(&body).unwrap(), pages); + rx.send(ZEROED_KV_PAGES, &[]).unwrap(); + assert!(tx.receive(ZEROED_KV_PAGES).unwrap().is_empty()); +} diff --git a/helios/src/execution/parallel/wire.rs b/helios/src/execution/parallel/wire.rs index e80eced04..c9c19efb1 100644 --- a/helios/src/execution/parallel/wire.rs +++ b/helios/src/execution/parallel/wire.rs @@ -24,6 +24,8 @@ pub(super) const PREPARE_MORE: u8 = 10; pub(super) const TUNE: u8 = 11; pub(super) const TUNED: u8 = 12; pub(super) const STARTED: u8 = 13; +pub(super) const ZERO_KV_PAGES: u8 = 14; +pub(super) const ZEROED_KV_PAGES: u8 = 15; const MAX_PACKET: usize = 64 * 1024 * 1024; pub(super) const TIMEOUT: Duration = Duration::from_secs(120); @@ -495,3 +497,28 @@ pub(super) fn timing(reader: &mut Reader<'_>) -> Result Result> { + let byte_len = pages + .len() + .checked_mul(size_of::()) + .filter(|&n| n <= MAX_PACKET) + .ok_or_else(|| invalid("zero_kv_pages packet exceeds its size limit"))?; + let mut bytes = Vec::with_capacity(byte_len); + for &page in pages { + bytes.extend_from_slice(&page.to_le_bytes()); + } + Ok(bytes) +} + +pub(super) fn decode_page_ids(bytes: &[u8]) -> Result> { + if !bytes.len().is_multiple_of(size_of::()) { + return Err(invalid("truncated zero_kv_pages control packet")); + } + let mut pages = Vec::with_capacity(bytes.len() / size_of::()); + for chunk in bytes.chunks_exact(size_of::()) { + pages.push(u32::from_le_bytes(chunk.try_into().unwrap())); + } + Ok(pages) +} diff --git a/helios/src/execution/ranks.rs b/helios/src/execution/ranks.rs index 766ce261d..909ddee8c 100644 --- a/helios/src/execution/ranks.rs +++ b/helios/src/execution/ranks.rs @@ -87,6 +87,15 @@ impl RankExecutorInner { } } + #[cfg(feature = "server")] + fn zero_kv_pages(&mut self, pages: &[u32]) -> Result<()> { + match self { + Self::Local(executor) => executor.zero_kv_pages(pages), + Self::Parallel(executor) => executor.zero_kv_pages(pages), + Self::Threaded(executor) => executor.zero_kv_pages(pages), + } + } + fn close(&mut self) -> Shutdown { match self { Self::Local(executor) => executor.close(), @@ -188,6 +197,11 @@ impl RankExecutor { self.inner.next_fence() } + #[cfg(feature = "server")] + pub(crate) fn zero_kv_pages(&mut self, pages: &[u32]) -> Result<()> { + self.inner.zero_kv_pages(pages) + } + pub(crate) fn close(&mut self) -> Shutdown { let shutdown = self.inner.close(); self.leases.clear(); diff --git a/helios/src/execution/threaded.rs b/helios/src/execution/threaded.rs index c67cac425..fc1e2a8dd 100644 --- a/helios/src/execution/threaded.rs +++ b/helios/src/execution/threaded.rs @@ -830,6 +830,7 @@ impl protocol::PendingFrame for InFlightFrame { pub(crate) struct ThreadedExecutor { local: GraphExecutor, + peer_zeros: Vec<(flare_selene::CacheGeometry, crate::cuda::Stream)>, peers: Vec, ring: Arc, watchdog_state: Arc, @@ -869,10 +870,19 @@ impl ThreadedExecutor { .unwrap_or(0) .max(16); let ring = Arc::new(DispatchRing::new(manifest.input_frame_bytes, max_uploads)); + // Open peer zero streams before rank zero's executor so rank zero's context + // remains bound on the coordinator thread once construction completes. + let mut peer_zeros = Vec::new(); + for rank in &ranks { + if let Some(cache) = rank.cache.clone() { + peer_zeros.push((cache, crate::cuda::Stream::open(rank.context, rank.device)?)); + } + } let local = unsafe { GraphExecutor::new_unstarted(manifest)? }; let watchdog_state = Arc::new(WatchdogState::new()); let mut result = Self { local, + peer_zeros, peers: Vec::new(), ring, watchdog_state, @@ -1203,6 +1213,49 @@ impl ThreadedExecutor { root.timing.wall_ns = frame.dispatched.elapsed().as_nanos().min(u64::MAX as u128) as u64; Ok(Some(root)) } + #[cfg(feature = "server")] + pub(crate) fn zero_kv_pages(&mut self, pages: &[u32]) -> Result<()> { + if pages.is_empty() { + return Ok(()); + } + if let Some(error) = &self.poison { + return Err(error.clone()); + } + if self.shutdown.is_some() { + return Err(invalid("rank executor is closed")); + } + let _wd_guard = WatchdogCallGuard::enter(&self.watchdog_state, !self.pending.is_empty()); + let result = (|| -> Result<()> { + let peer_runs = self + .peer_zeros + .iter() + .map(|(cache, _)| super::transport::coalesce_page_runs(pages, cache.page_capacity)) + .collect::>>()?; + let local_enqueued = self.local.enqueue_zero_kv_pages(pages)?; + for ((cache, stream), runs) in self.peer_zeros.iter().zip(&peer_runs) { + super::transport::enqueue_zero_cache_pages(cache, stream, runs)?; + } + if local_enqueued { + self.local.sync_zero_kv_pages()?; + } + for (cache, stream) in &self.peer_zeros { + if !cache.planes.is_empty() { + stream.with_context(|| stream.synchronize())?; + } + } + Ok(()) + })(); + match result { + Ok(()) => { + self.watchdog_state.record_progress(); + Ok(()) + } + Err(error) => { + self.poison = Some(error.clone()); + Err(error) + } + } + } pub fn close(&mut self) -> Shutdown { if let Some(shutdown) = &self.shutdown { return shutdown.clone(); @@ -1217,6 +1270,9 @@ impl ThreadedExecutor { if let Some(error) = &self.poison { return Err(error.clone()); } + for (_, stream) in &self.peer_zeros { + stream.with_context(|| stream.synchronize())?; + } close_peers( &self.ring, &mut self.peers, @@ -1239,8 +1295,16 @@ impl ThreadedExecutor { } self.watchdog_state.record_progress(); let shutdown = match result { - Ok(()) => self.local.close(), - Err(error) => self.local.abandon(error), + Ok(()) => { + self.peer_zeros.clear(); + self.local.close() + } + Err(error) => { + // Retain undrained peer zero streams rather than calling cuStreamDestroy_v2 + // on a potentially wedged CUDA context. + std::mem::forget(std::mem::take(&mut self.peer_zeros)); + self.local.abandon(error) + } }; drop(self.watchdog.take()); self.shutdown = Some(shutdown.clone()); diff --git a/helios/src/execution/transport.rs b/helios/src/execution/transport.rs index 7b21e4e3a..e77745911 100644 --- a/helios/src/execution/transport.rs +++ b/helios/src/execution/transport.rs @@ -570,6 +570,7 @@ impl InputCopyBatches { struct Resources { model: Stream, copy: Stream, + zero: Stream, frames: [Frame; 2], engram: Option, input_copies: InputCopyBatches, @@ -622,6 +623,7 @@ impl GraphExecutor { .saturating_mul(manifest.request_capacity()); let model = Stream::open(manifest.context, manifest.device)?; let copy = Stream::open(manifest.context, manifest.device)?; + let zero = Stream::open(manifest.context, manifest.device)?; let mut frame_index = 0; let mut frame = || -> Result { let index = frame_index; @@ -718,6 +720,7 @@ impl GraphExecutor { resources: Some(Resources { model, copy, + zero, frames, engram, input_copies: InputCopyBatches::new(upload_capacity.saturating_add(2)), @@ -1351,6 +1354,42 @@ impl GraphExecutor { })) } + pub(super) fn enqueue_zero_kv_pages(&mut self, pages: &[u32]) -> Result { + if pages.is_empty() { + return Ok(false); + } + if let Some(error) = &self.poison { + return Err(ExecutionError::Poisoned(Failure::caused_by( + format!("executor failed: {error}"), + error.clone(), + )) + .into()); + } + let Some(cache) = self.manifest.cache.as_ref() else { + return Ok(false); + }; + let Some(resources) = self.resources.as_ref() else { + return Err(Error::execution(ExecutionError::State, "executor is closed")); + }; + let runs = coalesce_page_runs(pages, cache.page_capacity)?; + enqueue_zero_cache_pages(cache, &resources.zero, &runs)?; + Ok(!cache.planes.is_empty()) + } + + pub(super) fn sync_zero_kv_pages(&self) -> Result<()> { + let Some(resources) = self.resources.as_ref() else { + return Err(Error::execution(ExecutionError::State, "executor is closed")); + }; + resources.zero.with_context(|| resources.zero.synchronize()) + } + + pub(crate) fn zero_kv_pages(&mut self, pages: &[u32]) -> Result<()> { + if self.enqueue_zero_kv_pages(pages)? { + self.sync_zero_kv_pages()?; + } + Ok(()) + } + pub fn close(&mut self) -> Shutdown { if let Some(shutdown) = &self.shutdown { return shutdown.clone(); @@ -1361,6 +1400,7 @@ impl GraphExecutor { } let compute = resources.model.synchronize().map_err(Error::drain); let copy = resources.copy.synchronize().map_err(Error::drain); + let zero = resources.zero.synchronize().map_err(Error::drain); let engram = resources .engram .as_ref() @@ -1373,10 +1413,12 @@ impl GraphExecutor { .and_then(|worker| worker.control.as_ref()) .map_or(Ok(()), |control| control.stop()) .map_err(Error::drain); - let drained = compute.is_ok() && copy.is_ok() && engram.is_ok() && worker.is_ok(); + let drained = + compute.is_ok() && copy.is_ok() && zero.is_ok() && engram.is_ok() && worker.is_ok(); let error = compute .err() .or(copy.err()) + .or(zero.err()) .or(engram.err()) .or(worker.err()) .or(self.poison.take()); @@ -1397,6 +1439,74 @@ impl Drop for GraphExecutor { } } +pub(super) fn coalesce_page_runs(pages: &[u32], capacity: u64) -> Result> { + if pages.is_empty() { + return Ok(Vec::new()); + } + let mut sorted = pages.to_vec(); + sorted.sort_unstable(); + sorted.dedup(); + let mut runs: Vec<(u64, u64)> = Vec::new(); + for page in sorted { + let page = u64::from(page); + if page >= capacity { + return Err(Error::execution( + ExecutionError::State, + format!("reclaimed KV page {page} exceeds cache page capacity {capacity}"), + )); + } + if let Some((start, count)) = runs.last_mut() + && *start + *count == page + { + *count += 1; + } else { + runs.push((page, 1)); + } + } + Ok(runs) +} + +pub(super) fn enqueue_zero_cache_pages( + cache: &flare_selene::CacheGeometry, + stream: &Stream, + runs: &[(u64, u64)], +) -> Result<()> { + if runs.is_empty() || cache.planes.is_empty() { + return Ok(()); + } + stream.with_context(|| { + for plane in &cache.planes { + if plane.unit_bytes == 0 { + continue; + } + for &(start, count) in runs { + let offset = start.checked_mul(plane.unit_bytes).ok_or_else(|| { + Error::execution(ExecutionError::State, "KV page address offset overflow") + })?; + let dst = plane.address.checked_add(offset).ok_or_else(|| { + Error::execution(ExecutionError::State, "KV page address overflow") + })?; + let total_bytes = count.checked_mul(plane.unit_bytes).ok_or_else(|| { + Error::execution(ExecutionError::State, "KV page zero byte length overflow") + })?; + let nbytes = usize::try_from(total_bytes).map_err(|_| { + Error::execution( + ExecutionError::State, + "KV page zero byte length exceeds usize", + ) + })?; + // SAFETY: `start + count <= cache.page_capacity`, all reclaimed pages were retired + // past their last GPU fence before `release_snapshot` freed them, and no new kernel + // or host restore has been submitted against them yet. + unsafe { + stream.memset_d8_async(dst, 0, nbytes)?; + } + } + } + Ok(()) + }) +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(super) struct ResolvedUpload { pub(super) host_offset: usize, @@ -2050,4 +2160,21 @@ mod confidence_tests { ParkAction::Sleep(std::time::Duration::from_micros(PARK_FALLBACK_SLEEP_US)) ); } + + #[test] + fn coalesce_page_runs_sorts_dedups_merges_and_bounds_checks() { + assert_eq!( + coalesce_page_runs(&[], 16).unwrap(), + Vec::<(u64, u64)>::new() + ); + assert_eq!( + coalesce_page_runs(&[5, 2, 3, 2, 7, 4, 8], 16).unwrap(), + vec![(2, 4), (7, 2)] + ); + assert_eq!( + coalesce_page_runs(&[0, 15], 16).unwrap(), + vec![(0, 1), (15, 1)] + ); + assert!(coalesce_page_runs(&[0, 16], 16).is_err()); + } } diff --git a/helios/src/scheduler.rs b/helios/src/scheduler.rs index daae9d9fb..b7142970f 100644 --- a/helios/src/scheduler.rs +++ b/helios/src/scheduler.rs @@ -666,6 +666,7 @@ pub struct RequestScheduler { free_snapshots: BTreeSet, snapshot_pages: Vec>, page_snapshot_refs: Vec, + reclaimed_snapshot_pages: Vec, freeable_prefix_scratch: std::cell::RefCell>, retired: Vec, submissions: BTreeMap, @@ -768,6 +769,7 @@ impl RequestScheduler { free_snapshots: (0..limits.snapshots).map(SnapshotId).collect(), snapshot_pages: Vec::new(), page_snapshot_refs: vec![0; limits.pages as usize], + reclaimed_snapshot_pages: Vec::new(), freeable_prefix_scratch: std::cell::RefCell::new(Vec::new()), retired: Vec::new(), submissions: BTreeMap::new(), diff --git a/helios/src/scheduler/cache_memory.rs b/helios/src/scheduler/cache_memory.rs index eba62540a..03a20b275 100644 --- a/helios/src/scheduler/cache_memory.rs +++ b/helios/src/scheduler/cache_memory.rs @@ -828,10 +828,22 @@ impl RequestScheduler { if *count == 0 { self.stats.snapshot_backing_pages -= 1; assert!(self.free_pages.insert(PageId(page))); + self.reclaimed_snapshot_pages.push(page); } } } } + + /// Drain KV page IDs whose last aliased snapshot reference dropped to zero. + /// + /// Aliased snapshot rows share physical memory with KV pages; when snapshots store + /// non-FP8 state (for example BF16 draft rings or recurrent state), raw bytes + /// containing `0x7F`/`0xFF` act as FP8 E4M3FN NaN in unwritten KV page tails + /// (`0.0 * NaN = NaN` in SM103 FP8 BMM2 attention). Callers must zero these pages + /// on the GPU before any kernel or host-to-GPU restore uses them. + pub fn take_reclaimed_snapshot_pages(&mut self) -> Vec { + std::mem::take(&mut self.reclaimed_snapshot_pages) + } } #[cfg(test)] mod tests { @@ -2840,4 +2852,34 @@ mod tests { } s.free_pages.extend(held); } + + #[test] + fn release_snapshot_records_only_reclaimed_pages_and_drains() { + let mut s = super::super::tests::scheduler(1, 4, 3); + s.share_snapshot_pages(&[0..3, 2..4, 0..0]).unwrap(); + s.reserve_snapshot_id(SnapshotId(0)); + s.reserve_snapshot_id(SnapshotId(1)); + s.reserve_snapshot_id(SnapshotId(2)); + assert!(s.take_reclaimed_snapshot_pages().is_empty()); + + // Releasing an empty-range snapshot queues nothing. + s.release_snapshot(SnapshotId(2)); + assert!(s.take_reclaimed_snapshot_pages().is_empty()); + + // Releasing snapshot 0 drops pages 0 and 1 from 1 -> 0, while shared page 2 stays at refcount 1. + s.release_snapshot(SnapshotId(0)); + assert_eq!(s.take_reclaimed_snapshot_pages(), vec![0, 1]); + assert!(s.take_reclaimed_snapshot_pages().is_empty()); + + // Releasing snapshot 1 drops remaining pages 2 and 3 from 1 -> 0. + s.release_snapshot(SnapshotId(1)); + assert_eq!(s.take_reclaimed_snapshot_pages(), vec![2, 3]); + assert!(s.take_reclaimed_snapshot_pages().is_empty()); + + // A subsequent reserve/release cycle queues the reclaimed pages again cleanly. + s.reserve_snapshot_id(SnapshotId(0)); + s.release_snapshot(SnapshotId(0)); + assert_eq!(s.take_reclaimed_snapshot_pages(), vec![0, 1, 2]); + assert!(s.take_reclaimed_snapshot_pages().is_empty()); + } } diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index d58403da3..40d154541 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -1607,17 +1607,23 @@ impl<'a> Worker<'a> { // Input construction stays inside the worker's unwind and drain boundary. self.inputs = Some(crate::model::Inputs::new(self.config, executor.manifest())?); while !self.stop.load(Ordering::Acquire) { - let std::ops::ControlFlow::Continue(mut progress) = self.admit()? else { + let std::ops::ControlFlow::Continue(mut progress) = + self.admit_with_executor(Some(executor))? + else { return Ok(()); }; if let Some(completion) = executor.poll()? { let kind = executor.manifest().graphs[completion.graph_index].kind; self.complete(kind, completion)?; + self.zero_reclaimed_kv_pages(executor)?; progress = true; } progress |= self.publish()?; + self.zero_reclaimed_kv_pages(executor)?; progress |= self.service_store()?; + self.zero_reclaimed_kv_pages(executor)?; let (step, planned) = self.plan()?; + self.zero_reclaimed_kv_pages(executor)?; progress |= planned; if let Some(step) = step { progress |= self.submit(executor, &step)?; @@ -1779,7 +1785,23 @@ impl<'a> Worker<'a> { Ok(progress) } + fn zero_reclaimed_kv_pages(&mut self, executor: &mut RankExecutor) -> Result<()> { + let pages = self.scheduler.take_reclaimed_snapshot_pages(); + if !pages.is_empty() { + executor.zero_kv_pages(&pages)?; + } + Ok(()) + } + + #[cfg(test)] fn admit(&mut self) -> Result> { + self.admit_with_executor(None) + } + + fn admit_with_executor( + &mut self, + mut executor: Option<&mut RankExecutor>, + ) -> Result> { self.scheduler .advance_to(super::observation::monotonic_ns())?; let mut progress = self.complete_image_preparation()?; @@ -1832,6 +1854,9 @@ impl<'a> Worker<'a> { progress = true; } } + if let Some(executor) = executor.as_deref_mut() { + self.zero_reclaimed_kv_pages(executor)?; + } while self.scheduler.has_available_slot() { let now = std::time::Instant::now(); for incoming in self.pending.iter_mut().chain(self.parked.iter_mut().map(|(incoming, _)| incoming)) { @@ -1911,11 +1936,22 @@ impl<'a> Worker<'a> { incoming.prompt.grammar.is_some() && (!unmasked_reasoning || !speculative); self.scheduler .advance_to(super::observation::monotonic_ns())?; + let mut zero_error = None; let admission = if let Some(store) = self.store.as_mut().filter(|_| incoming.host_lookup && !spec.prompt_logprobs) { + 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(()) + }; admit_with_host_store( &mut self.scheduler, + &mut zero_pages, store.as_mut(), HostAdmissionProbe { spec, @@ -1946,6 +1982,9 @@ impl<'a> Worker<'a> { checkpoint_accounting, ) }; + if let Some(error) = zero_error { + return Err(error); + } let handle = match admission { Ok(handle) => handle, // Pages are short: wait for running requests to finish or yield theirs. @@ -2122,6 +2161,9 @@ impl<'a> Worker<'a> { }); progress = true; } + if let Some(executor) = executor.as_deref_mut() { + self.zero_reclaimed_kv_pages(executor)?; + } if self.preparing_image.is_none() { if let Some(preparation) = &self.image_preparation { for offset in 0..self.active.len() { @@ -3175,6 +3217,7 @@ impl<'a> Worker<'a> { )?; let fence = executor.next_fence()?; self.reserve_and_pack(step, fence)?; + self.zero_reclaimed_kv_pages(executor)?; let feedback = self.scheduler.submitted_step(fence)?.requires_feedback; let mut flags = [0u8; crate::execution::REQUEST_LANES * size_of::()]; let mut counts = [0u8; crate::execution::REQUEST_LANES * size_of::()]; @@ -3813,6 +3856,7 @@ struct HostAdmissionProbe<'a> { /// checkpoint, and start a restore when the transfer beats recomputation. fn admit_with_host_store( scheduler: &mut RequestScheduler, + mut zero_kv_pages: impl FnMut(&[u32]) -> Result<()>, store: &mut dyn flare_selene::HostStore, probe: HostAdmissionProbe<'_>, prefill_rate: f64, @@ -3951,6 +3995,10 @@ fn admit_with_host_store( let key = ticket.key; let row_only = hit.pages == 0; let admitted_accounting = scheduler.request(admitted.handle)?.checkpoint_accounting(); + let reclaimed = scheduler.take_reclaimed_snapshot_pages(); + if !reclaimed.is_empty() { + zero_kv_pages(&reclaimed)?; + } if row_only { row_restore_latency.start(key, source); } diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 9a7599b38..0ebe4c295 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -12245,3 +12245,152 @@ async fn chat_continuous_usage_preserves_initial_cached_tokens_across_preemption assert_eq!(chunks.last().unwrap()["usage"]["completion_tokens"], 3); } } + +#[test] +fn admit_with_host_store_zeros_reclaimed_snapshot_pages_before_fetch() { + use std::cell::RefCell; + use std::rc::Rc; + + struct RecordingStore { + inner: FakeStore, + events: Rc>>, + } + impl flare_selene::HostStore for RecordingStore { + fn lookup( + &mut self, + h: &dyn flare_selene::History, + r: u64, + b: u64, + ) -> Option { + self.inner.lookup(h, r, b) + } + fn fetch( + &mut self, + hit: flare_selene::HostHit, + ticket: flare_selene::InboundTicket, + ) -> flare_selene::Result<()> { + self.events.borrow_mut().push("fetch"); + self.inner.fetch(hit, ticket) + } + fn store( + &mut self, + p: &flare_selene::PublishedCheckpoint, + ) -> flare_selene::Result { + self.inner.store(p) + } + fn poll( + &mut self, + events: &mut Vec, + ) -> flare_selene::Result<()> { + self.inner.poll(events) + } + fn stats(&self) -> flare_selene::StoreStats { + self.inner.stats() + } + fn close(&mut self) -> flare_selene::Result<()> { + self.inner.close() + } + } + + for inject_zero_error in [false, true] { + let mut fixture = Fixture::new(); + fixture.config.limits.max_sequence_tokens = 512; + let (sender, receiver) = mpsc::channel(); + let mut worker = prompt_capture_worker(&fixture, receiver); + let mut graphs = crate::model::testing::manifest(&fixture.config).graphs; + for graph in &mut graphs { + graph.estimated_duration_ns = if graph.kind == GraphKind::Snapshot { + 10 + } else if graph.kind.is_prefill() { + 30_000_000_000 + } else { + 1000 + }; + } + worker.scheduler.measured_graph_durations(&graphs).unwrap(); + // Snapshots 0 and 1 each alias 6 disjoint KV pages (4..10 and 10..16), while + // remaining snapshots alias 4..16, so two cached checkpoints tie up pages 4..16 + // and leave only 2 free KV pages. + let mut aliases = vec![4..16; 16]; + aliases[0] = 4..10; + aliases[1] = 10..16; + worker.scheduler.share_snapshot_pages(&aliases).unwrap(); + + // Populate and retire two cached checkpoints holding snapshots 0 and 1 (backing 4..16). + let _gen1 = capture_store_prompt(&fixture, &mut worker, &sender, 7, 1, 1); + assert!(worker.publish().unwrap()); + let _gen2 = capture_store_prompt(&fixture, &mut worker, &sender, 8, 1, 10); + assert!(worker.publish().unwrap()); + assert!(worker.active.iter().all(Option::is_none)); + assert_eq!(worker.scheduler.stats().snapshot_backing_pages, 12); + assert_eq!(worker.scheduler.free_page_count(), 2); + assert!(worker.scheduler.take_reclaimed_snapshot_pages().is_empty()); + + // Admit a 320-token (5-page) host hit: allocating its 5 pages requires evicting + // snapshots 0 and 1, reclaiming pages 4..16. + let (incoming, _gen3, hit) = incoming_with_hit(&fixture, vec![9; 320], 4, 320); + let events = Rc::new(RefCell::new(Vec::new())); + let zeroed_pages = Rc::new(RefCell::new(Vec::::new())); + let mut store = RecordingStore { + inner: FakeStore::new(Some(hit)), + events: Rc::clone(&events), + }; + let events_zero = Rc::clone(&events); + let pages_zero = Rc::clone(&zeroed_pages); + let mut restore_wait = RestoreWait::default(); + let result = admit_with_host_store( + &mut worker.scheduler, + |pages| { + events_zero.borrow_mut().push("zero"); + pages_zero.borrow_mut().extend_from_slice(pages); + if inject_zero_error { + return Err(Error::execution( + ExecutionError::State, + "injected zero_kv_pages failure", + )); + } + Ok(()) + }, + &mut store, + HostAdmissionProbe { + spec: incoming.spec(), + prefill_spans: &incoming.prompt.data.spans, + conditioned_images: &incoming.prompt.conditioned_inputs, + core_parameters: &incoming.prompt.core_parameters, + pool_lookup: None, + queued_plan: None, + plan_refreshed: false, + accounting: None, + }, + worker.prefill_rate, + &mut worker.row_restore_latency, + worker.metrics, + &mut restore_wait, + ); + + if !inject_zero_error { + assert!(result.is_ok(), "unexpected admission result: {result:?}"); + } + let mut actual_zeroed = zeroed_pages.borrow().clone(); + actual_zeroed.sort_unstable(); + let expected_reclaimed: Vec = (4..16).collect(); + assert_eq!(actual_zeroed, expected_reclaimed, "result={result:?}"); + assert!(worker.scheduler.take_reclaimed_snapshot_pages().is_empty()); + if inject_zero_error { + assert!(result.is_err()); + assert_eq!(*events.borrow(), vec!["zero"]); + assert!(store.inner.fetched.is_empty()); + } else { + let (_handle, outcome) = result.unwrap(); + assert_eq!(outcome, Some(crate::offload::LookupOutcome::Admitted)); + assert_eq!(*events.borrow(), vec!["zero", "fetch"]); + assert_eq!(store.inner.fetched.len(), 1); + // The inbound ticket reused pages reclaimed from the evicted snapshots, which were already zeroed. + let fetched_pages = &store.inner.fetched[0].1.pages; + assert!( + fetched_pages.iter().any(|&p| (4..16).contains(&p.0)), + "expected inbound restore to allocate at least one reclaimed snapshot page, got {fetched_pages:?}" + ); + } + } +} From ccf4e3657e7239ed51b2a97ca2e86a65e601a849 Mon Sep 17 00:00:00 2001 From: ebfio Date: Fri, 4 Dec 2026 22:10:24 -0500 Subject: [PATCH 2/8] fix(helios): bump rank-control wire version and poison on zeroing failure Bumps the rank-control layout version 6 -> 7 so a patched rank cannot pass HELLO against an unpatched peer and then fail mid-serving with an unexpected rank command on the first snapshot eviction, and records poison on coalesce, memset and sync failures in enqueue_zero_kv_pages/zero_kv_pages so close() reports the cause instead of a clean shutdown. --- helios/src/execution/parallel/tests.rs | 2 +- helios/src/execution/parallel/wire.rs | 4 +++- helios/src/execution/transport.rs | 20 +++++++++++++++++--- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/helios/src/execution/parallel/tests.rs b/helios/src/execution/parallel/tests.rs index 86cec70c2..978677868 100644 --- a/helios/src/execution/parallel/tests.rs +++ b/helios/src/execution/parallel/tests.rs @@ -226,7 +226,7 @@ fn prepare_packets_preserve_large_and_partial_uploads_on_both_transports() { manifest.graphs[0].input_bindings[2].nbytes = buffer.nbytes; manifest.input_frame_bytes = 16 + buffer.nbytes; manifest.validate().unwrap(); - assert_eq!(u64::from_le_bytes(layout(&manifest)[..8].try_into().unwrap()), 6); + assert_eq!(u64::from_le_bytes(layout(&manifest)[..8].try_into().unwrap()), 7); for (sender, receiver) in [crate::execution::rank_stream::test_pair().unwrap(), (client.into(), server.into())] { let mut sender = Channel::new(sender).unwrap(); diff --git a/helios/src/execution/parallel/wire.rs b/helios/src/execution/parallel/wire.rs index c9c19efb1..6837eae95 100644 --- a/helios/src/execution/parallel/wire.rs +++ b/helios/src/execution/parallel/wire.rs @@ -185,7 +185,9 @@ pub(super) fn validate_completion_packet(manifest: &ExecutionManifest) -> Result pub(super) fn layout(manifest: &ExecutionManifest) -> Vec { let mut bytes = Vec::new(); for value in [ - 6, + // 7: adds ZERO_KV_PAGES/ZEROED_KV_PAGES, so a patched rank cannot + // pass HELLO against an unpatched peer and fail on the first eviction. + 7, manifest.completion_token_capacity, manifest.max_active, manifest.input_frame_bytes, diff --git a/helios/src/execution/transport.rs b/helios/src/execution/transport.rs index e77745911..d4514481b 100644 --- a/helios/src/execution/transport.rs +++ b/helios/src/execution/transport.rs @@ -1371,8 +1371,19 @@ impl GraphExecutor { let Some(resources) = self.resources.as_ref() else { return Err(Error::execution(ExecutionError::State, "executor is closed")); }; - let runs = coalesce_page_runs(pages, cache.page_capacity)?; - enqueue_zero_cache_pages(cache, &resources.zero, &runs)?; + let runs = match coalesce_page_runs(pages, cache.page_capacity) { + Ok(runs) => runs, + Err(error) => { + // Match submit/poll: a failed zeroing must not leave the executor + // usable, or close() reports a clean Shutdown and drops the cause. + self.poison = Some(error.clone()); + return Err(error); + } + }; + if let Err(error) = enqueue_zero_cache_pages(cache, &resources.zero, &runs) { + self.poison = Some(error.clone()); + return Err(error); + } Ok(!cache.planes.is_empty()) } @@ -1385,7 +1396,10 @@ impl GraphExecutor { pub(crate) fn zero_kv_pages(&mut self, pages: &[u32]) -> Result<()> { if self.enqueue_zero_kv_pages(pages)? { - self.sync_zero_kv_pages()?; + if let Err(error) = self.sync_zero_kv_pages() { + self.poison = Some(error.clone()); + return Err(error); + } } Ok(()) } From f46b564467231cec0302b8b5ce08ea68a64398ac Mon Sep 17 00:00:00 2001 From: ebfio Date: Fri, 4 Dec 2026 22:11:31 -0500 Subject: [PATCH 3/8] test(helios): cover zero-reply interleaving and the async zero memset Adds the two tests the review asked for: a CPU test that drives the ZEROED_KV_PAGES wait with interleaved READY/COMPLETE control frames and asserts they survive into the pending queue, and an ignored CUDA test that fills two planes with 0x7F, zeroes one page through enqueue_zero_cache_pages, and asserts the reclaimed page is zero while the live page stays byte-identical. --- helios/src/execution/parallel/tests.rs | 39 ++++++++++++ helios/src/execution/transport.rs | 86 ++++++++++++++++++++++++++ 2 files changed, 125 insertions(+) diff --git a/helios/src/execution/parallel/tests.rs b/helios/src/execution/parallel/tests.rs index 978677868..ad786272b 100644 --- a/helios/src/execution/parallel/tests.rs +++ b/helios/src/execution/parallel/tests.rs @@ -852,3 +852,42 @@ fn zero_kv_pages_wire_roundtrip_and_truncation() { rx.send(ZEROED_KV_PAGES, &[]).unwrap(); assert!(tx.receive(ZEROED_KV_PAGES).unwrap().is_empty()); } + +#[test] +fn zero_reply_interleaved_with_control_frames_keeps_control_frames() { + // Mirrors TensorParallelExecutor::zero_kv_pages: the ZEROED_KV_PAGES wait must + // consume interleaved READY/COMPLETE control frames into the pending queue + // rather than dropping them or mistaking them for the reply. + let manifest = super::super::tests::manifest(); + let (sender, receiver) = crate::execution::rank_stream::test_pair().unwrap(); + let mut sender = Channel::new(sender).unwrap(); + let mut receiver = Channel::new(receiver).unwrap(); + + sender.send(READY, &identity(Fence(1), 0)).unwrap(); + sender.send(COMPLETE, &completion(&completed(1))).unwrap(); + sender.send(ZEROED_KV_PAGES, &[]).unwrap(); + + let mut pending = std::collections::VecDeque::new(); + loop { + let (tag, bytes) = receiver.wait(false).unwrap(); + if tag == ZEROED_KV_PAGES { + assert!(bytes.is_empty(), "the zero reply carries no payload"); + break; + } + apply_peer_message(&mut pending, &manifest, 0, tag, bytes).unwrap(); + } + assert_eq!(pending.len(), 2, "both control frames survived into the queue"); + + // A payload on the reply tag is rejected, and an unknown tag is not swallowed. + sender.send(ZEROED_KV_PAGES, &[1]).unwrap(); + let (tag, bytes) = receiver.wait(false).unwrap(); + assert_eq!((tag, bytes), (ZEROED_KV_PAGES, vec![1])); + assert!(apply_peer_message( + &mut std::collections::VecDeque::new(), + &manifest, + 0, + 0xFE, + Vec::new() + ) + .is_err()); +} diff --git a/helios/src/execution/transport.rs b/helios/src/execution/transport.rs index d4514481b..9859b54a5 100644 --- a/helios/src/execution/transport.rs +++ b/helios/src/execution/transport.rs @@ -2191,4 +2191,90 @@ mod confidence_tests { ); assert!(coalesce_page_runs(&[0, 16], 16).is_err()); } + + #[test] + #[ignore = "requires a CUDA device selected through CUDA_VISIBLE_DEVICES"] + fn enqueue_zero_cache_pages_zeroes_reclaimed_pages_across_planes() { + // Exercises the path the CPU tests never reach: the async memset issued on + // the dedicated zero stream. Page 0 is "reclaimed" (0x7F fill, an FP8 + // E4M3 NaN payload); page 1 must stay byte-identical. + use crate::runtime_core::driver::Driver; + const UNIT: usize = 4096; + const PAGES: u64 = 2; + let bytes = UNIT * PAGES as usize; + + let driver = Driver::load().unwrap(); + let mut context = std::ptr::null_mut(); + let mut addresses = [0u64; 2]; + unsafe { + driver.check("cuInit", (driver.init)(0)).unwrap(); + let mut device = 0; + driver + .check("cuDeviceGet", (driver.device)(&mut device, 0)) + .unwrap(); + driver + .check( + "cuCtxCreate_v2", + (driver.context_create)(&mut context, 0, device), + ) + .unwrap(); + for address in addresses.iter_mut() { + driver + .check("cuMemAlloc_v2", (driver.allocate)(address, bytes)) + .unwrap(); + } + } + let poison = vec![0x7Fu8; bytes]; + for address in addresses { + unsafe { + driver + .check( + "cuMemcpyHtoD_v2", + (driver.upload)(address, poison.as_ptr().cast(), bytes), + ) + .unwrap(); + } + } + + let plane = |name: &str, address: u64| flare_selene::Plane { + name: name.to_owned(), + address, + unit_bytes: UNIT as u64, + }; + let cache = flare_selene::CacheGeometry { + page_tokens: 1, + page_capacity: PAGES, + row_capacity: 1, + row: plane("row", addresses[0]), + planes: vec![plane("k", addresses[0]), plane("v", addresses[1])], + snapshot_pages: Vec::new(), + codec_fields: Vec::new(), + placement: flare_selene::KvCompression::Off, + }; + + let stream = Stream::open(context as usize, 0).unwrap(); + let runs = coalesce_page_runs(&[0], cache.page_capacity).unwrap(); + enqueue_zero_cache_pages(&cache, &stream, &runs).unwrap(); + stream.synchronize().unwrap(); + + for (index, address) in addresses.iter().enumerate() { + let mut host = vec![0u8; bytes]; + unsafe { + driver + .check( + "cuMemcpyDtoH_v2", + (driver.download)(host.as_mut_ptr().cast(), *address, bytes), + ) + .unwrap(); + } + assert!( + host[..UNIT].iter().all(|byte| *byte == 0), + "plane {index} page 0 must be zeroed after enqueue_zero_cache_pages" + ); + assert!( + host[UNIT..].iter().all(|byte| *byte == 0x7F), + "plane {index} page 1 must stay byte-identical" + ); + } + } } From 3fa4419de438e2defaeeb878f1c15dfa6d1b8440 Mon Sep 17 00:00:00 2001 From: ebfio Date: Fri, 4 Dec 2026 22:19:12 -0500 Subject: [PATCH 4/8] test(helios): pass the speculative flag to RequestSpec in the host-admission test The rebase onto main carried a call written against the pre-#729 signature. Host admission is a non-speculative path, matching runtime.rs:3758, so the test passes false. cargo check never caught this because #[cfg(test)] code is only built by cargo test. --- helios/src/server/runtime/phase_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index 0ebe4c295..58a12cf32 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -12353,7 +12353,7 @@ fn admit_with_host_store_zeros_reclaimed_snapshot_pages_before_fetch() { }, &mut store, HostAdmissionProbe { - spec: incoming.spec(), + spec: incoming.spec(false), prefill_spans: &incoming.prompt.data.spans, conditioned_images: &incoming.prompt.conditioned_inputs, core_parameters: &incoming.prompt.core_parameters, From 0aa750e3ff10de090a568bed4e5975b0f2cf55a5 Mon Sep 17 00:00:00 2001 From: ebfio Date: Fri, 4 Dec 2026 22:19:48 -0500 Subject: [PATCH 5/8] test(helios): reach KvCompression through the offload module flare_selene re-exports CacheGeometry and Plane at the crate root but not KvCompression, so the new CUDA test must name flare_selene::offload::KvCompression. Found by building the test target, which cargo check does not cover. --- helios/src/execution/transport.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/helios/src/execution/transport.rs b/helios/src/execution/transport.rs index 9859b54a5..f7e5a09a3 100644 --- a/helios/src/execution/transport.rs +++ b/helios/src/execution/transport.rs @@ -2249,7 +2249,7 @@ mod confidence_tests { planes: vec![plane("k", addresses[0]), plane("v", addresses[1])], snapshot_pages: Vec::new(), codec_fields: Vec::new(), - placement: flare_selene::KvCompression::Off, + placement: flare_selene::offload::KvCompression::Off, }; let stream = Stream::open(context as usize, 0).unwrap(); From ba11282d82d1875feac9ac969adfdf1d30a46788 Mon Sep 17 00:00:00 2001 From: ebfio Date: Fri, 4 Dec 2026 22:27:54 -0500 Subject: [PATCH 6/8] test(helios): give the interleaving test real pending frames and host the CUDA test under server tests The interleaving test fed a READY for a fence rank 0 had never submitted, so record_ready rejected it with 'unexpected rank readiness fence'; it now seeds the pending queue with the draining frame and a committed frame that the COMPLETE belongs to. The CUDA zero-page test lived in the runtime-core-gated confidence_tests module, which the gate's --features server build never compiles; it now sits in its own #[cfg(test)] module so it is compiled and listed as ignored. --- helios/src/execution/parallel/tests.rs | 36 ++++++++++++++++---------- helios/src/execution/transport.rs | 6 +++++ 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/helios/src/execution/parallel/tests.rs b/helios/src/execution/parallel/tests.rs index ad786272b..ffe892105 100644 --- a/helios/src/execution/parallel/tests.rs +++ b/helios/src/execution/parallel/tests.rs @@ -855,19 +855,35 @@ fn zero_kv_pages_wire_roundtrip_and_truncation() { #[test] fn zero_reply_interleaved_with_control_frames_keeps_control_frames() { - // Mirrors TensorParallelExecutor::zero_kv_pages: the ZEROED_KV_PAGES wait must - // consume interleaved READY/COMPLETE control frames into the pending queue - // rather than dropping them or mistaking them for the reply. + // Mirrors TensorParallelExecutor::zero_kv_pages: the wait for ZEROED_KV_PAGES + // must consume interleaved READY/COMPLETE control frames into the pending + // queue rather than dropping them or mistaking them for the reply. let manifest = super::super::tests::manifest(); let (sender, receiver) = crate::execution::rank_stream::test_pair().unwrap(); let mut sender = Channel::new(sender).unwrap(); let mut receiver = Channel::new(receiver).unwrap(); + // Rank 0 submitted frame 1 (awaiting READY) and committed frame 3 (awaiting + // the peer's COMPLETE); both must survive the zeroing wait. + let mut pending = std::collections::VecDeque::new(); + for (fence, graph, committed) in [(Fence(1), 0usize, false), (Fence(3), 2usize, true)] { + pending.push_back(Pending { + fence, + graph, + grammar: false, + uploads: Vec::new(), + dispatched: std::time::Instant::now(), + committed, + queued: false, + ready: vec![false; 1], + completions: (0..=1).map(|_| None).collect(), + }); + } + sender.send(READY, &identity(Fence(1), 0)).unwrap(); sender.send(COMPLETE, &completion(&completed(1))).unwrap(); sender.send(ZEROED_KV_PAGES, &[]).unwrap(); - let mut pending = std::collections::VecDeque::new(); loop { let (tag, bytes) = receiver.wait(false).unwrap(); if tag == ZEROED_KV_PAGES { @@ -876,18 +892,12 @@ fn zero_reply_interleaved_with_control_frames_keeps_control_frames() { } apply_peer_message(&mut pending, &manifest, 0, tag, bytes).unwrap(); } - assert_eq!(pending.len(), 2, "both control frames survived into the queue"); + assert!(pending[0].ready[0], "READY recorded on the draining frame"); + assert!(pending[1].completions[1].is_some(), "COMPLETE recorded on the committed frame"); // A payload on the reply tag is rejected, and an unknown tag is not swallowed. sender.send(ZEROED_KV_PAGES, &[1]).unwrap(); let (tag, bytes) = receiver.wait(false).unwrap(); assert_eq!((tag, bytes), (ZEROED_KV_PAGES, vec![1])); - assert!(apply_peer_message( - &mut std::collections::VecDeque::new(), - &manifest, - 0, - 0xFE, - Vec::new() - ) - .is_err()); + assert!(apply_peer_message(&mut std::collections::VecDeque::new(), &manifest, 0, 0xFE, Vec::new()).is_err()); } diff --git a/helios/src/execution/transport.rs b/helios/src/execution/transport.rs index f7e5a09a3..bc27475fd 100644 --- a/helios/src/execution/transport.rs +++ b/helios/src/execution/transport.rs @@ -2192,6 +2192,12 @@ mod confidence_tests { assert!(coalesce_page_runs(&[0, 16], 16).is_err()); } +} + +#[cfg(test)] +mod zero_page_tests { + use super::*; + #[test] #[ignore = "requires a CUDA device selected through CUDA_VISIBLE_DEVICES"] fn enqueue_zero_cache_pages_zeroes_reclaimed_pages_across_planes() { From 3821189bbee5cbbca805051f409ef4d9269f6711 Mon Sep 17 00:00:00 2001 From: ebfio Date: Fri, 4 Dec 2026 22:29:41 -0500 Subject: [PATCH 7/8] test(helios): gate the CUDA zero-page test on runtime-core The test drives Driver::load and Stream directly, and Driver lives in runtime_core, which the server feature does not enable. check.py builds --features server, so an ungated module broke that build; the lifecycle workflow builds runtime-core,server, where the test is now compiled and listed as ignored. --- helios/src/execution/transport.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/helios/src/execution/transport.rs b/helios/src/execution/transport.rs index bc27475fd..8c77c4c01 100644 --- a/helios/src/execution/transport.rs +++ b/helios/src/execution/transport.rs @@ -2194,7 +2194,7 @@ mod confidence_tests { } -#[cfg(test)] +#[cfg(all(test, feature = "runtime-core"))] mod zero_page_tests { use super::*; From 83b05b41e55fc591477300e543b39811ab63e71d Mon Sep 17 00:00:00 2001 From: ebfio Date: Fri, 4 Dec 2026 22:41:13 -0500 Subject: [PATCH 8/8] test(helios): queue the committed frame ahead of the draining one record_peer_completion selects the first frame with a free completion slot for that rank and only then validates committed/fence/graph, so a COMPLETE for the committed frame is rejected when an uncommitted frame sits ahead of it in the queue. The fixture now orders the committed frame first; READY stays fence-addressed and lands on the draining frame. --- helios/src/execution/parallel/tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/helios/src/execution/parallel/tests.rs b/helios/src/execution/parallel/tests.rs index ffe892105..e5549ed73 100644 --- a/helios/src/execution/parallel/tests.rs +++ b/helios/src/execution/parallel/tests.rs @@ -866,7 +866,7 @@ fn zero_reply_interleaved_with_control_frames_keeps_control_frames() { // Rank 0 submitted frame 1 (awaiting READY) and committed frame 3 (awaiting // the peer's COMPLETE); both must survive the zeroing wait. let mut pending = std::collections::VecDeque::new(); - for (fence, graph, committed) in [(Fence(1), 0usize, false), (Fence(3), 2usize, true)] { + for (fence, graph, committed) in [(Fence(3), 2usize, true), (Fence(1), 0usize, false)] { pending.push_back(Pending { fence, graph, @@ -892,8 +892,8 @@ fn zero_reply_interleaved_with_control_frames_keeps_control_frames() { } apply_peer_message(&mut pending, &manifest, 0, tag, bytes).unwrap(); } - assert!(pending[0].ready[0], "READY recorded on the draining frame"); - assert!(pending[1].completions[1].is_some(), "COMPLETE recorded on the committed frame"); + assert!(pending[0].completions[1].is_some(), "COMPLETE recorded on the committed frame"); + assert!(pending[1].ready[0], "READY recorded on the draining frame"); // A payload on the reply tag is rejected, and an unknown tag is not swallowed. sender.send(ZEROED_KV_PAGES, &[1]).unwrap();