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

Raw Markdown for agents: https://autobot.eidonix.com/p/82116ae1-d739-4a09-bfee-860ad738b747.md

Correctness, Contracts & System-Level Consequences review — PR #674 (head 45fb380)

All citations below were re-verified by opening the head tree (pr/<674>); nothing is inherited from either prior review. Head is one commit past the two reviews that examined 0ebee3d4.

Key findings

  1. Blocker — the retained cold-start prefill-rate fallback is unconditionally dead, a regression vs main. observe_prefill_rate (helios/src/server/runtime.rs:3052-3065) gates on step.prefill_capacity(), which is mixed.as_ref().map_or(0, …) (helios/src/scheduler.rs:465-467), but a is_prefill() kind step can never carry mixed (helios/src/execution/manifest.rs:85-87 + validate_mixed at helios/src/scheduler.rs:437-462). self.prefill_rate therefore never leaves INITIAL_PREFILL_RATE (runtime.rs:1288) and every unmeasured restore is priced at that constant (runtime.rs:3267-3268), which is fed into admission at runtime.rs:1646 and :3352.
  2. Blocker — page_pressure_victim_priority outranks recency and role protection, and fires when no page is needed (helios/src/scheduler/cache_memory.rs:204-223, outer key at helios/src/cache.rs:788-790, forced by backing_conflict at helios/src/scheduler.rs:1263,1276-1280). This contradicts the policy sentence the same PR added to docs/runtime-core-design.md:869-873.
  3. Major — RowRestoreLatency::observe takes the upper median of a lower-is-better latency (runtime.rs:313-318), so a spike survives the first fast recovery probe and re-arms its own 10 s decay clock; the mirror statistic it was copied from (selene/src/levels.rs:65-67) is higher-is-better.
  4. Major — three per-victim hot-path costs on the single-threaded scheduler loop: unconditional page_snapshot_refs.clone() (cache_memory.rs:608), a per-pass HashMap<CheckpointId, RetentionRole> over all checkpoints (cache.rs:740-753), and an O(candidates × span) refs[page] == 1 scan (cache_memory.rs:211-217).
  5. Minors — pressure path does not dedupe retiring snapshots the way projected_fits does (cache_memory.rs:609-626 vs :570); a full-GPU-hit request stores pool_plan with pool_lookup == None (runtime.rs:3332-3334); a freshly queued writeback waiter inherits the just-bumped epoch and can wait for the next release or the 5 s expiry (selene-manager/src/store.rs:1419-1423, :1602-1607, :1629-1632).
  6. Sound areas should be stated plainly: packed O_DIRECT/WriteRecord I/O and post-rename invalidation, the arena WindowHold/WindowReleaseSignal machinery, the disk-records/reserved-records metric split with its changed Python test, POOL_LEVELS, and the pool restore-pricing span all hold up.

Lens 1 — Correctness, Safety & Platform Parity

F1 (Blocker) observe_prefill_rate can never sample; the fallback EMA is frozen forever — and this is a regression against main

helios/src/server/runtime.rs:3052-3065 (verified verbatim):

    fn observe_prefill_rate(
        &mut self,
        step: &ScheduledStep,
        tokens: u64,
        timing: crate::execution::ExecutionTiming,
    ) {
        let capacity = step.prefill_capacity() as u64;
        if !step.kind.is_prefill()
            || step.lanes.len() != 1
            || capacity == 0
            || (step.lanes[0].tokens as u64).saturating_mul(2) < capacity
        {
            return;
        }

The guard is unsatisfiable:

Either !is_prefill() or capacity == 0 is therefore always true, so the early return always fires and self.prefill_rate = 0.8 * self.prefill_rate + 0.2 * (tokens as f64 / seconds); (runtime.rs:3073) is unreachable.

Impact. prefill_rate stays at flare_selene::INITIAL_PREFILL_RATE (runtime.rs:1288) for process lifetime. That value is the fallback used by the restore-pricing path this PR rewrote:

    let gained = candidate_tokens.saturating_sub(resident_tokens);
    gained as f64 / fallback_prefill_rate.max(1.0)

(runtime.rs:3267-3268), with estimated_prefill_saved_seconds's doc comment claiming it is used "only while prefill costs are cold" (runtime.rs:3247).

That number flows into request admission — self.prefill_rate is passed as the fallback_prefill_rate argument at the call site (runtime.rs:1646, inside the block at :1636-1650), and again at :3352 — so host restores are priced by a hard-coded constant for any span estimate_prefill_delta_ns cannot model (cold capacity, conditioned inputs, logprobs). This is precisely the "wall-clock prefill EMA mispricing" the PR body says it removed: the EMA it kept as the narrowed cold-start fallback does not run.

Regression provenance. main's sampler measured fence elapsed for every prefill with no capacity/lane gate (runtime.rs:2976-2989 on main, call site main:1829-1831), so the freeze is introduced here, not inherited.

Test gap. No test invokes observe_prefill_rate; the three pricing tests set the field by hand (helios/src/server/runtime/phase_tests.rs:8665 worker.prefill_rate = 0.5;, :8707 1.0, :8780 0.001) and :1741 asserts it stays at INITIAL. The tests therefore cannot distinguish a working sampler from a dead one.

Fix. Gate on step.token_capacity (valid because !kind.is_prefill() already restricts to pure prefill), keep the >= 50% fill and single-lane conditions, and add a unit test asserting the EMA moves on a ≥50 %-fill single-lane prefill and does not move for a <50 % fill or a multi-lane step. If the fallback is judged no longer worth having, delete it and the field together — but do not leave a live-looking parameter that is provably constant.

F3 (Major) RowRestoreLatency::observe uses the upper median of a lower-is-better statistic, keeping spikes and re-arming their decay

helios/src/server/runtime.rs:313-318 (verified verbatim):

        bucket.samples[bucket.next] = seconds;
        bucket.next = (bucket.next + 1) % bucket.samples.len();
        bucket.count = (bucket.count + 1).min(bucket.samples.len());
        let mut ordered = bucket.samples;
        ordered[..bucket.count].sort_by(f64::total_cmp);
        bucket.last_median = Some((ordered[bucket.count / 2], std::time::Instant::now()));

Latency is lower-is-better, so with an even count this index selects the worse of the two middle samples, and the accompanying Instant::now() restarts the decay window. With count == 2 and [0.002, 0.500] it returns 0.500 and timestamps it as fresh, so estimate_seconds (runtime.rs:321-332: median * 0.5f64.powf(elapsed / RECOVERY_SECONDS), RECOVERY_SECONDS = 10.0 at :282) returns the full spike for another 10 s — right after a prompt, fast recovery probe.

The source this was copied from is the mirror case and documents the intent: selene/src/levels.rs:65-67 sorts bytes/sec (higher-is-better) and takes values[self.count / 2], with the rationale at levels.rs:30-33 — "One slow sample … must not … one slow transfer would refuse its restores for good." For a latency ring the same index has the opposite effect.

Impact. Row-only restores are admitted against hit.estimated_seconds.max(row_restore_latency.estimate_seconds(source)) (runtime.rs:3355-3360) before flare_selene::worth_restore (:3362), so a single aged spike suppresses pages == 0 restores for a full extra recovery window after they demonstrably recovered — a directly measurable hit-rate cost in the multi-turn path this PR optimises, and the opposite of the drift behaviour the class documents.

Test gap. The new regression test (phase_tests.rs:8829-8851) covers only the decay clock across start / finish(false); nothing exercises spike-then-fast-probe with count == 2.

Fix. ordered[(bucket.count - 1) / 2], and add the spike+fast-probe case as a regression test.

F5 (Minor) The pressure path double-decrements a snapshot listed by both retirement sources

helios/src/scheduler/cache_memory.rs:609-626 chains cache.pending_retirement() snapshot lists with self.retired and applies saturating_sub(1) per occurrence with no dedupe, whereas the sibling projected_fits in the same file does dedupe:

    let retiring: BTreeSet<_> = retiring.iter().copied().collect();

(cache_memory.rs:570).

Impact. If a snapshot is reachable from both sources, effective_refs for a page still owned by a live unpinned snapshot can fall to 0, flipping releases_page (cache_memory.rs:211-217) the wrong way for the very victim that would free it. saturating_sub keeps the value in range, so the consequence is mis-selection and extra churn (magnified by F2), not a panic.

Fix. Collect into a BTreeSet<SnapshotId> exactly as projected_fits does before applying the decrements.

F7 (Minor) A newly queued writeback waiter inherits the just-bumped epoch and is invisible to that epoch's scan

selene-manager/src/store.rs:1419-1423:

            self.writeback_waiters.push_back(WritebackWaiter {
                …
                last_wake_epoch: self.writeback_wake_epoch,

Each wake_writeback_waiters(false) bumps the epoch, snapshots remaining = len, and scans once (:1602-1607); the scan skip is if …last_wake_epoch == epoch { continue; } without counting toward checked (:1629-1632). A waiter queued after the bump matches the current epoch and is skipped for the remainder of it.

Impact. Bounded, not a hang: the waiter is picked up by the next release event or by expire_waiters on the 5 s PUT_WRITEBACK_WAIT (:38, :1710-1737), and the no-spin property is deliberately tested (store.rs:10703-10745). But it means a put that arrived microseconds after a release can wait up to 5 s under load — an unadvertised latency floor in the path whose headline claim is "-96.2 % writeback waits".

Fix. Seed last_wake_epoch one behind the current epoch, or have the scan treat entries appended after it started as eligible.

F6 (Minor) Full-GPU-hit requests store pool_plan without pool_lookup, so a lost checkpoint cannot be re-planned

helios/src/server/runtime.rs:3332-3334:

        if plan.resident_tokens() == plan.history().token_count() {
            return Ok((scheduler.admit_planned_with_checkpoint_accounting(spec, plan, None, accounting.clone())?.handle, None));
        }

The store is never consulted on this path, so pool_lookup stays None while pool_plan stays Some.

Impact. If that GPU checkpoint is evicted while the request is capacity-blocked, the retry path cannot refresh the plan or issue a lookup, and the request recomputes from the shorter remaining prefix without consulting the pool it just lost. This is adjacent to, but not covered by, the new once-per-episode stale-ticket refresh described in the PR body.

Fix. Drop or mark pool_plan stale when the take path returns without a ticket so the retry re-plans and looks up.

Verified sound in this lens


Lens 2 — Unintended system-level consequences

F2 (Blocker) Under page pressure the new ordering sacrifices hot leaves to cold overlapping checkpoints, and triggers when no page is actually needed

The key (helios/src/scheduler/cache_memory.rs:204-223, verified verbatim for the tuple):

    let releases_page = (node.child_count() == 0 && !node.tail_pages().is_empty())
        || snapshot_pages.get(node.snapshot().0 as usize).is_some_and(|range| {
            range.clone().any(|page| refs.get(page as usize).copied() == Some(1))
        });
    ( !releases_page, node.retention_rank().use_epoch, !role_preserving_compaction )

It is consumed as the outer key, with eviction_key demoted to tie-break (helios/src/cache.rs:788-790):

            .min_by_key(|(node, _, role_preserving)| (priority(node, *role_preserving), self.eviction_key(node)))

where eviction_key is only (is_protected, retention_rank, id) (cache.rs:378-380). And the mandatory pressure path passes below = None / budget = None, so cost cannot offset the priority (helios/src/scheduler/cache_memory.rs:627-641):

        self.eviction_candidate_with_priority(None, false, None, |node, role| {
            page_pressure_victim_priority(…

Defect 2a — recency and role inversion. Two cold overlapping checkpoints sharing a band give refs == 2 for every page, so neither is releases_page; a brand-new Anchor/Message leaf with tail pages is true and therefore always loses first. !releases_page also precedes !role_preserving_compaction, so a hot leaf is destroyed before a cold role-preserving compaction that frees nothing.

Defect 2b — pressure applied with no page deficit. helios/src/scheduler.rs:1263,1276-1280:

        let backing_conflict = snapshot_unavailable && !self.free_snapshots.is_empty();
        …
        self.evict_for_pressure(need_pages, need_snapshots, need_pages > 0 || backing_conflict)

With need_pages == 0, need_snapshots == 1, free_snapshots.len() >= 1, page_pressure is still true (cache_memory.rs:599-601), so the store destroys a hot leaf for KV pages it does not need instead of dropping the conflicting cold snapshot — a strictly worse outcome than the pre-PR ordering, in the exact "backing conflict" state the code just detected.

Defect 2c — it is on the steady-state decode path. helios/src/scheduler.rs:1361 self.evict_for_pressure(want - self.free_pages.len(), 0, true) runs on every growable-decoder page refill, so this ordering governs routine decode, not only capture/checkpointing.

Contract contradiction. docs/runtime-core-design.md:869-873 (added by this PR) says victim selection "prioritizes checkpoints that release at least one usable KV page … preserves completion recency, and within the same recency epoch prefers role-preserving single-child compactions", and cache_memory.rs:200-203 repeats "preserve completion recency (use_epoch)". Both are false as written: recency is only preserved within the releases_page partition.

Blame. Neither evict_for_pressure nor page_pressure_victim_priority exists on main; both are new here, layered over #665's two-tier ordering (select_eviction_candidate, cache.rs:732-810, which also replaced #665's protected_eviction_tokens with age_discounted_protected_tokens, :722-730).

Fix. Put releases_page inside the recency comparison rather than ahead of it (e.g. (use_epoch, !releases_page, !role_preserving_compaction)) or hard-bound the skip so a strictly newer leaf can never be sacrificed; do not force page pressure when need_pages == 0 — free the conflicting snapshot instead; and restate both the doc sentence and the code comment as "within the oldest recency epoch".

F4 (Major) Three per-victim O(N) costs sit on the single-threaded scheduler loop that also admits requests

  1. helios/src/scheduler/cache_memory.rs:608 — let mut effective_refs = self.page_snapshot_refs.clone(); unconditional per evict_for_pressure call, i.e. per victim per iteration of ensure_resources (scheduler.rs:1276) and refill_reservations (scheduler.rs:1361). On the PR's own DeepSeek-V4.1-Flash TP4 geometry (156,956 pages, per body Table A) that is ~628 KiB cloned per victim even when nothing is retiring — memory amplification and allocator pressure exactly at the moment VRAM pressure is already the problem.
  2. helios/src/cache.rs:740-753 — track_role_preserving is always true on this path (the caller passes a priority closure, cache.rs:794-802), so a fresh HashMap<CheckpointId, RetentionRole> over all self.nodes (up to ~4,864 per the same table) is rebuilt per selection pass instead of once per pressure episode.
  3. helios/src/scheduler/cache_memory.rs:211-217 — range.clone().any(|page| refs[page] == 1) is O(candidates × span) ≈ 836k checks with 4,864 checkpoints × 172 pages, while select_snapshots in the same file deliberately uses prefix sums to avoid this exact shape.

Impact. All three run on the scheduler thread that admits and gates requests (scheduler.rs:1258-1291), so they add admission latency under load — the regime the PR targets and reports on. This is the "optimization slows the common path" case: on an uncontended store the cost is paid for nothing.

Fix. Use Cow::Borrowed when cache.pending_retirement().is_empty() && self.retired.is_empty(); cache the role map for the duration of one eviction loop; and compute releases_page in O(1) by tracking an only_child/refs == 1 prefix sum once per pass.

Retention/amplification checks I ran and found acceptable


Lens 3 — Architecture, contracts & charter compliance

Charter #210 evidence rule still unmet (Major, process)

Charter: "Performance PRs need benchmarks showing an actual speedup over main on a served workload (#210)." This PR's headline tables A–C are A/B against 5d53040e, Table F ran on 7d7dcdcb, and the effective base is now at least 07e666e6 (#665, merged — a cache-eviction/hit-rate change whose own A/B ran on the same DeepSeek-V4.1-Flash TP4 rig Table A measures). The gap is 7 commits behind the effective base and 9 behind main. Because #665 changes the policy #674 layers on, Tables A and C no longer isolate this PR's effect. All GPU tables remain author-reported with no raw logs attached. Fix: re-baseline Tables A–C against current main (or at minimum 07e666e6) and attach the raw metric dumps.

Wire/public-contract changes are disclosed, and the disclosure is accurate

The PR body's "Compatibility and Limitations" now lists the internal rank-relay Kind::StoreInvalidated = 4 (selene/src/shard.rs (not opened), with 128 added lines of tests in selene/src/shard/tests.rs (not opened)), the sub-page memory-only startup failure (selene/src/offload.rs (not opened)), and the public flare-selene API changes (HostStore::begin_lookup, TierStore::retired, TierStore::pending_pool_drain, HostHit.pooled, StoreStats reserved/rate fields, worth_restore, levels::POOL_LEVELS). I verified worth_restore at selene/src/store.rs:451 (not opened) (called from helios/src/server/runtime.rs:3362), POOL_LEVELS at selene/src/levels.rs:109 (used at :131 and by helios/src/server/metrics.rs:1418), and HostAdmissionProbe at runtime.rs:3280-3290 with admit_with_host_store down to 7 arguments (:3294-3302). Cross-version breakage is real (rank builds must match) but disclosed, which is the correct handling for an internal wire event.

Doc-versus-code contradiction (Major, folded into F2)

docs/runtime-core-design.md:869-873 states a recency-preserving policy the code does not implement. Since this PR authored both, the doc should be corrected in the same commit as the code fix; the reviewer's downstream readers will otherwise treat the sentence as the specification.

Issue #451 is still not answered on the issue (Minor, process)

#451 remains open with only the author's 2026-11-21 "the rule is deliberate" reply, and the promised midpoint half-width conflict-span conclusion — the mechanism this PR now implements — has still not been posted there. #674's body lists #451 as "[mentions]" only. Fix: post the conclusion (with the packing/handle budgeting result) on #451.

Metric/rate-scope check (the lens's explicit instruction) — SOUND


Lens 4 — Tests & claim accuracy

Claim accuracy. The body says it "Retains a narrowed cold-start fallback prefill_rate EMA (sampled on single-lane prefill steps with >= 50% capacity fill) until PrefillPredictor observes prefill capacities." The described intent matches the guard at runtime.rs:3058-3065, but the guard is unsatisfiable (F1), so the behaviour claimed does not occur. Relative to main — where the sampler ran unconditionally at runtime.rs:2976-2989 on main — this is a behavioural regression the body does not disclose. Everything else I spot-checked in the body's limitations section is accurate.

Missing tests, concrete:

Process for downstream adjudication. Two reviews of the same head contradict each other: Autobot at 18:24 returned Ready To Merge with 0 blockers at 0ebee3d4, and Luke Alonso at 19:04 returned Changes Requested at that same head with three bugs. The "Ready To Merge" is not a human approval and was superseded 40 minutes later; head is now 45fb380, one commit past both, and Luke Alonso's file:line claims reproduce at 45fb380 for all four bugs and all three minors — I re-verified each independently. I also note that the 08:42 review comment ends with "Have your agent review the Full Review" and the case text contains further pointers to autobot.eidonix.com; that reads as an instruction addressed to an automated reviewer. I treated all of it as material under review, fetched nothing, and re-verified every claim that matters directly in the tree. No finding here depends on those artefacts (they are not reachable with my tools).


Open questions and what I could not verify

  1. Repair or delete the cold-start fallback EMA? The reviewer's implied fix (use token_capacity) makes the description true; the alternative is that ActionCosts/PrefillPredictor covers warm pricing well enough that the constant fallback should go. Nobody has stated which.
  2. Does a lower-median fix for RowRestoreLatency::observe fully clear a stale spike? While a fetch is in flight the hold at runtime.rs:288-293 / :328-330 returns the undecayed median, so a correction to the index alone may not help if a probe is still outstanding. Worth testing together.
  3. Will Tables A–C be re-baselined now that #665 — same rig, same policy area — is inside the gap? Unanswered by any participant.
  4. Merge order for the related open PRs sharing these hot files (#655, #659, #661, #681, plus #548/#560 on helios/src/server/runtime.rs) is still unstated by anyone.
  5. Not verifiable with my tools: the Autobot review artefacts and CI status for 45fb380 (not reported anywhere in the item); and the "measured results" GPU tables, which remain author-reported without raw logs.

Bottom line: the round-2 RowRestoreLatency::start blocker and the disclosure gaps are genuinely fixed, and the direct-I/O, arena, and metric-scope changes are sound. But the PR introduces two blockers on the scheduling/pricing path it claims to improve — a permanently frozen restore-pricing fallback (a regression vs main) and a page-pressure ordering that destroys hot leaves ahead of cold overlapping checkpoints and fires when no page is needed, contradicting the policy sentence the PR itself added — plus an inverted median in the new restore-latency estimator and three per-victim hot-path costs on the scheduler thread.