Subtractive report · NVIDIA/hyperflare-inference #496

Raw Markdown for agents: https://autobot.eidonix.com/p/0a08dbe1-11e4-4fbf-a8e8-9ef7d9870e04.md

PR #496 subtraction review — "Coalesce shared ancestor reads across concurrent Selene disk fetches"

Head reviewed: cb3db468 (rebased onto main 6d74db3a), strictly through the Subtraction lens. Nothing here re-argues the design; every item below is a removal or a shortening, verified in the source at this head (no toolchain, GPU or test run was available, so all counts are static).

Key findings

Charter hooks: line 9 ("the smallest footprint in shared code") and line 42 (supported-matrix review) — every cut below removes duplication inside Selene's own disk tier without changing behaviour or dropping a covered case.

Findings, ranked by lines saved

1. Should fix — ~100–115 lines: nine copies of the same store fixture in the new tests

DiskStore::new(record::DirectoryLock::acquire(&directory).unwrap(), IDENTITY, FINGERPRINT, 1 << 30, geometry, records, Box::new(Staged::new(Some(pool.clone()), copier, DiskThread::start("…").unwrap()))).unwrap() appears nine times, 13–17 lines each, at selene/src/disk_store.rs:9499-9512, :9593-9606, :9716-9729, :9839-9852, :9954-9967, :10034-10047, :10169-10182, :10370-10386, :10423-10439. Each is preceded by the same two pool lines (let intake = crate::offload::intake_slots(&layout, N); let pool = SlabPool::new(layout.page_record_bytes, intake, intake).unwrap(); at :9496, :9589, :9712, :9831, :9951, :10031, :10115, :10367, :10418), and six sites rebuild the same parent-plus-children records vec (vec![scanned(parent)] + loop at :9489-9492, :9584-9588, :9707-9711, :9826-9830, :9947-9950, :10027-10030).

Smaller — two helpers, ~24 lines total, each site becomes one or two lines:

fn staged_store(directory: &Path, name: &str, geometry: Vec<CacheGeometry>, records: Vec<Scanned>,
                intake: usize, copier: SharedCopier) -> (DiskStore, SlabPool) { … }
fn scanned_tree(directory: &Path, fixture: &AncestorBranchFixture) -> Vec<Scanned> { … }

Nothing lost: each test keeps its own directory, its own counters and its own assertions; only the boilerplate collapses.

2. Should fix — ~65–80 lines: the demand table and demand-aware picker only reorder window starts

build_pending_demand (:2271-2294), pick_next_pending_plan (:2296-2331), the demand: Option<&mut HashMap<WindowKey, usize>> parameter on attach_pending (:2250-2253) with its decrement block (:2261-2266), and the demand plumbing in pump_device_inbound (:2464-2482) exist solely to make a leader prefer a window a sibling also wants. Coalescing does not depend on it: find_best_existing_window_for (:2204-2220) plus find_reusable_window (:2185-2202) attach to any live window regardless of start order, and plan_windows(.., true) guarantees aligned (first, count, row) equality. The table is empty by construction for the common single-restore case (if self.device_inbound.len() <= 1 { return demand; }, :2275).

Smaller — delete the table, the parameter and both decrements; the picker becomes a position() over the free-slot filter:

fn pick_next_pending_plan(&self, id: JobId) -> Option<usize> {
    let record = self.device_inbound.get(&id)?;
    self.resources.pool.as_ref()?;
    let free = self.resources.free_slots();
    let transfers = lock(&self.resources.transfers);
    let layout = transfers.layout();
    record.plans.iter().enumerate().position(|(i, plan)| {
        !record.started[i]
            && (record.segments[plan.segment].segment.expected.0.packed.is_some()
                || layout.record_slots(plan.count, plan.row) <= free)
    })
}

Caveat to state plainly: this relaxes the arrival-order preference the PR credits for the staggered rows of its table (+25 ms stagger: 3.76× vs 4.22× physical read reduction). It is the one finding whose absence could show in a measurement, so re-run the staggered row if it is cut. The cheap middle ground, if the stagger matters, is a single peer_demand > 0 lookup through window_index instead of the HashMap<WindowKey, usize>.

3. Should fix — ~70–75 lines: the close-drain test duplicates the burst test

staged_close_drains_active_coalesced_fetches_cleanly (:10014-10090) and concurrent_burst_coalesces_shared_ancestor_opens_and_window_reads (:9476-9570) build the same fixture (write_shared_ancestor_tree, parent-plus-children records, intake_slots-sized SlabPool, SimulatedGpu::shared_mapped, per-branch InboundTicket), assert the same counters (disk_opens() == 1 + BRANCHES, coalesced_windows() == 3 * (BRANCHES - 1), pool fully free) and run the same per-page and row equality loops. They differ only in BRANCHES/PARENT_PAGES and in whether store.close() runs before polling (:10063-10065).

Smaller — one test driven by for close_early in [false, true], with BRANCHES = 4, PARENT_PAGES = 3 * WINDOW_PAGES, and the in_flight().1 == BRANCHES / close() / stats().fetched lines moved inside if close_early. The 4-aligned-window shape is still covered by different_skip_pages_coalesce_aligned_windows_to_exact_gpu_pages (:9694, 3 * WINDOW_PAGES + 7).

4. Should fix — ~55–65 lines: ObservedTransport and the recomputed rate

selene/src/disk_store.rs:10290-10347 is a 58-line DiskTransport implementation that delegates all twelve methods to Staged only to copy (bytes, elapsed) window samples into an Arc<Mutex<Vec<_>>> (drain_inbound_samples, :10324-10331). The test then rebuilds a Rate from that log (:10499-10514) purely to compare store.stats().inbound_rate with a value derived from the same samples the store was fed (:10531-10535). The meaningful physical-vs-logical assertion is already rate_after_physical_reads (:10466) versus the final rate (:10523-10530), which runs for the staggered pass.

Smaller — delete the wrapper, single_samples (:10363, :10383, :10413), recorded_samples (:10422, :10436, :10499-10514) and the expected_bps assertion; keep staged.disk_window_reads() == 2 (:10496, already present), the coalesced count (:10497), the bytes_in check (:10519-10522), and hoist the existing 5%-tolerance before_followers comparison out of the if let so it runs for both passes. Only the absolute rate value for the non-staggered pass goes, and stats.inbound_rate > 0.0 && is_finite() still covers that case.

5. Nit — ~20 lines: HeaderIdentity wrapper is now redundant

selene/src/disk_store.rs:1440-1456 defines struct HeaderIdentity(Arc<Header>) with a manual PartialEq (Arc::ptr_eq fast path), Eq and Hash that just forwards to Header's. This PR puts Hash on Header beside its PartialEq (selene/src/shared/record.rs:165-202) and derives Hash on RankSizes, so the wrapper only exists to be the expected field of SegmentKey (:1459-1462). Make it SegmentKey { path: Arc<Path>, expected: Arc<Header> } and derive; delete :1440-1456 and the .0 unwraps at :1628, :2316, :2504, :2527, :2610, :2792, plus HeaderIdentity(Arc::new(..)) at :3110 → Arc::new(..). The Arc::ptr_eq fast path buys nothing correctness-wise: equal Arcs are equal by value and hash equal, and Header hashing is not expensive relative to a window read.

6. Nit — ~14 lines: poll_all_fetches duplicates crate::testing::poll_until

selene/src/disk_store.rs:9398-9415 re-implements poll_until (selene/src/testing.rs:25-37), which already stops on the wanted event. poll_until takes impl Fn(&StoreEvent) -> bool (not FnMut), so counting to N needs a Cell in the closure at the seven call sites (:9530, :9662, :9766, :9986, :10231, :10741, :10834). Saves the 18-line helper net of ~4 added lines. Modest; a thin local wrapper over poll_until is also defensible, but then it should call it rather than reimplement the loop.

7. Nit — ~12 lines: HostInbound's segment list always has one element

Owner::HostInbound(JobId, usize) (:276) plus HostInbound::new(vec![segment], …) at the only two constructors (:1814, :1824, :1853, :1863-1867). Owner::HostInbound(JobId) and segment: Segment removes the vec![], the index, segments.get_mut(segment) (:1143), and the [window.plan.segment] indirections at :1227, :1278, :1324, :1413, :1426. The device-side Vec<DeviceSegmentRef> is genuinely multi and must stay.

8. Nit — ~12 lines: Pass 1 and Pass 5b walk each record's active list twice

Pass 1 (:2422-2444) reaps upload_done windows; Pass 5b walks the same list again with if active.upload_submitted { continue; } to submit uploads. Folding the reap into the head of one reap-and-upload loop removes a full traversal, the active_len copy, and the self.device_inbound[&id].active[index] re-lookup per upload. Lowest-confidence item: confirm the pump interleaving with the author, since the counting tests loop and tolerate an extra pump.

9. Nit — ~10 lines: Staged::close's abandoned-job arithmetic is over-built

selene/src/disk_store.rs:3183-3194 computes maintenance_jobs (a filter over owners), store_jobs (sum of three maps plus that count), then abandoned_jobs = store_jobs.max(self.owners.len()).max(self.maintenance.len()). Every maintenance job is already inserted into owners (:3134, :3151) and every store job inserts an owner, so self.owners.len() alone counts abandoned disk jobs and neither extra term can raise it. Replace the four bindings with let abandoned_jobs = self.owners.len();, keeping the leaked_shared count (:3195) as is, which is the separate thing close() reports.

10. Nit — ~5 lines: the physical-vs-logical contract is stated twice in the docs

docs/prefix-cache-offload.md:447-448 (§2.4: "See section 4 for StoreStats.bytes_in and StoreStats.inbound_rate accounting under coalesced restores") and :1612-1617 (§4) say the same thing, and §2.4 additionally restates the module doc at selene/src/disk_store.rs:13-27 clause by clause. Keep §4's measurement note; drop the §2.4 restatement.

Cleared — do not re-raise

Open questions