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

Raw Markdown for agents: https://autobot.eidonix.com/p/b556f722-26e4-4cdd-ba61-52d3927de8ab.md

#1 [high] F1: Existing-publication path promotes unconditionally, bypassing every new gate (docs false)

Verified at head c9197427.

helios/src/cache.rs:481-491 (in publish_with_retention):

if let Some(id) = self.prefixes.get(&prefix).copied() {
    let existing = self.nodes.get_mut(&id).unwrap();
    existing.role = existing.role.max(role);
    let ready = existing.ready;
    self.touch_hit(id, use_epoch)?;

=> any duplicate publication (PublishResult::Existing) marks the node reused/protected and resets its turnover counters, regardless of who asks.

helios/src/scheduler.rs:1884-1891 gates ONLY the Created branch:

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

If finish_inbound gets PublishResult::Existing (scheduler.rs:1865-1872, e.g. a cold request published the same prefix first — exercised by scheduler/tests.rs:2914 finish_inbound_attaches_to_an_existing_checkpoint_and_frees_the_ticket), the promotion already happened inside publish_with_retention. So a waiterless (all-cancelled) restore and a preempted re-admission still promote.

Same hole on completion: scheduler.rs:3102-3106 calls publish_with_retention unconditionally; request.preempted is consulted only afterwards at :3097 for refresh_recency. A preempted request's duplicate terminal publication therefore promotes a probationary entry.

Doc contradiction (both synced by this PR):

Tests: the two new finish_inbound tests (scheduler/tests.rs:3233, :3258) only exercise the Created path (empty cache at finish_inbound time). No test covers Existing + cancelled-waiter/preempted.

Fix: give the reuse promotion an explicit parameter/entry point instead of doing it inside publish_with_retention — e.g. Existing branch does plain touch and callers that represent a real hit call touch_hit afterwards (admission hit at scheduler.rs:1734-1740, fresh finish_inbound on both branches); or add publish_with_retention(..., promote_reuse: bool). Then the preempted/cancelled path stays probationary, and add a finish_inbound test where a cold request publishes the key first.

#2 [high] F2: prefix-cache-offload.md contradicts itself on victim ordering after this PR's sync

Verified at head c9197427, both passages are post-PR text in docs/prefix-cache-offload.md.

:298-303 (added by this PR):

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 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.

:374-377 (untouched by this PR, still live):

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.

The second passage now describes the pre-PR single-key order with no protection tier, and points at core-design.md#branching-and-lifetime, which this PR rewrote to the two-tier order (docs/core-design.md:1536-1584). AGENTS.md:52-60 requires documents to specify the architecture the code implements. So an operator reading the eviction section (the passage that appears last) gets the superseded rule, and the two orderings in one file disagree. Discovery dossier finding 5; I re-verified line numbers unchanged.

Fix: rewrite :374-377 to the same two-tier sentence (keep the "demand recency belongs to the selected snapshot" and parent-refresh sentences, which remain true).

#4 [high] F4: mutation gate still does not cover any new guard (check.py has 2 cache.rs targets, both pre-existing)

Verified at head c9197427 (not just from the dossier; re-ran the greps).

search_code for is_protected|demote_expired_reused|eviction_key|touch_hit|ready_tail_pages|evicted_pages in verification/helios-lifecycle/check.py → no matches. search_code for scan_resistant|sticky_demotion|compaction_pressure|continuation_inherits|dual_turnover|policy_regime_shift|finish_inbound_ in check.py → no matches.

check.py:511-520 — the only two helios/src/cache.rs mutation targets, both pre-existing:

check_mutations(cargo, ROOT / "helios/src/cache.rs", CHECKS[4][1], [
    ("lost inherited fence", "child.last_use = child.last_use.max(node.last_use).max(node.ready_after);",
     "child.last_use = child.last_use;", "compaction lost inherited last-use fence"),
])
check_mutations(cargo, ROOT / "helios/src/cache.rs", CHECKS[7][1], [
    ("unbounded endpoint leaf eviction",
     "let tokens = self.protected_eviction_tokens(node, rank);",
     "let tokens = 0;", ...),
])

check.py:323-336 aux_tests lists 12 tests; none of the five new cache tests and neither new finish_inbound test is there.

So the reported "26/26 Rust mutations KILLED" evidences the pre-existing protected_eviction_tokens and compaction last-use guards, not the new victim-ordering/protection/aging state machine. docs/design-review.md:226-228 requires mutation testing "when adding or changing safety guards", and :247-251 states an unrun applicable check blocks acceptance ("noting it as a limitation does not make the omission acceptable"). eviction_candidate_within_budget is explicitly a guard: check.py's own target at :515 feeds it.

Concrete mutants that would be worth adding and would detect real faults this PR's own tests are designed to catch:

Severity: Major. Charter/process compliance gap, not a runtime bug, but it is the one blocking gate named in docs/design-review.md and the PR body claims it is satisfied.

#9 [high] Research summary

I completed the Correctness, Contracts & System-Level Consequences lens on PR #665 at head c9197427, opening every changed production file (helios/src/cache.rs, helios/src/scheduler.rs), their full tests, the docs diff, and the direct callers on the hot paths (ensure_resources, refill_reservations, finish_inbound, retire/finish, publish_boundary, simulate_snapshot_quote/apply_snapshot_quote, retire_leaf/compact_ancestor), plus docs/design-review.md and verification/helios-lifecycle/check.py. Findings are in seven scratchpad notes (F1–F6 plus a verified-sound register).

Headline: the core policy is sound — sticky demotion genuinely closes the old non-monotonic-aging blocker, the new ready_tail_pages counter is paired on every mutation and guarded by a #[cfg(test)] full-scan assert, victim ordering cannot livelock or filter victims, and Fixture::key()'s dedup collision is properly fixed without touching projection(). Two substantive items remain. F1 (Major): the promotion gate is only half applied — publish_with_retention's Existing branch calls touch_hit unconditionally (cache.rs:481-491) while finish_inbound gates only the Created branch (scheduler.rs:1884-1891), so a waiterless restore or a preempted re-admission still promotes a probationary entry and resets its turnover stamp; the same hole exists on completion, since retire calls publish_with_retention before consulting request.preempted. This makes the sentence this PR added to docs/prefix-cache-offload.md:300-303 false as written, and the two new finish_inbound tests only cover the Created path. F2 (Major): the same file still states the pre-PR flat demand-epoch/role ordering at :374-377, contradicting the two-tier text the PR added at :298-303. F3 (Major): no mutation target in check.py touches is_protected, demote_expired_reused, eviction_key, touch_hit, ready_tail_pages or evicted_pages (grep returns nothing), and none of the seven new tests is in aux_tests, so the reported 26/26 Rust kills evidence only the two pre-existing cache.rs guards — docs/design-review.md:226-228/:247-251 requires this coverage for new safety guards. Minor items: an unenforced (I verified not reachable in production) invariant that demote_expired_reused ages unready nodes while eviction candidates are ready-only, an O(all-nodes) demotion walk added to every retirement on the admission and decode hot paths (amplified inside repeated cache.clone() snapshot quotes), and A/B numbers measured on a head that predates all the hardening — the new 2x demotion branch only removes protection, so the shipped policy can only score at or below the reported gains, and the host-restore path has no live evidence.

#10 [high] FINAL REPORT INDEX: finding set, severities, label reconciliation, evidence limits

IMPORTANT — reconcile the labels used in my finish summary against the scratchpad entries, and use this list as the authoritative finding set for the report.

Authoritative mapping (scratchpad entry → finding → severity):

  1. entry 1 (F1) — Blocker-critical, report as Blocker or top Major. Existing-publication path promotes unconditionally (helios/src/cache.rs:481-491), while helios/src/scheduler.rs:1884-1891 gates only PublishResult::Created; the same hole exists at completion (scheduler.rs:3102-3106 runs before the request.preempted check at :3097). Makes docs/prefix-cache-offload.md:300-303 ("only when a live fresh-admission waiter is attached, while preempted re-admissions and waiterless restores refresh demand recency only") false as written, and the two new tests (scheduler/tests.rs:3233, :3258) only exercise the Created path. Call it Major (policy still functions; a documented invariant and an intended guard are defeated).
  2. entry 2 (F2) — Major. docs/prefix-cache-offload.md:374-377 still states the superseded flat demand-epoch/role order, contradicting the PR's new :298-303; violates AGENTS.md:52-60.
  3. entry 4 (F4) — Major. No check.py mutation target or aux_tests entry covers any new guard (is_protected, demote_expired_reused, eviction_key, touch_hit, ready_tail_pages, evicted_pages); only two pre-existing helios/src/cache.rs targets at check.py:511-520. docs/design-review.md:226-228, :247-251. Note: my finish summary called this "F3" — it is entry 4.
  4. entry 8 (corrected F3) — Minor. demote_expired_reused (cache.rs:360-376) ages unready nodes although eviction_candidates is ready-only (cache.rs:699-705); I verified this is not reachable in production (scheduler.rs:2953-2956 errors on unready boundary publication, finish pre-checks last_use > completed at :3044-3047, finish_inbound passes ready_after: self.completed at :1856). Report as an unenforced invariant with a one-line defensive fix, not a runtime bug. Also note this supersedes the Discovery Dossier's carried-forward "unready inheritance + aging" concern, which assumed a production path that the code above closes.
  5. entry 6 (F6) — Minor. O(all-nodes) demote_expired_reused walk per retirement on the admission path (ensure_resources, scheduler.rs:1273) and per decode step (refill_reservations, :1357), plus per simulated eviction inside simulate_snapshot_quote's repeated self.cache.clone() (cache_memory.rs:337, and the double simulation at :306-320 / validation re-simulation at :412-424). Suggest a protected-set index.
  6. entry 5 (F5) — Minor. A/B evidence measured on a7568c2c, i.e. before sticky demotion, compaction turnover and restore gating; the new || node_turnover >= snapshot_horizon branch (cache.rs:363, :370-372) and the tightened restore gate can only remove protection, so the reported 1.89x/1.74x hits are an upper bound for the shipped policy. Plus n=2, one boot, --prefix-cache-memory 0, no variance, no live host-restore evidence. Charter #210 asks for served-workload A/B; the effect is large, so this is a precision/scope caveat, not an absent result.

Report the verified-sound register (entry 7) explicitly so the reader knows what I cleared: ready_tail_pages pairing and the stats() full-scan assert (cache.rs:913-932), ordering cannot livelock (cache.rs:762 is min_by_key, not a filter), Existing is not a self-promotion (cache.rs:454-463 rejects tail_tokens == 0), sticky demotion closes the old blocker (cache.rs:351-355, test cache/tests.rs:1472), Fixture::key() fix is correct and leaves projection()/CacheOwnership.tla's 29-tuple intact (lifecycle_tests.rs:499-526, check.py:27-28), and fresh_admission wiring is consistent (scheduler.rs:1678, :1698, :1709, :1886; touch uses max so epoch 0 at :1696 cannot move accessed backwards).

Evidence limits to state: I could not run check.py, cargo test, or any A/B in this environment, and no CI status is visible for c9197427; every claim above comes from reading the files at head plus the greps recorded in the entries. Nothing in the PR thread attempted to direct my behaviour — the only non-author text is the autobot intake/review, which is stale against head a7568c2.

#3 [medium] F3: inheritance + sticky aging demotes unready children; no test covers it

Verified at head c9197427.

helios/src/cache.rs:360-376 — no ready filter, unlike every other consumer of protection:

fn demote_expired_reused(&mut self, page_horizon: u64, node_horizon: u64) {
    ...
    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;
        }
    }
}

Children are created with inherited protection and reused_at_* stamped at creation (cache.rs:517-519) even when ready == false (ready is proposal.ready_after <= self.completed at :501; publish_boundary passes ready_after: request.last_use, scheduler.rs:2949, which can be ahead of completed). A long prefill that drives evictions between publication and readiness therefore burns the child's entire aging horizon before it is ever evictable, so it arrives already demoted, and per the sticky rule (cache.rs:351-355 is_protected == node.reused) it can only recover through a touch_hit.

Eviction candidates by contrast are ready-only (cache.rs:699-705 node.ready && ...), and the horizon counters only advance for ready nodes (cache.rs:620-626, :672-675), so the aging clock is being applied to a node the eviction path cannot yet see.

Impact: a legitimate multi-turn continuation that inherits protection across a long prefill silently lands probationary and loses to a cold one-shot scan — the failure mode this PR exists to prevent, at low probability. No test covers unready inheritance (the five new cache tests at cache/tests.rs:1315/1347/1396/1472/1569 all publish with ready_after: 0 against completed: 0, i.e. immediately ready).

Fix: skip !node.ready in demote_expired_reused (or stamp reused_at_* at readiness in advance_completed, cache.rs:887-893). Add a test that publishes a child with ready_after ahead of completed, evicts past the horizon, advances to readiness, and asserts the child is still protected.

#5 [medium] F5: PR-body claim "Long-MT ... measured on a7568c2c before sticky-demotion/compaction-turnover/restore-gating hardening"

PR body (Conclusion "Result" section) states: "Single-boot A/B vs 5d53040e ... n = 2 trials/arm; measured on a7568c2c before sticky-demotion/compaction-turnover/restore-gating hardening". Limits paragraph: "GPU A/B ran on a7568c2c, and host-restore gating is verified by unit tests rather than live offload."

Consequences I can state from the diff:

Fix: re-run the A/B on c9197427 (or state plainly that the measured policy was an earlier head and that the current one is expected to be equal-or-more aggressive), and report per-arm spread.

#7 [medium] Verified-sound areas (do not report as issues)

Areas I inspected and found sound — state plainly in the report rather than inventing issues.

Counter bookkeeping (ready_tail_pages) is correct. Every mutation is paired: count (+ :263), uncount (- :274), unready→ready in advance_completed (+ :890), and compaction transfer of moved_pages into a ready heir (:669-671). node.ready is only ever set false→true (cache.rs:889 is the single assignment; search_code '\.ready = ' returns nothing else) and tail_pages only changes at creation (:507) and in compact_ancestor (:663), which is covered. The #[cfg(test)] full-scan assertion in stats() (cache.rs:913-932) now checks ready_tail_pages against the nodes on every stats read, so drift is caught by the whole test suite. The horizon is captured before uncount (cache.rs:616-619, :644-646) — deliberate and correct; capturing after removal would use the post-eviction count.

Victim ordering cannot livelock or filter out every victim. is_protected only reorders min_by_key (cache.rs:762); it is not a filter, so evict's loop (cache.rs:789-805) and eviction_candidate_within_budget's budget filter (:749-761) still terminate exactly as before. evict's .unwrap() on evict_checkpoint (:796) remains safe because the id came from eviction_candidate in the same borrow-free sequence.

Existing-branch touch is not a self-promotion. The upstream "one request promotes itself" concern does not hold: publish_with_retention rejects tail_tokens == 0 (cache.rs:454-463) before reaching self.prefixes, and publish_boundary advances request.prefix_tokens on Created (scheduler.rs:2966-2967), so Existing needs genuine cross-request reuse. The problem is narrower and different — see F1.

Sticky demotion closed the non-monotonic-aging blocker. is_protected reading only node.reused (cache.rs:351-355) means no growth in ready_checkpoints/ready_tail_pages can re-promote a demoted node; sticky_demotion_does_not_reprotect_after_fresh_publications (cache/tests.rs:1472-1568) proves it, and compact_ancestor aging (:672-675) with the 2x snapshot-bound branch (:363, :370-372) is covered by compaction_pressure_ages_out_stale_protected_entry_without_page_evictions (cache/tests.rs:1569-1630).

Fixture::key() collision is fixed correctly. The new tail (lifecycle_tests.rs:499-526) appends, per node in eviction_key order, the semantic id, a reused flag and both elapsed turnovers; projection() (lifecycle_tests.rs:316-353) is untouched so CacheOwnership.tla's 29-integer tuple (check.py:27-28) still matches; Fixture::fork copies the new fields (:76-98). Residual (very low): key() is computed from self.cache.evicted_pages minus the node's stamp, so two states with equal elapsed turnover but different absolute counters collapse. That is intentional (the policy reads only differences) and safe.

fresh_admission wiring is consistent. Set once at scheduler.rs:1678 from accounting.is_none(), first-waiter insert :1698, OR'ed on join :1709, consumed :1886. Ticket.demand_epoch starts at 0 (:1696) and is max-raised at :1816, so touch_hit(id, 0) cannot move accessed backwards (touch uses max, cache.rs:395).

#8 [medium] F3 (corrected): unready-inheritance aging is latent only, not reachable

CORRECTION to my earlier draft — this is a latent inconsistency, NOT a reachable bug. Report as Minor with the reachability caveat, and do not claim a runtime defect.

helios/src/cache.rs:360-376 demote_expired_reused walks self.nodes.values_mut() with no ready filter, and children are stamped with inherited protection at creation even when ready == false (cache.rs:501 let ready = proposal.ready_after <= self.completed;, :517-519).

However, every production publication is created ready:

So the unready+inherited state exists only in unit tests (e.g. the lifecycle fixture) — I found no production path. The dossier's carried-forward note ("a checkpoint that inherited protection while unready can be demoted at the first retirement after a long prefill") assumes a production path that the code above closes.

What remains legitimately reportable: the invariant "protected nodes are always ready, so aging and eviction see the same set" is implicit and unenforced — demote_expired_reused is the one consumer of protection without a ready guard, while eviction_candidates (cache.rs:699-705) guards on node.ready and the horizon counters only advance for ready nodes (cache.rs:620-626, :672-675). If any future caller publishes with ready_after ahead of completed (the field is public on Publication, cache.rs:51, and the scheduler already has two defensive !ready branches at scheduler.rs:1876-1883), such a child would silently arrive probationary.

Fix (cheap, defensive): add if !node.ready { continue; } to the loop at cache.rs:364, or document the invariant at the field's definition.

#6 [low] F6: hot-path cost of the per-retirement full-node demotion scan (incl. quote re-simulation clones)

Two low-severity but concrete consequences on the eviction hot path.

  1. demote_expired_reused is an O(all nodes) walk executed on every ready retirement (helios/src/cache.rs:620-626 in retire_leaf, :672-675 in compact_ancestor), with no early exit — it must visit every node to find the reused ones. evict already re-scans all candidates per iteration (eviction_candidate → eviction_candidates, cache.rs:699-705, :789-805), so each eviction pass now costs roughly twice as much. Callers are admission-critical: ensure_resources (scheduler.rs:1273-1276) runs on every admission under pressure and refill_reservations (scheduler.rs:1357-1360) on every decode step while a growable decoder is short of pages. With the PR's own geometry (20,366 pages) and thousands of checkpoints this is a constant factor, not a cliff, but it is on the synchronous admission path. Cheap fix: maintain a protected: BTreeSet<CheckpointId> (or a count) so the walk visits only reused nodes, and/or return early once no node is protected.

  2. simulate_snapshot_quote clones the whole cache per simulation (helios/src/scheduler/cache_memory.rs:337 let mut cache = self.cache.clone();), and quote_snapshots_preserving_with_budget runs it up to twice (cache_memory.rs:306-320), then apply_snapshot_quote re-simulates to validate (cache_memory.rs:412-424). Each simulated eviction now also runs the new O(n) demotion walk (cache_memory.rs:369 cache.evict_checkpoint(id)), and each clone carries 3 new u64/bool fields per node. Memory amplification is ~24 bytes/node per clone; the time amplification is the demotion walk per simulated victim. Not a defect, but worth stating that the new policy is re-simulated several times per optional capture.

Neither is a blocker. Both vanish with a protected-set index.