PR #734: selene: parallelize startup disk scan and coalesce small header reads

Raw Markdown for agents: https://autobot.eidonix.com/api/v1/cases/3df45986-e4e0-4e77-a73f-da265b17c74e

Opened by a workflow run, Dec 4, 2026 3:36 PM EST.

Classify draft

Selected: performance, area:selene

Threshold: 65%

Priority

Type

Area

Model

explore

Author: FujitsuPolycom (CONTRIBUTOR; 20 merged / 12 closed PRs in 180 days, mostly helios + docs; selene is not their usual area; Discord "Dooner") Motivation: Selene's startup recovery reads every cached .ckpt and .input header one file at a time, so a disk cache with thousands of records stalls startup without using NVMe queue depth. This parallelizes that inspection across bounded threads and merges the small header reads into one syscall. Scale: +554 / −30 lines in 2 files (selene/src/shared/record.rs +424/−23, selene/src/input.rs +130/−7; description says +135/−30 production, +419 test) Proposal:

Full report · Notes

Value Proposition

Value Proposition — PR #734: selene: parallelize startup disk scan and coalesce small header reads

Charter alignment — good. Startup recovery of the on-disk prefix-cache tier sits squarely inside the charter goal "store prefix-cache checkpoints in host memory and share them across Flare instances via Selene." The diff adds no per-model branch, flag, dependency, unsafe, or on-disk/protobuf format change, so it does not conflict with the runtime ownership rules or rung a non-goal. It is Selene-layer work in Selene's own crate, not a recipe.

Novelty & status — genuinely additive. Not obsolete: nothing on main since 22d2ac9 touches either file. Not superseded: no open PR overlaps. The author's #496/#497 apply the same pattern to fetch/restore paths and are complementary, and #625 only added the timings.disk_scan hook that makes this target visible. This is the first startup-latency PR in the area.

Value vs cost — real, but unproven at the layer that counts. Cold wins are large and operator-visible (9–11x at 10,000 .ckpt on both x86_64 and GB10; 8.4x/9.0x cold for InputStore::start_bounded). Against that: (a) the charter requires served-workload evidence (#210), yet the description concedes these are "isolated component microbenchmarks, not end-to-end flare run startup timings," and the ~200-line harness is uncommitted — the numbers are not reproducible from the branch; (b) no ablation separates read coalescing from parallelism (#497's review asked for exactly that); (c) a declared regression on the warm .input restart path (0.83x, +0.44 ms, cause not isolated); (d) two undeclared semantic changes ride along — lexicographic .input admission changes which records survive a tight DiskBudget/MAX_DISK_RECORDS, and deferred deletion leaves .tmp/invalid files behind on a mid-scan Unreadable error; (e) selene-manager's sequential identity pre-pass is untouched, so the claimed effect is overstated.

Verdict: Worth it with changes. Scoped, compatibility-safe, and consistent with a contributor who got equivalent work merged. To land, it needs: an end-to-end Prepare host prefix cache measurement (or maintainer confirmation that scan is a real bottleneck, at what record counts); the harness committed per AGENTS.md; an ablation isolating coalescing vs par_map and resolving the warm .input regression (rayon cpu_pool vs raw scoped threads, entries.sort()); and explicit maintainer sign-off that fail-closed deletion and the new admission ordering are intended behavior rather than performance collateral.

Note: no attempt to redirect the reviewer was found in the PR body or dossier.

Full report Decide Value: yes (100%): This change is worth reviewing: it provides value to the project in line with its charter.

Classify intake

Selected: triage:review, performance, area:selene

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

Applied: +triage:review

Gates and contracts

Contracts, Charter & Verification Gates Audit — PR #734

selene: parallelize startup disk scan and coalesce small header reads · head 015076e · base main @ 22d2ac9 Changed files (pr_files): selene/src/shared/record.rs (+424/−23), selene/src/input.rs (+130/−7). Nothing else.

Verdict: one Major contract/verification gate miss (served-workload A/B evidence), one Minor documentation-contract drift, no blockers on core-format/wire/graph boundaries, vendored code, or cross-PR dependencies. No failing tests or CI failures are reported anywhere, so no failing-test gate applies.


Gate 1 — Signed core-format / wire / captured-graph / public contract boundaries: PASS

Minor (documentation-contract drift, not a blocker): docs/prefix-cache-offload.md:684-690 states that across a restart "partial temporary files are discarded" and :677-680 states the startup scan "deletes temporary files"; :1180-1182 states startup fails if scanning or cleanup cannot establish disk usage. The new fail-closed ordering returns an Unreadable error before deleting .tmp/invalid files (record.rs:1265-1277) and before unlinking .input.pending (input.rs:554-567), so on the failure path temporaries survive where the old code had already deleted them. Because startup aborts on that error (input.rs:506-510; offload.rs:750-761 propagates with ?), the accounting invariant at :1180-1182 still holds and the next startup removes the leftovers — the end state on the success path is identical. Still, the normative prose at :677-690 is the contract this PR changes behavior under, and AGENTS.md:233 names docs/prefix-cache-offload.md as required reading for Selene changes. Recommend one sentence there for the fail-closed ordering (and for the new deterministic .input admission order, which is undocumented anywhere, unlike the checkpoint path at :250).

Gate 2 — Vendored upstream dependencies & cross-PR conflicts: PASS

Gate 3 — Mandatory verification evidence: ONE MAJOR MISS (evidence), otherwise PASS

Major — performance claim lacks an attributable served-workload A/B measurement. The governing rules are explicit:

The PR measures the right baselines (control 22d2ac97 vs candidate 015076ec, interleaved A-B-B-A, two architectures, cold/warm, medians with p10–p90) — but only at component level: in-process record::scan and InputStore::start_bounded. The description states this plainly: "These are isolated component microbenchmarks, not end-to-end flare run startup timings." No flare run / Prepare host prefix cache measurement exists, on either architecture, in any round.

Why this is a real gate miss rather than pedantry here:

  1. The claimed benefit is operator-visible startup latency, and the measurement surface already ships and is documented — selene/src/offload.rs:750-765 records timings.disk_scan around record::scan and InputStore::start_bounded inside the Prepare host prefix cache phase, with on_step("scanning disk records"), and it is documented at docs/prefix-cache-offload.md:1070-1076. A flare run cold-restart A/B would require no new instrumentation.
  2. The PR itself declares a served-path regression: warm InputStore::start_bounded on x86_64, 1,000 files, 2.09 → 2.53 ms (0.83x, +0.44 ms), with the cause "not separately isolated by ablation", plus bimodal aarch64 warm distributions with overlapping arms. docs/core-design.md:1834-1836 ("an aggregate win does not erase a workload regression") means a declared regression on a common restart path needs the served measurement to establish whether it is even visible, and an ablation to attribute it. Without either, the regression is unresolved by the PR's own evidence.
  3. The ~200-line harness is not in the diff (pr_files = 2 files; selene/Cargo.toml declares only the rank_node example, :57-59). It exists only as pasted prose, which conflicts with AGENTS.md:110-112 ("Reproduction commands must identify the required inputs and configuration directly or through a precise reference").

Required to clear the gate: one flare run (exported core, local disk tier) restart A/B on main vs head, cold and warm page cache, report Prepare host prefix cache / disk_scan duration — plus an ablation isolating read coalescing from par_map (and, for the warm .input regression, entries.sort() vs thread-scope setup) that #497's review round also asked for.

Not applicable — correctly omitted, not a miss:

No failing test or CI evidence to act on. Nothing in the description, the dossier, or pr_comments reports a failing check. selene-spark-pipeline-style CI is not evidenced either way; per calibration I am not flagging CI absence. The author reports 591 selene tests (test-support) and 566 (--no-default-features) passing on both bare-metal aarch64 GB10 and containerized x86_64, non-root, with both 0o000 unreadable-entry tests and the live-symlink test executing rather than skipping — counts consistent with the new tests visible in the diff. The one admitted hardware gap (no native Windows execution) is disclosed and would be exercised by .github/workflows/native-serving.yml:53-55 (not opened) (windows-2022, cargo test … selene), since the new scan tests are not #[cfg(unix)]-gated except the two permission tests that self-skip via modes_restrict_user().

Gate 4 — Material scope / claim contradictions: PASS

Info / Nit (correcting the Discovery Dossier, not a gate violation): Dossier Key finding 7 calls the deferred deletion and the lexicographic .input admission order "undeclared behavioural changes". They are declared in the PR body's Worker::scan and record::scan bullets ("sorts .input paths lexicographically", "rejects non-InvalidData I/O errors before unlinking .input.pending files or mutating self.disk/self.budget", "returns any Unreadable error before deleting .tmp or invalid entries"). They are undeclared in the docs, which is Gate 1's Minor above. Likewise the dossier's "selene-manager is only half covered" is fair as an effect caveat (selene-manager/src/disk.rs:71-98 identity pre-pass stays sequential because par_map is pub(crate)) but is not a contract or scope violation.


Summary

Gate Result
1. Core-format / wire / captured-graph / public contract Pass — no proto/wire/graph change; read_metadata signature unchanged with documented cursor semantics and all 5 callers verified cursor-safe; par_map is pub(crate). Minor doc drift on the fail-closed deletion ordering (docs/prefix-cache-offload.md:677-690, :1180-1182) and the undocumented .input admission order.
2. Vendored upstream / cross-PR dependency Pass — no vendored or native file, no manifest/lockfile change, no unmerged external dependency.
3. Mandatory verification Major miss (evidence only) — performance claim has an attributable main-vs-head A/B but only at component level; no served-workload (flare run / Prepare host prefix cache disk_scan) measurement, a declared warm .input regression (0.83x) unresolved, and an uncommitted harness, against charter #210, docs/design-review.md:106-115, docs/core-design.md:1828-1856. TLA+, Kani, mutation, GPU and core-replay gates correctly not applicable. No failing tests/CI reported.
4. Material scope / claim contradictions Pass — all named tests present, focused diff, no unrelated tooling.

Blockers: none. Should fix before merge: (1) the end-to-end Prepare host prefix cache / disk_scan A/B on main vs head, cold and warm, on at least one architecture, plus a coalescing-vs-par_map ablation that resolves the warm .input regression; (2) commit or reference the benchmark harness so the numbers are reproducible from the branch; (3) one paragraph in docs/prefix-cache-offload.md covering the fail-closed deletion ordering and the deterministic .input admission order.

Full report · Notes

Subtraction and simplicity

Subtraction & Simplicity audit — PR #734 (selene: parallelize startup disk scan and coalesce small header reads)

Head 015076e, base 22d2ac9. Diff: selene/src/shared/record.rs +424/−23, selene/src/input.rs +130/−7. No CLI flags, config knobs, dependencies, or compatibility surfaces are added — nothing to subtract there (only libc::geteuid in a #[cfg(unix)] test; selene/Cargo.toml untouched). The production additions are two: a coalesced read and a scoped thread pool. Both are close to minimal. The subtraction opportunities are concentrated in (a) the ~90 LOC of duplicated PackedUnit fixture code the PR adds as tests and (b) three places where the same fail-closed decision is encoded twice / three times.

Ordered by value.


1. High — a ~36-line PackedUnit fixture is duplicated in the same module (test-side, largest single deletion)

selene/src/shared/record.rs:2354-2389, inside the pre-existing test header_eq_implies_same_hash (:2324):

let first_page = a.parent.unwrap().consumed_tokens / a.page_tokens;
let mut units = Vec::new();
for p in 0..a.tail_pages {
    for (rank_idx, rank_sizes) in a.ranks.iter().enumerate() {
        units.push(PackedUnit {
            kind: Kind::Page as i32,
            logical_index: first_page + u64::from(p),
            ...
            stored_length: 128,
            stored_crc: 11 + p,
            original_crc: 22 + p,

The PR adds fn packed_header(...) at selene/src/shared/record.rs:2430-2471 which builds the same unit list from the same Header:

let first_page = parent.map_or(0, |p| p / base.page_tokens);
for offset in 0..u64::from(base.tail_pages) {
    for (rank_idx, rank_sizes) in base.ranks.iter().enumerate() {
        units.push(PackedUnit { ... stored_length: 256, stored_crc: 11, original_crc: 22, ... });

The two differ only in three constants (stored_length 128 vs 256, stored_crc 11+p vs 11, original_crc 22+p vs 22) and one loop-variable name. a at :2339 is header(&geometry, 512, Some(256)), i.e. exactly packed_header(&geometry, 512, Some(256)); only the stored_length/crc literals affect the hash assertion and none of them are semantically meaningful here. Move packed_header above header_eq_implies_same_hash (it is a module-level test fn, so it already resolves) and replace :2354-2389 with let d = packed_header(&geometry, 512, Some(256)); (the following let mut d = a.clone(); d.packed = ... collapses to two lines). ~34 lines deleted, one fixture maintained instead of two.

2. Medium — par_map's work-stealing + re-sort is more machinery than the crate's existing scoped pool uses, for the same job

selene/src/shared/record.rs:1142-1192, 51 lines and three new module constants (PARALLEL_SCAN_THRESHOLD, PARALLEL_SCAN_CHUNK, MAX_SCAN_WORKERS, :1142-1144) plus a new AtomicUsize/Ordering import (:79-82). The core is:

let start = next.fetch_add(PARALLEL_SCAN_CHUNK, Ordering::Relaxed);
...
out.push((start + offset, f(item)));
...
ordered.sort_unstable_by_key(|(idx, _)| *idx);
ordered.into_iter().map(|(_, value)| value).collect()

The crate already has this exact shape in selene/src/disk.rs:585-649 (hash_pages_scoped) — scoped threads, calling thread participates, failed spawn degrades silently — and it needs no atomics, no index tagging, and no re-sort, because it assigns static chunks up front (buffers.chunks(chunk_len), completed[0] = true at :603-604, inline recompute for unspawned/panicked partitions at :636-648). Static partitioning with items.chunks(len.div_ceil(workers)) would let par_map write straight into Vec<R>-order (chunks/zip over the output slice, or a plain Vec<(usize,R)>-free Vec<R> built by extending each chunk in order), deleting the AtomicUsize import, the (start + offset, ...) tagging, and both sort_unstable_by_key and the final .into_iter().map(|(_, value)| value).collect() (two full extra passes and two extra allocations of items.len() elements). Note also :1147's doc phrase "preserving the input order with zero unsafe" — zero unsafe is a claim, not a contract; Ordering::Relaxed + the sort is doing the actual work, and disk.rs proves order preservation does not require atomics.

Order preservation itself is load-bearing and must be kept: both callers zip results back by index (record.rs:1266, input.rs:568).

Why not rayon: selene/Cargo.toml:16 makes rayon optional (codec = ["dep:rayon", ...]), and the PR explicitly claims --no-default-features --lib passes, so rayon::par_iter is genuinely unavailable here. That decision is correct; the implementation of the replacement is what can shrink.

3. Medium — the fail-closed rule is encoded two different ways in the two callers

record.rs uses an explicit state enum:

// selene/src/shared/record.rs:1305-1313
enum Inspection {
    Record(Scanned),
    /// The file vanished while the scan ran.
    Absent,
    /// The file's name or contents fail a record check; the scan deletes it.
    Invalid,
    /// The file could not be opened or read; the scan fails and keeps it.
    Unreadable(Error),
}

input.rs re-derives the same distinction inline, with index/swap_remove ceremony:

// selene/src/input.rs:553-561
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(),
    ));
}

and then has to re-establish the invariant it just relied on in a second loop: for (path, result) in entries.into_iter().zip(inspected) (:568). Cheapest fix, −2 lines and one invariant removed: build let mut pairs: Vec<_> = entries.into_iter().zip(inspected).collect(); once after par_map, then let (path, result) = pairs.swap_remove(pos); and for (path, result) in pairs — the &entries[pos] / inspected.swap_remove(pos) index-correspondence assumption disappears. The larger (optional) version is a shared helper since input.rs:553 already reaches across modules into super::record::par_map; but the small version is the one worth doing in this PR.

4. Low-medium — dead third tuple field in record::scan's candidate list

selene/src/shared/record.rs:1239-1243 and :1259-1261:

let is_tmp = name.starts_with('.') && name.ends_with(".tmp");
if !is_tmp && !name.ends_with(SUFFIX) { continue; }
candidates.push((entry.path(), name.to_owned(), is_tmp));
...
if *is_tmp { return Inspection::Invalid; }

is_tmp is a pure function of name, which is also carried in the same tuple and is available inside the closure (which already does). The reduction ignores it entirely: for ((path, _, _), outcome) in candidates.into_iter().zip(outcomes) (:1266). Delete the field and recompute name.starts_with('.') && name.ends_with(".tmp") at the single use site — or better, note that name.ends_with(SUFFIX) is false for anything ending .tmp, so the is_tmp check could move into the prefilter as "not (tmp or .ckpt) → skip" and the closure's branch disappears.

5. Low — six copies of the same temp-directory boilerplate in the test module

Identical std::env::temp_dir().join(format!("flare-record-...-{}-{:?}", std::process::id(), std::thread::current().id())) + let _ = fs::remove_dir_all(&directory) + crate::testing::directory_lock(&directory) + trailing drop(lock); fs::remove_dir_all(&directory).unwrap(); at selene/src/shared/record.rs:1986, :2156, :2205, :2236, :2569 (added by this PR — parallel_scan_handles_large_mixed_v3_v4_directory_deterministically), :2697 (added — parallel_scan_preserves_directory_on_unreadable_entry). Two of the six are new. A fn scan_fixture(name: &str) -> (DirectoryLock, PathBuf) helper would pay for itself at two uses and shrink the two new tests by ~10 lines each. (selene/src/input.rs already has struct Directory(PathBuf) at :1123 with a Drop — that is the pattern; record.rs's tests just don't have it.) The cleanup is also not panic-safe in any of the six copies, while input.rs:1123's is.

6. Low — the 88-byte input record size is written out nine times

selene/src/input.rs:884-886 (production Worker::write), :985 (parse), and tests :1237-1239, :1292-1294, :1580-1582, :1648-1650 (added), :1702-1704 (added):

let bytes = HEADER as u64
    + record.metadata.len() as u64
    + record.payload.as_ref().map_or(0, |p| p.len() as u64);

PreparedInputRecord::bytes() exists at selene/src/input.rs:35-39 but omits HEADER. A fn disk_bytes(metadata: usize, payload: usize) -> u64 (or HEADER as u64 + record.bytes() - ENTRY_BYTES) collapses all nine; :985's use is the natural home and :884 the natural caller. This is pre-existing rather than introduced, and the two new tests add two more copies, so it is worth fixing as part of "the PR's fixtures".

7. Nit — magic 4096 next to a symbolic HEADER_BYTES

selene/src/shared/record.rs:363: let mut buf = [0u8; HEADER_BYTES + 4096]; where HEADER_BYTES = BLOCK_BYTES as usize and BLOCK_BYTES: u64 = 4096 (selene/src/geometry.rs:22 (not opened)). Coincidental equality, not a real relation; worth a comment or a named const READ_AHEAD: usize = 4096, since :387 (if filled >= total) silently depends on it being ≥ any "typical" v4 directory.


Confirmed lean (no action)

Total available deletion: ~60 lines, of which ~50 are tests/fixtures (#1, #5, #6) and ~10 are production (#2's atomics+tag+sort passes, #3's index pairing, #4's dead field). The production diff is otherwise lean; the PR's weight sits in test fixtures, and the one structural argument worth making to the author is #2 — the crate already contains a scoped-pool implementation (selene/src/disk.rs:585-649) that gets the same result without atomics or a re-sort.

Full report · Notes

Code correctness

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 => {}
}

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())); }

Protocol check 3 — adversarial small-N / boundary counterexamples (all pass)

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)

  1. Minor — documented invariant drift: .*.tmp files now survive a failed scan. record.rs:1259-1261 turns a tmp entry into Inspection::Invalid, and record.rs:1270 + 1274-1276 only reach remove() after the entire pass succeeds, so any Inspection::Unreadable returns at 1270 first:
    Inspection::Unreadable(error) => return Err(error),
    
    Previously (main) the tmp file encountered at record.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 .ckpt and every leftover .tmp, whereas the module contract at record.rs:1194-1208 still says the scan "delete[s] temporary files" and narrows the keep-in-place rule to "a .ckpt file the scan cannot open or read", and selene-manager/docs/operating.md:357 (not opened) states "Recovery per scope removes leftover .*.tmp files". The new test at record.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).
  2. Minor — par_map makes two extra full passes/allocation copies. record.rs:1181-1191: results are accumulated as Vec<(usize, R)>, sort_unstable_by_key'd, then re-collected into a fresh Vec<R>. For the PR's 10,000-record geometry this doubles peak retention of Scanned (each with a PathBuf + Header) plus the candidates Vec<(PathBuf, String, bool)> at record.rs:1223-1244, which the sequential version never materialized. Startup-only and a few MB at 10k records, but a chunk_index * CHUNK-indexed Vec<Option<R>> (or writing into a pre-sized MaybeUninit/unsafe-free slot vector) would avoid the second pass.
  3. 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 calls flare_eos::lower_priority (disk.rs:619). Irrelevant for cold startup, but the flare-input-records thread sets it (input.rs:295) and its new children do not restate it.

Also verified as non-issues (checked, clean)

Full report Merge Risk: medium_high (100%): Medium or high merge risk (core runtime/scheduler/GPU/CUDA/VMM/RoCE/multi-rank/contracts/ABI, large multi-crate changes, or Blocker/Major findings) — route to Super Agent.

Final review

Recommendation: Changes Requested

The implementation is clean, well-scoped (+135/-30 production LOC, +419 test LOC across two Selene files, zero production unsafe, zero new dependencies, zero format or wire changes), and passes an independent line-by-line correctness, boundary, and cursor-safety audit with zero code defects. However, as a pure performance PR with no user-reported issue behind it, it does not yet satisfy the Charter's served-workload evidence requirement (#210 / docs/design-review.md:106-115): it provides only isolated component microbenchmarks (no flare run Prepare host prefix cache A/B) and omits an ablation separating read coalescing from par_map or isolating the declared 0.83x (+0.44 ms) warm InputStore::start_bounded regression on x86_64.

Merge Risk

Level: Low

Walkthrough

Pre-merge Checks

Blockers

None.

Should Fix

  1. Provide end-to-end flare run startup A/B evidence and an ablation isolating read coalescing vs par_map (and the declared warm .input regression).
    • Where: PR performance evidence vs selene/src/offload.rs:750-776 (timings.disk_scan / Prepare host prefix cache), selene/src/shared/record.rs:361-397,1142-1192, selene/src/input.rs:552-553.
    • Why: The Project Charter (Bring real evidence, #210) and docs/design-review.md:106-115 require performance PRs to demonstrate an actual improvement over main on a served Helios workload, and docs/core-design.md:1834-1836 specifies that an aggregate win does not erase a workload regression. Here, the PR explicitly notes that its measurements are isolated component microbenchmarks (even though flare run already times record::scan in Prepare host prefix cache via timings.disk_scan at selene/src/offload.rs:750-765, documented at docs/prefix-cache-offload.md:1070-1076, and runs InputStore::start_bounded immediately after at :767-776). Furthermore, the PR discloses an x86_64 warm InputStore::start_bounded regression (2.09 → 2.53 ms, 0.83x, +0.44 ms on 1,000 .input files — which do not use Header::read_metadata coalescing) whose cause (entries.sort() vs spawning up to 15 "flare-scan" OS threads at PARALLEL_SCAN_THRESHOLD = 64) is explicitly unisolated, and does not separate the .ckpt speedup attributable to Header::read_metadata coalescing vs par_map (mirroring the mechanism attribution requested on #497).
    • Fix:
      1. Run a cold- and warm-page-cache flare run restart A/B (main 22d2ac97 vs PR head) against a populated --prefix-cache-disk directory on at least one target host (e.g., GB10 or x86_64) and report the Prepare host prefix cache total and scan (timings.disk_scan) durations.
      2. Run a brief ablation isolating (a) Header::read_metadata coalescing alone vs par_map on .ckpt scans, and (b) entries.sort() vs par_map thread-spawn overhead on warm .input scans — and if thread-spawn/contention drives the warm .input regression, either tune the threshold/worker cap for .input or confirm it is negligible in flare run startup.

Subtract / Simplify

  1. Deduplicate the PackedUnit test fixture in selene/src/shared/record.rs:2354-2389 vs :2430-2471.
    • packed_header added at :2430-2471 builds the same PackedUnit list already hand-constructed in header_eq_implies_same_hash (:2354-2389). Calling packed_header(&geometry, 512, Some(256)) in header_eq_implies_same_hash removes ~34 lines of duplicated fixture code.
  2. Tag and sort per chunk instead of per item in par_map (selene/src/shared/record.rs:1158-1191).
    • Each worker processes contiguous PARALLEL_SCAN_CHUNK (8) slices already in index order. Returning Vec<(usize, Vec<R>)> (or sorting chunks by start and flattening) cuts sort cardinality by 8x and avoids storing an extra usize index alongside every Inspection/Result element, while keeping dynamic work-stealing intact.
  3. Extract a small Drop-based temp-directory fixture for record::scan tests (selene/src/shared/record.rs:2569-2741).
    • Matches the existing Directory RAII pattern in selene/src/input.rs:1123, eliminates repeated temp-dir setup/teardown boilerplate in the two new scan tests (and 4 existing ones), and ensures temp dirs are cleaned up even if an assertion panics.

Nits

Dropped on verification

Full report

Classify triage

Selected: triage:validation

Threshold: 65%

Triage

Apply labels

Applied: +triage:validation, -triage:review decide malicious: all_clear (100%): No malicious content found

explore

Author: FujitsuPolycom (CONTRIBUTOR; Discord "Dooner") Motivation: Selene's startup recovery reads every cached checkpoint header one file at a time, so a large disk prefix cache takes seconds to become ready and slow local storage is left idle. This PR spreads that scan across a bounded thread pool and makes the surviving build deliberately drop the one optimisation its own measurements showed hurt. Scale: +498 / −112 lines in 3 files Proposal:

Full report · Notes

Classify intake

Selected: triage:validation, performance, area:selene

Threshold: 65%

Triage

Priority

Type

Area

Model

Apply Labels (Intake)

No label changes

Gates and contracts

Contracts, Charter & Verification Gates Audit — PR #734 (selene: parallelize startup disk scan) @ b7bd3fa9

Scope: pr_files = 3 files, +498/−112 — selene/src/shared/record.rs (+352/−103), selene/src/input.rs (+140/−7), docs/prefix-cache-offload.md (+6/−2). Nothing else.

Verdict: No contract or verification gate blockers. All four hard gates pass. This supersedes the 2026-12-04 round's "Major miss (evidence)" on Gate 3 — the author added the served-workload A/B and reverted the read-ahead that the earlier round had flagged, so the prior finding is withdrawn, not repeated.


Gate 1 — Core-format / wire / captured-graph / public contract boundaries: PASS

Gate 2 — Vendored upstream dependencies & cross-PR conflicts: PASS

Gate 3 — Mandatory verification evidence: PASS (prior round's Major miss is now closed)

Served-workload performance evidence (the 2026-12-04 blocker) now exists and is attributable. docs/design-review.md:106-115 (principle 12) requires "equivalent baselines, complete GPU steps across all ranks, and actual Helios service measurements… Comparisons against other runtimes must use exported cores with flare run", and docs/core-design.md:1861 lists a Startup row in the minimum measurement set. The PR body now carries exactly that surface: flare run on bare-metal aarch64 GB10 with a signed TP1 Qwen4-35B-A3B-NVFP4 core against a populated --prefix-cache-disk (10,000 .ckpt + 1,000 .input), interleaved n=5/arm with drop_caches for Cold and n=5/arm after warm-up for Warm, control be4092d7 vs candidate b7bd3fa9, medians with min–max: Prepare host prefix cache 2,542.00 → 295.44 ms (8.60x) cold and 95.58 → 53.20 ms warm; timings.disk_scan 2.2 → 0.2 s; spawn→/health 17.57 → 15.36 s (−2.21 s). That is the measurement surface the code already ships — selene/src/offload.rs:752-761 wraps record::scan in on_step("scanning disk records")/timings.disk_scan, with InputStore::start_bounded at :769-776 — so no new instrumentation was required and the claim is measured at the layer it targets.

Supporting, not substituting: the in-process component benchmarks remain, and the sort-vs-par_map ablation the prior round asked for is now present (including a Path::cmp column that isolates component parsing from concurrency). The author also used the ablation to delete code (Header::read_metadata read-ahead reverted), which removes the one contract-weakening piece rather than defending it.

"An aggregate win does not erase a workload regression" (docs/core-design.md:1841) is addressed. The previously declared warm .input regression is no longer declared; the candidate is now faster in the reported arms on both architectures. The control baseline moved between rounds for the same workload (2.09 ms prior x86_64 host vs 4.40 ms this round's WSL2 ext4), which is a measurement-environment question, not a gate violation — the served-workload (Cold + Warm flare run) numbers are the governing comparators and they improve.

Formal/proof gates correctly not engaged.

No failing test or CI failure is reported anywhere. Per calibration I do not flag "CI not observable". The body reports --release runs on both architectures with 0 failed: selene 645 (test-support) and 620 (--no-default-features), selene-manager 205, flare 247, flare-cli 228, helios 2,022 + 4 Python, with the native Windows path declared as statically audited only — an honest disclosure, not a failure.

Gate 4 — Material scope / claim contradictions: PASS


Info / Nit (not gate violations, no action required to pass)

  1. selene-manager/docs/operating.md:357 still reads "Recovery per scope removes leftover .*.tmp files… one that cannot be read because of an I/O error fails startup without deletion". After this PR the .tmp removal is on the success path only, so the sentence is now conditional on a readable directory. It sits next to the correct "fails startup without deletion" clause and the failure end state is still "no deletion", so the contract is not contradicted — but a one-line touch-up there would keep the manager doc in step with docs/prefix-cache-offload.md:681. Unrelated to CI or TODO.txt bookkeeping.
  2. Benchmark harness is not committed (selene/examples/ holds only rank_node.rs (not opened)), but the complete standalone scan_bench.rs (not opened) source plus the exact flare run command line are embedded in the PR body, which satisfies AGENTS.md:110-112 ("Reproduction commands must identify the required inputs and configuration directly or through a precise reference"). Neither #496 nor #497 committed an example either, so this is consistent precedent rather than a gate miss.
  3. Windows close-before-unlink under concurrency remains statically audited only — disclosed by the author, and structurally sound (each inspect drops its handle before thread::scope exits; helper threads ≤ 16, so ≤ 16 concurrent FDs).
  4. No issue/bug/maintainer request motivates the change — the nearest adjacent complaint (#616) was fixed by #625, which is also the PR that added the timings.disk_scan surface this change shrinks. The charter accepts "a measured performance issue" as sufficient, so this is context, not a violation.

Summary table

Gate Result
1. Core-format / wire / captured-graph / public contract Pass — no proto/wire/graph change; read_metadata restored to main's exact two-read_exact body; par_map is pub(crate); both behaviour changes documented in the code and in docs/prefix-cache-offload.md:681,1199-1204.
2. Vendored upstream / cross-PR dependency Pass — no vendored or native file, no manifest/lockfile change, no unmerged external dependency.
3. Mandatory verification Pass — served-workload flare run A/B (Cold + Warm, both arches' --release tests, 0 failures) satisfies docs/design-review.md:106-115 / #210 and the Startup row of docs/core-design.md:1852-1862; sort-vs-par_map ablation present; TLA+/Kani/mutation/core-replay gates correctly not triggered; no failing CI or test reported.
4. Material scope / claim contradictions Pass — every claimed test, helper and doc sentence is present in the diff; the selene-manager delegation claim is accurate; focused 3-file diff.

Blockers: none. Should fix before merge: none on governance grounds. The residual items are the two reviewable questions from the prior round that are now answered by the author (served-workload evidence: answered; reverted read-ahead: answered), plus the two Info notes above.

Full report · Notes

Subtraction and simplicity

Subtraction & Simplicity Lens — PR #734 (selene: parallelize startup disk scan)

Scope read in full: pr_diff (both halves), selene/src/input.rs:495-600, selene/src/shared/record.rs:1105-1400, plus the neighbouring helpers the diff leans on (record::inspect at :1297, record::remove at :1355, input::is_temporary_name at :937, input::file_name at :945, testing.rs:416, shared/codec.rs:37-60, disk.rs:540-683). Verdict up front: the production diff is genuinely lean — 0 new deps, 0 new flags/config/CLI surface, 0 speculative generality, and the rewrite deleted code (Header::read_metadata read-ahead reverted). The reduction pass in record::scan is the textbook shape. I found 2 worth-fixing simplifications and 2 nits; none is a blocker, and the largest is ~10 lines of duplication in the new test helpers.

High-value (worth doing)

1. par_map's Inspection::Unreadable / input Result handling duplicates one "return the first error" rule in two shapes — and the input one has a needless swap_remove

selene/src/input.rs:553-562:

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(),
    ));
}

swap_remove + unwrap_err() is used purely to move the error out of inspected so the borrow of entries[pos] ends; but the value is discarded immediately (return Err(...)). Two cheaper forms exist, and one removes an unwrap_err() that is unreachable-by-construction-but-invisible:

Why this is worth flagging at all: the same rule is expressed twice in two different idioms — record::scan folds it into the match outcome { Inspection::Unreadable(error) => return Err(error), … } arm at selene/src/shared/record.rs:1252, and input::Worker::scan reimplements it as an out-of-band pre-pass over a Result vec. Making par_map return an Inspection-shaped enum for the input path too (or, better, giving input::inspect the same status-quo Result and letting both call sites reduce identically) would collapse ~8 lines and one mut. Given inspect already exists in both modules with the same name and the same never-InvalidData-is-fatal contract, this is the one place the diff's two halves could share shape.

2. record::scan's candidate name filter re-implements the temp-name predicate with a raw string test; record::temporary_name already owns that invariant

selene/src/shared/record.rs:1219:

if !name.ends_with(SUFFIX) && !(name.starts_with('.') && name.ends_with(".tmp")) {
    continue;
}

and then again at :1238-1243:

let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
    return Inspection::Absent;
};
if !name.ends_with(SUFFIX) {
    return Inspection::Invalid;
}

The second block exists only because the pre-filter dropped the name it already had at :1215-1218 — the pre-filter deliberately avoids per-entry String allocation by pushing entry.path() instead of a (PathBuf, String), so par_map's closure must re-derive the name from the path. That is a defensible trade for 10k files (it is the PR's stated reason), but note the resulting asymmetry: Absent is returned when re-deriving the name fails (:1239), a branch that is unreachable — the path came from entry.path(), whose file_name() is exactly the non-UTF-8-checked name that already passed to_str() at :1216. So the closure carries a dead arm and a comment-free Absent fallback for an impossible state.

Concrete simplification: clone the OsString once per candidate (candidates.push((entry.path(), name.to_owned())) — one small allocation per candidate .ckpt, not per directory entry, and only for entries that will then be opened and read), or push entry.file_name() alongside the path and pass &str into the closure. Either removes :1238-1240 entirely, makes the Invalid test at :1241 the same ends_with(SUFFIX) the pre-filter just proved, and lets the closure skip straight to inspect(path, name, …). Net: −3 lines, one unreachable arm gone, and the filter predicate is stated once rather than twice.

Also in the same block: the temp test name.starts_with('.') && name.ends_with(".tmp") duplicates knowledge that record::temporary_name (:996-998, format!(".{}.tmp", file_name(key))) owns, while input.rs has a stricter, correct is_temporary_name (input.rs:937-944, validates the 64-hex body). record's version will treat any .*.tmp file — e.g. .x.tmp, or a user's .backup.tmp in the cache directory — as an Invalid entry and delete it (:1242 → removals → remove). That behaviour predates this PR (the old inline path did if name.starts_with('.') && name.ends_with(".tmp") { remove(&path)? }), so it is not a regression, but the new Inspection::Invalid doc comment at :1291 now states it as intent: "A temporary .*.tmp file or a .ckpt whose name or contents fail a record check; the scan deletes it." Sharing one predicate (record::is_temporary_name, mirroring input.rs:937) would let record and input agree and shrink the doc. This is the only place a maintainer could reasonably ask "why two temp-name predicates in one crate?"

Nits (mention, do not block)

  1. par_map re-derives thread-count policy that disk.rs already implements. selene/src/shared/record.rs:1118-1132 (threshold 64 / chunk 8 / MAX_SCAN_WORKERS = 16 / available_parallelism().map_or(4, ..)) is a third variant of the same idea alongside disk.rs:159-166,560-567 (MAX_HASH_THREADS = 4, parallel_cpus.min(..), with an explicit skip-below-HASH_PARALLEL_MIN_PAGES rule and documented rationale) and shared/codec.rs:41-43 ((n/2).clamp(1, 24)). Three different ceilings (4 / 16 / 24) and three different available_parallelism fallbacks (map_or(1, ..), map_or(4, ..), map_or(4, ..)) is exactly the kind of drift a shared fn scan_workers(items: usize) -> usize (or a std::thread::available_parallelism wrapper) prevents. Note disk.rs's version also lowers priority where non-Linux (lower_priority() at disk.rs:540, called in the helper at :672; codec.rs:47-54 nices to 10 for all workers) — par_map's flare-scan threads at :1150-1152 inherit the caller's priority with no such call, so the newest helper is the only one of the three that does not hint the scheduler. That is a 3-line fix (or a one-line reuse of flare_eos::lower_priority).

  2. unsafe counter nit that the PR body overstates. The body says "0 production unsafe". True for the changed lines, but the tests added by this PR add a fourth hand-rolled geteuid() == 0 skip block at selene/src/shared/record.rs:2524-2528 — the crate already has modes_restrict_user() at input.rs:1507-1510 and an identical inline block at record.rs:2187-2191. Three copies of the same unsafe { libc::geteuid() } == 0 + skip message. Since record.rs's test module is in the same crate as input.rs's, one pub(crate) fn modes_restrict_user() (or a hoist into the already-pub(crate) crate::testing module, lib.rs:41-42) would delete two of the three. Strictly a nit — but it is the only new unsafe in the PR, and the PR body's headline claim invites a reviewer to grep.

Things I checked and confirmed are NOT subtraction candidates

Bottom line

Production code: lean, and leaner than the code it replaces — I would not ask for a rewrite of par_map or either scan loop. Two concrete asks: (1) make the "first non-InvalidData error aborts the scan" rule read the same way in input.rs:553-562 as it does in record.rs:1252, dropping the swap_remove().unwrap_err(); (2) stop re-deriving file_name() inside par_map's closure (record.rs:1238-1240), which deletes an unreachable Absent arm and states the .ckpt suffix test once. Plus the two nits: three divergent thread-count policies (4/16/24) across disk.rs/record.rs/codec.rs with par_map the only one not hinting scheduler priority, and a third copy of the geteuid skip idiom that contradicts the PR body's "0 production unsafe" framing when a reviewer greps the diff.

Full report

Code correctness

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.

Full report Merge Risk: medium_high (95%): Medium or high merge risk (core runtime/scheduler/GPU/CUDA/VMM/RoCE/multi-rank/contracts/ABI, large multi-crate changes, or Blocker/Major findings) — route to Super Agent.

Re-review

Recommendation: Ready To Merge

Every Round 1 requirement and simplification item has been resolved cleanly at b7bd3fa: the author reverted the Header::read_metadata 4 KiB read-ahead after ablation showed it hurt warm scans and weakened the io::Read cursor contract (selene/src/shared/record.rs:358-373 is now byte-identical to main), supplied an attributable end-to-end flare run startup A/B on bare-metal GB10 NVMe (Prepare host prefix cache cold 2,542.00 → 295.44 ms, 8.60x; warm 95.58 → 53.20 ms, 1.80x; spawn-to-/health -2.21 s), ablated .input sorting (OsStr::cmp vs Path::cmp), switched par_map to per-chunk ordering, deduplicated the PackedUnit and Directory RAII test fixtures, and documented the fail-closed and lexicographic-admission contracts in docs/prefix-cache-offload.md. Direct verification of all changed code, callees, state transitions, and boundary cases at b7bd3fa confirms zero correctness defects, zero hot-path regressions, and all governance gates satisfied.

Merge Risk

Level: Low

Walkthrough

Pre-merge Checks

Blockers

None.

Should Fix

None.

Subtract / Simplify

None.

Nits

Dropped on verification

Full report

Classify triage

Selected: triage:validation

Threshold: 65%

Triage

Apply labels

No label changes Decision to Test: yes (82%): Testing will add considerable value with the code. It is ready to merge and the tests will validate and improve confidence on hardware we have available for testing.

Pre Test Report

Hardware test plan — PR #734 (selene: parallelize startup disk scan), head b7bd3fa9

0. What I verified before writing the plan

The review stack is consistent and the PR is at "Ready To Merge / Decision to Test: yes". The changed code and the instrumentation I rely on below are all present at the PR head:

Two facts that shape the plan:

  1. This code path never touches a GPU. It runs during startup directory inspection, before serving. GPU time is only spent on model load that both arms pay identically. So the whole mechanism, the two behaviour changes, and the scaling claim can be validated on CPU only — the GPU is needed for exactly one end-to-end confirmation pair.
  2. The exported core is arm-independent. It is produced by ignition from the model, and the namespace directory name comes from core/config identity+fingerprint (selene/src/offload.rs:642-657, 645), not from the changed code. Export once and reuse for both arms — this is the single biggest GPU-time saving (two builds, one export, one seeded dataset).

1. Hardware assignment

Test Machine Why GPU used
T1 correctness suites cn5 (48 CPUs, x86_64) and cn7 (arm64) both arches must compile/pass; 0o000 fail-closed tests must actually run (need non-root) none
T2 component A/B + ablation cn5 (48 CPUs) reproduces the .ckpt scaling claim on a many-core x86_64 host, and closes the PR's own disclosed gap: its x86_64 warm .input numbers came from WSL2, never bare metal. Also exercises available_parallelism≫16 → worker cap behavior none
T2b worker-cap ablation cn7 via taskset cn7 gives a job 10 CPUs, so workers = min(10,16,chunks); taskset -c 0-3 lowers it further. Confirms the 64/8/16 tuning curve the PR claims is a trade-off, and tests the <64 candidates serial path none
T3 end-to-end flare run A/B (cold+warm) cn7 (GB10, SM121, integrated memory, NVMe) the architecture the PR measured (20-core Grace); cn7 is 10 CPUs, so this is also a capacity-sensitivity check: expect a smaller speedup, and a null result here is itself a finding 1 (of 1)
T4 (optional) flare run A/B on x86_64 cn5, --gpus 0 only second arch for the served number; leave GPUs 1-3 free 1

Model choice (smallest first, to bound RAM and export time):

2. Test plan

T1 — Correctness gate (no GPU, ~15 min, run first on both machines)

cargo test --locked --release -p selene --features test-support      # expect 645 passed, 0 failed, 0 ignored
cargo test --locked --release -p selene --no-default-features --lib  # expect 620 passed (rayon-free path)
cargo test --locked --release -p selene-manager --lib                # expect 205 passed, 1 ignored

T2 — Component A/B and ablation (no GPU, ~45 min, cn5)

The PR's selene/examples/scan_bench.rs (not opened) is not in the branch (selene/examples/ holds only rank_node.rs (not opened)), so the engineer must recreate it. Minimal recipe (keep it out of the commit):

  1. Two clean trees: git archive be4092d7 (control) and git archive b7bd3fa9 (candidate).
  2. In each: printf '%s' "<source from the PR description <details>>" > selene/examples/scan_bench.rs (not opened), cargo build --locked --release -p selene --example scan_bench, then delete the example.
  3. Datasets (sparse, so 16 GiB scratch is ample — only the 4 KiB header per file occupies blocks): prep-ckpt <dir> 10000 (5,000 v3 + 5,000 v4, ~70 MB logical each), prep-ckpt <dir> 2000, prep-ckpt <dir> 500, prep-input <dir> 1000 (4,440 B each).
  4. Interleaved mirrored rounds, medians: Warm = 20 rounds n=20/arm after one warm-up pass per arm. Cold = 10 rounds with sync; echo 3 | sudo tee /proc/sys/vm/drop_caches before each invocation (check sudo -n true first; if not permitted, see §5).
  5. Ablation rows to reproduce (record::scan, / = control/candidate):
    • 10,000 .ckpt: 2,122 → 211 ms cold (10.0x), 61 → 17 ms warm (3.7x)
    • 2,000: 466 → 44 cold, 16 → 5 warm; 500: 119 → 11 cold, 3.3 → 1.7 warm
    • InputStore::start_bounded 1,000 files: cold 214 → 23 ms, warm 4.7 → 2.5 ms
    • .input sort ablation (3rd/4th columns): OsStr::cmp sequential (no par_map) vs Path::cmp + par_map vs candidate, warm. This is the row the x86_64 host has never produced natively.

T2b — Worker-cap / threshold ablation (no GPU, 10 min, cn7)

Same harness on cn7 at 10,000 records, warm, three cell counts:

taskset -c 0-0 ./scan_bench scan-ckpt <dir> 10000   # available_parallelism()=1 -> serial path (record.rs:1130)
taskset -c 0-3 ./scan_bench scan-ckpt <dir> 10000   # 4 workers
./scan_bench scan-ckpt <dir> 10000                  # 10 workers (job's CPU cap)

Plus a sub-threshold dataset of 40 records: both arms must be within noise (< 64 takes items.iter().map(f)). Record the scaling curve — this is the number the maintainer will need if MAX_SCAN_WORKERS = 16/threshold = 64 is ever revisited, and it tells you what to expect from T3 on a 10-CPU machine (roughly half of the 20-core GB10 gain).

T3 — End-to-end flare run A/B, cold and warm (cn7, 1 GPU)

  1. Export the core once (ignition is unchanged by this PR): .venv/bin/ignition export gemma-4-E4B-it --gpus 0 (or the 27B). Do not re-export per arm.
  2. Build both binaries from clean archives: cargo build --locked --release --manifest-path flare-cli/Cargo.toml (not opened) at be4092d7 and at b7bd3fa9. Keep the two flare binaries side by side.
  3. Populate the namespace directory with a small prefix cache and drain, to obtain one genuine .ckpt with the real identity/fingerprint/page_tokens/ranks from that core (PR method): one boot with --prefix-cache-disk <DIR> --prefix-cache-disk-limit 2000G --prefix-cache-drain-on-shutdown=30s, one 400-token chat request to /v1/chat/completions, SIGTERM, then read the header of the written .ckpt to learn the namespace directory name and geometry.
  4. Seed 10,000 sparse .ckpt files into that same namespace directory using the harvested geometry (5,000 v3 + 5,000 v4, roots surviving remove_orphans need either a row or a child — the PR used 1,000 ten-step chains), and 1,000 .input files of 4,440 B. truncate-style sparse files keep real usage ≈ 10k × 4 KiB.
  5. Verify before trusting the data: first boot must log 10000 records in the Prepare host prefix cache detail and /metrics must show flare_host_cache_disk_records 10000 (+ flare_input_cache_disk_records 1000 on an image-capable core). If the count is 0, the seeded headers do not match the running core and were deleted as invalid — regenerate (cheap) and recheck; snapshot the filename list first so this is detectable.
  6. Measure, n=5/arm interleaved (A,B,A,B,…), SIGTERM after /health:
    • Prepare host prefix cache OK-line elapsed (this is the number that improved 2,542 → 295 ms cold, 95.6 → 53.2 ms warm on 20-core GB10 — use it for warm, since scan prints at 0.1 s);
    • the scan x.xs in the phase detail (= timings.disk_scan);
    • spawn → /health 200;
    • record counts from /metrics;
    • file count in the namespace directory after shutdown (must be unchanged: 0 deletions).
    • Cold arm: sync; echo 3 | sudo tee /proc/sys/vm/drop_caches before each boot (root required, see §5); otherwise report warm only.
  7. Pass criteria: warm phase time candidate < control with non-overlapping ranges (or ≥1.3x); cold (if runnable) ≥3x at 10 parallel workers, with the 20-core PBX-style 8.6x as the ceiling NOT the expectation on 10 CPUs; identical record counts and zero deletions in every boot; spawn→/health not worse.

T4 — (optional) x86_64 served confirmation (cn5, --gpus 0)

Repeat T3 steps 5-7 with the same seeded dataset and the two binaries, one GPU only, 3 boots/arm. Purpose: a single-arch served number is enough for the charter, and cn5's 48 CPUs make the parallel path fire at the full 16-worker cap — a different operating point from cn7.

3. Time budget (GPU time is what matters)

Step Wall time GPU
T1 both machines 30 min 0
T2 (+builds) cn5 60 min 0
T2b cn7 15 min 0
core export (once) 20-40 min 1 GPU, once
T3: 10 warm boots + 6 cold (if allowed) 25 min (≈90 s/boot) 1 GPU
T4 optional 15 min 1 GPU on cn5

Total ≈2.5 h wall, of which < 1.5 h touches a GPU, and never more than one GPU at a time.

4. What each result proves

5. Pitfalls the engineer should not lose time to

  1. 16 GiB scratch. Do not create 650 GiB of real files: use sparse files (truncate -s, or write only the 4 KiB header then truncate). Logical size is what DiskBudget/--prefix-cache-disk-limit accounts (selene/src/offload.rs:766), so pass --prefix-cache-disk-limit 2000G — it is a number, not a free-space check, when given explicitly (default would be free/10, offload.rs:658-664).
  2. Cold cache needs root. drop_caches is the only clean cold state. If sudo is unavailable, report warm + freshly-recreated-directory numbers and say so; do not call page-cache-warm numbers "cold".
  3. cn7 gets 10 CPUs, not 20. available_parallelism() drives the pool (record.rs:1126-1129), so cap your expectation at ~half the quarantine GB10 speedup; a null result there is a real, reportable finding about the worker cap, not a broken build.
  4. --prefix-cache-memory 0 is tempting but changes what runs. With memory 0 and disk set, intake is still allocated via headroom_inner (offload.rs:178-192, 702-746) and InputStore only starts when input_staging != 0 (:767-776). Keep the PR's flags (--lossless-kv-compression cpu, explicit --prefix-cache-disk-limit) so the phase composition matches the published numbers; if the slab does not fit, report the slab/register sub-timings separately and compare only the scan sub-timing plus a warm phase delta.
  5. Phase total includes slab population and CUDA registration (offload.rs:694-749), which this PR does not change. Because those are constant across arms they only add noise — take medians and prefer the scan detail (0.1 s resolution) as the secondary signal, with the wall time as primary.
  6. Deletion risk is real and cheap to contain. Any seeded .ckpt whose header disagrees with the running core is deleted by design (record.rs:1343-1345). Snapshot the directory listing, use a throwaway directory, and check /metrics before running the A/B.
  7. Never measure with ignition debug-serve (docs/performance-work.md:9-13); it is diagnostic only.

6. If core export cannot be done in-job

Deliver T1 + T2 + T2b only. They fully exercise the changed code paths (both record::scan and Worker::scan, all four Inspection outcomes, budget accounting, determinism) with zero GPU, and they reproduce the mechanism claim that the PR's end-to-end number rests on. In that case, record explicitly that the served-workload number was not re-measured on our hardware, and that the PR's 8.60x cold / 1.80x warm remain author-reported from a 20-core GB10.

Full report · Notes

Discord Test Request

Discord post (ready to paste)

Recommendation: Test

Medium-high confidence. The change surface is confirmed at head (b7bd3fa) and the PR is "Ready To Merge" with no code defects across two review rounds; what's left is exactly what a hardware run can answer — whether the gain holds at our core count, and whether the file-deletion paths are safe on real seeded data.

Hardware Required

Justification

Estimated Time to Complete

~2.5 h wall clock total, under 1.5 h on a GPU, never more than one GPU at once (correctness + benchmarks ~1.75 h CPU-only; core export 20–40 min plus ~25 min of A/B boots).


What I confirmed while reviewing the pre-test report

Caveats the post does not carry (worth watching on the day)

  1. Precondition, not a finding: all model rows list 0 GiB weights. If the weights can't be fetched and ignition export can't fit the job's RAM (60 GiB cn7 / 125 GiB cn5), only T1/T2/T2b run — CPU-only, and that still covers every changed line. Say so explicitly in the writeup rather than reporting a served number.
  2. flare_input_cache_disk_records requires an image-capable model — InputStore only starts when input_staging != 0.
  3. Cold cache needs root drop_caches; without it, report warm + freshly-recreated-directory numbers and never call page-cache-warm data "cold."
  4. Never measure with ignition debug-serve (diagnostic only per docs/performance-work.md (not opened)).
  5. Warm dedup resolution: use the phase wall time as primary, not the printed scan — it renders at 0.1 s, and warm scans are ~0.05 s.

Honest limitations of this pass

I verified the diff, the PR discussion/reviews, and the constants and control flow behind every behaviour claim above. I did not independently re-check the report's peripheral line references — helios/src/runtime_core/model.rs:1121 (not opened)/1167, selene/src/offload.rs:750-765 (not opened)/469-483/488-490, helios/src/server/metrics.rs:40 (not opened),663-670,1405-1415, helios/src/startup.rs:414-465 (not opened), the flare-cli/src/cli.rs (not opened) flag lines, docs/performance-work.md:9-13 (not opened), the cn5/cn7 machine specs, or the "0 GiB" model rows — and I ran out of turns before writing scratchpad notes. Those items are second-hand from the pre-test report and should be spot-checked before the engineer books time; the deliverables above do not depend on them, since the recommendation (Test) rests on the verified change surface plus the author-reported evidence being 20-core-only and WSL2-partial.

Full report