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

Raw Markdown for agents: https://autobot.eidonix.com/p/917564dc-2d3b-43f7-adc1-b97aa8aa87fd.md

Subtraction, Simplicity & Conventions review — PR #496 "Coalesce shared ancestor reads across concurrent Selene disk fetches"

Reviewed at head ba1c73fd6c0b0d08c612dd947ed47ceaee8ce457 (base 6d74db3a). Files changed: selene/src/disk_store.rs (+337/−288), selene/src/disk_store/coalesce.rs (+1416), selene/src/disk_store/coalesce/tests.rs (+3217), selene/src/shared/record.rs (+119/−1), selene/src/shared/packed.rs (+44), docs/prefix-cache-offload.md (+48/−2).

Read for this lens: all 1416 lines of the new mod coalesce; the disk_store.rs diff in full plus targeted reads at HostInbound/submit_reads/pump_all/close; shared/record.rs:120-202; shared/packed.rs:60-141 and :280-340; the pre-existing neighbours the new code duplicates (pool/pins.rs:300-370, shared/packed.rs accessors); docs/prefix-cache-offload.md diff; AGENTS.md; the project charter; levels.rs:36-87 (to check the rode_preexisting downward guard is not a new knob); coalesce/tests.rs:520-616. Correctness bugs are deliberately not re-reported (separate lens); where a workaround should be deleted rather than patched I say so explicitly.

Key findings

  1. HIGH — the packed window byte-range math, which is the PR's own new logic, exists in a third copy. The new site is selene/src/disk_store/coalesce.rs:984-1004; byte-equivalent twins already exist at selene/src/disk_store.rs:1340-1352 (HostInbound::submit_reads) and selene/src/pool/pins.rs:338-347 (PinnedRecord::read_packed). This PR is what creates the third copy, so the extraction belongs in it: one packed::Layout::window_range(first, count, row) -> Range<u64> beside page_offset/physical_bytes (selene/src/shared/packed.rs:297-308) collapses all three.
  2. HIGH — SharedWindow::error is dead state: written twice, read nowhere. Declared selene/src/disk_store/coalesce.rs:166, seeded at :451 (result discarded) and at :469 (only to clone itself straight back out). Delete the field and both get_or_insert calls; first-error-wins semantics are already provided by DeviceInbound::fail's get_or_insert at :251-253.
  3. MEDIUM — the "this segment accepts reads" two-condition predicate is inlined three times (coalesce.rs:122-128, :574-580, :1133-1137), with a fourth, narrower variant inside reusable(). One accepts_reads() on SharedFileState plus SharedSegment::readable() removes two hand-copied condition pairs whose drift would silently mis-open or silently skip segments.
  4. MEDIUM — acquire_shared_segment linear-scans every segment while its sibling lookup is a keyed index. coalesce.rs:345-350 filters/min_by_keys all of shared_segments for a SegmentKey match; DeviceCoalescer already maintains window_index: HashMap<WindowKey, SharedWindowId> for exactly this purpose (:261, unindex_window :426-434). A HashMap<SegmentKey, SharedSegmentId> makes it O(1) and lets the function stop returning a cloned SegmentKey.
  5. MEDIUM/LOW — six copies of the test-support window-read counter block (coalesce.rs:1021-1025, :1067-1071, :1095-1099; disk_store.rs:1361-1365, :1385-1390, :1403-1407). One note_window_read helper makes each site a single line; instrumentation only, so risk is negligible.
  6. LOW — Staged::close's three-way .max() chain is more code than the number it prints (disk_store.rs:1983-1994). It reduces to one sum, consistent with the pre-PR self.owners.len() it replaced.
  7. Clean bill elsewhere: no speculative flags, config knobs, feature toggles or extension points were added (align_to_window: bool on plan_windows is the only new boolean and it has two real callers with genuinely different behaviour); the whole Destination / InPhase::Uploading / submit_upload / old unwind device arm is deleted; the test-support counter gating, the exhaustive Hash impls and the pump multi-pass shape are each load-bearing and match repo conventions. See "Cleared, no action" below.

S1 (HIGH) — De-duplicate the packed window byte-range math: one packed::Layout::window_range

selene/src/disk_store/coalesce.rs:984-1004:

        let (offset, length) = {
            let win = &self.shared_windows[&win_id];
            let expected = win.key.segment.expected.header();
            let layout = expected.packed.as_ref().unwrap();
            let start_rel = if win.key.count == 0 && win.key.row {
                layout.page_offset(layout.page_count())
            } else {
                layout.page_offset(win.key.first as usize)
            };
            let end_rel = if win.key.row {
                layout.physical_bytes()
            } else {
                layout.page_offset(win.key.first as usize + win.key.count)
            };
            let offset = expected.page_segment + start_rel;
            let Ok(length) = usize::try_from(end_rel - start_rel) else {
                self.fail_window(win_id, invalid("packed window length overflow"));
                return;
            };
            (offset, length)
        };

Pre-existing twin #1, selene/src/disk_store.rs:1340-1354 (this PR's rewritten HostInbound::submit_reads, identical expressions with first/count/window.plan.row):

                let first = window.plan.first as usize;
                let count = window.plan.count;
                let start_rel = if count == 0 && window.plan.row {
                    layout.page_offset(layout.page_count())
                } else {
                    layout.page_offset(first)
                };
                let end_rel = if window.plan.row {
                    layout.physical_bytes()
                } else {
                    layout.page_offset(first + count)
                };
                let offset = seg.expected.page_segment + start_rel;
                let length = usize::try_from(end_rel - start_rel)
                    .map_err(|_| invalid("packed window length overflow"))?;

Pre-existing twin #2, selene/src/pool/pins.rs:338-347 (PinnedRecord::read_packed) — same shape with window.first_page / window.page_count / window.row plus a checked_sub.

Simplification: add one accessor beside page_offset / physical_bytes in selene/src/shared/packed.rs:297-308:

/// Byte range within a record's packed payload covering `count` pages from
/// `first`, extended to the file end when `row` is set.
pub fn window_range(&self, first: usize, count: usize, row: bool) -> std::ops::Range<u64> { .. }

then coalesce.rs:984-1004 becomes let range = layout.window_range(win.key.first as usize, win.key.count, win.key.row); let offset = expected.page_segment + range.start; let Ok(length) = usize::try_from(range.len()) else { .. };, and the HostInbound and pins.rs sites shrink the same way. Three copies → one. The three call sites still need their own error mapping, so keep the closure shape; only the arithmetic moves.

S2 (HIGH) — Delete SharedWindow::error (dead field, discounted writes)

Declaration, selene/src/disk_store/coalesce.rs:166:

    error: Option<Error>,

Inside fail_segment_users, selene/src/disk_store/coalesce.rs:449-454:

            if win.segment == seg_id && win.phase == SharedWindowPhase::Reading {
                win.phase = SharedWindowPhase::Failed;
                win.error.get_or_insert_with(|| error.clone());
                Self::unindex_window(&mut self.window_index, &win.key, win_id);

Inside fail_window, selene/src/disk_store/coalesce.rs:467-470:

        win.phase = SharedWindowPhase::Failed;
        Self::unindex_window(&mut self.window_index, &win.key, win_id);
        let err = win.error.get_or_insert(error).clone();

A grep of the whole crate for win.error / self.error in this module returns only :252 (DeviceInbound::fail, a different type), :451 and :469; no code ever reads the value back. The only non-test purpose of the field is :469, which immediately clones it out again.

Simplification: drop the field (and its error: None initialiser at :942), drop the statement at :451, and replace :469 with let err = error;. First-error-wins behaviour is preserved because followers go through record.fail(...), which already keeps the first error (coalesce.rs:251-253: self.error.get_or_insert(error);). This is the "delete, don't patch" case: if a correctness lens reports the discarded write at :451, the fix is deletion, not a read.

S3 (MEDIUM) — One predicate for "this segment can serve reads"

selene/src/disk_store/coalesce.rs:122-133:

    fn reusable(&self) -> bool {
        self.open_error.is_none()
            && matches!(
                self.state,
                SharedFileState::Unopened | SharedFileState::Opening | SharedFileState::Opened
            )
    }

Same pair inlined at selene/src/disk_store/coalesce.rs:574-580 (window reuse check):

                self.shared_segments.get(&win.segment).is_some_and(|seg| {
                    seg.open_error.is_none()
                        && matches!(
                            seg.state,
                            SharedFileState::Opening | SharedFileState::Opened
                        )
                })

and again at selene/src/disk_store/coalesce.rs:1133-1137 (submit_pending_reads):

                .filter(|seg| {
                    seg.open_error.is_none()
                        && matches!(seg.state, SharedFileState::Opening | SharedFileState::Opened)
                })

Simplification: put the state half on the enum (SharedFileState at coalesce.rs:90-102):

impl SharedFileState {
    fn accepts_reads(self) -> bool {
        matches!(self, Self::Opening | Self::Opened)
    }
}

and one SharedSegment::readable(&self) -> bool { self.open_error.is_none() && self.state.accepts_reads() }; reusable() then becomes matches!(self.state, SharedFileState::Unopened) || self.readable(), :574-580 becomes .is_some_and(SharedSegment::readable), :1133-1137 becomes .filter(SharedSegment::readable). Two hand-copied two-condition pairs disappear and there is a single place to change if "unopened" ever stops being readable.

S4 (MEDIUM) — Replace the O(n) segment scan with a keyed index

selene/src/disk_store/coalesce.rs:345-350:

        let existing = self
            .shared_segments
            .iter()
            .filter(|(_, seg)| seg.reusable() && seg.key == key)
            .min_by_key(|&(&id, _)| id)
            .map(|(&id, seg)| (id, seg.key.clone()));

Every attached fetch pays a scan of all live segments plus a SegmentKey clone, and min_by_key(id) exists only to make reuse deterministic — an artefact of the scan, not a requirement. The module already shows the intended pattern for windows: window_index: HashMap<WindowKey, SharedWindowId> (coalesce.rs:261), maintained on create and cleared by unindex_window (:426-434).

Simplification: add segment_index: HashMap<SegmentKey, SharedSegmentId>, insert on creation (:359-377) and remove in remove_shared_segment (:1307-1317); the lookup becomes let existing = self.segment_index.get(&key).filter(|id| self.shared_segments[id].readable()).copied(); (with reusable() folded into a small guard, or keeping the segment there if the Unopened variant must stay reachable). The function then returns SharedSegmentId instead of (SharedSegmentId, SegmentKey) (:344), deleting the seg.key.clone() that exists only to hand the key back to a caller that already owns it.

S5 (MEDIUM/LOW) — Six copies of the test-support window-read counter

selene/src/disk_store/coalesce.rs:1021-1025 (same block at :1067-1071, :1095-1099; and in disk_store.rs at :1361-1365, :1385-1390, :1403-1407):

        #[cfg(any(test, feature = "test-support"))]
        if !win.disk_read_counted {
            win.disk_read_counted = true;
            resources.disk_window_reads += 1;
        }

Simplification: one helper, e.g. on Resources:

fn note_window_read(&mut self, counted: &mut bool) {
    #[cfg(any(test, feature = "test-support"))]
    if !*counted {
        *counted = true;
        self.disk_window_reads += 1;
    }
    #[cfg(not(any(test, feature = "test-support")))]
    let _ = counted;
}

each site becomes resources.note_window_read(&mut win.disk_read_counted);. The #[cfg] is repeated six times today; one copy is enough and keeps the test-support gating convention the crate already uses.

S6 (LOW) — Staged::close's .max() chain is a sum

selene/src/disk_store.rs:1983-1994:

        let maintenance_jobs = self
            .owners
            .values()
            .filter(|owner| matches!(owner, Owner::Truncate(_) | Owner::Unlink(_)))
            .count();
        let store_jobs = self.outbound.len()
            + self.host_inbound.len()
            + self.device.in_flight()
            + maintenance_jobs;
        let abandoned_jobs = store_jobs
            .max(self.owners.len())
            .max(self.maintenance.len());

self.owners already holds an entry for every submitted disk job, maintenance included, so the filter, the intermediate store_jobs binding and both .max() calls are compensating for double counting rather than measuring anything. This is cosmetic (abandoned_jobs only feeds the "did not complete" message) and it is the PR's own rewrite of a line that used to be self.owners.len().

Simplification: let abandoned_jobs = self.outbound.len() + self.host_inbound.len() + self.device.in_flight() + self.owners.len(); — one expression, same message, no filtering of Owner variants that the sum already covers.

Cleared — checked and deliberately not raised

Repo conventions (structural ones that could have bitten)

AGENTS.md:188-193 — "Reject unsupported abstractions and churn… Do not add frameworks, extension points, speculative compatibility, fallback layers, or configuration switches without a concrete requirement" — satisfied; the only additions are the coalescer and the accessors it needs. The same paragraph requires refactoring to "directly support the requested behavior or remove a demonstrated source of defect or cost" (:192-193): S1 is inside the PR's own new surface plus the twins that surface duplicates, S2-S6 are all inside lines this PR writes, so none of the suggestions is drive-by churn. Nothing in the PR body, its comments or the docs attempted to direct the reviewer.

Open questions / could not verify