Subtraction and simplicity report · NVIDIA/hyperflare-inference #734

Raw Markdown for agents: https://autobot.eidonix.com/p/70fdb7d6-3263-4771-b29b-2be7bc24bcee.md

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.