Code correctness report · NVIDIA/hyperflare-inference #734

Raw Markdown for agents: https://autobot.eidonix.com/p/03b95aa6-2e1d-43f3-9413-d44526142d09.md

Deep Correctness / Invariants / Hot-Path Audit — PR #734 (selene: parallelize startup disk scan)

Partitioning decision: 3 files, +498/−112 (≈610 changed lines), single top-level crate (selene/) plus one doc file. Below both large-PR thresholds (>12 files, >900 LOC across 2+ crates), so no sub-agents were used; audited directly at head b7bd3fa.

Bottom line: I found no verified Blocker or Major code defect. The parallelization preserves record::scan's fail-closed and determinism invariants, the .input scan preserves its budget/index invariants, and both call-site contracts (selene/src/offload.rs:754, selene-manager/src/disk.rs:101) still hold. Two Minor observations are documented below; neither is a correctness break. Details of everything I proved are listed so the "no bug" conclusion is auditable.


Protocol 1 — Callee / enum-variant / design-invariant resolution

Inspection enum re-purposing (record.rs:1287-1295) — the new variant semantics are Record / Absent (vanished or not a regular file) / Invalid (temp file, bad name, bad contents) / Unreadable (metadata or content read failure, fail the scan). I verified every producer/consumer agrees:

Two-predicate guard at record.rs:1219: !name.ends_with(SUFFIX) && !(name.starts_with('.') && name.ends_with(".tmp")). I resolved both against SUFFIX = ".ckpt" (record.rs:94) and temporary_name (record.rs:996: format!(".{}.tmp", file_name(key))) and file_name (record.rs:988). Domains are not disjoint (a temp name is .…ckpt.tmp, so it fails the first predicate but passes the second) — the guard is live in both directions and neither conjunct is dead. No unsatisfiable/dead-code defect.

par_map generic bounds (record.rs:1124): T: Sync, R: Send, F: Fn(&T) -> R + Sync. worker is a Fn closure capturing &f, &next, &items — AtomicUsize is Sync, &[T] is Sync when T: Sync, &F is Sync when F: Sync. Sound for both call sites: &[PathBuf] and R = Inspection / std::io::Result<(InputKey, u64, bool)>, both Send. Ordering::Relaxed on the chunk cursor is sufficient — the cursor only hands out disjoint index ranges and all cross-thread data movement happens through Scope's join. No data race, no chunk lost or duplicated (each fetch_add returns a unique start; start >= len terminates).

workers guard is live, not dead: if items.len() < 64 || workers <= 1 (record.rs:1130). workers = available_parallelism().min(16).min(chunk_count). With len >= 64, chunk_count >= 8, so workers <= 1 iff available_parallelism() == 1 (e.g. a 1-CPU cgroup). That is a genuine single-core fallback, not a dead guard — correctly retained.

is_temporary_name (input.rs:937-944) unchanged semantics: requires exactly 64 lowercase-hex digits + .input.pending. Verified a name like user.pending does not match, so the deferred-removal refactor does not widen what gets unlinked; the existing test restart_bounds_the_disk_index_and_preserves_unrelated_pending_files (input.rs:1336-1349) still asserts this and still passes under the new code path (temporaries are only those returned by is_temporary_name).

Design-doc cross-check (docs/prefix-cache-offload.md:678-682, :1196-1205): the doc's new normative claims match the code exactly — (i) unreadable .ckpt fails before deleting temp/invalid files (record.rs:1252 vs 1256); (ii) startup fails if removing over-budget/corrupt/temp .input files fails (input.rs:563-567 and 582-583 both use ? on remove_file); (iii) .input recovery admits in lexicographic path order (input.rs:552).

Protocol 2 — Order-of-operations & state-transition tracing

record::scan reduction (record.rs:1246-1259): traced read-before-write — records/removals are accumulated first, then a single deletion pass, then remove_orphans(records). No state is mutated before the fail-closed return Err; remove_orphans is only entered with a fully-successful inspection set, so the orphan fixpoint (record.rs:1262-1284) can never delete a descendant of a record whose inspection failed. Pre-PR interleaved deletion could not make that guarantee.

Worker::scan state ordering (input.rs:514-587): traced the exact order — entries/temporaries collected → sort → par_map → error gate (554-562) → temporaries unlinked (563-567) → admission loop mutating self.disk + self.budget.reserve_input (568-585). Confirmed the gate strictly precedes both the .input.pending unlinks and every self.disk.insert / reserve_input call, so an unreadable entry leaves self.disk empty and the budget uncharged. The caller Worker::new (input.rs:506-510) then does budget.release_input(disk.values().map(...).sum()) — with disk empty that is a no-op, so no double-charge and no under-release. This is exactly what the new test parallel_scan_preserves_directory_and_budget_on_unreadable_entry (input.rs:1716-1746) asserts via checkpoint_limit() == limit, checkpoint_pressure() == 0, and budget.reserve_input(limit).

Error-path index alignment (input.rs:554-561) — verified, and this is the subtlest hunk in the PR: inspected.iter().position(...) yields pos in entries order because par_map restores index order; entries[pos] is therefore the same file whose error is reported, and inspected.swap_remove(pos).unwrap_err() extracts that same Err. swap_remove is safe here only because the function returns immediately after — I confirmed there is no subsequent use of inspected on that path. (Also note the borrow checker accepts the overlapping immutable/mutable borrows only under NLL, which holds.) No wrong-file-reported and no index-shift defect.

Same-iteration flag check: the admission guard self.disk.len() < MAX_DISK_RECORDS && self.budget.reserve_input(bytes) (input.rs:570-571) short-circuits so the budget is not charged when the record-count cap rejects — preserving the pre-PR ordering exactly. And within an iteration nothing later in the loop body clears a flag read earlier in that iteration (the loop only inserts/removes).

Handle-close-before-unlink (Windows safety): inspect opens let mut file = fs::File::open(path) (record.rs:1306) and returns Inspection by value, so file is dropped at every return path inside the parallel closure. All remove/remove_file calls happen in the sequential reductions (record.rs:1256-1258, input.rs:563/582) after par_map has returned. Verified for both call sites — no handle is held across an unlink.

Protocol 3 — Adversarial small-N / boundary / sort-order counterexamples

Protocol 4 — Hot-path big-O

par_map (record.rs:1124-1171) at N = 10,000: O(N) work, O(N/chunk) chunk vectors, one sort_unstable_by_key over N/8 = 1,250 entries (O((N/8)·log(N/8)), ~2% of the linear work), and a final Vec::with_capacity(N) flattened move-copy of N R values. Acquire is Relaxed on an AtomicUsize touched once per 8 items — negligible contention. No O(N·span), no per-iteration Vec::clone/HashMap::new, no re-scan inside the loop. remove_orphans (record.rs:1262-1284) is unchanged: its HashSet rebuild per orphan-generation is pre-existing and bounded by chain depth.


Minor observations (verified, not correctness breaks)

Minor 1 — record::scan holds three live N-sized path collections at peak (record.rs:1203, 1224, 1246-1255).

let mut candidates = Vec::new();            // path 1: PathBuf per candidate
...
let outcomes = par_map(&candidates, |path| { ... });   // candidates still live
let mut records = Vec::new();
let mut removals = Vec::new();
for (path, outcome) in candidates.into_iter().zip(outcomes) {   // outcomes + records + removals live

inspect also allocates a second PathBuf per record via path.to_path_buf() (record.rs:1349) which is then moved into records. Peak is therefore ≈ 2 path copies for survivors plus the Inspection vector, versus 1 path copy on main. At the PR's own 10,000-record scale this is ≈ 10,000 × ~100 B ≈ 1 MB of extra transient allocation — irrelevant next to the 649 GiB working set, but it is a genuine 2–3× increase in scan-index memory that is unnecessary. Fix: have par_map produce the path inside the outcome only for survivors (or take the paths by Vec::into_iter and have inspect return Inspection without path, re-attaching path during the reduction) — the reduction loop already owns path.

Minor 2 — the parallel path is chosen purely by item count, ignoring actual storage queue depth / device (record.rs:1130). record::scan will spawn 16 threads on a network filesystem or a single-spindle device just as readily as on local NVMe; the PR's own motivation is "local NVMe caches" and its warm measurements show a 1.8–3.7× rather than 10× gain. This is an absolute improvement in every measured case (never a regression in the supplied data), so it is not a defect — but the threshold is a fixed 64 items rather than a per-entry cost probe, so on a high-latency remote mount the fan-out could add contention on top of tail-latency-bound I/O. Not a bug; noting only because the constant is unconfigurable.


Explicitly checked and found sound (so this is not a "looked briefly" pass)

Limitations of this audit

I performed a static audit at b7bd3fa and did not execute cargo test (no toolchain in this environment), so the claim "every test passes" rests on my line-by-line reading of the new fixtures against the actual packed::Layout::new, Header PartialEq/Hash, DiskBudget, and ModeGuard definitions rather than on a run. Windows execution remains unverified, as the author discloses, but the close-before-unlink property is structurally guaranteed by inspect's handle lifetime.