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:
record.rs:1225-1244(par_mapclosure) is the only producer.symlink_metadataNotFound→Absent(matches pre-PRcontinue); non-regular →Absent(matches pre-PRif !metadata.is_file() { continue; }at old line 1147); non-.ckptname →Invalidbut this is unreachable dead-by-construction becauserecord.rs:1219already filtered!(ends_with(".ckpt") || (starts_with('.') && ends_with(".tmp"))). A.tmpname therefore always reachesInvalid→ deletion, matching pre-PRremove(&path).inspect(record.rs:1297-1353) returnsInvalidonly forUnexpectedEof/InvalidData/Header::decodefailure/semantic mismatch, andUnreadableotherwise — byte-for-byte the same classification as pre-PR inline code.- Critical invariant checked:
Inspection::Unreadablemust not be reachable in the.tmp-deletion path. Verified:record.rs:1248-1255accumulatesremovalsforInvalidonly, andUnreadablereturnsErrat line 1252 before thefor path in removals { remove(&path)?; }loop at 1256-1258. So a.tmpsibling of an unreadable.ckptnow survives a failed scan — this is the intended, documented fail-closed change (record.rs:1185-1188,docs/prefix-cache-offload.md:681).
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
n = 0, 1, 2, 63, 64, 65:chunk_count = len.div_ceil(8).len = 0→chunk_count = 0→workers = min(ap,16,0) = 0→ note: the check isworkers <= 1, which catches0, solen = 0returnsitems.iter().map(f).collect()(empty) rather than spawning zero workers and returning empty via the parallel path. Correct by luck of the<= 1(not== 1) comparison — worth keeping.len = 63→ sequential;len = 64→chunk_count = 8, parallel.len = 65→ chunks[0..8, 8..16, …, 64..65], last chunk of 1 —end = (start + 8).min(65)handles it, andsort_unstable_by_keyrestores order. No off-by-one.- Sort-order counterexample (
.inputadmission):entries.sort_unstable_by(|a, b| a.as_os_str().cmp(b.as_os_str()))(input.rs:552) compares rawOsStrbytes on Unix — a total order on the full path bytes, so it is deterministic and independent of filesystem readdir order (FIFO/tmpfs-LIFO/ext4-hash). Verified there is no cross-platform divergence that matters: on WindowsOsStrcompares UTF-16 code units, still a total order, so admission is deterministic per platform (not identical across platforms, but recovery was never cross-platform-ordered). The new test seeds(1..140).step_by(2).chain((0..140).step_by(2))and thenkeys.sort_unstable()before assertingkeys[..80]survive — that is exactly the counterexample that fails if the sort is removed, so the invariant is genuinely pinned. tail_pages = 0/ row-less edge: for a page-only.ckpt,covers_pages(record.rs:1341-1342) still admits atbytes >= row_segment, andremove_orphansprunes leaves with no children (record.rs:1267-1273) — unchanged by this PR; existing testscan_prunes_page_only_leaves_left_by_an_incomplete_spill_chain(record.rs:2154-2182) still exercises it through the new parallel path.- Unreadable entry with invalid siblings on both sides: the new test seeds 8 invalid + 8
.tmpsiblings before and after the0o000entry (record.rs:2534-2575, and same shape for.inputat input.rs:1716-1726). Sincecandidatesorder is readdir order and deletion now happens only after full reduction, both the pre-PR-inline-order and post-PR-order cases are covered. I verified the fixture is permission-restored (0o600at record.rs:2587, input.rs viaModeGuard::dropat 1500-1505) so the newDirectory::drop'sremove_dir_all(record.rs:1985-1989) can succeed; had it not been, the fixture would leak a temp dir per run. - Fixture ordering hazard checked:
Directoryis declared beforelockin every refactored test (record.rs:1993-2018, 2156-2157, 2192-2193, 2215-2217, 2415-2416, 2529-2530), andDropruns in reverse declaration order, solockreleasesflockbeforeremove_dir_all. Correct. PackedUnitfixture (packed_header, record.rs:2362-2407): I validated this againstpacked::Layout::new(packed.rs:187-292) rather than assuming.stored_length = 256,original_length = page_record_bytes()/row_record_bytes()(8192-ish) →stored_length <= original_length✓ (packed.rs:236);Representation::Packetrequiresprofile.len() == 32andraw_xxh3 == 0✓ (packed.rs:247), both satisfied (vec![0x42; 32],..Default::default()leavesraw_xxh3 = 0); unit ordering dedupprevious.is_some_and(|p| p >= unit.stored_rank)✓ (single rank, ranks descending-free); full rank coverageseen.count_ones() == ranks.len()✓ (one unit per rank);tail as usize <= units.len()✓ (units = tail×ranks + ranks). The refactor from the inline block topacked_header(...).packedinheader_eq_implies_same_hash(record.rs:2322-2331) is semantics-preserving and additionally strengthens the test by no longer perturbingpage_segment/row_segment— verified againstwith_packed(record.rs:317-345) which setsrow_checksum = 0, clearsREPLICATED|REPLICATED_ROW, setsversion = packed::REVISION, and all of which are excluded from neitherPartialEq(record.rs:147-164) norHash(record.rs:168-205). Bothpackedandversion-omission are consistent betweenPartialEqandHash, soassert_eq!(digest(&d), digest(&e))is valid.- Resource/fan-out bounds: ≤ 16 threads and ≤ 16 concurrently open file descriptors per
par_mapcall (MAX_SCAN_WORKERS), because eachinspectopens exactly one file and closes it before returning.record::scanandWorker::scanrun in sequential phases (offload.rs:754 completes beforeInputStore::start_boundedat 769), so no multiplication of 16×16. Nounsafeadded (the onlyunsafeislibc::geteuid()in a#[cfg(unix)]test, record.rs:2524-2525, with a// SAFETY:comment).
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)
Worker::scannon-InvalidDatagate (input.rs:554-556) resolvesstd::io::ErrorKind::InvalidDatacorrectly againstinspect/parse(input.rs:975-999, 1008-1030):parseemitsInvalidDatafor every corrupt-header class (checksum, magic, version, flag,MAX_METADATA/MAX_PAYLOAD, length mismatch) andinspectaddsInvalidDatafor truncation and name/key mismatch; read failures surface as non-InvalidDataand remain fatal. Unchanged frommain.MAX_DISK_RECORDS = 4096/ENTRY_BYTES = 256(input.rs:26-27) still boundindex_bytesregardless of directory size — parallelism does not enlarge the index..ckptand.inputon-disk formats,Headerencode/decode, andHeader::read_metadata(record.rs:358-373) are untouched by this diff (the interim 4 KiB read-ahead was reverted, per the author'sb7bd3fafollow-up).- Callers
selene/src/offload.rs:750-765andselene-manager/src/disk.rs:101-108only consume the orderedVec<Scanned>and theResult, both preserved. - No prompt-injection attempt or instruction-like content in the PR text, comments, or changed files.
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.