Subtraction, Simplicity & Conventions review — PR #665 (helios scan-resistant dual-turnover prefix cache eviction), head c9197427
Key findings
The production diff is already lean. No flags, environment knobs, config switches, fallback branches, floats, unsafe, speculative traits or extension points were added, and nothing dead was left behind (the old existing.accessed write was correctly deleted now that touch_hit refreshes accessed). AGENTS.md:450-460 ("Feature toggles, experiment switches, tuning overrides, debug modes, and alternate code paths selected through the environment are prohibited") is respected. So this is a "5 concrete simplifications" report, not a "this needs rework" report. Total removable duplication: ~60 lines of test scaffolding, ~20 lines of production code, and one stale doc passage.
| # | Where | What to cut | Size |
|---|---|---|---|
| 1 | helios/src/cache.rs:615-626, :643-675 |
Same horizon capture + eviction accounting + demotion written twice, with a call-ordering subtlety a reader must re-derive | ~14 lines |
| 2 | helios/src/cache.rs:351-355, :378-380 |
is_protected is a one-line wrapper over a public-in-crate field, and it forces &self through eviction_key |
6 lines |
| 3 | helios/src/cache.rs:382-389, :399-404 |
mark_reused exists only for touch_hit and costs a second nodes probe per hit |
8 lines |
| 4 | helios/src/scheduler/policy_tests.rs:6379-6480, helios/src/cache/tests.rs:1395-1567 |
Two new tests are near-verbatim copies of their immediate predecessors | ~60 lines |
| 5 | docs/prefix-cache-offload.md:374-376, helios/README.md:713-715 |
Stale spec left contradicting the rule this PR added; helios/README.md is required reading for cache changes per AGENTS.md:227 |
5 lines |
1. retire_leaf and compact_ancestor duplicate the whole turnover-accounting ritual — collapse into one helper
helios/src/cache.rs:615-626:
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);
}
helios/src/cache.rs:643-645 and :672-675 re-state the same three steps:
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;
...
if node.ready {
self.evicted_checkpoints = self.evicted_checkpoints.saturating_add(1);
self.demote_expired_reused(page_horizon, node_horizon);
}
The only difference between the two sites is that a compaction evicts no pages (pages: Vec::new() at :681, pages move to the heir at :650/:670), so evicted_pages is not incremented there. The duplication is worse than line count suggests: both sites must capture the horizons before self.uncount(&node) (:619, :649) or the aging thresholds are measured against already-decremented counters, and that ordering constraint is currently enforced only by copy-paste fidelity. Replace both blocks with one helper called immediately after self.nodes.remove(&id).unwrap() and before uncount (that placement preserves today's semantics exactly — horizons pre-uncount, retired node already out of nodes, which demote_expired_reused's for node in self.nodes.values_mut() at :364 requires):
fn note_ready_retirement(&mut self, node: &Checkpoint, pages: u64) {
if !node.ready {
return;
}
let page_horizon = self.ready_tail_pages.max(1) as u64;
let node_horizon = self.ready_checkpoints.max(1) as u64;
self.evicted_pages = self.evicted_pages.saturating_add(pages);
self.evicted_checkpoints = self.evicted_checkpoints.saturating_add(1);
self.demote_expired_reused(page_horizon, node_horizon);
}
Call sites: self.note_ready_retirement(&node, node.tail_pages.len() as u64); in retire_leaf, self.note_ready_retirement(&node, 0); in compact_ancestor. That folds the if node.ready guard, the two .max(1) horizon captures, both counter bumps and the demotion into one place, and makes the "compaction evicts nodes but not pages" asymmetry a literal 0 argument rather than an omission the reader has to notice by comparing two functions.
2. is_protected is a wrapper over a field, and it drags &self into eviction_key
helios/src/cache.rs:351-355 and :378-380:
/// 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
}
pub(crate) fn eviction_key(&self, node: &Checkpoint) -> (bool, RetentionRank, CheckpointId) {
(self.is_protected(node), node.retention_rank(), node.id)
}
is_protected reads exactly one field and never touches self; the doc comment describes demote_expired_reused (:357-376), not the getter. Its three uses are cache.rs:494 (self.is_protected(parent) && parent_len.saturating_mul(2) >= tail_tokens), cache.rs:762 (self.eviction_key(node)), and helios/src/cache/lifecycle_tests.rs:504 (ordered.sort_by_key(|node| self.cache.eviction_key(node))). Because the wrapper is a method, eviction_key is also a method — which is why succinct sorting in lifecycle_tests has to reach through self.cache as a receiver rather than call a free function.
Replace both with one associated function:
pub(crate) fn eviction_key(node: &Checkpoint) -> (bool, RetentionRank, CheckpointId) {
(node.reused, node.retention_rank(), node.id)
}
Then node.reused at :494, Self::eviction_key(node) at :762, and Cache::eviction_key(node) (or the imported path) at lifecycle_tests.rs:504. Deletes 6 lines and one indirection, and makes the tuple order at :379 the single place that says "protection is the primary key" — which is the actual contract worth reading.
Related, same lines: pub(crate) at :378 is wider than needed. cache::tests and cache::lifecycle_tests are child modules of cache (declared under #[cfg(test)] mod tests; in cache.rs), so they can see private items; plain fn suffices. This matches how the rest of the cache keeps internal surface private.
3. mark_reused exists only to be called by touch_hit, and re-probes the map for a node it already had
helios/src/cache.rs:382-389 and :399-404:
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 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(())
}
mark_reused has exactly one caller (touch_hit, at :402), and touch (:392-397) has already done self.checkpoint(id)? and a get_mut on the same key — so every hit pays two hash probes and two unwrap()s for one node. The split into two functions buys nothing: the fields are disjoint (reused* vs accessed), so the body folds into touch_hit directly:
/// Refresh demand recency and record a cross-request prefix reuse hit.
pub fn touch_hit(&mut self, id: CheckpointId, use_epoch: u64) -> Result<()> {
self.checkpoint(id)?;
let evicted_pages = self.evicted_pages;
let evicted_checkpoints = self.evicted_checkpoints;
let node = self.nodes.get_mut(&id).unwrap();
node.accessed = node.accessed.max(use_epoch);
node.reused = true;
node.reused_at_evicted_pages = evicted_pages;
node.reused_at_evicted_nodes = evicted_checkpoints;
Ok(())
}
Removes one function and one lookup per reuse hit on the admission path this PR is optimizing.
Naming, same lines: the field reused_at_evicted_nodes (cache.rs:86) is compared against the counter evicted_checkpoints (:369, :388, lifecycle_tests.rs:517). The PR's other new name is evicted_checkpoints; the field is the only one that says "nodes" for the same quantity. Pick one word so demote_expired_reused reads as a single vocabulary.
4. Two new tests are near-verbatim copies of the test above them
4a. policy_regime_shift_ages_out_reused_old_large_documents_… (helios/src/scheduler/policy_tests.rs:6429-6480) is policy_regime_shift_ages_out_old_large_documents_… (:6379-6427) plus one extra turn per document. Everything from for i in 0..16u32 through both closing braces is character-identical, including the surviving_old census, the two-turn Phase-2 conversation and both assertion messages. The only delta is inside the Phase-1 loop:
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);
Collapse to one test parameterized over that loop — for reuse_each_doc in [false, true] around the existing body, or fn regime_shift_reaps_old_documents(reuse_each_doc: bool) called by two thin #[test] wrappers. Keeps both names in the test list (so the mutation/aux-test lists do not change) while deleting ~48 duplicated lines.
4b. sticky_demotion_does_not_reprotect_after_fresh_publications (helios/src/cache/tests.rs:1471-1567) repeats dual_turnover_aging_demotes_stale_reused_entry_after_page_and_node_turnover (:1395-1469) verbatim for its first 56 lines: same stale at history(1, 0) + touch_hit(stale, 2), same kept at history(1, 500) + touch_hit(kept, 4), same big_scan at history(4, 1000)/proposal(None, 256, &[2,3,4,5], …), same evict(EvictionTarget { pages: 1, snapshots: 0 }) assertion, and the same loop:
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();
Extract fn aged_out_pair(cache: &mut PrefixCheckpointCache) -> (CheckpointId, CheckpointId) returning (stale, kept) after the two scan evictions; each test then keeps only its own distinctive tail (the demotion point versus the three fresh publications at :1531-1557). ~45 duplicated lines removed, and the difference between "demotes" and "stays demoted" becomes the visible subject of each test instead of something to diff.
5. Doc: the PR synced three docs but left two stale statements about the same policy
5a. Self-contradiction inside docs/prefix-cache-offload.md. The PR's new sentence at :298-303 is correct:
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 newly
created GPU checkpoint into the reuse-protected tier only when a live
fresh-admission waiter is attached, while preempted re-admissions and waiterless
restores refresh demand recency only.
but :374-376 in the same file still specifies the pre-PR flat order:
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).
The second passage contains no mention of the protection tier and is what an operator reaches when reading the eviction section, after having read the contradiction. Delete it or reduce it to a pointer (GPU eviction order is specified in [checkpoint lifetime](core-design.md#branching-and-lifetime).) so the two-tier rule is stated once. Per .agents/skills/repo-prose/SKILL.md (not opened), stale claims are replaced rather than layered — this is exactly the case the rule names.
5b. helios/README.md:713-715 still calls the policy "LRU". AGENTS.md:227 makes helios/README.md required reading for "Helios runtime, scheduling, caches" changes, so this is a convention-relevant omission rather than cosmetics:
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`,
"Leaf LRU eviction" no longer describes the victim order — eviction_candidate_within_budget (cache.rs:736-764) sorts by (is_protected, retention_rank, id) and only breaks down to leaf-versus-compaction afterwards. One clause ("Leaf eviction prefers un-reused checkpoints and ranks within each tier by demand, role, and consumed tokens, accepting separate page and snapshot pressure targets …") brings the module spec in line with the three docs the PR did sync.
Note for the record (cross-lens, reported here because the fix is a deletion rather than a patch): the Existing-publication path still promotes unconditionally at cache.rs:481-491 — self.touch_hit(id, use_epoch)?; at :485 — while the restore path gates on ticket.fresh_admission && !ticket.waiters.is_empty() (scheduler.rs:1886). That makes the absolute "host-store restores promote … only when a live fresh-admission waiter is attached" at prefix-cache-offload.md:298-303 false as written. Whether the asymmetry is intended is a correctness question (Correctness lens); the subtraction-relevant observation is that if it is not intended, deleting the promotion at :485 is the fix — do not add a matching flag/parameter.
Non-findings: checked and deliberately not raised
Recorded so this report does not read as an exhaustive list of everything touched:
- No configuration surface. No env var, flag,
OnceLock,cfg!(feature), float threshold, orunsafein the diff; the whole policy is constants-in-code (saturating_mul(2)atcache.rs:363,saturating_mul(2) >= tail_tokensat:494).AGENTS.md:450-460satisfied. - No speculative generality. No trait, no generic parameter, no unused
pubitem.is_protected/eviction_key/touch_hitall have live call sites (cache.rs:485, :494, :762,scheduler.rs:1736, :1887,lifecycle_tests.rs:504). - No dead code left behind. The removed
existing.accessedwrite (nowcache.rs:481-491) is correctly gone becausetouch_hit→touchrefreshesaccessed; the redundantreclaimable_if_pinned_matches_evict_with_mixed_*test is deleted; the blank-line nit is fixed. - Do not delete the new counters.
ready_tail_pages/ready_checkpoints/evicted_pages/evicted_checkpoints(cache.rs:216-223) could in principle be derived, but derivation would put a fullnodesscan on every retirement — the exact path this PR makes cheaper. The counters are the right call. - Do not delete the
#[cfg(test)]count assert atcache.rs:913-932. It is compiled out in production and is the only drift check onready_tail_pages, which is maintained in four places (cache.rs:263, :274, :670-ish,:890). - Do not fold the two scheduler call sites (
scheduler.rs:1734-1740,:1884-1891) into one cache method taking aprotect: bool. Both are three lines, and a boolean mode parameter is precisely the "optional path" styleAGENTS.md:450-460discourages; the duplication is smaller than the abstraction. - Do not cut
demote_expired_reused's2xsnapshot-bound branch (cache.rs:363, :370-372) or the one-third inheritance rule (:494). These are the policy the PR's A/B argues for, not generality; the subtraction lens has no basis to remove measured policy.
Open questions / what could not be verified
- Intent of the
Existing-path promotion (cache.rs:485) — intended reuse semantics, or an oversight left whenCreatedgained its gate? Decides whether finding 5's cross-lens note is a doc fix or a one-line deletion. - Which of
prefix-cache-offload.md:298-303and:374-376the author meant to survive the sync. Only the author can say; both cannot stand. - Source-level only. No
cargo build/cargo testand no mutation or boundary run was possible in this environment. Findings 1-3 are behaviour-preserving by construction (they change no ordering, threshold or call count on the eviction path), but each must be re-verified withcargo test --manifest-path helios/Cargo.toml (not opened) --features runtime-core,server, and re-run throughverification/helios-lifecycle/check.py (not opened) --mutationssince findings 1-3 touch functions that mutations target. verification/helios-lifecycle/check.py(not opened) was not opened in this pass. The dossier's finding stands: it has no mutation target foris_protected/demote_expired_reused/ready_tail_pages, sodocs/design-review.md:226-228(not opened)'s safety-guard coverage is unmet for this code — worth fixing alongside finding 1, since one helper gives one mutation target instead of two divergent copies.- Interaction with #549 (open,
e65d158): it edits theCheckpointfields block (cache.rs:81-86),Fixture::forkandFixture::key()— the same regions findings 1-3 touch. Whichever merges second resolves textually; findings 1-3 shrink this PR's side of that conflict slightly (they move logic into one helper), which is a mild bonus, not a reason to defer.