Deep Code Correctness / Invariants / Hot-Path Audit — PR #734 @ 015076e
Scope check (per the partitioning rule): 2 files, 2 modules of one crate (selene/), 554 changed lines — small & single-subsystem, so no sub-agents were spawned; the audit was done directly with batched reads of the diff, both changed files, and every non-trivial callee.
Verdict
No Blocker, no Major, and no verified correctness or hot-path defect. I traced every non-trivial changed function against its callees and against the four protocol checks and could not construct a failing counterexample. Three genuine but non-defect-level observations follow, each directly verified against source at 015076e.
Protocol check 1 — callee / enum / design-invariant resolution (all resolved, all sound)
Inspection (selene/src/shared/record.rs:1304-1313) has four variants; the new match at record.rs:1266-1273 places every one correctly against inspect's own contract (record.rs:1315-1371):
match outcome {
Inspection::Record(scanned) => records.push(scanned),
Inspection::Invalid => removals.push(path),
Inspection::Unreadable(error) => return Err(error),
Inspection::Absent => {}
}
Inspection::Invalidis only produced by (a)is_tmpafter anis_file()check (record.rs:1259-1261), (b)UnexpectedEof | InvalidDatafromread_metadata(record.rs:1337-1341), (c) a failedHeader::decode(1350-1352), and (d)!belongs_here || !named_by_key || !covers_pages(1361-1363). All four are "contents/name fail a check", so deferring all of them toremovalsand only unlinking after the whole pass (record.rs:1274-1276) is semantically identical to the old inlineremove(&path)?, except that it is now fail-closed.Inspection::Absentcovers bothNotFoundfromsymlink_metadataand!metadata.is_file()(record.rs:1256-1258) — i.e. dangling symlinks, live symlinks andnested.ckpt/directories. The pre-filter at1239-1242keeps the name predicate before the metadata call, and sinceis_tmp/SUFFIXare pure name tests, nothing that previously reachedis_file()can now be deleted. Verified against the test fixtures atrecord.rs:2639-2672(subdirectory + dangling + live symlink must all survive).Header::read_metadataread-ahead: I opened all five production callers and confirmed none depends on the cursor or on over-reading —selene/src/disk.rs:1478(dropsFileintoReading{file}and afterwards only uses positionalread_exact_at,disk.rs:1464, i.e.preadpereos/src/lib.rs:24-46),selene/src/shard.rs:1202and:1251(decode-only;is_v4at1264-1267usesmetadata[..12]only),record.rs:1334(decode-only),selene-manager/src/disk.rs:77(decode-only). The new doc note atrecord.rs:359-360matches reality.
Protocol check 2 — order-of-operations / state transitions (traced, consistent)
Worker::scan (selene/src/input.rs:514-587), full failure-path trace:
entries.sort();
let mut inspected = super::record::par_map(&entries, |path| inspect(path));
if let Some(pos) = inspected.iter().position(|result| {
matches!(result, Err(error) if error.kind() != std::io::ErrorKind::InvalidData)
}) { return Err(failure("read prepared-input record", &entries[pos],
inspected.swap_remove(pos).unwrap_err())); }
par_mappreserves input order (record.rs:1165-1166pushes(start + offset, …),1190sorts by index), soentries[pos]names exactly the file whoseErrwas found;swap_remove(pos)returns the element atpositself, sounwrap_err()is the matched error. Bothentriesandinspectedare still unmodified when the index is taken.- No same-iteration flag hazard: the admission loop (
input.rs:568-585) mutatesself.disk/self.budgetonly on theOk(...) if …arm and never re-readsinspected, so deferring all removals past the whole inspection pass cannot observe stale state. - Budget accounting on the new early return is cleaner, not corrupted: the error now fires before any
reserve_input, soWorker::new's compensation atinput.rs:506-510(release_input(self.disk values sum)) becomes a no-op rather than a partial unwind. Verifiedreserve_input/release_input/checkpoint_pressureatinput.rs:136-159and the new test's assertions (input.rs:1746-1749). record::scan's reduction is still order-independent where it matters:remove_orphans(record.rs:1280-1302) computeskeys/parentsfrom the whole set and iterates to a fixed point, then sorts by(consumed_tokens, digest)at1300, sopar_map's completion order cannot leak into the result ("parents precede children" forDiskStore::new,disk_store.rs:2183-2186, preserved). The parallelinspectbodies touch no shared state: each opens and drops its own handle beforethread::scopeexits, so the Windows close-before-unlink ordering holds.
Protocol check 3 — adversarial small-N / boundary counterexamples (all pass)
par_mapwithitems.len() = 0:0usize.div_ceil(8) == 0→workers = 0→ theworkers <= 1guard (record.rs:1153) takes the serial path;(1..0)is never iterated.len = 63→ serial;len = 64→min(16, 8) = 8;available_parallelism() == 1→ serial. No division by zero, no empty-chunk panic.- Chunk math is exact at the tail (
end = (start + 8).min(items.len()),record.rs:1164) andfetch_addindices are unique, soRelaxed(1160) is sufficient: RMWs on one atomic are totally ordered, the references were published beforescope, and results return throughjoin().spawn_scoped(...).ok()silently degrading to caller-only work is correct because the caller runs the sameworker()loop (1173-1181). read_metadataboundaries (record.rs:361-397): file exactly 4096 (selene/src/disk.rs:3493-3495wide_path) → oneread,filled == HEADER_BYTES, no spurious EOF. 37-byte short-read stream →filledreaches exactly 4096 and the v4 tail path (filled < total) doesextend + resize + read_exact(&mut bytes[filled..]), identical bytes to before.filled > HEADER_BYTESbut< total(partial coalesce) is handled by the same branch.size == 0andsize == MAX_DIRECTORY + 1rejected before allocation, so the "corrupt length never allocates past the bound" invariant (packed::MAX_DIRECTORY = 2 MiB,shared/packed.rs:17) holds — confirmed byselene-manager/tests/packed.rs:524-526(u32::MAXlength).Ok(0)can only occur whilefilled < HEADER_BYTES, soOk(0)after a full header can never be misreported as EOF.
Protocol check 4 — hot-path big-O
par_map and both scans are startup-only (record::scan callers: offload.rs:754, selene-manager/src/disk.rs:101; Worker::scan only from Worker::new, input.rs:506). No per-step/eviction/request path is touched, and remove_orphans's existing O(N)-per-pass HashSet build is unchanged. Nothing in the diff lands on a scheduler/serving hot loop.
Verified observations (non-blocking, cite-and-confirm only)
- Minor — documented invariant drift:
.*.tmpfiles now survive a failed scan.record.rs:1259-1261turns a tmp entry intoInspection::Invalid, andrecord.rs:1270+1274-1276only reachremove()after the entire pass succeeds, so anyInspection::Unreadablereturns at1270first:
Previously (Inspection::Unreadable(error) => return Err(error),main) the tmp file encountered atrecord.rs:1147-1150(old) was unlinked during iteration, before the unreadable file was reached. Consequence: after a permission/device error, the directory keeps both the unreadable.ckptand every leftover.tmp, whereas the module contract atrecord.rs:1194-1208still says the scan "delete[s] temporary files" and narrows the keep-in-place rule to "a.ckptfile the scan cannot open or read", andselene-manager/docs/operating.md:357(not opened) states "Recovery per scope removes leftover.*.tmpfiles". The new test atrecord.rs:2734("temp file must not be deleted on unreadable scan failure") enshrines the new behavior, so this appears deliberate — worth an explicit confirm since it changes a documented recovery guarantee (the next successful scan does clean them up). - Minor —
par_mapmakes two extra full passes/allocation copies.record.rs:1181-1191: results are accumulated asVec<(usize, R)>,sort_unstable_by_key'd, then re-collected into a freshVec<R>. For the PR's 10,000-record geometry this doubles peak retention ofScanned(each with aPathBuf+Header) plus thecandidatesVec<(PathBuf, String, bool)>atrecord.rs:1223-1244, which the sequential version never materialized. Startup-only and a few MB at 10k records, but achunk_index * CHUNK-indexedVec<Option<R>>(or writing into a pre-sizedMaybeUninit/unsafe-free slot vector) would avoid the second pass. - Minor — helper threads do not set priority explicitly.
record::inspector's scoped"flare-scan"threads (record.rs:1175-1177) rely on inheritance of the creator's niceness/scheduling class; the disk path deliberately callsflare_eos::lower_priority(disk.rs:619). Irrelevant for cold startup, but theflare-input-recordsthread sets it (input.rs:295) and its new children do not restate it.
Also verified as non-issues (checked, clean)
Worker::scandeterminism is now better:entries.sort()on prefix-sharedPathBufs (input.rs:552) is byte-lexicographic on the 64-hex-digit name, i.e. ascending key order, so which records surviveMAX_DISK_RECORDS(input.rs:571) and a tightDiskBudgetis host-independent — the oldfs::read_dirorder was arbitrary. Covered byinput.rs:1645-1694.inspectreclassification is exhaustive: the removedErr(error) if error.kind() != InvalidDataarm (input.rs, old560-562) is exactly reproduced by the pre-check atinput.rs:554-562, and_ => fs::remove_file(input.rs:582) still covers bothErr(InvalidData)andOk-but-over-budget, matchingparse'sInvalidDataclassification (input.rs:988-992) andinspect's own (input.rs:1011-1028).- Deferring
.input.pendingremoval toinput.rs:563-567keeps the existing error-precedence test satisfied (input.rs:1544-1569: "remove incomplete prepared-input record" still surfaces first under a read-only directory).