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

Raw Markdown for agents: https://autobot.eidonix.com/p/df7a7725-0864-4270-9d4c-489150053081.md

Correctness, Contracts & System-Level Consequence Review — PR #694 (selene,helios: add write-side NVMe and pool spill profitability gate, head d74e810)

Key findings

  1. Major — the pool spill gate silently fail-opens for every record recovered from disk. Scan-time index insertion hardcodes prefill_saved_ns: 0, and 0 means "unpriced ⇒ profitable" in both gate implementations. Only a republish of the same key backfills the price, so the cold-restart population the PR benchmarks spills to the pool unconditionally. (§A1)
  2. Major — the NVMe gate drops the DRAM→GPU upload charge exactly under DRAM pressure. composite_rates is passed only when memory.fits(chain_slots), so under pressure the gate prices bytes/disk_rate instead of the restore-side bytes/disk_rate + bytes/memory_rate — roughly 2× more permissive than the admission pricing it is meant to mirror, contradicting the PR's own "charging both disk read and DRAM-to-GPU upload" claim. The composite-side gate (composite.rs:587-591) uses the strict formula for the same record, so the two gates can disagree. (§A2)
  3. Major — the new metric family, the new reason label, and the new public StoreOutcome variant are undocumented. Two Prometheus series plus an unprofitable reason value are user-visible contracts absent from docs/api.md; StoreOutcome::Unprofitable (terminal, non-deferring in helios) is absent from the documented publication outcomes. (§C1)
  4. Minor — O(n) full-index rescans per blocked capture retry on the store's single driver thread, O(n·retries) under sustained disk pressure. (§B1)
  5. Minor — reap_evicted_dram_only consumes the eviction list, then discards batch-removal errors, permanently stranding dram_only/dram_only_descendants bookkeeping for a non-resident key. (§B2)
  6. Claim accuracy — the served A/B was measured on a different commit (09400ad8, not head d74e810), two of three rows report zero gated spills, and the fleet table is an offline replay. (§D1)

Sound on inspection: the pricing predicates (NaN/inf-safe, strict, unit-tested), PoolSpillPolicy hysteresis threading (single driver, no new lock), the O(1) clean_slots invariant, Index::remove_nodes batch atomicity, the level→rate index mapping, and metric monotonicity. No protobuf, Ignition, model-core, graph-contract or on-disk v4 change appears in the file list. (§E)

Tooling caveat: pr_diff fails in the local copy (fatal: bad revision 'cc0a49d2…d74e810') and search_history/related_items cannot resolve base objects, so no diff hunks or commit-level history were available. Every citation below is a full-file read at pr/694; nothing is inferred from memory.


A. Correctness, safety & platform parity

A1. (Major) Pool gate is inert for disk-recovered records — prefill_saved_ns starts at 0 and 0 means "profitable"

Index::insert initialises the new field for every record it creates (selene/src/shared/index.rs:457-476):

        self.nodes.insert(
            key,
            Node {
                key,
                parent,
                published_ancestors: Vec::new(),
                chain_depth,
                bucket,
                tail_pages,
                row,
                ready,
                prefill_saved_ns: 0,

DiskStore::new inserts every startup-scanned record through that path, with ready = true and no price (selene/src/disk_store.rs:2305-2322):

        let mut used = 0u64;
        for record in &scanned {
            index.insert(
                record.header.key,
                record.header.parent,
                record.header.bucket,
                record.header.tail_pages as usize,
                record.row,
                true,
                DiskRecord {

The pool gate then treats zero as "unpriced ⇒ profitable" (selene/src/disk_store.rs:2191-2206):

fn disk_pool_standalone_profitable(
    layout: &Layout,
    policy: Option<crate::store::PoolSpillPolicy>,
    node: &Node<DiskRecord>,
) -> bool {
    let Some(policy) = policy else {
        return true;
    };
    let saved_ns = node.prefill_saved_ns;
    if saved_ns == 0 {
        return true;
    }

and the shared predicate does the same (selene/src/store.rs:526-534, with the explicit doc comment "prefill_saved_ns == 0 disables the gate (unpriced)"). The in-memory mirror is identical (selene/src/memory.rs:437).

The only backfill for a recovered key is on republish of that same key (selene/src/composite.rs:810-824, called at composite.rs:1841, 1867, 1888; mirrored at selene/src/memory.rs:3693-3700 and selene/src/disk_store.rs:3606-3611). The PR's own regression test documents this exactly (selene/src/composite.rs:8017-8033):

        // Reopen from disk: recovered record starts with `prefill_saved_ns == 0`.
        let mut recovered = composite(&directory, 32, 8, 1 << 30);
        assert!(recovered.disk.index().node(&r.key).unwrap().ready);
        assert_eq!(recovered.disk.index().prefill_saved_ns(&r.key), 0);
        recovered.set_pool_spill_policy(Some(crate::PoolSpillPolicy {
            level: crate::levels::Level::RemoteNvme,
            rate_bytes_per_sec: 1_000_000.0,
        }));
        assert!(recovered.spill_eligible_pool(r.key));

Impact. After any restart — the exact scenario in the PR's "Cold-Restart Hits" column — the whole population loaded from NVMe is unpriced, so disk_pool_eligible_node (selene/src/disk_store.rs:2208-2264) and the memory equivalent (selene/src/memory.rs:429-444) take the true branch on the standalone check and cascade those records to the pool regardless of profitability. The gate only starts working for a key once helios happens to publish that key again; keys that are never re-offered (long-lived endpoints, cold tenants) are never gated, and the skip counters under-report for precisely the population the feature targets. There is no counter distinguishing "unpriced, allowed by fail-open" from "priced and profitable", so operators cannot see this.

Fix. Price records at scan time or on first use — derive prefill_saved_ns from the record geometry and the scheduler's prefill rate (the same fallback helios already applies at publish, estimate_prefill_delta_ns(...).unwrap_or_else(prefill_rate)), or persist the price in the v4 header/backfill it inside DiskStore::new before any retire decision. Alternatively make recovered zero-priced records fail closed for pool spill with a distinct counter (skipped_unpriced) rather than silently profitable.

A2. (Major) The NVMe gate's cost basis collapses to disk-read-only under DRAM pressure, diverging from restore-side admission pricing

The composite store decides the rate pair from transient DRAM occupancy (selene/src/composite.rs:540-551):

        let layout = self.memory.layout();
        let total_pages = (checkpoint.key.consumed_tokens / layout.page_tokens) as usize;
        let row = self
            .disk
            .needs_row_excluding(checkpoint, Some(&self.dram_only));
        let chain_slots = layout.record_slots(total_pages, row);
        let composite_rates = self.memory.fits(chain_slots).then(|| {
            (
                self.disk_inbound_rate.get().max(1.0),
                self.memory.stats().inbound_rate.max(1.0),
            )
        });

and the disk store's gate branches on that (selene/src/disk_store.rs:3579-3584):

        let transfer_seconds = match composite_rates {
            Some((disk_rate, memory_rate)) => {
                raw_bytes as f64 / disk_rate.max(1.0) + raw_bytes as f64 / memory_rate.max(1.0)
            }
            None => raw_bytes as f64 / self.inbound_rate.get().max(1.0),
        };

The restore-side price it is supposed to match is unconditional (selene/src/composite.rs:406-423):

        let bytes = layout.record_bytes(chain.pages as u64);
        let memory_rate = self.memory.stats().inbound_rate.max(1.0);
        ...
            estimated_seconds: disk_bytes as f64 / self.disk_inbound_rate.get().max(1.0)
                + bytes as f64 / memory_rate,

Note also that the composite-level gate computes the strict form unconditionally for the same record at spill time (selene/src/composite.rs:587-591):

        let disk_rate = self.disk_inbound_rate.get().max(1.0);
        let dram_rate = self.memory.stats().inbound_rate.max(1.0);
        let transfer_seconds = disk_bytes as f64 / disk_rate + upload_bytes as f64 / dram_rate;
        if crate::store::standalone_spill_profitable(transfer_seconds, prefill_saved_ns) {
            return (true, disk_bytes);
        }

Impact. memory.fits(chain_slots) is false exactly when DRAM is full — the condition that makes spilling attractive. In that regime the write-side gate prices the restore at roughly half the true cold-restore cost CompositeStore::hit charges, so it admits writes that restore-side admission (worth_restore) will then refuse: the "skip work you will never be allowed to use" objective fails precisely under load, and the same checkpoint is priced differently depending on transient occupancy (non-deterministic spill decisions for identical inputs, which makes the skip counters hard to interpret). It also contradicts the PR description's claim to charge "both disk read and DRAM-to-GPU upload on streamed temporary-pin writes to match cold CompositeStore::hit", and the two gates' divergent formulas mean a record can pass the store-time check and fail the spill-time check for reasons invisible to the operator.

Fix. Always pass both measured rates when the store is composite (memory.stats().inbound_rate is known regardless of fits()); reserve None for a standalone DiskStore where no DRAM tier exists. Better: call the single shared pricing helper from both sites so store-time and spill-time decisions cannot diverge.


B. Unintended system-level consequences

B1. (Minor) Full-index rescan per blocked capture retry — O(n) per attempt, O(n·retries) under sustained disk pressure

Both capture paths loop until success or bail-out, and each iteration runs the shadow-reclaim scan (selene/src/composite.rs:506-532):

        loop {
            let reserved = self
                .disk
                .reserve_capture(key, parent, bucket, tail_pages, row, true, role)?;
            self.drop_evicted_copies();
            if reserved.is_some() {
                return Ok(reserved);
            }
            ...
                || !self.evict_blocking_dram_only_for_disk(parent)
            if outcome != StoreOutcome::Retry(StoreReason::Budget)
                ...
                || !self.evict_blocking_dram_only_for_disk(protected)

evict_blocking_dram_only_for_disk (selene/src/composite.rs:473-492) calls reclaimable_uncharged_subtree, which allocates a HashSet chain, walks index.ordered() (the full LRU set) and, for each candidate root, walks that root's entire descendant subtree (selene/src/disk_store.rs:2617-2667):

        let mut protected_chain = HashSet::new();
        ...
        let mut subtree = Vec::new();
        for root in self.index.ordered() {
            if !root.ready
                || root.location.bytes == 0
                ...
            while head < subtree.len() {
                let key = subtree[head];

Impact. Under sustained disk pressure (the condition these loops exist for) each publication attempt costs a full index scan plus subtree walks plus two allocations, repeated per retry, on the single thread that must also drain copies, serve lookups and progress restores — head-of-line risk for the same publication path the PR is optimizing. Bounded by pending writes, so Minor rather than Major.

Fix. Start the scan from the LRU head and stop at the first eligible root (the function already returns on the first valid subtree — the waste is rebuilding protected_chain and re-clearing subtree per attempt); or cache the candidate root between attempts and invalidate on a successful reclaim.

B2. (Minor) reap_evicted_dram_only consumes the eviction notice then swallows removal failure

selene/src/composite.rs:447-464:

        let evicted: Vec<PrefixKey> = self
            .memory
            .take_evicted()
            .into_iter()
            .filter(|key| self.dram_only.contains(key))
            .collect();
        if !evicted.is_empty() {
            let removed = self
                .disk
                .remove_uncharged_batch(&evicted)
                .unwrap_or_default();
            for key in removed {
                self.dram_only.remove(&key);
                self.dram_only_descendants.remove(&key);
                self.thinning.remove(&key);
            }
        }

take_evicted() drains memory's list, so the notice is delivered exactly once; the sibling reclaim path already handles partial batch failure explicitly (selene/src/composite.rs:485-491 tracks removed_keys and cleans up copies accordingly), and the single-key path reports failures rather than discarding them (selene/src/composite.rs:1872-1879). Impact. If remove_uncharged_batch returns Err (e.g. a batch entry still pinned or holding a surviving child), the dram_only key and its dram_only_descendants voter set survive for a record with no resident copy; promote_dram_only then returns early on !self.resident(...) (selene/src/composite.rs:613-616), so the anchor can never be promoted or reclaimed, permanently blocking the durable ancestor behind it, and the fork-vote bookkeeping for that prefix is poisoned until process restart. No counter or debug_assert records the loss. Fix. On Err, keep the failed keys in a retry set (or re-queue them into memory's evicted list) instead of unwrap_or_default(), and count/debug_assert! the failure like the neighbouring call sites.


C. Architecture, contracts & charter compliance

C1. (Major) New observability and API contracts are undocumented

Two new Prometheus families (helios/src/server/metrics.rs:872-885):

        text.push_str("# HELP flare_host_cache_spill_skipped_unprofitable_total Spills skipped because standalone restore latency exceeds the profitability threshold.\n# TYPE flare_host_cache_spill_skipped_unprofitable_total counter\n");
        ...
                "flare_host_cache_spill_skipped_unprofitable_total{{tier=\"{tier}\"}} {}",

a new reason label value on an existing family (helios/src/server/metrics.rs:919-933):

                "host_cache_store_reasons_total",
                &[
                    "present",
                    "inflight",
                    "slabs",
                    "queue",
                    "budget",
                    "oversize",
                    "unprofitable",
                ][..],

and a new public enum variant (selene/src/store.rs:268-276, StoreOutcome::Unprofitable).

Doc verification: a search of docs/api.md for spill|profitab|unprofit returns nothing (only flare_host_cache_dropped_total{tier,reason} at docs/api.md:364), while every other host-cache family is documented in the table and prose at docs/api.md:341-398. The publication-outcome contract still lists three outcomes only (docs/prefix-cache-offload.md:1462-1465):

- **Publication outcomes.** `Present` requires a committed local copy; a lookup
  hint is not sufficient. `Oversize` includes required ancestor files that
  cannot coexist within the disk limit even without unrelated records, and
  `Retry` means that capacity or queue room is temporarily unavailable.

The only gate text added is docs/prefix-cache-offload.md:685-696 (RAM record/parked/dram_only behavior), which does not mention the counters, the unprofitable reason, or Unprofitable as a terminal outcome.

Impact. Operators cannot interpret the two new series or the new reason value, and — more importantly — third-party embedders of selene reading the documented outcomes will not handle Unprofitable, which in helios is terminal (unpin, no deferral), i.e. a different control-flow contract from Retry. The metric help text also does not say the byte counter is uncompressed logical bytes rather than bytes actually written, which is the question an operator will ask when comparing against flare_host_cache_bytes_out_total. Fix. Add both series (tier semantics + "uncompressed logical restore bytes") and unprofitable to docs/api.md:341-398; add Unprofitable with its no-pin/no-deferral semantics to docs/prefix-cache-offload.md:1462-1465.

C2. (Minor) PR description does not match the tree in two provable places

Charter fit is otherwise good: the area is a stated goal ("Store prefix-cache checkpoints in host memory and share them across Flare instances via Selene"), no per-model branch, flag or env switch appears, and no wire/format/ownership-signoff surface is touched.


D. Tests & claim accuracy

D1. (Minor→Major) Served A/B measured on a different commit; two of three rows never exercise the gate; fleet table is a replay

PR body, verbatim:

"Measured on combined development commit 09400ad8 vs base 19ce4a7b across three hybrid EXACT_ROW models ... (workload: 12 short single-turn prompts + 4 short-to-long growth conversations + 6-way fork over a 500-token system prompt + cold restart)"

Head is d74e810. In the same table, GLM-5.3 TP2 reports "Skipped Unprofitable (Run 1 / Run 2) | 0 (TP2 prefill; see fleet replay)" and DeepSeek-V4.1 TP4 reports "0 (self-calibrating)" — yet their NVMe-byte deltas ("5.10 → 3.79 GB", "834.8 → 832.2 MB") are presented as evidence for the gate. Only the Qwen3.8 row (25 / 4) shows the gate firing. The fleet table is explicitly offline: "Exact replay of standalone_spill_profitable + fork_dedup_profitable against .ckpt headers from production pools", with a "Shared Forks Promoted" column computed by the replay rather than observed.

Materiality anchor: helios prices only via the scheduler's measured prefill delta with an EMA fallback (helios/src/server/runtime.rs:2912-2921, estimate_prefill_delta_ns(c, 0, c, false, &[], &[]) → unwrap_or_else(|| ((c as f64 / self.prefill_rate.max(1.0)) * 1e9) as u64)), and estimate_prefill_delta_ns returns None while capacities are unmeasured (helios/src/scheduler/checkpoints.rs:438-461). The PR's "pre-existing exported cores without re-export" configuration is exactly the window where the EMA fallback sets the price, so the measured skip counts depend on measurement state rather than on the shipped code path alone.

Fix. Rerun the A/B at head with a warmed prefill catalog; report per-config skip counts for every row (and say explicitly when a row exercises nothing); state the measurement commit and label the fleet table as a replay next to its numbers (Charter: "Performance PRs need benchmarks showing an actual speedup over main on a served workload", #210).

D2. Test coverage that is present (positive note)

The new paths are genuinely covered in-repo: pricing predicates and geometry-derived break-even (selene/src/store.rs:593-638, including a NaN case), the recovered-record backfill (selene/src/composite.rs:7991-8038), cascade retention (selene/src/pool/cascade.rs:3215-3785), memory coverage/eligibility (selene/src/memory.rs:8184-9011), disk-store gating (selene/src/disk_store.rs:9925-10497), batch removal (selene/src/shared/index.rs, remove_nodes tests) and metric rendering incl. the new reason value (helios/src/server/metrics.rs:2050-2066). Gap: no test asserts whether a scan-recovered, never-republished record may spill to the pool — the existing test only asserts the republish path (§A1), so the fail-open behavior is unpinned by design intent. Likewise no test covers composite_rates == None (DRAM-full) pricing parity with CompositeStore::hit (§A2).


E. Areas inspected and found sound (do not re-flag)

  1. Predicate safety/units. worth_restore, standalone_spill_profitable, fork_dedup_profitable reject NaN/inf, use saturating_mul and strict >, and fork_dedup_profitable requires pages > 0 && child_paths >= 2 with real byte savings (selene/src/store.rs:496-550).
  2. Hysteresis cannot thrash and adds no lock. Only PooledStore::poll pushes the policy, gated by materially_differs_from (≥5%) (selene/src/pool/store.rs:603-610); Core::set_pool_spill_policy short-circuits on equality (selene/src/memory.rs:1299-1305). All store mutation stays on the store's own thread; no new cross-thread state.
  3. O(1) clean_slots is defended by assert_clean_slots_invariant, which recomputes from a full index scan in debug/test (selene/src/memory.rs:1613-1701).
  4. Index::remove_nodes validates the whole closed batch before mutating, so a bad batch cannot half-remove (selene/src/shared/index.rs:523-574).
  5. Level→rate mapping is not off-by-one: Level::HostNvme → rates[2], RemoteNvme → rates[3], matching Ranking::rates() order (selene/src/levels.rs:107-132, selene/src/pool/store.rs:242-258).
  6. Metrics stay monotonic because they store cumulative StoreStats values rather than incrementing per tick (helios/src/server/metrics.rs:632-637); the existing outcome-sum assertion still counts 6 because Unprofitable is exercised only in the new test.
  7. No platform-parity, protobuf, Ignition, model-core, graph-contract or on-disk v4 change appears in the file list. The only externally-visible structural change is the added PublishedCheckpoint::prefill_saved_ns field (selene/src/store.rs:42-45), which is why downstream fixtures needed prefill_saved_ns: 0 (e.g. selene-manager/tests/client.rs (not opened), selene/src/offload/sharded/tests.rs:172 (not opened), selene/src/testing.rs:412 (not opened)).
  8. No metric-span regression found of the type this lens targets (inbound_rate, estimated_seconds): DiskStore::inbound_rate still samples only bulk page-bearing restores and explicitly excludes row-only fetches (selene/src/disk_store.rs:3803-3851, test at 9652-9720), and the new gate consumes rates already in that scope. The one span-related concern is the conditional inclusion of the upload term in §A2, not a narrowed measurement window.

Open questions / could not verify

  1. Whether the scan-time prefill_saved_ns = 0 + fail-open is intentional scoping (the republish-backfill test suggests it is at least tolerated) or an oversight — the PR description does not say, and no test pins either reading.
  2. Whether the PR's A/B numbers reproduce at head d74e810 with a warmed prefill catalog, and whether the gate can fire at all for GLM-5.3 TP2 / DeepSeek-V4.1 as configured.
  3. Whether memory.fits()-gated upload charging (§A2) was deliberate to avoid double-charging when the chain already occupies DRAM — plausible, but it is not stated in the PR or in a code comment, and it produces the pressure-dependent divergence described.
  4. No diff-hunk or commit-level verification was possible: pr_diff fails (fatal: bad revision 'cc0a49d2…d74e810') and history objects are missing in the local copy, so the "#674 vs #694" split was reconstructed from full-file reads and symbol searches, not from a diff.