diff --git a/docs/core-design.md b/docs/core-design.md index 0db26a73f..af32e746c 100644 --- a/docs/core-design.md +++ b/docs/core-design.md @@ -1533,16 +1533,31 @@ request publishes additional shared ancestors. Track logical references separately from outstanding GPU use. A page or slot becomes reusable only after both have ended. -GPU retention orders eligible checkpoints by logical-request demand epoch, then -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. Each successfully admitted logical request receives a demand epoch; -its captures inherit that epoch. Cache reuse and promotion touch only the selected +GPU retention partitions eligible checkpoints into two tiers—probationary +(un-reused) entries before reuse-protected entries—and orders victims within +each tier by logical-request demand epoch, then 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. Within a tier, demand recency takes precedence over role, so an idle +conversation's anchor can be reclaimed before a recently used endpoint in the +same tier. Each successfully admitted logical request receives a demand epoch; +its captures inherit that epoch. Fresh cross-request admission hits, duplicate capture +publications, and host-store restores with a live fresh-admission waiter promote +the selected checkpoint into the reuse-protected tier. A newly published child +inherits reuse protection only when its parent is currently protected and the +parent covers at least one-third of the combined prefix (`parent_len * 2 >= tail_tokens`), +preserving linear multi-turn continuations while keeping low-reuse scans that +share a short boilerplate prefix probationary. Whenever a ready leaf or compacted +ready ancestor retires, cumulative retired ready pages and ready checkpoints +advance; any protected checkpoint whose elapsed retirements since its last reuse +hit reach either full dual turnover (both `ready_tail_pages.max(1)` pages and +`ready_checkpoints.max(1)` checkpoints) or `2x` `ready_checkpoints.max(1)` +checkpoints under snapshot-bound pressure permanently demotes to probationary +until a subsequent reuse hit. 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 +its direct parent with one completion-time epoch without promoting probationary +entries into the reuse-protected tier. 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. @@ -1562,9 +1577,11 @@ 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 one child and no direct request pin. Fenced retirement and alias ownership still control when its resources can be reused. Optional capture cannot displace an -equal or higher retention rank. Optional `Anchor` and `Message` captures reclaim lower-rank victims strictly by -demand-recency order. Optional `Endpoint` captures (prompt-end and ordinary -terminal endpoints) use the same demand-recency order while bounding cumulative +equal or higher retention rank. Optional `Anchor` and `Message` captures reclaim +lower-rank victims in the two-tier `(is_protected, RetentionRank, id)` order +(probationary victims first, ordered by demand recency, role, and token length +within each tier). Optional `Endpoint` captures (prompt-end and ordinary +terminal endpoints) use the same two-tier victim order while bounding cumulative protected victim destruction by their marginal token gain beyond their already-resident parent checkpoint (or full consumed length when no parent is resident): role-preserving single-child interior compactions (`child.role >= diff --git a/docs/prefix-cache-offload.md b/docs/prefix-cache-offload.md index c3b64c6a6..7a8c196f8 100644 --- a/docs/prefix-cache-offload.md +++ b/docs/prefix-cache-offload.md @@ -295,8 +295,15 @@ requires a committed local copy. `Retry` accepts no copy. The worker retains onl checkpoint IDs for retries after store progress and discards IDs that have left the GPU cache. `Deferred` releases the copy pin and schedules the same retry when a queued publication cannot obtain host capacity. A failed transfer releases its -pin without retrying. GPU eviction uses demand/role retention ranking with leaf removal or -ancestor compaction. `fetch` copies a looked-up chain into the ticket's page IDs and state slot. +pin without retrying. GPU eviction prefers probationary (un-reused) checkpoints +before reuse-protected checkpoints, ordering victims within each tier by +demand/role retention ranking with leaf removal or ancestor compaction; +host-store restores promote a GPU checkpoint (created or existing) into the +reuse-protected tier only when a live fresh-admission waiter is attached +(normal child inheritance from an already reuse-protected GPU parent still +applies on creation), while preempted re-admissions and waiterless restores +refresh demand recency only. `fetch` copies a looked-up chain into the ticket's +page IDs and state slot. Submissions never wait; `poll` drains completions and failures. A `PublishedCheckpoint` names the GPU checkpoint, its key and bucket digest, its complete page chain, and the state slot of its row. It lists up to 256 @@ -367,8 +374,10 @@ The manager stores a root with the complete chain only when it holds none of the chosen ancestor's chain is already half the lookup limit long, or when the arena is under pressure. -GPU eviction ranks eligible checkpoints by logical-request demand epoch, -retention role, consumed-token count, and identity, as specified in +GPU eviction partitions eligible checkpoints into probationary (un-reused) +entries before reuse-protected entries, and ranks victims within each tier 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 diff --git a/docs/scheduling-runtime-design.md b/docs/scheduling-runtime-design.md index 1adb19266..76a8e65ca 100644 --- a/docs/scheduling-runtime-design.md +++ b/docs/scheduling-runtime-design.md @@ -655,8 +655,11 @@ already executed. A row guarded for the later anchor protects it from earlier optional captures; mandatory execution may revoke an unused guard. Armed destinations and in-flight copies retain their rows through GPU completion and cancellation. The alias-aware global allocator -uses demand recency, checkpoint role, and endpoint length to compare eligible -victims; optional `Endpoint` captures additionally bound cumulative +orders probationary (un-reused) victims ahead of reuse-protected victims and +uses demand recency, checkpoint role, and endpoint length within each tier +(with continuation inheritance and sticky turnover demotion specified in +[checkpoint lifetime](core-design.md#branching-and-lifetime)); optional +`Endpoint` captures additionally bound cumulative age-discounted protected victim cost (`leaf_tokens / (1 + age)` for higher-role/root leaves and role-destroying compactions) by their marginal token gain beyond their resident parent, while leaving role-preserving single-child diff --git a/helios/README.md b/helios/README.md index 9c5f7b782..56842e086 100644 --- a/helios/README.md +++ b/helios/README.md @@ -711,10 +711,13 @@ fence before releasing resources. Pinning increments the selected checkpoint and every ancestor. Direct pin accounting prevents an ancestor unpin from consuming a descendant's reference. The scheduler records GPU use through `mark_used` before submission; releasing -logical pins does not imply completion of that use. Leaf LRU eviction accepts -separate page and snapshot pressure targets and produces `RetiredResources`, -which explicitly carry their final-use fence. The cache continues reserving -those IDs. Only `advance_completed(...).reusable` grants permission to reuse +logical pins does not imply completion of that use. Two-tier scan-resistant +eviction (probationary before reuse-protected, ordered by demand recency and +role within each tier, via leaf removal or single-child ancestor compaction) +accepts separate page and snapshot pressure targets and produces +`RetiredResources`, which explicitly carry their final-use fence. The cache +continues reserving those IDs. Only `advance_completed(...).reusable` grants +permission to reuse the corresponding storage. Fences describe a single monotonic completion timeline covering model execution diff --git a/helios/src/cache.rs b/helios/src/cache.rs index 057f0747b..c2f72b806 100644 --- a/helios/src/cache.rs +++ b/helios/src/cache.rs @@ -81,6 +81,9 @@ pub struct Checkpoint { pins: u64, accessed: u64, role: RetentionRole, + reused: bool, + reused_at_evicted_pages: u64, + reused_at_evicted_nodes: u64, } impl Checkpoint { @@ -213,6 +216,12 @@ pub struct PrefixCheckpointCache { ready_checkpoints: usize, unready_checkpoints: usize, tail_pages: usize, + ready_tail_pages: usize, + /// Cumulative ready pages and ready checkpoints (leaves and compacted ancestors) + /// retired from the cache, used to age reuse protection across workload shifts + /// without configuration knobs. + evicted_pages: u64, + evicted_checkpoints: u64, } impl PrefixCheckpointCache { @@ -241,6 +250,9 @@ impl PrefixCheckpointCache { ready_checkpoints: 0, unready_checkpoints: 0, tail_pages: 0, + ready_tail_pages: 0, + evicted_pages: 0, + evicted_checkpoints: 0, }) } @@ -248,6 +260,7 @@ impl PrefixCheckpointCache { fn count(&mut self, node: &Checkpoint) { if node.ready { self.ready_checkpoints += 1; + self.ready_tail_pages += node.tail_pages.len(); } else { self.unready_checkpoints += 1; } @@ -258,6 +271,7 @@ impl PrefixCheckpointCache { fn uncount(&mut self, node: &Checkpoint) { if node.ready { self.ready_checkpoints -= 1; + self.ready_tail_pages -= node.tail_pages.len(); } else { self.unready_checkpoints -= 1; } @@ -334,6 +348,46 @@ impl PrefixCheckpointCache { Ok(self.clock) } + /// Whether a checkpoint retains reuse protection over un-reused entries. + /// Demotion is sticky once turnover expires and only a new reuse hit restores it. + fn is_protected(&self, node: &Checkpoint) -> bool { + node.reused + } + + /// Permanently demote reused checkpoints whose elapsed retirements since their last + /// reuse hit have turned over either both the ready-page footprint and ready-checkpoint + /// count, or twice the ready-checkpoint count under snapshot-bound pressure. + fn demote_expired_reused(&mut self, page_horizon: u64, node_horizon: u64) { + let evicted_pages = self.evicted_pages; + let evicted_checkpoints = self.evicted_checkpoints; + let snapshot_horizon = node_horizon.saturating_mul(2); + for node in self.nodes.values_mut() { + if !node.reused { + continue; + } + let page_turnover = evicted_pages.saturating_sub(node.reused_at_evicted_pages); + let node_turnover = evicted_checkpoints.saturating_sub(node.reused_at_evicted_nodes); + if (page_turnover >= page_horizon && node_turnover >= node_horizon) + || node_turnover >= snapshot_horizon + { + node.reused = false; + } + } + } + + pub(crate) fn eviction_key(&self, node: &Checkpoint) -> (bool, RetentionRank, CheckpointId) { + (self.is_protected(node), node.retention_rank(), node.id) + } + + fn mark_reused(&mut self, id: CheckpointId) { + let evicted_pages = self.evicted_pages; + let evicted_checkpoints = self.evicted_checkpoints; + let node = self.nodes.get_mut(&id).unwrap(); + node.reused = true; + node.reused_at_evicted_pages = evicted_pages; + node.reused_at_evicted_nodes = evicted_checkpoints; + } + /// Refresh this snapshot's demand; sharing ancestor pages does not reuse their snapshots. pub fn touch(&mut self, id: CheckpointId, use_epoch: u64) -> Result<()> { self.checkpoint(id)?; @@ -342,6 +396,13 @@ impl PrefixCheckpointCache { Ok(()) } + /// Refresh demand recency and record a cross-request prefix reuse hit. + pub fn touch_hit(&mut self, id: CheckpointId, use_epoch: u64) -> Result<()> { + self.touch(id, use_epoch)?; + self.mark_reused(id); + Ok(()) + } + pub fn promote(&mut self, id: CheckpointId, role: RetentionRole, use_epoch: u64) -> Result<()> { self.touch(id, use_epoch)?; let node = self.nodes.get_mut(&id).unwrap(); @@ -355,6 +416,17 @@ impl PrefixCheckpointCache { proposal: &Publication, role: RetentionRole, use_epoch: u64, + ) -> Result { + self.publish_with_retention_with_hit(history, proposal, role, use_epoch, true) + } + + pub(crate) fn publish_with_retention_with_hit( + &mut self, + history: &PrefixHistory, + proposal: &Publication, + role: RetentionRole, + use_epoch: u64, + record_existing_hit: bool, ) -> Result { self.history_matches(history)?; let prefix = history.key_at(proposal.consumed_tokens).ok_or( @@ -419,16 +491,23 @@ impl PrefixCheckpointCache { } if let Some(id) = self.prefixes.get(&prefix).copied() { let existing = self.nodes.get_mut(&id).unwrap(); - existing.accessed = existing.accessed.max(use_epoch); existing.role = existing.role.max(role); let ready = existing.ready; - self.touch(id, use_epoch)?; + if record_existing_hit { + self.touch_hit(id, use_epoch)?; + } else { + self.touch(id, use_epoch)?; + } for ancestor in parent_chain { let node = self.nodes.get_mut(&ancestor).unwrap(); node.last_use = node.last_use.max(proposal.ready_after); } return Ok(PublishResult::Existing { id, ready }); } + let inherited_reuse = proposal.parent.is_some_and(|parent_id| { + let parent = &self.nodes[&parent_id]; + self.is_protected(parent) && parent_len.saturating_mul(2) >= tail_tokens + }); let next_id = self .next_id .checked_add(1) @@ -450,6 +529,9 @@ impl PrefixCheckpointCache { pins: 0, accessed: use_epoch, role, + reused: inherited_reuse, + reused_at_evicted_pages: self.evicted_pages, + reused_at_evicted_nodes: self.evicted_checkpoints, }; self.next_id = next_id; self.owned_pages.extend(candidate_pages); @@ -546,8 +628,17 @@ impl PrefixCheckpointCache { } fn retire_leaf(&mut self, id: CheckpointId) -> RetiredResources { + let page_horizon = self.ready_tail_pages.max(1) as u64; + let node_horizon = self.ready_checkpoints.max(1) as u64; let node = self.nodes.remove(&id).unwrap(); self.uncount(&node); + if node.ready { + self.evicted_pages = self + .evicted_pages + .saturating_add(node.tail_pages.len() as u64); + self.evicted_checkpoints = self.evicted_checkpoints.saturating_add(1); + self.demote_expired_reused(page_horizon, node_horizon); + } self.prefixes.remove(&node.prefix); if let Some(parent) = node.parent { self.nodes.get_mut(&parent).unwrap().child_count -= 1; @@ -565,25 +656,38 @@ impl PrefixCheckpointCache { } fn compact_ancestor(&mut self, id: CheckpointId) -> RetiredResources { + let page_horizon = self.ready_tail_pages.max(1) as u64; + let node_horizon = self.ready_checkpoints.max(1) as u64; let node = self.nodes.remove(&id).unwrap(); + let moved_pages = node.tail_pages.len(); // The ancestor leaves the counts, while its pages stay cached in its heir. self.uncount(&node); - self.tail_pages += node.tail_pages.len(); - let child = self - .nodes - .values_mut() - .find(|child| child.parent == Some(id)) - .unwrap(); - debug_assert_eq!(node.direct_pins, 0); - debug_assert_eq!(node.child_count, 1); - debug_assert_eq!(node.pins, child.pins); - let heir = child.id; - let mut pages = node.tail_pages; - pages.append(&mut child.tail_pages); - child.tail_pages = pages; - child.parent = node.parent; - // Transferred pages retain outstanding reads from the removed ancestor. - child.last_use = child.last_use.max(node.last_use).max(node.ready_after); + self.tail_pages += moved_pages; + let (heir, child_ready) = { + let child = self + .nodes + .values_mut() + .find(|child| child.parent == Some(id)) + .unwrap(); + debug_assert_eq!(node.direct_pins, 0); + debug_assert_eq!(node.child_count, 1); + debug_assert_eq!(node.pins, child.pins); + let heir = child.id; + let mut pages = node.tail_pages; + pages.append(&mut child.tail_pages); + child.tail_pages = pages; + child.parent = node.parent; + // Transferred pages retain outstanding reads from the removed ancestor. + child.last_use = child.last_use.max(node.last_use).max(node.ready_after); + (heir, child.ready) + }; + if child_ready { + self.ready_tail_pages += moved_pages; + } + if node.ready { + self.evicted_checkpoints = self.evicted_checkpoints.saturating_add(1); + self.demote_expired_reused(page_horizon, node_horizon); + } self.prefixes.remove(&node.prefix); let retired = RetiredResources { checkpoint: id, @@ -670,7 +774,7 @@ impl PrefixCheckpointCache { }; Some((node, cost)) }) - .min_by_key(|(node, _)| (node.retention_rank(), node.id)) + .min_by_key(|(node, _)| self.eviction_key(node)) .map(|(node, cost)| (node.id, cost)) } @@ -694,8 +798,9 @@ impl PrefixCheckpointCache { }) } - /// Retire removable checkpoints in demand-recency and retention-role order. - /// Only advance_completed permits reuse of the returned storage. + /// Retire removable checkpoints preferring un-reused entries before actively + /// reused checkpoints, ordered by demand recency and retention role within + /// each tier. Only advance_completed permits reuse of the returned storage. pub fn evict(&mut self, target: EvictionTarget) -> EvictionReport { let mut report = EvictionReport::default(); while report.pages_scheduled < target.pages || report.snapshots_scheduled < target.snapshots @@ -797,6 +902,7 @@ impl PrefixCheckpointCache { for node in self.nodes.values_mut() { if !node.ready && node.ready_after <= completed { node.ready = true; + self.ready_tail_pages += node.tail_pages.len(); update.published.push(node.id); } } @@ -821,11 +927,21 @@ impl PrefixCheckpointCache { // Tests check the kept counts against a full scan on every read. #[cfg(test)] assert_eq!( - (self.ready_checkpoints, self.unready_checkpoints, self.tail_pages), + ( + self.ready_checkpoints, + self.unready_checkpoints, + self.tail_pages, + self.ready_tail_pages, + ), ( self.nodes.values().filter(|node| node.ready).count(), self.nodes.values().filter(|node| !node.ready).count(), self.nodes.values().map(|node| node.tail_pages.len()).sum::(), + self.nodes + .values() + .filter(|node| node.ready) + .map(|node| node.tail_pages.len()) + .sum::(), ), "cache counts drifted from the checkpoints they count" ); diff --git a/helios/src/cache/lifecycle_tests.rs b/helios/src/cache/lifecycle_tests.rs index 05de00924..475aafc6b 100644 --- a/helios/src/cache/lifecycle_tests.rs +++ b/helios/src/cache/lifecycle_tests.rs @@ -76,6 +76,9 @@ impl Fixture { pins: node.pins, accessed: node.accessed, role: node.role, + reused: node.reused, + reused_at_evicted_pages: node.reused_at_evicted_pages, + reused_at_evicted_nodes: node.reused_at_evicted_nodes, }, ) }) @@ -90,6 +93,9 @@ impl Fixture { ready_checkpoints: cache.ready_checkpoints, unready_checkpoints: cache.unready_checkpoints, tail_pages: cache.tail_pages, + ready_tail_pages: cache.ready_tail_pages, + evicted_pages: cache.evicted_pages, + evicted_checkpoints: cache.evicted_checkpoints, }, ids: self.ids, histories: self.histories.clone(), @@ -492,10 +498,30 @@ impl Fixture { fn key(&self) -> Vec { let mut key = self.projection(); - // Relative retention order preserves eviction choices without an unbounded clock. + // Relative retention order and reuse/turnover state preserve future eviction + // choices without an unbounded clock. let mut ordered: Vec<_> = self.cache.nodes.values().collect(); - ordered.sort_by_key(|node| (node.retention_rank(), node.id)); - key.extend(ordered.iter().map(|node| self.semantic(node.id) as u64)); + ordered.sort_by_key(|node| self.cache.eviction_key(node)); + for node in ordered { + key.push(self.semantic(node.id) as u64); + if node.reused { + key.push(1); + key.push( + self.cache + .evicted_pages + .saturating_sub(node.reused_at_evicted_pages), + ); + key.push( + self.cache + .evicted_checkpoints + .saturating_sub(node.reused_at_evicted_nodes), + ); + } else { + key.push(0); + key.push(0); + key.push(0); + } + } key } diff --git a/helios/src/cache/tests.rs b/helios/src/cache/tests.rs index af16ec6d4..fb32e0324 100644 --- a/helios/src/cache/tests.rs +++ b/helios/src/cache/tests.rs @@ -1310,3 +1310,322 @@ fn equal_epoch_victims_use_role_and_preserve_direct_pins() { assert_eq!(cache.evict(EvictionTarget { pages: 0, snapshots: 1 }).retired[0].checkpoint, anchor); assert!(cache.evict(EvictionTarget { pages: 0, snapshots: 1 }).retired.is_empty()); } + +#[test] +fn scan_resistant_eviction_prefers_unreused_scan_over_older_reused_checkpoint() { + let mut cache = cache(); + let hot = cache + .publish_with_retention( + &history(1, 0), + &proposal(None, 64, &[0], 0, 0), + RetentionRole::Endpoint, + 1, + ) + .unwrap() + .id(); + cache.touch_hit(hot, 2).unwrap(); + let scan = cache + .publish_with_retention( + &history(4, 1000), + &proposal(None, 256, &[1, 2, 3, 4], 1, 0), + RetentionRole::Endpoint, + 5, + ) + .unwrap() + .id(); + // Creator completion recency refresh must not mark an un-reused scan as protected. + cache.touch(scan, 6).unwrap(); + let report = cache.evict(EvictionTarget { + pages: 1, + snapshots: 0, + }); + assert_eq!(report.retired[0].checkpoint, scan); + assert!(cache.checkpoint(hot).is_ok()); +} + +#[test] +fn continuation_inherits_protection_while_low_reuse_boilerplate_scan_stays_probationary() { + let mut cache = cache(); + let agent_hist = history(4, 0); + let mut scan_hist = history(2, 0); + scan_hist.append(&[999; 512], &[]).unwrap(); + + let shared = cache + .publish_with_retention( + &agent_hist, + &proposal(None, 128, &[0, 1], 0, 0), + RetentionRole::Anchor, + 1, + ) + .unwrap() + .id(); + cache.touch_hit(shared, 2).unwrap(); + + // Agent turn reuses 128 tokens and appends 128 tokens (128 * 2 >= 128) -> protected. + let agent = cache + .publish_with_retention( + &agent_hist, + &proposal(Some(shared), 256, &[2, 3], 1, 0), + RetentionRole::Endpoint, + 3, + ) + .unwrap() + .id(); + // Boilerplate scan reuses 128 tokens and appends 512 tokens (128 * 2 < 512) -> probationary. + let scan = cache + .publish_with_retention( + &scan_hist, + &proposal(Some(shared), 640, &[4, 5, 6, 7, 8, 9, 10, 11], 2, 0), + RetentionRole::Endpoint, + 4, + ) + .unwrap() + .id(); + cache.touch(scan, 5).unwrap(); + + let report = cache.evict(EvictionTarget { + pages: 1, + snapshots: 0, + }); + assert_eq!(report.retired[0].checkpoint, scan); + assert!(cache.checkpoint(agent).is_ok()); + assert!(cache.checkpoint(shared).is_ok()); +} + +#[test] +fn dual_turnover_aging_demotes_stale_reused_entry_after_page_and_node_turnover() { + let mut cache = cache(); + let stale = cache + .publish_with_retention( + &history(1, 0), + &proposal(None, 64, &[0], 0, 0), + RetentionRole::Endpoint, + 1, + ) + .unwrap() + .id(); + cache.touch_hit(stale, 2).unwrap(); + let kept = cache + .publish_with_retention( + &history(1, 500), + &proposal(None, 64, &[1], 1, 0), + RetentionRole::Endpoint, + 3, + ) + .unwrap() + .id(); + cache.touch_hit(kept, 4).unwrap(); + + // One large scan eviction turns over pages (4 >= 3) but only 1 node (< 3 ready_checkpoints). + let big_scan = cache + .publish_with_retention( + &history(4, 1000), + &proposal(None, 256, &[2, 3, 4, 5], 2, 0), + RetentionRole::Endpoint, + 5, + ) + .unwrap() + .id(); + assert_eq!( + cache.evict(EvictionTarget { pages: 1, snapshots: 0 }).retired[0].checkpoint, + big_scan + ); + cache.advance_completed(Fence(0)).unwrap(); + + // Still protected against newer probationary scans until node turnover reaches ready_checkpoints. + for (offset, epoch) in [(2000, 6), (2500, 7)] { + let scan = cache + .publish_with_retention( + &history(1, offset), + &proposal(None, 64, &[2], 2, 0), + RetentionRole::Endpoint, + epoch, + ) + .unwrap() + .id(); + assert_eq!( + cache.evict(EvictionTarget { pages: 1, snapshots: 0 }).retired[0].checkpoint, + scan + ); + cache.advance_completed(Fence(0)).unwrap(); + } + + // After 3 leaf evictions (6 pages >= 3 cached pages, and 3 nodes >= 3 cached nodes), + // `stale` demotes to probationary and yields to newer demand while refreshed `kept` survives. + let fresh = cache + .publish_with_retention( + &history(1, 3000), + &proposal(None, 64, &[2], 2, 0), + RetentionRole::Endpoint, + 10, + ) + .unwrap() + .id(); + cache.touch_hit(kept, 11).unwrap(); + let victim = cache.evict(EvictionTarget { pages: 1, snapshots: 0 }).retired[0].checkpoint; + assert_eq!(victim, stale); + assert!(cache.checkpoint(fresh).is_ok()); + assert!(cache.checkpoint(kept).is_ok()); +} + +#[test] +fn sticky_demotion_does_not_reprotect_after_fresh_publications() { + let mut cache = cache(); + let stale = cache + .publish_with_retention( + &history(1, 0), + &proposal(None, 64, &[0], 0, 0), + RetentionRole::Endpoint, + 1, + ) + .unwrap() + .id(); + cache.touch_hit(stale, 2).unwrap(); + let kept = cache + .publish_with_retention( + &history(1, 500), + &proposal(None, 64, &[1], 1, 0), + RetentionRole::Endpoint, + 3, + ) + .unwrap() + .id(); + cache.touch_hit(kept, 4).unwrap(); + + // Three leaf evictions turn over both pages (6 >= 3) and ready checkpoints (3 >= 3), + // permanently demoting `stale`. + let big_scan = cache + .publish_with_retention( + &history(4, 1000), + &proposal(None, 256, &[2, 3, 4, 5], 2, 0), + RetentionRole::Endpoint, + 5, + ) + .unwrap() + .id(); + assert_eq!( + cache.evict(EvictionTarget { pages: 1, snapshots: 0 }).retired[0].checkpoint, + big_scan + ); + cache.advance_completed(Fence(0)).unwrap(); + for (offset, epoch) in [(2000, 6), (2500, 7)] { + let scan = cache + .publish_with_retention( + &history(1, offset), + &proposal(None, 64, &[2], 2, 0), + RetentionRole::Endpoint, + epoch, + ) + .unwrap() + .id(); + assert_eq!( + cache.evict(EvictionTarget { pages: 1, snapshots: 0 }).retired[0].checkpoint, + scan + ); + cache.advance_completed(Fence(0)).unwrap(); + } + assert!(!cache.is_protected(cache.checkpoint(stale).unwrap())); + + // Publishing multiple fresh checkpoints grows both ready_checkpoints and ready_tail_pages + // beyond `stale`'s elapsed turnover; `stale` must remain probationary and evict first. + let fresh1 = cache + .publish_with_retention( + &history(1, 3000), + &proposal(None, 64, &[2], 2, 0), + RetentionRole::Endpoint, + 10, + ) + .unwrap() + .id(); + let fresh2 = cache + .publish_with_retention( + &history(1, 3500), + &proposal(None, 64, &[3], 3, 0), + RetentionRole::Endpoint, + 11, + ) + .unwrap() + .id(); + let fresh3 = cache + .publish_with_retention( + &history(1, 4000), + &proposal(None, 64, &[4], 4, 0), + RetentionRole::Endpoint, + 12, + ) + .unwrap() + .id(); + cache.touch_hit(kept, 13).unwrap(); + assert!(!cache.is_protected(cache.checkpoint(stale).unwrap())); + + let victim = cache.evict(EvictionTarget { pages: 1, snapshots: 0 }).retired[0].checkpoint; + assert_eq!(victim, stale); + assert!(cache.checkpoint(fresh1).is_ok()); + assert!(cache.checkpoint(fresh2).is_ok()); + assert!(cache.checkpoint(fresh3).is_ok()); + assert!(cache.checkpoint(kept).is_ok()); +} + +#[test] +fn compaction_pressure_ages_out_stale_protected_entry_without_page_evictions() { + let mut cache = cache(); + let stale = cache + .publish_with_retention( + &history(1, 0), + &proposal(None, 64, &[0], 0, 0), + RetentionRole::Endpoint, + 1, + ) + .unwrap() + .id(); + cache.touch_hit(stale, 2).unwrap(); + + let mut chain_hist = history(1, 1000); + let mut chain_head = cache + .publish_with_retention( + &chain_hist, + &proposal(None, 64, &[1], 1, 0), + RetentionRole::Endpoint, + 3, + ) + .unwrap() + .id(); + + // Repeated snapshot-only ancestor compactions free 0 pages while turning over 2x the + // 3-checkpoint cache (6 compactions), aging out `stale` without any page evictions. + for step in 1..=6u32 { + chain_hist.append(&[2000 + step; 64], &[]).unwrap(); + let next = cache + .publish_with_retention( + &chain_hist, + &proposal(Some(chain_head), (step as u64 + 1) * 64, &[1 + step], 1 + step, 0), + RetentionRole::Endpoint, + 3 + step as u64, + ) + .unwrap() + .id(); + let retired = cache.evict(EvictionTarget { pages: 0, snapshots: 1 }).retired; + assert_eq!(retired.len(), 1); + assert_eq!(retired[0].checkpoint, chain_head); + assert_eq!(retired[0].heir, Some(next)); + assert!(retired[0].pages.is_empty()); + cache.advance_completed(Fence(0)).unwrap(); + chain_head = next; + } + + assert_eq!(cache.evicted_pages, 0); + assert!(!cache.is_protected(cache.checkpoint(stale).unwrap())); + let fresh = cache + .publish_with_retention( + &history(1, 9000), + &proposal(None, 64, &[20], 20, 0), + RetentionRole::Endpoint, + 50, + ) + .unwrap() + .id(); + let victim = cache.evict(EvictionTarget { pages: 1, snapshots: 0 }).retired[0].checkpoint; + assert_eq!(victim, stale); + assert!(cache.checkpoint(fresh).is_ok()); + assert!(cache.checkpoint(chain_head).is_ok()); +} diff --git a/helios/src/scheduler.rs b/helios/src/scheduler.rs index 7d73f063e..e23c44914 100644 --- a/helios/src/scheduler.rs +++ b/helios/src/scheduler.rs @@ -628,7 +628,7 @@ struct Ticket { pages: Vec, snapshot: SnapshotId, history: PrefixHistory, - waiters: Vec, + waiters: Vec<(RequestHandle, bool)>, demand_epoch: u64, role: RetentionRole, } @@ -1679,6 +1679,7 @@ impl RequestScheduler { slot: slot as u32, generation, }; + let fresh_admission = accounting.is_none(); let mut ticket = None; if let Some(inbound) = &inbound { if creating { @@ -1695,7 +1696,7 @@ impl RequestScheduler { pages: pages.clone(), snapshot, history: history.clone(), - waiters: vec![handle], + waiters: vec![(handle, fresh_admission)], demand_epoch: 0, role: RetentionRole::Endpoint, }, @@ -1710,7 +1711,7 @@ impl RequestScheduler { .get_mut(&inbound.key) .unwrap() .waiters - .push(handle); + .push((handle, fresh_admission)); } } let mut reserved_pages: Vec<_> = (0..reserved_count) @@ -1735,7 +1736,13 @@ impl RequestScheduler { }; checkpoints.clear_reservations(); let demand_epoch = checkpoints.demand_epoch; - if let Some(id) = lookup.checkpoint { self.cache.touch(id, demand_epoch)?; } + if let Some(id) = lookup.checkpoint { + if fresh_admission { + self.cache.touch_hit(id, demand_epoch)?; + } else { + self.cache.touch(id, demand_epoch)?; + } + } let message_boundaries = spec.message_boundaries; self.slots[slot].generation = generation; self.slots[slot].request = Some(LiveRequest { @@ -1853,7 +1860,14 @@ impl RequestScheduler { }, ready_after: self.completed, }; - let result = match self.cache.publish_with_retention(&ticket.history, &proposal, ticket.role, ticket.demand_epoch) { + let has_fresh_waiter = ticket.waiters.iter().any(|&(_, fresh)| fresh); + let result = match self.cache.publish_with_retention_with_hit( + &ticket.history, + &proposal, + ticket.role, + ticket.demand_epoch, + has_fresh_waiter, + ) { Ok(result) => result, Err(error) => { self.fail_ticket(ticket)?; @@ -1874,18 +1888,23 @@ impl RequestScheduler { if !ready { // The checkpoint becomes ready at a later fence; the waiters are // re-admitted rather than left waiting without a ticket. - for handle in &ticket.waiters { - self.retire(*handle, false)?; + for &(handle, _) in &ticket.waiters { + self.retire(handle, false)?; } - return Ok(ticket.waiters); + return Ok(ticket.waiters.into_iter().map(|(handle, _)| handle).collect()); } if matches!(result, PublishResult::Created { .. }) { self.stats.snapshot_publications += 1; + if has_fresh_waiter { + self.cache.touch_hit(id, ticket.demand_epoch)?; + } else { + self.cache.touch(id, ticket.demand_epoch)?; + } } self.record_publication(id); let snapshot = self.cache.checkpoint(id)?.snapshot(); let shared_pages = self.cache.page_chain(id)?; - for handle in ticket.waiters { + for (handle, _) in ticket.waiters { self.request(handle)?; self.cache.pin(id)?; let request = self.request_mut(handle)?; @@ -1907,10 +1926,10 @@ impl RequestScheduler { if let Some(parent) = ticket.parent { self.cache.unpin(parent)?; } - for handle in &ticket.waiters { - self.retire(*handle, false)?; + for &(handle, _) in &ticket.waiters { + self.retire(handle, false)?; } - Ok(ticket.waiters) + Ok(ticket.waiters.into_iter().map(|(handle, _)| handle).collect()) } /// Queue GPU-ready checkpoint notifications for an attached host store. @@ -3083,7 +3102,7 @@ impl RequestScheduler { fn retire(&mut self, handle: RequestHandle, publish: bool) -> Result> { if self.request(handle)?.phase == RequestPhase::Inbound { for ticket in self.tickets.values_mut() { - ticket.waiters.retain(|waiter| *waiter != handle); + ticket.waiters.retain(|(waiter, _)| *waiter != handle); } } let request = self.request(handle)?; diff --git a/helios/src/scheduler/policy_tests.rs b/helios/src/scheduler/policy_tests.rs index 99d58599f..1a9d0b3a4 100644 --- a/helios/src/scheduler/policy_tests.rs +++ b/helios/src/scheduler/policy_tests.rs @@ -6426,6 +6426,59 @@ fn policy_regime_shift_ages_out_old_large_documents_for_newer_chat_workload() { ); } +#[test] +fn policy_regime_shift_ages_out_reused_old_large_documents_for_newer_chat_workload() { + // Phase 1 loads and reuses 4 distinct 1,536-token documents so all 4 enter the + // reuse-protected tier inside a snapshot-bound 6-snapshot pool. Phase 2 then shifts to + // 16 newer 256-token chats with 64-token replies, followed by a 2-turn conversation. + // Turnover aging must demote and reap all 4 stale reused Phase-1 documents. + let mut s = retention_engine(512, 6); + let old_docs: Vec> = (0..4u32) + .map(|i| vec![100 + i; 1_536]) + .collect(); + for (i, doc) in old_docs.iter().enumerate() { + let mut first = doc.clone(); + first.extend(vec![300 + i as u32; 32]); + let (reused_first, _) = run_turn_to_completion(&mut s, first, vec![1_536], 17); + assert_eq!(reused_first, 0); + let mut second = doc.clone(); + second.extend(vec![350 + i as u32; 32]); + let (reused_second, _) = run_turn_to_completion(&mut s, second, vec![1_536], 17); + assert_eq!(reused_second, 1_536); + } + + for i in 0..16u32 { + let prompt = vec![400 + i; 256]; + let _ = run_turn_to_completion(&mut s, prompt, vec![224], 65); + } + + let mut surviving_old = 0usize; + for doc in &old_docs { + let mut history = PrefixHistory::new([19; 32]); + history.append(doc, &[]).unwrap(); + if s.cache.lookup(&history).unwrap().checkpoint.is_some() { + surviving_old += 1; + } + } + assert_eq!( + surviving_old, 0, + "stale reused Phase-1 document anchors must age out and be reaped by newer traffic" + ); + + let turn1_prompt = vec![900; 256]; + let (reused1, emitted1) = run_turn_to_completion(&mut s, turn1_prompt.clone(), vec![256], 65); + assert_eq!(reused1, 0); + let mut turn2_prompt = turn1_prompt; + turn2_prompt.extend(&emitted1); + turn2_prompt.extend(vec![901; 32]); + let (reused2, _) = run_turn_to_completion(&mut s, turn2_prompt, vec![256, 353], 33); + assert_eq!( + reused2, + 256 + 64, + "Phase-2 multi-turn continuation must restore full prompt plus 64-token reply" + ); +} + #[test] fn policy_long_reasoning_reply_reclaims_stale_short_anchors_for_next_turn() { // 5-snapshot pool: 4 rows hold older trivial 128-token short-chat Anchors. diff --git a/helios/src/scheduler/tests.rs b/helios/src/scheduler/tests.rs index 14ac3a1f2..dba39b1d3 100644 --- a/helios/src/scheduler/tests.rs +++ b/helios/src/scheduler/tests.rs @@ -3207,6 +3207,270 @@ fn cancelled_inbound_waiter_leaves_ticket_resources_until_finish_inbound() { assert_eq!(scheduler.stats().cached_checkpoints, 0); } +fn publish_distinct_prompt( + scheduler: &mut RequestScheduler, + offset: u32, + fence: u64, +) -> CheckpointId { + let mut request = spec(64, 1); + request.prompt = (offset..offset + 64).collect(); + let handle = scheduler.admit(request).unwrap(); + init(scheduler, fence); + let step = scheduler.plan().unwrap(); + scheduler.commit(&step, Fence(fence + 1)).unwrap(); + scheduler + .complete( + Fence(fence + 1), + &records(handle, fence + 1, 64, 1, 88, 2), + Default::default(), + ) + .unwrap(); + freeze(scheduler, handle, fence + 2); + scheduler.finish(handle).unwrap().unwrap() +} + +#[test] +fn finish_inbound_fresh_admission_protects_restored_checkpoint_over_cold_scan() { + let mut scheduler = host_scheduler(2, 8, 4); + let admitted = inbound(&mut scheduler, spec(65, 2), 64); + let ticket = admitted.ticket.unwrap(); + assert!( + scheduler + .finish_inbound(ticket.key, true) + .unwrap() + .is_empty() + ); + let restored = scheduler.request(admitted.handle).unwrap().prefix().unwrap(); + // Cancel before inference so `retire` unpins `restored` without refreshing recency. + scheduler.cancel(admitted.handle).unwrap(); + + // A newer un-reused cold scan finishes at a higher epoch but remains probationary. + let scan = publish_distinct_prompt(&mut scheduler, 1000, 1); + let evicted = scheduler.evict(EvictionTarget { + pages: 1, + snapshots: 0, + }); + assert_eq!(evicted.retired[0].checkpoint, scan); + assert!(scheduler.cache().checkpoint(restored).is_ok()); +} + +#[test] +fn finish_inbound_preempted_and_cancelled_tickets_remain_probationary() { + // 1. All waiters cancelled before transfer completion -> plain touch (probationary). + let mut scheduler = host_scheduler(2, 8, 4); + let admitted = inbound(&mut scheduler, spec(65, 2), 64); + let ticket = admitted.ticket.unwrap(); + scheduler.cancel(admitted.handle).unwrap(); + assert!( + scheduler + .finish_inbound(ticket.key, true) + .unwrap() + .is_empty() + ); + let restored = scheduler.take_publications()[0].id; + let scan = publish_distinct_prompt(&mut scheduler, 1000, 1); + let evicted = scheduler.evict(EvictionTarget { + pages: 1, + snapshots: 0, + }); + assert_eq!(evicted.retired[0].checkpoint, restored); + assert!(scheduler.cache().checkpoint(scan).is_ok()); + + // 2. Preempted re-admission carrying prior CheckpointAccounting -> plain touch (probationary). + let mut scheduler = host_scheduler(2, 8, 4); + let prior = scheduler.admit(spec(65, 2)).unwrap(); + let accounting = scheduler + .request(prior) + .unwrap() + .checkpoint_accounting() + .clone(); + scheduler.cancel(prior).unwrap(); + let request = spec(65, 2); + let plan = scheduler.plan_admission(&request).unwrap(); + let key = plan.history().key_at(64).unwrap(); + let readmitted = scheduler + .admit_planned_with_checkpoint_accounting( + request, + plan, + Some(InboundRequest { + key, + consumed_tokens: 64, + pages: 1, + }), + Some(accounting), + ) + .unwrap(); + let ticket = readmitted.ticket.unwrap(); + assert!( + scheduler + .finish_inbound(ticket.key, true) + .unwrap() + .is_empty() + ); + let restored = scheduler + .request(readmitted.handle) + .unwrap() + .prefix() + .unwrap(); + scheduler.cancel(readmitted.handle).unwrap(); + let scan = publish_distinct_prompt(&mut scheduler, 2000, 1); + let evicted = scheduler.evict(EvictionTarget { + pages: 1, + snapshots: 0, + }); + assert_eq!(evicted.retired[0].checkpoint, restored); + assert!(scheduler.cache().checkpoint(scan).is_ok()); +} + +#[test] +fn finish_inbound_cancelling_fresh_waiter_leaves_preempted_waiter_probationary() { + let mut scheduler = host_scheduler(3, 8, 4); + let prior = scheduler.admit(spec(65, 2)).unwrap(); + let accounting = scheduler + .request(prior) + .unwrap() + .checkpoint_accounting() + .clone(); + scheduler.cancel(prior).unwrap(); + + let fresh = inbound(&mut scheduler, spec(65, 2), 64); + let ticket = fresh.ticket.unwrap(); + + let request = spec(65, 2); + let plan = scheduler.plan_admission(&request).unwrap(); + let key = plan.history().key_at(64).unwrap(); + assert_eq!(key, ticket.key); + let preempted = scheduler + .admit_planned_with_checkpoint_accounting( + request, + plan, + Some(InboundRequest { + key, + consumed_tokens: 64, + pages: 1, + }), + Some(accounting), + ) + .unwrap(); + assert!(preempted.ticket.is_none()); + + // Cancel the fresh waiter before transfer completion; only the preempted waiter remains. + scheduler.cancel(fresh.handle).unwrap(); + assert!( + scheduler + .finish_inbound(ticket.key, true) + .unwrap() + .is_empty() + ); + let restored = scheduler + .request(preempted.handle) + .unwrap() + .prefix() + .unwrap(); + scheduler.cancel(preempted.handle).unwrap(); + + let scan = publish_distinct_prompt(&mut scheduler, 3000, 1); + let evicted = scheduler.evict(EvictionTarget { + pages: 1, + snapshots: 0, + }); + assert_eq!(evicted.retired[0].checkpoint, restored); + assert!(scheduler.cache().checkpoint(scan).is_ok()); +} + +#[test] +fn finish_inbound_existing_checkpoint_requires_live_fresh_waiter_for_promotion() { + // 1. Waiterless restore matching an existing probationary checkpoint refreshes recency only. + let mut scheduler = host_scheduler(2, 8, 4); + let waiterless = inbound(&mut scheduler, spec(65, 2), 64); + let ticket = waiterless.ticket.unwrap(); + scheduler.cancel(waiterless.handle).unwrap(); + let existing = publish_distinct_prompt(&mut scheduler, 0, 1); + assert!( + scheduler + .finish_inbound(ticket.key, true) + .unwrap() + .is_empty() + ); + assert_eq!(scheduler.stats().cached_checkpoints, 1); + let scan = publish_distinct_prompt(&mut scheduler, 4000, 10); + let evicted = scheduler.evict(EvictionTarget { + pages: 1, + snapshots: 0, + }); + assert_eq!(evicted.retired[0].checkpoint, existing); + assert!(scheduler.cache().checkpoint(scan).is_ok()); + + // 2. Preempted-only restore matching an existing probationary checkpoint refreshes recency only. + let mut scheduler = host_scheduler(2, 8, 4); + let prior = scheduler.admit(spec(65, 2)).unwrap(); + let accounting = scheduler + .request(prior) + .unwrap() + .checkpoint_accounting() + .clone(); + scheduler.cancel(prior).unwrap(); + let request = spec(65, 2); + let plan = scheduler.plan_admission(&request).unwrap(); + let key = plan.history().key_at(64).unwrap(); + let preempted = scheduler + .admit_planned_with_checkpoint_accounting( + request, + plan, + Some(InboundRequest { + key, + consumed_tokens: 64, + pages: 1, + }), + Some(accounting), + ) + .unwrap(); + let ticket = preempted.ticket.unwrap(); + let existing = publish_distinct_prompt(&mut scheduler, 0, 1); + assert!( + scheduler + .finish_inbound(ticket.key, true) + .unwrap() + .is_empty() + ); + assert_eq!( + scheduler.request(preempted.handle).unwrap().prefix(), + Some(existing) + ); + scheduler.cancel(preempted.handle).unwrap(); + let scan = publish_distinct_prompt(&mut scheduler, 5000, 10); + let evicted = scheduler.evict(EvictionTarget { + pages: 1, + snapshots: 0, + }); + assert_eq!(evicted.retired[0].checkpoint, existing); + assert!(scheduler.cache().checkpoint(scan).is_ok()); + + // 3. Live fresh waiter matching an existing probationary checkpoint promotes it. + let mut scheduler = host_scheduler(2, 8, 4); + let fresh = inbound(&mut scheduler, spec(65, 2), 64); + let ticket = fresh.ticket.unwrap(); + let existing = publish_distinct_prompt(&mut scheduler, 0, 1); + assert!( + scheduler + .finish_inbound(ticket.key, true) + .unwrap() + .is_empty() + ); + assert_eq!( + scheduler.request(fresh.handle).unwrap().prefix(), + Some(existing) + ); + scheduler.cancel(fresh.handle).unwrap(); + let scan = publish_distinct_prompt(&mut scheduler, 6000, 10); + let evicted = scheduler.evict(EvictionTarget { + pages: 1, + snapshots: 0, + }); + assert_eq!(evicted.retired[0].checkpoint, scan); + assert!(scheduler.cache().checkpoint(existing).is_ok()); +} + #[test] fn invalid_inbound_requests_reserve_nothing_and_planned_admission_matches_admit() { let mut scheduler = host_scheduler(1, 8, 4);