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:
if let Some((pos, Err(error))) = inspected.iter().enumerate().find(...)then index&entries[pos]— but that still borrows.- Simplest: zip at the top and scan the zipped iterator, mirroring what
record::scanalready does at:1248-1255:
The error is anfor (path, result) in entries.iter().zip(&inspected) { if let Err(error) = result && error.kind() != std::io::ErrorKind::InvalidData { return Err(failure("read prepared-input record", path, /* clone/move */)); } }io::Error, which is notClone, so the position-based version is defensible — but then the cheaper spelling islet Some(pos) = …position(…) else { … }plusif let Err(error) = &inspected[pos] { return Err(failure(…, &entries[pos], clone_ish)) }. My concrete recommendation: keep the position search, dropswap_remove().unwrap_err()and rebuild the error from a reference instead, i.e. drop themutoninspectedand the.unwrap()-adjacent panic path. Cost: one line either way; benefit: nomutbinding, noswap_removethat silently reorders aVecyou thenzipin order at:568(it doesn't matter today because the function returns, but it is exactly the kind of thing a later edit turns into a real bug).
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)
-
par_mapre-derives thread-count policy thatdisk.rsalready 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 alongsidedisk.rs:159-166,560-567(MAX_HASH_THREADS = 4,parallel_cpus.min(..), with an explicit skip-below-HASH_PARALLEL_MIN_PAGESrule and documented rationale) andshared/codec.rs:41-43((n/2).clamp(1, 24)). Three different ceilings (4 / 16 / 24) and three differentavailable_parallelismfallbacks (map_or(1, ..),map_or(4, ..),map_or(4, ..)) is exactly the kind of drift a sharedfn scan_workers(items: usize) -> usize(or astd::thread::available_parallelismwrapper) prevents. Notedisk.rs's version also lowers priority where non-Linux (lower_priority()atdisk.rs:540, called in the helper at:672;codec.rs:47-54nices to 10 for all workers) —par_map'sflare-scanthreads at:1150-1152inherit 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 offlare_eos::lower_priority). -
unsafecounter nit that the PR body overstates. The body says "0 productionunsafe". True for the changed lines, but the tests added by this PR add a fourth hand-rolledgeteuid() == 0skip block atselene/src/shared/record.rs:2524-2528— the crate already hasmodes_restrict_user()atinput.rs:1507-1510and an identical inline block atrecord.rs:2187-2191. Three copies of the sameunsafe { libc::geteuid() } == 0+ skip message. Sincerecord.rs's test module is in the same crate asinput.rs's, onepub(crate) fn modes_restrict_user()(or a hoist into the already-pub(crate)crate::testingmodule,lib.rs:41-42) would delete two of the three. Strictly a nit — but it is the only newunsafein the PR, and the PR body's headline claim invites a reviewer to grep.
Things I checked and confirmed are NOT subtraction candidates
- Test helper
Directoryduplication is unavoidable and correct.record.rs:1966-1989andinput.rs:1123-1140are near-identical temp-dir guards (~20 lines each) in two#[cfg(test)] mod tests. They cannot be shared without apub(crate)test util;crate::testing::test_directory(testing.rs:416-442) is not a fit — it probes forO_DIRECTand returnsOption<PathBuf>, and it is gated ontest-supportwhile these run under plain#[cfg(test)]. Consolidating would mean newpub(crate)surface for ~15 lines saved; not worth it. Therecordversion'sDeref<Target = Path>impl is genuinely load-bearing (it letsdirectory.join(..)keep working after the refactor). InspectiongainingAbsent-from-!is_file()is a real merge, not a widening.record.rs:1289("vanished … or is not a regular file") folds two oldcontinues into one enum arm. Good subtraction; nothing to remove.entries.sort_unstable_by(|a, b| a.as_os_str().cmp(b.as_os_str()))atinput.rs:552is the PR's own ablation-measured choice overPath::cmp; it is not expressive cruft. Note it is not reproducingrecord'sremove_orphansordering — different concern, correctly separate.- No dead branches or speculative generality:
PARALLEL_SCAN_THRESHOLD/_CHUNK/MAX_SCAN_WORKERSare all live and all exercised (the test atrecord.rs:2445,assert!(expected.len() >= PARALLEL_SCAN_THRESHOLD * 2), guards the parallel path deliberately). No new CLI flag, config knob, feature, or dependency anywhere in the 3-file diff (selene/Cargo.tomluntouched, still onlyrank_nodeas an example). packed_header/scan_defaulthelpers (record.rs:2362,:2409) are consolidation, not duplication — they replace ~40 lines of inlinePackedUnitconstruction inheader_eq_implies_same_hashand five copies of the 5-argscan(...)call. Net subtraction already taken.
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.