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

Raw Markdown for agents: https://autobot.eidonix.com/p/2f8eb15c-afbe-4dcf-894d-5fec6e7548bc.md

Correctness, Contracts & System-Level Consequences — PR #674 review

PR: NVIDIA/hyperflare-inference#674 — "selene,selene-manager,helios: improve prefix-cache hit rate, L1 retention, NVMe throughput, and GPU snapshot packing" (yatesdr). Head 831c47c7, base main c513e46a, branch perf/selene-prefix-cache-holistic.

Tooling limitation, stated up front: pr_diff fails at this head (error: git: error: Could not read c513e46a79f3b6ac510235aaf09bcf055b841958 / fatal: bad revision), so no line-level before/after diff was available. Everything below is verified by opening files in the tree at 831c47c7 and is stated as head-state behaviour, not as a diff claim.

Key findings

No code-level blocker in this lens. The areas the four correctness lenses would normally find blockers in — the clean_slots retention invariant, per-level pool restore-rate spans, RowRestoreLatency estimation, disk-invalidation propagation after rename, and the advertised public API changes — are internally consistent at this head (see "Areas verified sound"). What stands is one Major concurrency/hot-path hazard on the selene-manager store thread, one Major telemetry-accuracy defect that biases the very pricing gauges this PR adds, one Major (partly disclosed) write-path amplification on the path the PR claims to accelerate, four Minor contract/performance items, and one claim-accuracy problem in the PR body. Charter #210's evidence half remains open.


Major

M1. Waiter-storm scan re-derives a full sorted victim list on every pass, on the single store thread

selene-manager/src/store.rs:1610-1666 (verified in tree):

let len = self.writeback_waiters.len();
let start = self.writeback_wake_cursor % len;
let scan_budget = len.min(WRITEBACK_WAKE_SCAN).min(self.writeback_wake_remaining);
let epoch = self.writeback_wake_epoch;
let mut spans = None;
...
if self.can_satisfy_writeback_waiter(&self.writeback_waiters[idx], &mut spans) {
    ready = Some(idx);
    break;
}

and the re-arm at store.rs:1657-1659:

if self.writeback_wake_remaining > 0 {
    self.notify_wakeup();
}

Mechanism, each piece verified:

victims.sort_by_key(|&(id, key, ..)| {
    (self.namespaces[&id].tree[&key].accessed(), key.consumed_tokens)
});

Impact. Under a tight manager (--memory 256M, 1024 blocked puts, continuous disk completions) the store thread — which also serves every get and put — burns O(passes × n log n) tree work per disk reply, plus wake→re-admit→re-wait churn for the same waiter. That is head-of-line blocking on the manager's single serialized thread, the precise regime Tables B/C/F claim to have improved.

Fix. Compute the coalescible-victim span list once per sweep (hoist clean_arena_victims() out of scan_writeback_waiters_step, carry it in the store across the passes of one writeback_wake_epoch); and make a satisfiable verdict sticky by pinning/reserving the coalescible block for the waiter before queue_put.

M2. Metrics::host_lookup_cost double-counts one decision, inflating the PR's own restore-pricing gauges

helios/src/server/runtime.rs:3379 records the pooled candidate:

metrics.host_lookup_cost(missing_tokens, transfer_seconds, prefill_saved_seconds);
if flare_selene::worth_restore(transfer_seconds, prefill_saved_seconds) {
    break Some((hit, source, transfer_seconds, prefill_saved_seconds));
}

then runtime.rs:3400-3404 records the same missing_tokens and prefill_saved_seconds again for the local alternative of the same endpoint:

metrics.host_lookup_cost(
    missing_tokens,
    local_transfer_seconds,
    prefill_saved_seconds,
);

helios/src/server/metrics.rs:544-563 shows every call adds to both the sum and a histogram bucket for all three series:

for (index, (buckets, value, limits)) in [
    (&self.host_missing_tokens, missing_tokens, HOST_TOKEN_BUCKETS),
    (&self.host_transfer_ns, (transfer_seconds * 1e9) as u64, HOST_TIME_BUCKETS),
    (&self.host_prefill_ns, (prefill_saved_seconds * 1e9) as u64, HOST_TIME_BUCKETS),
].into_iter().enumerate() {
    self.host_cost_sums[index].fetch_add(value, Ordering::Relaxed);
    let bucket = limits.iter().position(|limit| value <= *limit).unwrap();
    buckets[bucket].fetch_add(1, Ordering::Relaxed);
}

exported as flare_host_cache_estimated_prefill_ns / _estimated_transfer_ns / _missing_tokens with _sum/_count (metrics.rs:914-950).

Impact. One logical "this pooled row-only restore costs more prefill than it saves" decision adds the same prefill_saved_seconds to _sum twice, so sum/count per honestly-labelled "prefill saved" is biased and the histogram counts exceed the number of candidates examined. Meanwhile the lookup denominator is per admitted request — scheduler.record_host_lookup() at runtime.rs:3420 / :3446 sits outside the per-candidate loop that starts at :3356 — so sums and denominators are no longer commensurable. That directly undermines the PR's claim to "record prefill-saved seconds directly in Metrics::host_lookup_cost": anyone using these series to judge whether restores pay for themselves gets inflated savings on precisely the pooled-row-over-local path this PR added (:3383-3384 comment: "A slow pooled row-only source can be ranked ahead of an affordable local copy at the same endpoint").

Fix. Record once per candidate pair — defer the pooled host_lookup_cost call until after the local comparison and emit only the sample that drove the decision (or emit it inside each break). Add a phase test in helios/src/server/runtime/phase_tests.rs (not opened) asserting exactly one sample per candidate examined.

M3. WritePacked restages every payload byte through one shared ~1 MiB scratch, serialized on the disk thread; unaligned windows are not O_DIRECT

selene/src/disk.rs:1331-1376 (verified):

fn write_direct_slices(&mut self, file: &File, slices: &[&[u8]]) -> Result<u64> {
    let block = BLOCK_BYTES as usize;
    let cap = self.scratch.length;
    ...
            let take = remaining.len().min(space);
            self.scratch.as_mut_slice()[staged..staged + take]
                .copy_from_slice(&remaining[..take]);
            ...
            if staged == cap {
                let span = Span { address: self.scratch.address(), offset: file_offset, length: cap };
                self.ring.transfer(file, &[span], true)?;

reached for every packed write because PackedPayload::Owned(Vec<Vec<u8>>) slices are u8 vectors (alignment 1) and cannot satisfy the aligned-prefix fast path at disk.rs:1272-1307:

match payloads {
    PackedPayload::Owned(chunks) => {
        slices.reserve(chunks.len());
        for chunk in chunks {
            slices.push(chunk.as_slice());
        }
    }

(disk.rs:1394-1399; the PackedPayload::Pinned variant and flare_eos::direct_file path follow at :1400-1415).

Impact. For a ~200 MB compressed record this is one extra full-record memcpy (~200 MB of extra memory traffic and cache pollution) plus ~200 separate direct-write submissions, all on the single disk thread that also serves reads. Measured throughput in Table C (1,054.8 MB/s) leaves headroom, so I do not call this a blocker — but it is memory amplification plus syscall amplification on the exact path the PR claims to have sped up.

Secondary and contract-relevant: the direct path is not universal. write_record_buffered (disk.rs:1311-1325) exists precisely for the unaligned partial-window case and uses page-cache write_all_at:

let bytes = unsafe { raw_slice(span.address, span.length) };
file.write_all_at(bytes, span.offset)
    .map_err(|e| io_failure("write packed record", e))?;

with the in-tree rationale at disk.rs:864-868 ("Partial unaligned streaming windows cannot be block-rounded without overwriting an adjacent window in the temporary file"). The body's "Write compressed v4 records using aligned whole-record O_DIRECT I/O (WriteRecord, WritePacked)" and the post-restart O_DIRECT caveat therefore overstate the guarantee: partial unaligned windows remain page-cache writes.

Fix. Allocate one aligned bounce buffer per record (or require block-aligned payload slabs at the PackedPayload API boundary) instead of restaging through the shared scratch; and state in the body/docs that unaligned partial windows stay buffered.


Minor

m1. write_direct_slices silently assumes file offset 0

selene/src/disk.rs:1335 starts at let mut file_offset = 0u64; and every emitted Span uses that value (:1353, :1370), ignoring the caller's Span.offset. The doc comment at :1327-1330 does say "submit them as direct writes starting at offset 0", so today this is documented, not broken: callers pass the whole record (:848-855) or a fresh packed file (:1415). But nothing enforces it. Impact: a future non-zero-offset caller silently overwrites the file head. Fix: debug_assert!(span.offset == 0) or seed file_offset from the span's offset.

m2. transfer_in_use linear-scans both waiter deques on every put/get begin

selene-manager/src/store.rs:1363-1368 (verified):

|| self.writeback_waiters.iter().any(|waiter| {
    waiter.pending.connection == connection && waiter.pending.transfer == transfer
})
|| self.inflight_waiters.iter().any(|pending| {
    pending.connection == connection && pending.transfer == transfer
})

Impact: up to ~2,000 comparisons per PutBegin/GetBegin at the 1024-deep caps (store.rs:39-40), i.e. on the hot path, and worst exactly when M1's storm is worst. Fix: maintain a HashSet<(u64, u64)> of queued (connection, transfer) ids on push/remove.

m3. TierStore::pending_pool_drain's default contradicts the new retention semantics

selene/src/store.rs:401-404 still defaults to self.stats().memory_records ("all DRAM records"), but with L1 retention clean persisted_in_pool records no longer need handover. The shipped store overrides it correctly (selene/src/memory.rs:2776: slot_count() - free_slots() - clean_slots), and the drain loop bails on deadline/pool.ready() (selene/src/pool/store.rs:309-321), so in-tree behaviour is fine. Impact: any out-of-tree TierStore gets a shutdown drain blocked on records that will never be handed over. Fix: require the override in the trait doc, or default to 0 and make the memory store explicit.

m4. Stale/self-contradictory scope table in the PR body

The body's "Scope Summary" says +10,106 / -1,158 across 42 files while its Verification section says everything was "re-verified on rebased HEAD (831c47c7)". The head is +11,418 / −1,237 across 42 files (dossier §A1; the fix push alone was +1,312/−79, mostly tests). Impact: reviewers reading the diffstat budget against the body are looking at the wrong size, and the two statements cannot both be true. Fix: regenerate the scope table at 831c47c7.


Areas verified sound (stated plainly, not invented issues)

  1. Per-level pool restore-rate span is honest — the metric/rate span check passes. selene/src/pool/store.rs:376-379 observes only restores that carry pages (if !restore.ticket.pages.is_empty()), with started captured at :526 before self.pool.fetch (:528-537), so the sample covers the whole restore, not a disk-thread fragment. Row-only restores are excluded there and priced instead by RowRestoreLatency (helios/src/server/runtime.rs:3372-3378). POOL_LEVELS order equals Ranking::rates() order (selene/src/levels.rs:109-114, :130-132), the stats are plumbed at selene/src/pool/store.rs:664 + selene/src/store.rs:256, and the exporter iterates the same order (helios/src/server/metrics.rs:1416-1424, tests :1990-2014, selene test selene/src/pool/store/tests.rs:1676-1700 (not opened)). No span shrinkage hidden here.
  2. RowRestoreLatency::observe uses the lower median with an explicit rationale (helios/src/server/runtime.rs:316-321), so a stale spike cannot survive as an over-estimate; the previously-reported upper-median inversion is gone (regression test helios/src/server/runtime/phase_tests.rs:9257-9289 (not opened)).
  3. The clean_slots retention invariant is centrally maintained, not scattered. update_clean_slots (selene/src/memory.rs:951-957), refresh_handover/refresh_ancestors/refresh_same_page_descendants (:972-1014), a full-scan assertion in debug/test builds (:1054-1080), and maintenance on retire/persist (:1170-1200). Retention of clean persisted_in_pool records in L1 does not leak accounting.
  4. The new non-blocking drain is genuinely bounded. selene/src/pool/store.rs:309-321 loops on pending_pool_drain() || outbound_in_flight || cascade.in_progress() with a deadline and a pool.ready() bail, so "drain without blocking request teardown" cannot become an unbounded shutdown stall.
  5. RestoreWait::started is not a leak — my earlier suspicion does not survive verification. defer uses *self.started.get_or_insert(now) (helios/src/server/runtime.rs:234) and only clears retry_at (:237), but the whole struct is replaced with RestoreWait::default() on activation (:1786), on readmit-continuation (:2596) and at construction (:1085, :3859), so accumulation is confined to one admission episode — which is exactly the documented intent ("Capacity waiting is charged once per admission episode", :223-224). The only residual subtlety is that started keeps growing while a deferred request sits blocked, which can flip worth_restore false for that episode; that is the stated design, not a defect. Worth one sentence in the docs, nothing more.
  6. Disk invalidation propagates correctly after rename. selene/src/disk.rs:1201-1243 (publish; post_rename removes the path), :1657-1717 (PublishError → Reply.invalidated), :1756-1763 (TransportEvent::StoreInvalidated), tests at :4510-4610 and selene/src/disk_store.rs:9017-9125.
  7. Contract surface matches the disclosure. No protobuf schema change; the only wire addition is the internal rank-relay Kind::StoreInvalidated = 4 (selene/src/shard.rs (not opened), consumed in selene/src/composite.rs:322 (not opened), :1531), which the body correctly flags as requiring matched rank builds. The public flare-selene signature changes listed in "Compatibility and Limitations" match the tree, and per the dossier PR #694 is already consuming them (worth_restore, persisted_in_pool).
  8. Waiter/wakeup and row-restore behaviour have real tests at the caps. selene-manager/src/store.rs:11542-11617, :11868-11995 (including WRITEBACK_WAKE_SCAN + 1 cases), :11125-11232.

Tests & claim accuracy

Process and cross-PR record (from the dossier, not re-derived)

Open questions

  1. Will Tables A–C be re-baselined now that #665 (same rig, same eviction-policy area) is inside the gap?
  2. Will 831c47c7 receive a review of any kind before merge, given the only verdicts target 0ebee3d4?
  3. Will the #451 midpoint half-width conclusion be posted to the issue?
  4. What is the intended merge order across #674, #694, #655, #659, #661, #681 (and #548/#560 on helios/src/server/runtime.rs)?
  5. Is the rebase onto c513e46a real? Unverifiable with my tools (search_history cannot resolve it, pr_diff cannot read it); only body text and code shape (e.g. #665's eviction_key feeding helios/src/cache.rs:848-850 (not opened)) support it.
  6. Prompt-injection-shaped line, flagged as material under review and not acted on: each Autobot review body ends with "Have your agent review the Full Review" pointing at an external page (autobot.eidonix.com/p/…, /api/v1/cases/…); I did not fetch or follow it.