From 3f6c74a160d00bba7ccf25f9e94b07e2e23edf15 Mon Sep 17 00:00:00 2001 From: Martin Vit Date: Sat, 14 Nov 2026 20:11:33 +0000 Subject: [PATCH 1/3] Preserve prefix-cache reuse under resource pressure Host restore admission discarded worthwhile cache hits when snapshot backing was temporarily held by requests or transfers, while checkpoint recency followed admission order even after a long request completed. Snapshot aliases and fenced ownership make capacity failures potentially transient. Defer restores within the existing transfer-versus-prefill cost budget and wake admissions on expiry or resource release, including inbound completion with no remaining waiters. Keep pooled lookup state across retries and reset wait accounting on admission. Refresh retained checkpoint chains after successful completion or cancellation with inference progress, excluding preemption and execution errors. Core formats and graph contracts remain compatible without re-export. The implemented policy is expected to avoid unnecessary prefills and retain recently completed conversations. CPU regressions qualify these decisions; GPU serving and performance remain unqualified and are tracked in docs/TODO.txt. Validation: tests for restore deferral and completion recency fail on base 70069281. The Helios library suite with server,runtime-core passes 1402 tests with 26 ignored. The patch applies cleanly to 3e9a95d3, whose library suite passes 1384 tests with 26 ignored using the same template fixtures. Ignored cases require CUDA, checkpoint/payload inputs, or manual CPU benchmarking. Nine bounded lifecycle model configurations and 361262 observed Rust transitions pass. Mutation checks detect all 8 TLA+ and 14 Rust faults, and restored-source checks pass. These checks assume truthful executor completion and drain signals and do not qualify CUDA execution. Signed-off-by: Martin Vit Design-Signed-Off-By: Codex (GPT-6); design-review=ed22 --- docs/TODO.txt | 7 + docs/core-design.md | 14 +- docs/prefix-cache-offload.md | 15 +- docs/runtime-core-design.md | 8 +- helios/src/cache.rs | 5 + helios/src/scheduler.rs | 20 ++ helios/src/scheduler/tests.rs | 172 ++++++++++++++++ helios/src/server/runtime.rs | 53 ++++- helios/src/server/runtime/phase_tests.rs | 237 +++++++++++++++++++++++ 9 files changed, 522 insertions(+), 9 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 98b5d3c58..61ba8080f 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -72,6 +72,13 @@ catalogs, host copy-out pressure, and tensor-parallel execution. See core-design.md#exact-endpoint-capture and scheduling-runtime-design.md. +[ ] Qualify capacity-blocked host restores and completion-time checkpoint recency + through exported Kimi K3.1 cores under concurrent long prompts, immediate + continuations, and aliased snapshot pressure. Compare reused tokens, request + latency, and throughput with equivalent clocks and cache budgets. Remove + after native serving confirms restoration progress and retention behavior; + CPU scheduler and worker tests do not establish serving performance. + [ ] Correct the 10-byte core payload fixtures in Orbit agent tests running_groups_are_stopped_and_outlive_their_controller_session and groups_run_together_on_disjoint_gpus_and_status_lists_them; their transfer diff --git a/docs/core-design.md b/docs/core-design.md index 89da5783f..4de1d4fc6 100644 --- a/docs/core-design.md +++ b/docs/core-design.md @@ -1528,10 +1528,16 @@ role, then consumed-token count, then checkpoint identity. Prompt and terminal endpoints have the lowest role, earlier message checkpoints follow, and the conversation anchor has the highest role. Demand recency takes precedence over role, so an idle conversation's anchor can be reclaimed before a recently used -endpoint. One successfully admitted logical request receives one demand epoch; -all its captures inherit that epoch. Cache reuse touches the matched checkpoint -and its ancestors. Duplicate publication retains the maximum role and epoch. -Preemption carries the epoch into readmission. +endpoint. Each successfully admitted logical request receives a demand epoch; +its captures inherit that epoch. Cache reuse touches the matched checkpoint +and its ancestors. Successful completion refreshes the terminal checkpoint and +its ancestors with a completion-time epoch, or the retained prefix when no +terminal checkpoint was captured. Cancellation after completed inference also +refreshes the retained prefix, including client stop sequences. This keeps a +long-running conversation recent when its response ends. Cancellation before +inference and execution failure do not refresh recency. Preemption carries the +admission epoch into readmission without refreshing it. Duplicate publication +retains the maximum role and epoch. The global allocator compares victims for both snapshot rows and physical page backing. A removable checkpoint is an unpinned leaf or an ancestor with exactly diff --git a/docs/prefix-cache-offload.md b/docs/prefix-cache-offload.md index d5846189d..607ea2b75 100644 --- a/docs/prefix-cache-offload.md +++ b/docs/prefix-cache-offload.md @@ -653,8 +653,19 @@ call from the worker returns without waiting. Admission consults the store after `plan_admission`: `lookup` runs above the GPU hit, the policy in section 2.10 decides whether to fetch, and -`admit_planned` receives the inbound request. A newly created ticket starts -the inbound job through `fetch`. On inbound failure the worker cancels each +`admit_planned` receives the inbound request. If capacity prevents reserving +the restore's pages and snapshot row, admission waits while existing requests, +inbound tickets, checkpoint pins, or fenced retirement may release resources. +Waiting plus estimated transfer time must remain below half the estimated +prefill time of the tokens gained. The worker retries after resource changes, +pin release, transfer completion, or wait-budget expiry; expiry is checked even +when resource counts stay unchanged. Other eligible requests can be admitted during this wait. +If no resource holder remains or the budget expires, admission tries recomputation. +If recomputation also lacks capacity, it waits for resource changes without +repeated timeout retries. A successful admission clears the wait accounting so +readmission after preemption starts a separate wait. Pooled lookups keep their +ticket and validated history across retries and recheck GPU residency. +A newly created ticket starts the inbound job through `fetch`. On inbound failure the worker cancels each waiter and pushes its `Incoming` to the front of the pending queue with host lookup disabled for that attempt. diff --git a/docs/runtime-core-design.md b/docs/runtime-core-design.md index 967c8ec94..43ad4cd27 100644 --- a/docs/runtime-core-design.md +++ b/docs/runtime-core-design.md @@ -725,8 +725,12 @@ Admission reserves the request's KV pages. System, prompt, and terminal snapshot acquire backing at their capture boundaries, evicting unpinned checkpoints when needed. If active requests or transfers hold all suitable backing, optional retention is skipped. An inbound host restore reserves both its row and pages -before transfer; if its snapshot prevents admission, the request recomputes its -prompt. Snapshot and page ownership remain exclusive through graph +before transfer. A capacity-blocked restore waits while requests, transfers, +or fenced retirement may release backing and its accumulated wait plus estimated +transfer time remains below half the estimated prefill time it replaces. Wait-budget expiry +permits a recompute attempt even without resource progress. With no remaining +resource holder, admission tries recomputation immediately. +Snapshot and page ownership remain exclusive through graph and transfer completion, including cancellation and duplicate publication. Once generation drains, unused output-page reservations are released before retaining the final checkpoint. diff --git a/helios/src/cache.rs b/helios/src/cache.rs index 573fb3461..815922a82 100644 --- a/helios/src/cache.rs +++ b/helios/src/cache.rs @@ -249,6 +249,11 @@ impl PrefixCheckpointCache { }) } + #[cfg(feature = "server")] + pub(crate) fn has_pins(&self) -> bool { + self.nodes.values().any(|node| node.direct_pins != 0) + } + pub(crate) fn single_child(&self, id: CheckpointId) -> Option { if self.nodes.get(&id)?.child_count != 1 { return None; diff --git a/helios/src/scheduler.rs b/helios/src/scheduler.rs index ef46d7b72..ef7a8ebd3 100644 --- a/helios/src/scheduler.rs +++ b/helios/src/scheduler.rs @@ -1136,6 +1136,15 @@ impl RequestScheduler { pub fn free_snapshot_count(&self) -> usize { self.free_snapshots.len() } + /// Whether requests, transfers, or retirement fences may release admission resources. + #[cfg(feature = "server")] + pub(crate) fn resources_in_flight(&self) -> bool { + self.slots.iter().any(|slot| slot.request.is_some() || slot.retiring) + || !self.cache.pending_retirement().is_empty() + || !self.retired.is_empty() + || !self.tickets.is_empty() + || self.cache.has_pins() + } pub fn has_available_slot(&self) -> bool { self.slots.iter().any(|slot| { slot.request.is_none() && !slot.retiring && slot.generation < i64::MAX as u64 @@ -2864,6 +2873,11 @@ impl RequestScheduler { }, ready_after: request.last_use, }); + let refresh_recency = !request.preempted + && request.error_code.is_none() + && (publish || request.consumed_tokens > request.admission_reused_tokens + || request.generated_tokens > 0); + let prefix = request.prefix; let result = match &publication { Some(proposal) => { let history = request.history.clone(); @@ -2871,6 +2885,12 @@ impl RequestScheduler { } None => None, }; + // Completed work is conversation activity, including a client stop after progress. + // Preemption and cancellation before inference must not advance cache recency. + if refresh_recency && let Some(id) = result.map(PublishResult::id).or(prefix) { + let epoch = self.cache.new_use_epoch()?; + self.cache.touch(id, epoch)?; + } let mut request = self.slots[handle.slot as usize].request.take().unwrap(); if let Some(guard) = request.anchor_guard.take() { self.release_snapshot(guard); } let mut snapshot = request.terminal_snapshot; diff --git a/helios/src/scheduler/tests.rs b/helios/src/scheduler/tests.rs index 8c182a1e7..ee1b1fa74 100644 --- a/helios/src/scheduler/tests.rs +++ b/helios/src/scheduler/tests.rs @@ -1143,6 +1143,7 @@ fn concurrent_identical_terminal_publications_release_duplicate_resources() { let second = scheduler.admit(spec(64, 1)).unwrap(); init(&mut scheduler, 1); let mut checkpoint = None; + let mut completion_epoch = 0; for (handle, fence) in [(first, 2), (second, 4)] { let step = scheduler.plan().unwrap(); assert_eq!(step.lanes[0].request, handle); @@ -1156,6 +1157,9 @@ fn concurrent_identical_terminal_publications_release_duplicate_resources() { .unwrap(); freeze(&mut scheduler, handle, fence + 1); let result = scheduler.finish(handle).unwrap(); + let epoch = scheduler.cache().checkpoint(result.unwrap()).unwrap().retention_rank().use_epoch; + assert!(epoch > completion_epoch); + completion_epoch = epoch; if checkpoint.is_none() { checkpoint = result; } else { @@ -1175,6 +1179,174 @@ fn concurrent_identical_terminal_publications_release_duplicate_resources() { scheduler.admit(unrelated).unwrap(); } +#[test] +fn a_request_that_finishes_last_outranks_requests_admitted_while_it_ran() { + let mut scheduler = scheduler(2, 8, 4); + let long = scheduler.admit(spec(64, 2)).unwrap(); + let mut other = spec(64, 1); + other.prompt[0] = 999; + let short = scheduler.admit(other).unwrap(); + init(&mut scheduler, 1); + let step = scheduler.plan().unwrap(); + assert_eq!( + (step.kind, step.lanes[0].request), + (GraphKind::Prefill, long) + ); + scheduler.commit(&step, Fence(2)).unwrap(); + scheduler + .complete( + Fence(2), + &records(long, 2, 64, 1, 88, 1), + Default::default(), + ) + .unwrap(); + let step = scheduler.plan().unwrap(); + assert_eq!( + (step.kind, step.lanes[0].request), + (GraphKind::Prefill, short) + ); + scheduler.commit(&step, Fence(3)).unwrap(); + scheduler + .complete( + Fence(3), + &records(short, 3, 64, 1, 89, 2), + Default::default(), + ) + .unwrap(); + freeze(&mut scheduler, short, 4); + let short_checkpoint = scheduler.finish(short).unwrap().unwrap(); + let step = scheduler.plan().unwrap(); + assert_eq!( + (step.kind, step.lanes[0].request), + (GraphKind::Snapshot, long) + ); + scheduler.commit(&step, Fence(5)).unwrap(); + scheduler + .complete( + Fence(5), + &state_records(&scheduler, &step, 5), + Default::default(), + ) + .unwrap(); + let step = scheduler.plan().unwrap(); + assert_eq!( + (step.kind, step.lanes[0].request), + (GraphKind::Decode, long) + ); + scheduler.commit(&step, Fence(6)).unwrap(); + scheduler + .complete( + Fence(6), + &records(long, 6, 65, 2, 90, 2), + Default::default(), + ) + .unwrap(); + freeze(&mut scheduler, long, 7); + let long_checkpoint = scheduler.finish(long).unwrap().unwrap(); + // The request admitted first finished last, so its conversation is the most recent one. + assert_eq!( + scheduler.cache().eviction_candidate(None, false), + Some(short_checkpoint) + ); + assert!( + scheduler + .cache() + .checkpoint(long_checkpoint) + .unwrap() + .retention_rank() + > scheduler + .cache() + .checkpoint(short_checkpoint) + .unwrap() + .retention_rank() + ); +} + +#[test] +fn cancellation_before_inference_and_preemption_preserve_checkpoint_demand_recency() { + for preempted in [false, true] { + let mut scheduler = scheduler(1, 8, 4); + let handle = scheduler.admit(spec(64, 4)).unwrap(); + init(&mut scheduler, 1); + let step = scheduler.plan().unwrap(); + scheduler.commit(&step, Fence(2)).unwrap(); + scheduler + .complete( + Fence(2), + &records(handle, 2, 64, 1, 88, 1), + Default::default(), + ) + .unwrap(); + retain_prompt(&mut scheduler, 3); + let id = scheduler.request(handle).unwrap().prefix.unwrap(); + let rank; + if preempted { + rank = scheduler.cache().checkpoint(id).unwrap().retention_rank(); + scheduler.finish_early(handle, true).unwrap(); + scheduler.finish(handle).unwrap(); + } else { + scheduler.cancel(handle).unwrap(); + let handle = scheduler.admit(spec(64, 4)).unwrap(); + rank = scheduler.cache().checkpoint(id).unwrap().retention_rank(); + scheduler.cancel(handle).unwrap(); + } + assert_eq!( + scheduler.cache().checkpoint(id).unwrap().retention_rank(), + rank + ); + } +} + +#[test] +fn completion_and_client_stop_refresh_the_retained_prefix_only_without_execution_errors() { + for (failed, cancelled) in [(false, false), (false, true), (true, false), (true, true)] { + let mut scheduler = scheduler(1, 8, 4); + let handle = scheduler.admit(spec(64, 4)).unwrap(); + init(&mut scheduler, 1); + let step = scheduler.plan().unwrap(); + scheduler.commit(&step, Fence(2)).unwrap(); + scheduler + .complete( + Fence(2), + &records(handle, 2, 64, 1, 88, 1), + Default::default(), + ) + .unwrap(); + retain_prompt(&mut scheduler, 3); + let id = scheduler.request(handle).unwrap().prefix.unwrap(); + let epoch = scheduler + .cache() + .checkpoint(id) + .unwrap() + .retention_rank() + .use_epoch; + if failed { + scheduler.request_mut(handle).unwrap().error_code = Some(1); + } + // Finishing at the retained endpoint needs no additional snapshot. + if cancelled { + scheduler.cancel(handle).unwrap(); + } else { + scheduler.finish_early(handle, false).unwrap(); + assert!( + scheduler + .request(handle) + .unwrap() + .terminal_snapshot + .is_none() + ); + assert_eq!(scheduler.finish(handle).unwrap(), Some(id)); + } + let completed_epoch = scheduler + .cache() + .checkpoint(id) + .unwrap() + .retention_rank() + .use_epoch; + assert_eq!(completed_epoch > epoch, !failed); + } +} + #[test] fn failed_terminal_snapshot_never_publishes_uninitialized_storage() { let mut scheduler = scheduler(1, 8, 2); diff --git a/helios/src/server/runtime.rs b/helios/src/server/runtime.rs index 0988eeb1f..9fced8fc0 100644 --- a/helios/src/server/runtime.rs +++ b/helios/src/server/runtime.rs @@ -201,6 +201,31 @@ struct Incoming { /// Replaced on readmission and counted once when this request ends. host_lookup_outcome: Option, pool_plan: Option, + restore_wait: RestoreWait, +} + +/// Capacity waiting is charged once per admission episode. Expiry wakes a blocked request +/// once; a failed recompute admission still waits for resources instead of polling lookups. +#[derive(Default)] +struct RestoreWait { + started: Option, + retry_at: Option, +} + +impl RestoreWait { + fn defer(&mut self, gained: u64, transfer_seconds: f64, prefill_rate: f64) -> bool { + let now = std::time::Instant::now(); + let started = *self.started.get_or_insert(now); + let waited = now.duration_since(started).as_secs_f64(); + let budget = 0.5 * gained as f64 / prefill_rate.max(1.0) - transfer_seconds; + self.retry_at = None; + if flare_selene::worth_transfer(gained, transfer_seconds + waited, prefill_rate) + && let Ok(remaining) = std::time::Duration::try_from_secs_f64(budget - waited) + { + self.retry_at = now.checked_add(remaining); + } + self.retry_at.is_some() + } } impl Drop for Incoming { fn drop(&mut self) { @@ -235,6 +260,13 @@ impl Incoming { } } + fn poll_restore_wait(&mut self, now: std::time::Instant) { + if self.restore_wait.retry_at.is_some_and(|deadline| now >= deadline) { + self.restore_wait.retry_at = None; + self.blocked = None; + } + } + fn awaits_pool(&self, now: std::time::Instant) -> bool { self.pool_lookup.as_ref().is_some_and(|ticket| { matches!(ticket.state(), flare_selene::pool::LookupState::Pending) @@ -853,6 +885,7 @@ impl ModelRuntime { pool_lookup_started: None, host_lookup_outcome: None, pool_plan: None, + restore_wait: RestoreWait::default(), }; let enqueue_ns = observation .filter(|timestamps| *timestamps) @@ -1281,11 +1314,13 @@ impl<'a> Worker<'a> { } } 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)) { if let Some(store) = self.store.as_mut().filter(|store| store.pooled()) { begin_pool_lookup(&mut self.scheduler, store.as_mut(), incoming); } incoming.poll_pool_lookup(); + incoming.poll_restore_wait(now); } let stats = self.scheduler.stats(); let resources = ( @@ -1341,6 +1376,7 @@ impl<'a> Worker<'a> { checkpoint_accounting, self.prefill_rate, self.metrics, + &mut incoming.restore_wait, ) .map(|(handle, outcome)| { if outcome.is_some() { @@ -1458,6 +1494,7 @@ impl<'a> Worker<'a> { incoming.pool_lookup = None; incoming.pool_plan = None; } + incoming.restore_wait = RestoreWait::default(); incoming.notify_admission(Ok(())); self.active[slot] = Some(Active { request: handle, @@ -2267,6 +2304,9 @@ impl<'a> Worker<'a> { } StoreEvent::Fetched { key, result } => { requeued.extend(self.scheduler.finish_inbound(key, result.is_ok())?); + // A ticket without waiters can become an evictable checkpoint without + // changing free counts. Its completion must still wake admissions. + released = true; } StoreEvent::ExportRequested { export, @@ -2623,6 +2663,7 @@ fn admit_with_host_store( accounting: Option, prefill_rate: f64, metrics: &super::metrics::Metrics, + restore_wait: &mut RestoreWait, ) -> Result<(RequestHandle, Option)> { let plan = match queued_plan { Some(plan) => scheduler.refresh_admission_plan(plan)?, @@ -2662,9 +2703,18 @@ fn admit_with_host_store( consumed_tokens: hit.consumed_tokens, pages: hit.pages, }; + let gained = hit.consumed_tokens - plan.resident_tokens(); let admitted = match scheduler.admit_planned_with_checkpoint_accounting(spec.clone(), plan, Some(inbound), accounting.clone()) { Ok(admitted) => admitted, - Err(Error::Admission(AdmissionError::Capacity(_))) => { + Err(Error::Admission(AdmissionError::Capacity(failure))) => { + // Resource holders may release snapshot backing without another admission. + // Bound that wait by the restore's estimated advantage over prefill. + if scheduler.resources_in_flight() + && restore_wait.defer(gained, hit.estimated_seconds, prefill_rate) + { + return Err(Error::Admission(AdmissionError::Capacity(failure))); + } + restore_wait.retry_at = None; let handle = admit_with_checkpoint_accounting(scheduler, spec, accounting.clone())?; scheduler.record_host_lookup(); return Ok((handle, Some(LookupOutcome::CapacityRejected))); @@ -3088,6 +3138,7 @@ mod tests { pool_lookup_started: None, host_lookup_outcome: None, pool_plan: None, + restore_wait: RestoreWait::default(), }; ( incoming, diff --git a/helios/src/server/runtime/phase_tests.rs b/helios/src/server/runtime/phase_tests.rs index d46447917..2ad7cdea6 100644 --- a/helios/src/server/runtime/phase_tests.rs +++ b/helios/src/server/runtime/phase_tests.rs @@ -257,6 +257,7 @@ impl Fixture { pool_lookup_started: None, host_lookup_outcome: None, pool_plan: None, + restore_wait: RestoreWait::default(), }, Generation { events: receiver, @@ -2426,6 +2427,242 @@ fn host_hit_recomputes_when_snapshot_backing_would_prevent_admission() { assert!(fake_store(&mut worker).fetched.is_empty()); } +#[test] +fn host_hit_waits_for_snapshot_backing_held_by_a_running_request() { + for pooled in [false, true] { + let fixture = Fixture::new(); + let (sender, receiver) = mpsc::channel(); + let mut worker = fixture.worker(receiver); + // Every snapshot row aliases pages reserved by the running request. + worker + .scheduler + .share_snapshot_pages(&vec![0..2; 16]) + .unwrap(); + let (running, running_generation) = fixture.incoming(vec![7; 70], 4); + sender.send(vec![running]).unwrap(); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + let (requests, _generations): (Vec<_>, Vec<_>) = + (0..2).map(|_| fixture.incoming(vec![0; 70], 4)).unzip(); + let mut history = crate::cache::PrefixHistory::new(fixture.config.identity); + history.append(&requests[0].prompt.tokens, &[]).unwrap(); + let mut store = FakeStore::new(Some(host_hit(&history, 70))); + store.pooled = pooled; + worker.attach_store(Some(Box::new(store))); + worker.prefill_rate = 1.0; + sender.send(requests).unwrap(); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + assert_eq!(worker.pending.len(), 2); + assert_eq!(worker.scheduler.stats().host_lookups, 0); + assert!(fake_store(&mut worker).fetched.is_empty()); + for incoming in &worker.pending { + assert!(incoming.restore_wait.started.is_some()); + assert_eq!(incoming.pool_plan.is_some(), pooled); + } + let attempts = fake_store(&mut worker).tickets_seen.len(); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(false)); + assert_eq!(fake_store(&mut worker).tickets_seen.len(), attempts); + + running_generation.cancelled.store(true, Ordering::Release); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + assert!(worker.pending.is_empty()); + for active in worker.active.iter().flatten() { + let live = worker.scheduler.request(active.request).unwrap(); + assert_eq!( + ( + live.phase, + live.consumed_tokens, + live.reused_prompt_tokens() + ), + (RequestPhase::Inbound, 70, 70) + ); + assert!(active.incoming.restore_wait.started.is_none()); + } + assert_eq!(worker.scheduler.stats().host_lookups, 2); + assert_eq!(worker.scheduler.stats().inbound_waiting, 2); + let store = fake_store(&mut worker); + assert_eq!(store.fetched.len(), 1); + assert!(store.tickets_seen.iter().all(|seen| *seen == pooled)); + assert_eq!(store.begun.len(), if pooled { 2 } else { 0 }); + } +} + +#[test] +fn host_restore_wait_expires_without_a_resource_change() { + let fixture = Fixture::new(); + let (sender, receiver) = mpsc::channel(); + let mut worker = fixture.worker(receiver); + worker + .scheduler + .share_snapshot_pages(&vec![0..2; 16]) + .unwrap(); + let (running, _running_generation) = fixture.incoming(vec![7; 70], 4); + sender.send(vec![running]).unwrap(); + let _ = worker.admit().unwrap(); + let (incoming, _generation) = fixture.incoming(vec![0; 70], 4); + let mut history = crate::cache::PrefixHistory::new(fixture.config.identity); + history.append(&incoming.prompt.tokens, &[]).unwrap(); + worker.attach_store(Some(Box::new(FakeStore::new(Some(host_hit(&history, 70)))))); + worker.prefill_rate = 1.0; + sender.send(vec![incoming]).unwrap(); + let _ = worker.admit().unwrap(); + assert_eq!(worker.pending.len(), 1); + let expired = std::time::Instant::now() - std::time::Duration::from_secs(60); + worker.pending[0].restore_wait.started = Some(expired); + worker.pending[0].restore_wait.retry_at = Some(expired); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + assert!(worker.pending.is_empty()); + let active = worker.active[1].as_ref().unwrap(); + assert_eq!( + worker.scheduler.request(active.request).unwrap().phase, + RequestPhase::Initialize + ); + assert!(matches!( + active.incoming.host_lookup_outcome, + Some(crate::offload::LookupOutcome::CapacityRejected) + )); + assert!(fake_store(&mut worker).fetched.is_empty()); +} + +#[test] +fn host_restore_wait_does_not_block_other_requests_or_cancellation() { + let fixture = Fixture::new(); + let (sender, receiver) = mpsc::channel(); + let mut worker = fixture.worker(receiver); + worker + .scheduler + .share_snapshot_pages(&vec![0..2; 16]) + .unwrap(); + let (running, _running_generation) = fixture.incoming(vec![7; 70], 4); + sender.send(vec![running]).unwrap(); + let _ = worker.admit().unwrap(); + let (waiting, waiting_generation) = fixture.incoming(vec![0; 70], 4); + let (unrelated, _unrelated_generation) = fixture.incoming(vec![1; 70], 4); + let mut history = crate::cache::PrefixHistory::new(fixture.config.identity); + history.append(&waiting.prompt.tokens, &[]).unwrap(); + let mut store = FakeStore::new(Some(host_hit(&history, 70))); + store.pooled = true; + let withdrawn = store.withdrawn.clone(); + worker.attach_store(Some(Box::new(store))); + worker.prefill_rate = 1.0; + sender.send(vec![waiting, unrelated]).unwrap(); + let _ = worker.admit().unwrap(); + assert_eq!(worker.pending.len(), 1); + assert_eq!(worker.scheduler.stats().active_requests, 2); + assert_eq!(withdrawn.load(Ordering::Relaxed), 1); + waiting_generation.cancelled.store(true, Ordering::Release); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(true)); + assert!(worker.pending.is_empty()); + assert_eq!(withdrawn.load(Ordering::Relaxed), 2); + assert_eq!(worker.scheduler.stats().active_requests, 2); + assert!(fake_store(&mut worker).fetched.is_empty()); +} + +#[test] +fn host_restore_wait_expires_once_when_recomputation_also_needs_capacity() { + let mut fixture = Fixture::new(); + fixture.config.limits.pages = 3; + let (sender, receiver) = mpsc::channel(); + let mut worker = fixture.worker(receiver); + let (running, _running_generation) = fixture.incoming(vec![7; 70], 4); + sender.send(vec![running]).unwrap(); + let _ = worker.admit().unwrap(); + let (incoming, _generation) = fixture.incoming(vec![0; 70], 4); + let mut history = crate::cache::PrefixHistory::new(fixture.config.identity); + history.append(&incoming.prompt.tokens, &[]).unwrap(); + worker.attach_store(Some(Box::new(FakeStore::new(Some(host_hit(&history, 70)))))); + worker.prefill_rate = 1.0; + sender.send(vec![incoming]).unwrap(); + let _ = worker.admit().unwrap(); + let expired = std::time::Instant::now() - std::time::Duration::from_secs(60); + worker.pending[0].restore_wait.started = Some(expired); + worker.pending[0].restore_wait.retry_at = Some(expired); + let attempts = fake_store(&mut worker).tickets_seen.len(); + let _ = worker.admit().unwrap(); + assert_eq!(fake_store(&mut worker).tickets_seen.len(), attempts + 1); + assert_eq!(worker.pending.len(), 1); + assert!(worker.pending[0].restore_wait.retry_at.is_none()); + assert_eq!(worker.admit().unwrap(), ControlFlow::Continue(false)); + assert_eq!(fake_store(&mut worker).tickets_seen.len(), attempts + 1); +} + +#[test] +fn host_restore_waits_for_a_transfer_after_its_last_waiter_is_cancelled() { + for success in [false, true] { + let mut fixture = Fixture::new(); + fixture.config.limits.snapshots = 1; + let (sender, receiver) = mpsc::channel(); + let mut worker = fixture.worker(receiver); + let (first, first_generation) = fixture.incoming(vec![1; 70], 4); + let mut history = crate::cache::PrefixHistory::new(fixture.config.identity); + history.append(&first.prompt.tokens, &[]).unwrap(); + worker.attach_store(Some(Box::new(FakeStore::new(Some(host_hit(&history, 70)))))); + worker.prefill_rate = 1.0; + sender.send(vec![first]).unwrap(); + let _ = worker.admit().unwrap(); + let (_, ticket) = fake_store(&mut worker).fetched.pop().unwrap(); + first_generation.cancelled.store(true, Ordering::Release); + let _ = worker.admit().unwrap(); + assert_eq!(worker.scheduler.stats().active_requests, 0); + assert_eq!(worker.scheduler.free_snapshot_count(), 0); + + let (incoming, _generation) = fixture.incoming(vec![0; 70], 4); + let mut history = crate::cache::PrefixHistory::new(fixture.config.identity); + history.append(&incoming.prompt.tokens, &[]).unwrap(); + fake_store(&mut worker).hit = Some(host_hit(&history, 70)); + sender.send(vec![incoming]).unwrap(); + let _ = worker.admit().unwrap(); + assert_eq!(worker.pending.len(), 1); + assert_eq!(worker.scheduler.stats().active_requests, 0); + fake_store(&mut worker) + .events + .push_back(flare_selene::StoreEvent::Fetched { + key: ticket.key, + result: if success { + Ok(1 << 20) + } else { + Err("transfer failed".into()) + }, + }); + worker.service_store().unwrap(); + let _ = worker.admit().unwrap(); + assert!(worker.pending.is_empty()); + assert_eq!(worker.scheduler.stats().inbound_waiting, 1); + assert_eq!(fake_store(&mut worker).fetched.len(), 1); + } +} + +#[test] +fn host_restore_waits_for_a_copyout_pin_without_live_requests() { + let mut fixture = Fixture::new(); + fixture.config.limits.snapshots = 1; + let (sender, receiver) = mpsc::channel(); + let mut worker = fixture.worker(receiver); + let mut store = FakeStore::new(None); + store + .store_outcomes + .push_back(flare_selene::StoreOutcome::Queued); + worker.attach_store(Some(Box::new(store))); + let id = unpinned_checkpoint(&mut worker, 1, 64); + worker.service_store().unwrap(); + assert_eq!(pins(&worker, id), 1); + assert_eq!(worker.scheduler.stats().active_requests, 0); + let (incoming, _generation) = fixture.incoming(vec![0; 70], 4); + let mut history = crate::cache::PrefixHistory::new(fixture.config.identity); + history.append(&incoming.prompt.tokens, &[]).unwrap(); + fake_store(&mut worker).hit = Some(host_hit(&history, 70)); + worker.prefill_rate = 1.0; + sender.send(vec![incoming]).unwrap(); + let _ = worker.admit().unwrap(); + assert_eq!(worker.pending.len(), 1); + assert!(fake_store(&mut worker).fetched.is_empty()); + complete_store(&mut worker, id, true); + worker.service_store().unwrap(); + let _ = worker.admit().unwrap(); + assert!(worker.pending.is_empty()); + assert_eq!(worker.scheduler.stats().inbound_waiting, 1); + assert_eq!(fake_store(&mut worker).fetched.len(), 1); +} + #[test] fn failed_restores_readmit_the_request_without_the_host_store() { for reject_at_fetch in [false, true] { From 8999ad14135acfb7ca0aa563ff7216d8e5e34c7d Mon Sep 17 00:00:00 2001 From: Martin Vit Date: Sat, 14 Nov 2026 22:43:24 +0000 Subject: [PATCH 2/3] Refresh prefix-cache recency only for selected snapshots Reusing or completing a long prefix refreshed every ancestor's eviction rank, protecting unused continuation rows that compete with KV pages and other conversations' captures. Descendants need ancestor pages, but only the selected checkpoint's snapshot; compaction can preserve those pages. Make PrefixCheckpointCache::touch update only the selected checkpoint's monotonic demand epoch. Reuse, promotion, duplicate publication, and completion use that rule. Older unpinned single-child rows can be compacted without changing descendant pages, branch pins, or retirement fences. Role ordering and capture budgets remain unchanged. Unused prompt and message rows can age even when a descendant finishes. Core formats and prepared graphs remain compatible without re-export. The implemented change is expected to reduce storage skips and retain more independently used prefixes under snapshot pressure. CPU regressions qualify recency and ownership behavior; native serving performance remains unqualified and is tracked in docs/TODO.txt. Five focused checks fail with PR #298's implementation and pass with this change. They cover slot and aliased-page pressure, admission, duplicate publication, promotion, and completion recency. Compaction preserves pages and fences at 64-, 128-, 256-, and 2048-token page geometries. The Helios server,runtime-core CPU suite passes 1405 tests with 26 ignored when run serially. A parallel run had one failure in unchanged payload-collection code; that test passes in isolation and in the serial suite. Ignored cases need CUDA, external checkpoint/payload fixtures, or manual CPU benchmarks. The patch applies to 3e9a95d3 plus PR #298; that base passes 1387 library tests with 26 ignored using the same serial CPU configuration. Signed-off-by: Martin Vit Design-Signed-Off-By: Codex (GPT-6); design-review=ed22 --- docs/TODO.txt | 7 +- docs/core-design.md | 20 +++-- docs/prefix-cache-offload.md | 11 ++- helios/src/cache.rs | 8 +- helios/src/cache/tests.rs | 121 ++++++++++++++++++++++++++-- helios/src/scheduler/tests.rs | 146 +++++++++++++++++++++++++++++++++- 6 files changed, 288 insertions(+), 25 deletions(-) diff --git a/docs/TODO.txt b/docs/TODO.txt index 61ba8080f..08de8f7d7 100644 --- a/docs/TODO.txt +++ b/docs/TODO.txt @@ -72,11 +72,12 @@ catalogs, host copy-out pressure, and tensor-parallel execution. See core-design.md#exact-endpoint-capture and scheduling-runtime-design.md. -[ ] Qualify capacity-blocked host restores and completion-time checkpoint recency +[ ] Qualify capacity-blocked host restores and demand recency for individual checkpoints through exported Kimi K3.1 cores under concurrent long prompts, immediate continuations, and aliased snapshot pressure. Compare reused tokens, request - latency, and throughput with equivalent clocks and cache budgets. Remove - after native serving confirms restoration progress and retention behavior; + latency, throughput, snapshot backing pages, and storage skips with equivalent + clocks and cache budgets; include prompt-end and message-boundary follow-ups. + Remove after native serving confirms restoration progress and retention behavior; CPU scheduler and worker tests do not establish serving performance. [ ] Correct the 10-byte core payload fixtures in Orbit agent tests diff --git a/docs/core-design.md b/docs/core-design.md index 4de1d4fc6..cbb6ea29d 100644 --- a/docs/core-design.md +++ b/docs/core-design.md @@ -1529,15 +1529,21 @@ endpoints have the lowest role, earlier message checkpoints follow, and the conversation anchor has the highest role. Demand recency takes precedence over role, so an idle conversation's anchor can be reclaimed before a recently used endpoint. Each successfully admitted logical request receives a demand epoch; -its captures inherit that epoch. Cache reuse touches the matched checkpoint -and its ancestors. Successful completion refreshes the terminal checkpoint and -its ancestors with a completion-time epoch, or the retained prefix when no -terminal checkpoint was captured. Cancellation after completed inference also -refreshes the retained prefix, including client stop sequences. This keeps a -long-running conversation recent when its response ends. Cancellation before +its captures inherit that epoch. Cache reuse touches only the matched checkpoint's +snapshot. Successful completion refreshes the terminal checkpoint with a +completion-time epoch, or the retained prefix when no terminal checkpoint was +captured. Ancestor snapshots retain their own demand epochs: sharing their pages +does not require restoring their rows. Older single-child ancestors can therefore +be compacted under pressure without discarding the recently used descendant's +page chain. Cancellation after completed inference also refreshes the retained +prefix, including client stop sequences. This keeps a long-running conversation +recent when its response ends. Cancellation before inference and execution failure do not refresh recency. Preemption carries the admission epoch into readmission without refreshing it. Duplicate publication -retains the maximum role and epoch. +retains the maximum role and epoch of the matching checkpoint only. A prompt-end +or message checkpoint gains recency when reused directly; completion of a +descendant does not refresh it. Branch points and direct pins still constrain +which checkpoints are removable. The global allocator compares victims for both snapshot rows and physical page backing. A removable checkpoint is an unpinned leaf or an ancestor with exactly diff --git a/docs/prefix-cache-offload.md b/docs/prefix-cache-offload.md index 607ea2b75..85860f405 100644 --- a/docs/prefix-cache-offload.md +++ b/docs/prefix-cache-offload.md @@ -257,9 +257,14 @@ unrestorable. GPU eviction ranks eligible checkpoints by logical-request demand epoch, retention role, consumed-token count, and identity, as specified in -[checkpoint lifetime](core-design.md#branching-and-lifetime). Host-store eviction -independently removes the least recently used unpinned leaf; when every leaf is -pinned, it compacts the least recently used unpinned single-child ancestor by +[checkpoint lifetime](core-design.md#branching-and-lifetime). GPU demand recency +belongs to the selected snapshot, not every ancestor supplying its pages. +Pressure can compact an older single-child ancestor while preserving the reused +descendant's complete page chain and reporting its compaction heir. Direct +copy-out pins and outstanding GPU-use fences still protect transfer resources. +Host-store eviction independently removes the least recently used unpinned leaf; +when every leaf is pinned, it compacts the least recently used unpinned +single-child ancestor by dropping its row and keeping its pages. A compacted host node stays in the tree as page-only, no longer matches lookups, and continues to supply chain pages. A node is evictable only when its store's policy allows it: the memory store standalone evicts any unpinned node, the diff --git a/helios/src/cache.rs b/helios/src/cache.rs index 815922a82..7db476c06 100644 --- a/helios/src/cache.rs +++ b/helios/src/cache.rs @@ -306,11 +306,11 @@ impl PrefixCheckpointCache { Ok(self.clock) } + /// Refresh this snapshot's demand; sharing ancestor pages does not reuse their snapshots. pub fn touch(&mut self, id: CheckpointId, use_epoch: u64) -> Result<()> { - for ancestor in self.chain(id)? { - let node = self.nodes.get_mut(&ancestor).unwrap(); - node.accessed = node.accessed.max(use_epoch); - } + self.checkpoint(id)?; + let node = self.nodes.get_mut(&id).unwrap(); + node.accessed = node.accessed.max(use_epoch); Ok(()) } diff --git a/helios/src/cache/tests.rs b/helios/src/cache/tests.rs index 4d9b3d460..27559367e 100644 --- a/helios/src/cache/tests.rs +++ b/helios/src/cache/tests.rs @@ -1144,18 +1144,127 @@ fn retention_prioritizes_demand_epoch_before_role_and_promotes_duplicates() { } #[test] -fn lookup_is_read_only_and_admission_touch_refreshes_ancestors() { +fn lookup_is_read_only_and_touch_refreshes_only_the_selected_snapshot() { let mut cache = cache(); let history = history(2, 0); - let parent = cache.publish_with_retention(&history, &proposal(None, 64, &[0], 0, 0), RetentionRole::Anchor, 1).unwrap().id(); - let child = cache.publish_with_retention(&history, &proposal(Some(parent), 128, &[1], 1, 0), RetentionRole::Endpoint, 1).unwrap().id(); + let parent = cache + .publish_with_retention( + &history, + &proposal(None, 64, &[0], 0, 0), + RetentionRole::Anchor, + 1, + ) + .unwrap() + .id(); + let child = cache + .publish_with_retention( + &history, + &proposal(Some(parent), 128, &[1], 1, 0), + RetentionRole::Endpoint, + 1, + ) + .unwrap() + .id(); cache.lookup(&history).unwrap(); - assert_eq!(cache.checkpoint(child).unwrap().retention_rank().use_epoch, 1); + assert_eq!( + cache.checkpoint(child).unwrap().retention_rank().use_epoch, + 1 + ); cache.new_use_epoch().unwrap(); let epoch = cache.new_use_epoch().unwrap(); cache.touch(child, epoch).unwrap(); - assert_eq!(cache.checkpoint(parent).unwrap().retention_rank().use_epoch, epoch); - assert_eq!(cache.checkpoint(child).unwrap().retention_rank().use_epoch, epoch); + assert_eq!( + cache.checkpoint(parent).unwrap().retention_rank().use_epoch, + 1 + ); + assert_eq!( + cache.checkpoint(child).unwrap().retention_rank().use_epoch, + epoch + ); + cache.touch(child, 1).unwrap(); + assert_eq!( + cache.checkpoint(child).unwrap().retention_rank().use_epoch, + epoch + ); + assert!(cache.touch(CheckpointId::new(999), epoch).is_err()); +} + +#[test] +fn duplicate_publication_and_promotion_do_not_refresh_ancestor_snapshots() { + for page_tokens in [64, 128, 256, 2048] { + let mut cache = PrefixCheckpointCache::new([7; 32], 32, 32, page_tokens).unwrap(); + let history = history((2 * page_tokens / 64) as u32, 0); + let endpoint = page_tokens as u64; + let parent = cache + .publish_with_retention( + &history, + &proposal(None, endpoint, &[0], 0, 0), + RetentionRole::Anchor, + 1, + ) + .unwrap() + .id(); + let child = cache + .publish_with_retention( + &history, + &proposal(Some(parent), 2 * endpoint, &[1], 1, 0), + RetentionRole::Endpoint, + 2, + ) + .unwrap() + .id(); + let duplicate = cache + .publish_with_retention( + &history, + &proposal(Some(parent), 2 * endpoint, &[2], 2, 5), + RetentionRole::Message, + 3, + ) + .unwrap(); + assert_eq!(duplicate.id(), child); + assert_eq!( + cache.checkpoint(parent).unwrap().retention_rank().use_epoch, + 1 + ); + cache.promote(child, RetentionRole::Anchor, 4).unwrap(); + cache.promote(child, RetentionRole::Endpoint, 2).unwrap(); + assert_eq!( + cache.checkpoint(parent).unwrap().retention_rank().use_epoch, + 1 + ); + assert_eq!( + cache.checkpoint(child).unwrap().retention_rank(), + RetentionRank { + use_epoch: 4, + role: RetentionRole::Anchor, + consumed_tokens: 2 * endpoint, + } + ); + // Recency is local to the snapshot; outstanding GPU reads still protect shared pages. + let retired = cache.evict(EvictionTarget { + pages: 0, + snapshots: 1, + }); + assert_eq!(retired.retired[0].checkpoint, parent); + assert_eq!(retired.retired[0].retire_after, Fence(5)); + assert_eq!(cache.page_chain(child).unwrap(), [PageId(0), PageId(1)]); + assert!( + cache + .advance_completed(Fence(4)) + .unwrap() + .reusable + .snapshots + .is_empty() + ); + assert_eq!( + cache + .advance_completed(Fence(5)) + .unwrap() + .reusable + .snapshots, + [SnapshotId(0)] + ); + } } #[test] diff --git a/helios/src/scheduler/tests.rs b/helios/src/scheduler/tests.rs index ee1b1fa74..892c032b9 100644 --- a/helios/src/scheduler/tests.rs +++ b/helios/src/scheduler/tests.rs @@ -1180,7 +1180,122 @@ fn concurrent_identical_terminal_publications_release_duplicate_resources() { } #[test] -fn a_request_that_finishes_last_outranks_requests_admitted_while_it_ran() { +fn snapshot_pressure_reclaims_untouched_ancestors_of_a_reused_prefix() { + capture_under_reused_chain_pressure(0); +} + +#[test] +fn page_pressure_reclaims_untouched_ancestors_of_a_reused_prefix() { + capture_under_reused_chain_pressure(16); +} + +fn capture_under_reused_chain_pressure(alias_pages: u32) { + let rows = if alias_pages == 0 { 9 } else { 10 }; + let mut scheduler = scheduler(2, 64.max(32 + rows * alias_pages), rows); + scheduler.enable_publications(); + scheduler.enable_evictions(); + scheduler + .share_snapshot_pages( + &(0..rows) + .map(|row| 32 + row * alias_pages..32 + (row + 1) * alias_pages) + .collect::>(), + ) + .unwrap(); + let long_history = history(512); + let mut chain = Vec::new(); + for index in 0..8 { + let epoch = scheduler.cache.new_use_epoch().unwrap(); + let snapshot = scheduler.reserve_snapshot(0).unwrap(); + let page = scheduler.free_pages.pop_first().unwrap(); + let consumed = (index + 1) * 64; + let id = scheduler + .cache + .publish_with_retention( + &long_history, + &Publication { + parent: chain.last().copied(), + consumed_tokens: consumed, + tail_pages: vec![page], + snapshot: StateSnapshot { + id: snapshot, + consumed_tokens: consumed, + }, + ready_after: Fence(0), + }, + RetentionRole::Anchor, + epoch, + ) + .unwrap() + .id(); + scheduler.record_publication(id); + chain.push(id); + } + let tip = *chain.last().unwrap(); + let pages = scheduler.cache.page_chain(tip).unwrap(); + let mut pending_spec = spec(64, 1); + pending_spec.prompt.fill(999); + let pending = scheduler.admit(pending_spec).unwrap(); + let mut other_history = PrefixHistory::new([9; 32]); + other_history.append(&[888; 64], &[]).unwrap(); + let epoch = scheduler.cache.new_use_epoch().unwrap(); + let snapshot = scheduler.reserve_snapshot(0).unwrap(); + let page = scheduler.free_pages.pop_first().unwrap(); + let other = scheduler + .cache + .publish_with_retention( + &other_history, + &Publication { + parent: None, + consumed_tokens: 64, + tail_pages: vec![page], + snapshot: StateSnapshot { + id: snapshot, + consumed_tokens: 64, + }, + ready_after: Fence(0), + }, + RetentionRole::Endpoint, + epoch, + ) + .unwrap() + .id(); + let hot = scheduler.admit(spec(512, 1536)).unwrap(); + assert_eq!(scheduler.request(hot).unwrap().prefix, Some(tip)); + // The remaining free row aliases live output pages when rows share KV backing. + assert_eq!( + scheduler.free_snapshot_count(), + usize::from(alias_pages != 0) + ); + assert!(scheduler.available_snapshot(0).is_none()); + let capture = scheduler.allocate_terminal_capture(pending).unwrap(); + assert!( + capture.is_some(), + "older interior rows must fund the pending capture" + ); + assert_eq!(scheduler.stats().checkpoint_skip_storage, 0); + assert!(scheduler.cache.checkpoint(chain[0]).is_err()); + assert!(scheduler.cache.checkpoint(other).is_ok()); + assert_eq!(scheduler.cache.page_chain(tip).unwrap(), pages); + assert_eq!( + scheduler.cache.lookup(&long_history).unwrap().checkpoint, + Some(tip) + ); + assert_eq!( + scheduler.cache.lookup(&other_history).unwrap().checkpoint, + Some(other) + ); + let evictions = scheduler.take_evictions(); + assert_eq!(evictions.len(), 1); + let heir = evictions[0].heir.as_ref().unwrap(); + assert_eq!(heir.parent, None); + assert_eq!(heir.chain_pages, pages[..2]); + scheduler.release_snapshot(capture.unwrap()); + scheduler.cancel(pending).unwrap(); + scheduler.cancel(hot).unwrap(); +} + +#[test] +fn completion_refreshes_terminal_recency_without_refreshing_its_prompt_snapshot() { let mut scheduler = scheduler(2, 8, 4); let long = scheduler.admit(spec(64, 2)).unwrap(); let mut other = spec(64, 1); @@ -1242,8 +1357,35 @@ fn a_request_that_finishes_last_outranks_requests_admitted_while_it_ran() { ) .unwrap(); freeze(&mut scheduler, long, 7); + let prompt = scheduler.request(long).unwrap().prefix.unwrap(); + let prompt_epoch = scheduler + .cache() + .checkpoint(prompt) + .unwrap() + .retention_rank() + .use_epoch; let long_checkpoint = scheduler.finish(long).unwrap().unwrap(); - // The request admitted first finished last, so its conversation is the most recent one. + let pages = scheduler.cache().page_chain(long_checkpoint).unwrap(); + assert_eq!( + scheduler + .cache() + .checkpoint(prompt) + .unwrap() + .retention_rank() + .use_epoch, + prompt_epoch + ); + let compacted = scheduler.evict(EvictionTarget { + pages: 0, + snapshots: 1, + }); + assert_eq!(compacted.retired[0].checkpoint, prompt); + assert_eq!(compacted.retired[0].heir, Some(long_checkpoint)); + assert_eq!( + scheduler.cache().page_chain(long_checkpoint).unwrap(), + pages + ); + // Completion recency protects the terminal even when its prompt snapshot is reclaimed. assert_eq!( scheduler.cache().eviction_candidate(None, false), Some(short_checkpoint) From b4e5902e3f3d053294e4a423357f3cda1fd59e99 Mon Sep 17 00:00:00 2001 From: Martin Vit Date: Sat, 14 Nov 2026 23:17:18 +0000 Subject: [PATCH 3/3] Refresh the direct parent of completed prefix checkpoints A long request can finish with a recent terminal snapshot but a prompt snapshot still ranked by admission time. Follow-ups that branch or rewrite generated history can then lose the prompt snapshot under pressure. The terminal's direct parent provides a bounded second resume point; immutable checkpoint sharing makes its usefulness independent of which request captured or restored it. Refresh the published terminal and its actual cached parent with the same completion epoch. Duplicate publication follows the retained terminal's parent link, which can differ from the completing request's prefix. Stop at that parent so earlier ancestors keep aging. Preemption and execution errors still suppress completion refresh, and completion without a terminal or cancellation after progress still refreshes only the retained prefix. Core formats, capture budgets, and resource lifetime rules remain compatible. The implemented policy is expected to retain useful prompt boundaries after long responses without protecting entire checkpoint chains. CPU tests qualify the retention decisions; live serving improvements remain unmeasured. Three regressions fail on 8999ad14 and pass with this change: interleaved request completion, duplicate publication, and a restored parent checkpoint. Tests also preserve grandparent compaction and page order, preemption epochs, and client-stop fallback behavior. The Helios library suite with server,runtime-core and pinned templates passes 1408 tests in serial CPU execution, with 26 ignored CUDA, external-fixture, or manual-benchmark cases. No GPU execution or service benchmark was performed. The combined patch applies to 3e9a95d3 plus PR #298 and passes 1390 library tests with 26 ignored using the same serial CPU configuration. Signed-off-by: Martin Vit Design-Signed-Off-By: Codex (GPT-6); design-review=ed22 --- docs/core-design.md | 33 ++--- docs/prefix-cache-offload.md | 2 + helios/src/scheduler.rs | 4 + helios/src/scheduler/boundary_tests.rs | 169 +++++++++++++++++++++++++ helios/src/scheduler/tests.rs | 36 ++++-- 5 files changed, 216 insertions(+), 28 deletions(-) diff --git a/docs/core-design.md b/docs/core-design.md index cbb6ea29d..a5ae5a9aa 100644 --- a/docs/core-design.md +++ b/docs/core-design.md @@ -1529,21 +1529,24 @@ endpoints have the lowest role, earlier message checkpoints follow, and the conversation anchor has the highest role. Demand recency takes precedence over role, so an idle conversation's anchor can be reclaimed before a recently used endpoint. Each successfully admitted logical request receives a demand epoch; -its captures inherit that epoch. Cache reuse touches only the matched checkpoint's -snapshot. Successful completion refreshes the terminal checkpoint with a -completion-time epoch, or the retained prefix when no terminal checkpoint was -captured. Ancestor snapshots retain their own demand epochs: sharing their pages -does not require restoring their rows. Older single-child ancestors can therefore -be compacted under pressure without discarding the recently used descendant's -page chain. Cancellation after completed inference also refreshes the retained -prefix, including client stop sequences. This keeps a long-running conversation -recent when its response ends. Cancellation before -inference and execution failure do not refresh recency. Preemption carries the -admission epoch into readmission without refreshing it. Duplicate publication -retains the maximum role and epoch of the matching checkpoint only. A prompt-end -or message checkpoint gains recency when reused directly; completion of a -descendant does not refresh it. Branch points and direct pins still constrain -which checkpoints are removable. +its captures inherit that epoch. Cache reuse and promotion touch only the selected +checkpoint's snapshot. Successful completion refreshes a published terminal and +its direct parent with one completion-time epoch. The parent commonly holds the +prompt end or last captured message boundary, which remains useful when a follow-up +rewrites generated history. The parent comes from the published checkpoint's cache +record, including duplicate publication; it need not have been captured by the +completing request and may have been restored from a host tier. + +Completion refreshes at most two checkpoints. Grandparents retain their own demand +epochs: sharing their pages does not require restoring their rows. Older single-child +ancestors can therefore be compacted under pressure without discarding descendant +pages. When no terminal is published, completion refreshes only the retained prefix. +Cancellation after completed inference also refreshes only that prefix, including +client stop sequences. Cancellation before inference and execution failure do not +refresh recency. Preemption carries the admission epoch into readmission without +refreshing it. Duplicate publication retains the maximum role and epoch of the +matching checkpoint; successful retirement then refreshes it and its direct parent. +Branch points and direct pins still constrain which checkpoints are removable. The global allocator compares victims for both snapshot rows and physical page backing. A removable checkpoint is an unpinned leaf or an ancestor with exactly diff --git a/docs/prefix-cache-offload.md b/docs/prefix-cache-offload.md index 85860f405..caf005839 100644 --- a/docs/prefix-cache-offload.md +++ b/docs/prefix-cache-offload.md @@ -259,6 +259,8 @@ GPU eviction ranks eligible checkpoints by logical-request demand epoch, retention role, consumed-token count, and identity, as specified in [checkpoint lifetime](core-design.md#branching-and-lifetime). GPU demand recency belongs to the selected snapshot, not every ancestor supplying its pages. +Successful terminal retirement also refreshes its direct parent, including a +shared or host-restored checkpoint, without refreshing earlier ancestors. Pressure can compact an older single-child ancestor while preserving the reused descendant's complete page chain and reporting its compaction heir. Direct copy-out pins and outstanding GPU-use fences still protect transfer resources. diff --git a/helios/src/scheduler.rs b/helios/src/scheduler.rs index ef7a8ebd3..87aa18cd1 100644 --- a/helios/src/scheduler.rs +++ b/helios/src/scheduler.rs @@ -2890,6 +2890,10 @@ impl RequestScheduler { if refresh_recency && let Some(id) = result.map(PublishResult::id).or(prefix) { let epoch = self.cache.new_use_epoch()?; self.cache.touch(id, epoch)?; + // Duplicate publication can retain a different parent than the request's prefix. + if result.is_some() && let Some(parent) = self.cache.checkpoint(id)?.parent() { + self.cache.touch(parent, epoch)?; + } } let mut request = self.slots[handle.slot as usize].request.take().unwrap(); if let Some(guard) = request.anchor_guard.take() { self.release_snapshot(guard); } diff --git a/helios/src/scheduler/boundary_tests.rs b/helios/src/scheduler/boundary_tests.rs index a7dec71cc..eeb987801 100644 --- a/helios/src/scheduler/boundary_tests.rs +++ b/helios/src/scheduler/boundary_tests.rs @@ -236,6 +236,175 @@ fn duplicate_finished_boundary_needs_no_terminal_snapshot() { assert_eq!(s.free_page_count(), 255); } +#[test] +fn completion_refreshes_only_terminal_and_canonical_parent_for_duplicate_publications() { + let mut s = scheduler(8, false); + let first = s.admit(spec(Some(70), 140, 3)).unwrap(); + let second = s.admit(spec(Some(70), 140, 3)).unwrap(); + let demand_epoch = s.request(second).unwrap().checkpoints.demand_epoch; + let terminal = finish(&mut s, first); + let parent = s.cache.checkpoint(terminal).unwrap().parent().unwrap(); + let ancestor = s.cache.checkpoint(parent).unwrap().parent().unwrap(); + let first_epoch = s + .cache + .checkpoint(terminal) + .unwrap() + .retention_rank() + .use_epoch; + assert_eq!( + s.cache.checkpoint(parent).unwrap().prefix().consumed_tokens, + 140 + ); + assert_eq!( + s.cache + .checkpoint(parent) + .unwrap() + .retention_rank() + .use_epoch, + first_epoch + ); + for _ in 0..250 { + if s.request(second).unwrap().phase == RequestPhase::Finishing { + break; + } + run_step(&mut s); + } + // Duplicate boundary publication keeps the second request's private page layout. + assert_ne!(s.request(second).unwrap().prefix, Some(parent)); + let pages = s.cache.page_chain(terminal).unwrap(); + assert_eq!(finish(&mut s, second), terminal); + let epoch = s + .cache + .checkpoint(terminal) + .unwrap() + .retention_rank() + .use_epoch; + assert!(epoch > first_epoch); + assert_eq!( + s.cache + .checkpoint(parent) + .unwrap() + .retention_rank() + .use_epoch, + epoch + ); + assert!( + s.cache + .checkpoint(ancestor) + .unwrap() + .retention_rank() + .use_epoch + <= demand_epoch + ); + let evicted = s.evict(EvictionTarget { + pages: 0, + snapshots: 1, + }); + assert_eq!(evicted.retired[0].checkpoint, ancestor); + assert_eq!(evicted.retired[0].heir, Some(parent)); + assert_eq!(s.cache.page_chain(terminal).unwrap(), pages); + assert_eq!( + s.cache.lookup(&history(140)).unwrap().checkpoint, + Some(parent) + ); +} + +#[test] +fn completion_refreshes_restored_parent_without_refreshing_its_ancestors() { + let mut s = scheduler(8, false); + let seed = s.admit(spec(Some(70), 140, 3)).unwrap(); + finish(&mut s, seed); + let request = spec(Some(70), 200, 5); + let plan = s.plan_admission(&request).unwrap(); + let ancestor = plan.lookup.checkpoint.unwrap(); + let key = history(200).key_at(200).unwrap(); + let pages = 200 / 64 - plan.lookup.consumed_tokens as usize / 64; + let admitted = s + .admit_planned( + request, + plan, + Some(InboundRequest { + key, + consumed_tokens: 200, + pages, + }), + ) + .unwrap(); + let ancestor_rank = s.cache.checkpoint(ancestor).unwrap().retention_rank(); + s.finish_inbound(key, true).unwrap(); + let parent = s.request(admitted.handle).unwrap().prefix.unwrap(); + let restored_epoch = s + .cache + .checkpoint(parent) + .unwrap() + .retention_rank() + .use_epoch; + assert_eq!(run_step(&mut s).kind, GraphKind::Restore); + assert_eq!(run_step(&mut s).kind, GraphKind::Resume); + assert_eq!(run_step(&mut s).kind, GraphKind::Decode); + s.finish_early(admitted.handle, false).unwrap(); + let terminal = finish(&mut s, admitted.handle); + let epoch = s + .cache + .checkpoint(terminal) + .unwrap() + .retention_rank() + .use_epoch; + assert_eq!(s.cache.checkpoint(terminal).unwrap().parent(), Some(parent)); + assert!(epoch > restored_epoch); + assert_eq!( + s.cache + .checkpoint(parent) + .unwrap() + .retention_rank() + .use_epoch, + epoch + ); + assert_eq!( + s.cache.checkpoint(ancestor).unwrap().retention_rank(), + ancestor_rank + ); +} + +#[test] +fn preemption_and_client_stop_do_not_refresh_ancestors_of_the_retained_prefix() { + for cancelled in [false, true] { + let mut s = scheduler(8, false); + let handle = s.admit(spec(Some(70), 140, 5)).unwrap(); + stop_at_capture(&mut s, handle, 140); + run_step(&mut s); + let parent = s.request(handle).unwrap().prefix.unwrap(); + let ancestor = s.cache.checkpoint(parent).unwrap().parent().unwrap(); + let parent_rank = s.cache.checkpoint(parent).unwrap().retention_rank(); + let ancestor_rank = s.cache.checkpoint(ancestor).unwrap().retention_rank(); + assert_eq!(run_step(&mut s).kind, GraphKind::Decode); + if cancelled { + s.cancel(handle).unwrap(); + assert!(s.cache.checkpoint(parent).unwrap().retention_rank() > parent_rank); + } else { + s.finish_early(handle, true).unwrap(); + let terminal = finish(&mut s, handle); + assert_eq!(s.cache.checkpoint(terminal).unwrap().parent(), Some(parent)); + assert_eq!( + s.cache.checkpoint(parent).unwrap().retention_rank(), + parent_rank + ); + assert_eq!( + s.cache + .checkpoint(terminal) + .unwrap() + .retention_rank() + .use_epoch, + parent_rank.use_epoch + ); + } + assert_eq!( + s.cache.checkpoint(ancestor).unwrap().retention_rank(), + ancestor_rank + ); + } +} + #[test] fn requests_finish_when_no_checkpoint_storage_is_available() { let mut s = scheduler(0, false); diff --git a/helios/src/scheduler/tests.rs b/helios/src/scheduler/tests.rs index 892c032b9..c089722d6 100644 --- a/helios/src/scheduler/tests.rs +++ b/helios/src/scheduler/tests.rs @@ -1295,7 +1295,7 @@ fn capture_under_reused_chain_pressure(alias_pages: u32) { } #[test] -fn completion_refreshes_terminal_recency_without_refreshing_its_prompt_snapshot() { +fn completion_refreshes_terminal_and_prompt_recency_after_other_requests_finish() { let mut scheduler = scheduler(2, 8, 4); let long = scheduler.admit(spec(64, 2)).unwrap(); let mut other = spec(64, 1); @@ -1366,6 +1366,13 @@ fn completion_refreshes_terminal_recency_without_refreshing_its_prompt_snapshot( .use_epoch; let long_checkpoint = scheduler.finish(long).unwrap().unwrap(); let pages = scheduler.cache().page_chain(long_checkpoint).unwrap(); + let completed_epoch = scheduler + .cache() + .checkpoint(long_checkpoint) + .unwrap() + .retention_rank() + .use_epoch; + assert!(completed_epoch > prompt_epoch); assert_eq!( scheduler .cache() @@ -1373,19 +1380,9 @@ fn completion_refreshes_terminal_recency_without_refreshing_its_prompt_snapshot( .unwrap() .retention_rank() .use_epoch, - prompt_epoch - ); - let compacted = scheduler.evict(EvictionTarget { - pages: 0, - snapshots: 1, - }); - assert_eq!(compacted.retired[0].checkpoint, prompt); - assert_eq!(compacted.retired[0].heir, Some(long_checkpoint)); - assert_eq!( - scheduler.cache().page_chain(long_checkpoint).unwrap(), - pages + completed_epoch ); - // Completion recency protects the terminal even when its prompt snapshot is reclaimed. + // Both useful endpoints outlive a conversation that completed while this request ran. assert_eq!( scheduler.cache().eviction_candidate(None, false), Some(short_checkpoint) @@ -1402,6 +1399,19 @@ fn completion_refreshes_terminal_recency_without_refreshing_its_prompt_snapshot( .unwrap() .retention_rank() ); + let evicted = scheduler.evict(EvictionTarget { + pages: 0, + snapshots: 1, + }); + assert_eq!(evicted.retired[0].checkpoint, short_checkpoint); + assert_eq!( + scheduler.cache().lookup(&history(64)).unwrap().checkpoint, + Some(prompt) + ); + assert_eq!( + scheduler.cache().page_chain(long_checkpoint).unwrap(), + pages + ); } #[test]