Correctness and contracts report · NVIDIA/hyperflare-inference #665

Raw Markdown for agents: https://autobot.eidonix.com/p/9859fb8a-6bc6-4d54-9fee-73dfa7c0d59c.md

Correctness, Contracts & System-Level Consequences review — PR #665 (head a7568c2)

Key findings

  1. The aging rule is not monotonic — is_protected divides a monotonic turnover numerator by current global counts, so a demoted checkpoint becomes protected again as the cache refills, during exactly the scan burst the PR targets (helios/src/cache.rs:346-361, denominators mutated at :256-274). Major.
  2. compact_ancestor never advances turnover, so single-child chains — the 4x127K multi-turn shape the PR benchmarks — can evict unboundedly without protection ever aging out; that is the livelock the PR says it prevents (helios/src/cache.rs:626-630 vs :601-609, dispatch at :749-753). Major.
  3. A first-ever GPU creation is recorded as a reuse hit: finish_inbound calls touch_hit on PublishResult::Created, so a cold scan restored from the host tier is born protected (helios/src/scheduler.rs:1884-1887). This contradicts the invariant the PR's own test asserts (helios/src/cache/tests.rs:1337-1338) and lives on the one path the description admits is unmeasured (--prefix-cache-memory 0). Major.
  4. Unconditional touch_hit in the Existing publication branch marks the same request's own re-publication as cross-request reuse (helios/src/cache.rs:466-477; callers helios/src/scheduler.rs:3101, :2948), so a one-shot scan can self-promote. Major.
  5. A documented, four-day-old contract is reversed with no doc update and no owner sign-off: is_protected becomes the first sort key (helios/src/cache.rs:363-365), while docs/core-design.md:1564-1566 and docs/scheduling-runtime-design.md:644-645 still promise strict demand-recency order; AGENTS.md:204-206 requires an explicit maintainer decision for invariant changes. Major.
  6. The lifecycle conformance key now depends on state the projection omits (helios/src/cache/lifecycle_tests.rs:498-505 sorting by eviction_key over a projection that has no evicted_pages/evicted_checkpoints), so the BFS can collide distinct states and prune live branches — the reported "TLA+ 12/12 checks passed" does not evidence the new ordering. Major.
  7. No check.py --mutations/cargo-mutants run despite adding a guard, which docs/design-review.md:226-228 and :247-251 call blocking; the claim "Selene restore touch_hit is verified by unit tests and TLA+" is not supported by any test in the diff. Major.
  8. Minor: zero observability for the new policy (CacheStats unchanged), and the inheritance threshold (token ratio) does not match the aging metric (page/node turnover), leaking protection onto scan endpoints (helios/src/cache.rs:478-481). Minor.

1. Correctness, safety & mechanism

F1 — Protection can be re-granted with no new reuse hit (Major)

helios/src/cache.rs:346-361:

    /// Whether a checkpoint retains reuse protection over un-reused entries.
    /// Protection ages out once evictions turn over both the current cached-page
    /// footprint and the current ready-checkpoint count without another reuse hit.
    fn is_protected(&self, node: &Checkpoint) -> bool {
        ...
        !(page_turnover >= self.tail_pages.max(1) as u64
            && node_turnover >= self.ready_checkpoints.max(1) as u64)
    }

tail_pages and ready_checkpoints are live counters, incremented on every publication and decremented on every retire (helios/src/cache.rs:256-274, :248-250). The numerators (evicted_pages/evicted_checkpoints, :605-608) only ever grow. Therefore turnover >= current_count is not a monotone predicate: after a node demotes, publishing new checkpoints raises the denominator and flips it back to protected.

Concrete sequence with the PR's own test geometry: reuse at (evicted_pages=0, evicted=0); with tail_pages=4, ready=1, evicting 5 pages / 1 node demotes the node (as helios/src/cache/tests.rs:1396-1505 asserts); then three new checkpoints raise tail_pages→7, ready→4; node_turnover = 1 < 4, so the stale node is promoted again with no second client. Impact: in a scan burst the cache refills fast, so stale reused sessions repeatedly regain priority over the fresh scans and eviction_key inverts back to pre-PR ordering mid-run — the doc comment's "ages out once evictions turn over both" is false. There is also an accounting asymmetry: the page denominator counts pages of all nodes via count/uncount, while only ready leaves increment the numerator (:604-609).

Fix: capture the thresholds at reuse time (store reused_at_tail_pages / reused_at_ready_checkpoints alongside the existing two fields at :84-86, set in mark_reused :367-374) and compare turnover against those snapshots, or make demotion sticky via an explicit demoted: bool written by is_protected's caller.

F2 — Compaction never ages protection (Major)

helios/src/cache.rs:626-630 (compact_ancestor):

    fn compact_ancestor(&mut self, id: CheckpointId) -> RetiredResources {
        let node = self.nodes.remove(&id).unwrap();
        // The ancestor leaves the counts, while its pages stay cached in its heir.
        self.uncount(&node);
        self.tail_pages += node.tail_pages.len();

versus helios/src/cache.rs:604-609 (retire_leaf):

        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);
        }

evict_checkpoint picks compaction whenever the victim has exactly one child (helios/src/cache.rs:749-753), i.e. for every interior node of a linear conversation — the 4x127K 4-turn shape in the PR's own A/B. Moving tail_pages from uncount back into tail_pages also keeps the denominator flat, so nothing observable changes: an unbounded number of interior snapshots can be retired while the reused checkpoint stays protected forever. That is precisely the "unbounded protection livelocks on workload phase shifts" failure the description claims to avoid, reachable through an unmodified path. No test covers compaction aging.

Fix: increment evicted_checkpoints in compact_ancestor too (and decide deliberately whether page turnover should count, since pages move rather than free), or age on snapshots retired rather than leaves.

F3 — Host restore of a brand-new prefix is treated as a reuse hit (Major)

helios/src/scheduler.rs:1884-1887:

        if matches!(result, PublishResult::Created { .. }) {
            self.stats.snapshot_publications += 1;
            self.cache.touch_hit(id, ticket.demand_epoch)?;
        }

finish_inbound publishes the restored ticket into the GPU cache at :1858; Created is returned only when prefixes does not already contain the key (helios/src/cache.rs:466-477 branch not taken), i.e. this is the first GPU publication of that prefix — a creator event, not a hit. Giving it touch_hit sets reused = true and resets both turnover marks (:367-374), so every cold scan pulled from the host tier enters the protected tier and outranks live sessions.

This contradicts the invariant the PR's own test pins, helios/src/cache/tests.rs:1337-1338:

    // Creator completion recency refresh must not mark an un-reused scan as protected.
    cache.touch(scan, 6).unwrap();

and it is invisible in the evidence, because both A/B arms run --prefix-cache-memory 0 (host tier off).

Fix: call plain touch here (host reuse is already accounted as CacheStats::host_hits), or derive the flag from evidence of prior reuse of that key rather than from Created.

F4 — Duplicate publication is inferred as cross-request reuse (Major)

helios/src/cache.rs:466-477:

        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_hit(id, use_epoch)?;

publish_with_retention is also called by the same request that owns the endpoint: RequestScheduler::retire publishes the terminal endpoint (helios/src/scheduler.rs:3101, followed by its own plain touch at :3107-3118) and publish_boundary re-publishes per message boundary (:2948). When the endpoint key already exists — routine when the prompt-end Anchor and the terminal endpoint coincide after few generated tokens — retire self-promotes the node, granting protection with no second client and no cross-request reuse. Nothing in the test suite distinguishes same-request from cross-request duplicates. This inflates the exact adversarial arm (one-shot scans ending at a resident prefix) the policy is meant to suppress.

Fix: thread an explicit hit: bool (or ReuseEvidence) into publish_with_retention from the caller instead of inferring reuse from Existing.

F9 — Inheritance metric ≠ aging metric (Minor)

helios/src/cache.rs:478-481:

        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
        });

A child is born reused: true (:503) on ≥33% shared tokens, then ages by page/node turnover. A 300-token child reusing 200 tokens of a hot prefix is protected even though 100 tokens are new scan content; the boundary is untested (the added tests use 128/128 and 128/512 at helios/src/cache/tests.rs:1365-1384). Impact is bounded (the child still has to survive turnover), but protection leaks from a hot root onto scan endpoints. Fix: gate inheritance on an absolute token/overlap threshold as well, or document why the ratio suffices.

F8 — No observability for the new policy (Minor)

CacheStats (helios/src/cache.rs:182-191, :880-905) and the server metric surface are unchanged; no counter exposes protected victims, reuse marks or turnover. Combined with "zero knobs, zero flags" this means an operator whose hit rate regresses under this policy cannot see which tier a victim came from or why. Fix: add protected_checkpoints / reuse_marks reporters next to the existing accepted/captured counters.


2. Unintended system-level consequences

Metric / rate / admission span check. This PR changes no metric's time or scope: stats.cache_hits/reused_tokens still increment once per admission at helios/src/scheduler.rs:1819-1821, stats.snapshot_publications still increments only on Created (:1885), and no threshold consuming those rates is altered. snapshot_hits/host_hits semantics are unchanged even though touch_hit is now also driven by them — that divergence (metric says "hit", policy says "created") is the F3 defect, not a metric-span change.


3. Architecture, contracts, charter compliance

F5 — Reverses #568's published invariant with no doc update and no owner sign-off (Major)

helios/src/cache.rs:363-365:

    pub(crate) fn eviction_key(&self, node: &Checkpoint) -> (bool, RetentionRank, CheckpointId) {
        (self.is_protected(node), node.retention_rank(), node.id)
    }

is_protected is now the primary key, so a reused lower-rank victim outranks an unreused higher-rank one. #568 (merged 2026-11-28) shipped the explicit invariant "Victim ordering remains strictly (node.retention_rank(), node.id)", and both design docs still state the old contract:

AGENTS.md:204-206 requires "an explicit maintainer decision on the design before implementing a change to that invariant; a commit acknowledgment or routine PR approval is not that decision", and AGENTS.md:227 lists docs/core-design.md as required guidance for cache changes. The diff touches only four files under helios/src — no docs, no verification/ — and the description never mentions #568, #298 or #416. Every comparable merged PR (#298, #416, #567, #568, #582, #655) edited docs/*.

Fix: update docs/core-design.md:1561-1583 and docs/scheduling-runtime-design.md:641-650 in this PR to describe the two-tier order, note the retirement of #568's strictness, and record the owner decision; also state in the description that #298's completion-recency refresh now confers order but not protection.

F6 — Conformance key now depends on state the projection omits (Major)

helios/src/cache/lifecycle_tests.rs:498-505:

    fn key(&self) -> Vec<u64> {
        let mut key = self.projection();
        // Relative retention order preserves eviction choices without an unbounded clock.
        let mut ordered: Vec<_> = self.cache.nodes.values().collect();
        ordered.sort_by_key(|node| self.cache.eviction_key(node));
        key.extend(ordered.iter().map(|node| self.semantic(node.id) as u64));
        key
    }

projection() (:315-352) emits completed created required[] and eight per-node fields — no evicted_pages, no evicted_checkpoints, no reused. Since eviction_key now depends on is_protected → reused/evicted_*, two states differing only in those counters produce the same key and one branch is dropped at visited.insert(next.key()) (:617). The ordering in the key is thus unsound as a canonicalization input, and — separately — verification/helios-lifecycle/README.md:240-241 still says the model does not prove demand/role retention ranking, so the reported TLA+ pass is not evidence for the changed ordering either way.

Fix: add reused and both turnover counters to projection(), or drop the ordered segment from key() and rely on an explicit canonical state; then re-run check.py.

Charter / scope

Zero flags, zero floats, no unsafe, no model branches, integer-only arithmetic, no core/wire-format change (new fields live only in the in-memory Checkpoint, helios/src/cache.rs:84-86), which matches "Keep the runtime small and model-agnostic". The served-workload A/B requirement (#210) is met in shape — named base commit, settings line, two workloads — but see §4 for scope limits. The host/Selene goal is untouched at the wire level; only GPU-tier ordering changes.


4. Tests & claim accuracy

F7 — Missing blocking mutation run; inaccurate evidence claim (Major)

docs/design-review.md:226-228: "Run mutation testing (check.py --mutations or cargo-mutants) when adding or changing safety guards", and :247-251: "Leaving an applicable crate test, simulator sweep, TLA+ conformance run, or Kani proof unrun blocks commit and PR acceptance; noting it as a limitation does not make the omission acceptable." This PR adds a guard (is_protected demotion, helios/src/cache.rs:346-361) and reports only check.py --jobs 4. The existing mutation target verification/helios-lifecycle/check.py:515-519 sits on let tokens = self.protected_eviction_tokens(node, rank); — the exact filter chain the new key is layered onto, so the omission is directly relevant.

Description claim, verbatim: "Selene restore touch_hit is verified by unit tests and TLA+, not live offload." Neither is true as stated: the four added tests (helios/src/cache/tests.rs:1315-1505) are cache-level only — none drives finish_inbound; the existing finish_inbound tests assert only pins/pages/rank (helios/src/scheduler/tests.rs:2914, :3048, :3152 with rank assert at :3179-3180), and verification/helios-lifecycle/README.md:240-241 disclaims retention ranking. Fix: correct the claim, add a finish_inbound test that asserts reused/is_protected after Created (which would have caught F3), and run --mutations.

Other test-coverage gaps (verified)

Claim accuracy (verified against the diff)

Accurate: the LOC split (+64/−4, +192, +6/−1, +9/−1) matches pr_files; "no CLI flags, floats, unsafe, model branches, or core-format changes" is true; "keep eviction_candidates(), reclaimable_if_pinned, and retirement fences unchanged" is true; the stated limits (--prefix-cache-memory 0, SM120 TP4, no effect when capacity fits or scans exceed capacity) are honest. Not stated but material: F1, F2, F3, F4 mechanics; the reversal of #568's ordering invariant; that A/B numbers are n=2 cold-salted trials on a single boot with no variance reported, and the Long-MT p50 TTFT swing (23,886.7/22,228.7 → 2,876.8/3,459.5 ms) is not explained by a 1.74× hit-rate change.


Verified sound (no issue found)

Open questions / could not verify

  1. Do #568's policy tests in helios/src/scheduler/policy_tests.rs still pass with is_protected first? Not run here; the PR does not single them out.
  2. Is F1 reachable in practice at the PR's scale? It needs a demoted node plus refill — plausible in the 20,366-page configuration, but only reproducible with the author's hardware.
  3. Does any off-GitHub (Discord) design decision cover the #568 invariant reversal ("Discord: Dooner")? Not reviewable from the repo.
  4. A/B numbers (n=2, single boot, cold-salted undefined) were not reproduced; no p99 or per-request distribution.
  5. Pre-30-day tracker history for user-facing scan/thrash reports was not exhaustively searched.
  6. Behaviour under #298's motivating 200k–580k-token Kimi K3.1 workload on 16 GPUs is unmeasured anywhere.