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
- Verdict: make it smaller first. The change is not padded in its core — the shared segment/window state machine, the reference counts that keep
SlabPoolslots and v4ReadPackedpayloads pinned until every follower's upload finishes, the private-vs-shared failure isolation, theFetched-after-disk_settledrule and the out-of-bandinbound_samplesdrain are each required by a stated goal and support the measured 3.5–4.2× physical-read reduction. What can go is duplication in the new tests (~165–190 lines) and one scheduler whose only effect is which new window a leader starts first (~65–80 lines), plus ~110 lines of nits. - About 360–400 lines removable in 10 places, of which ~25% of the new test module (
selene/src/disk_store.rs:9352-10856, ~1.5k lines) is duplicated fixture and assertion code. - Nothing is left dead behind the change.
Destination,InPhase,InboundRecord::apply_transfer/submit_upload, the old device branch of the inbound record andTransportEvent::InboundWindowSampleare all deleted in this same diff; the twounreachable!()s are gone; everyplan_windowscall site is updated. The earlierHeader-hash drift risk is fixed (this PR movesHashbesidePartialEq,selene/src/shared/record.rs:165-202). - Size, stated honestly:
pr_filesgives 5 files,selene/src/disk_store.rs +8470/−5627,selene/src/shared/packed.rs +44/−0,selene/src/shared/record.rs +119/−1,selene/src/shard.rs +11/−0,docs/prefix-cache-offload.md +38/−2; the orientation packet reports the whole PR as+8682/−5630. Part ofrecord.rs/packed.rsis main's #504 v4packedsupport re-ported across the rebase (author's 2026-11-27 comment), not new coalescing logic, so the raw totals overstate the feature.
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
- No superseded code left behind.
Destination,InPhase,InboundRecord::apply_transfer,InboundRecord::submit_uploadand the device branch of the old inbound record are deleted in this same diff.plan_windowsis the only pre-existing helper with rewritten call sites and all are updated (:1851false,:3101true, tests). - The out-of-band sample route is needed.
drain_inbound_samples(:150,Stagedimpl:3165-3167, forwarded inshard.rs, discarded inPeer::forward) is the only path from physical window reads toDiskStore::inbound_rate(:3649-3655) without adding aTransportEventvariant or inflatingStoreStats.progress; there is no smaller route, andTransportEventis unchanged by this PR. - Diagnostic counters stay.
disk_opens/disk_window_reads/coalesced_windowsand thedisk_read_countedflags are gated at every site (:207-212,:1288-1291,:1352-1356,:1377-1381,:1395-1399,:2513-2516,:2689-2693,:2725-2729,:2753-2757) and each getter has several test callers. - Load-bearing and must stay: the shared segment/window state machine (
:1488-1562,:2418-2955), the reference counts (disk_referenced/upload_referenced/followers), private-vs-shared failure isolation (:2040-2154), theFetched-after-disk_settledrule (:2894-2944), theinbound_samplesdrain, and the v4packedwindow path. - No re-export or on-disk format change, and
CompositeStore'sdisk_inbound_ratepath is outside this diff.
Open questions
- Finding 2: does the staggered benchmark row survive dropping the demand-order preference? Measure before cutting; the ordering relaxation is the PR's own stated behaviour at
docs/prefix-cache-offload.md:435-437. - Finding 8: is the Pass 1 / Pass 5b split load-bearing for a specific pump interleaving, or only historical?
- Finding 9: confirm no path inserts a maintenance or segment job id into
maintenance/shared_segmentswithout a matchingownersentry beforeclose()(source says every one does; worth an author confirmation). - Total removable: ~360–400 lines in 10 places (~7–8% of the diff, ~25% of the new test module).