Subtraction review — PR #496 "Coalesce shared ancestor reads across concurrent Selene disk fetches"
Head 0c04b1e2, base c0c4f798. Size from the diff: +3358 / −933 over 3 files — selene/src/disk_store.rs (+3313/−931), selene/src/shard.rs (+10/−0), docs/prefix-cache-offload.md (+35/−2). Of disk_store.rs, roughly +900 lines are the new test module (:8234-9357: the coalescing tests plus GatedCopier, write_shared_ancestor_tree, poll_all_fetches), so the production change is roughly +2400/−930.
Key findings
Verdict: make it smaller first. About 370-410 lines could go — roughly 11-12% of the change and about 42% of the new test lines — with no coverage or behaviour lost. The change is not padded: the shared segment/window state machine, the reference counts that keep SlabPool slots pinned until every follower's upload finishes, the private-vs-shared failure isolation, and the InboundWindowSample plumbing into DiskStore::inbound_rate are each required by a stated goal and support the measured 3.5-4.2x physical read reduction. What remains is duplication (mostly in the new tests) and one scheduler whose only effect is start order.
Ranked by lines saved:
| # | Lines | Severity | Where |
|---|---|---|---|
| 1 | ~90-110 | Should fix | 10 copies of the same store boilerplate in the new tests |
| 2 | ~65-80 | Should fix | per-pump demand table + demand-aware picker |
| 3 | ~70 | Should fix | close-drain test duplicates the burst test |
| 4 | ~60-75 | Should fix | ObservedTransport and the recomputed rate |
| 5 | ~50 added, net ~22 | Should fix | HeaderIdentity re-implements Header's identity |
| 6 | ~12 | Nit | Pass 1 / Pass 5b walk the same list twice |
| 7 | ~10-16 | Nit | poll_all_fetches duplicates crate::testing::poll_until |
| 8 | ~8 | Nit | Owner::HostInbound(JobId, usize) carries a one-element Vec<Segment> |
| 9 | ~5 | Nit | docs state the physical-vs-logical split twice |
| 10 | ~2-4 | Nit | dead term in Staged::close's max |
Nothing is left dead behind the change (details at the end).
1. Should fix — ten copies of the same DiskStore::new(...) boilerplate in the tests (~90-110 lines)
Every new coalescing test rebuilds the identical block. Example, selene/src/disk_store.rs:8313-8329:
let intake = crate::offload::intake_slots(&layout, 1);
let pool = SlabPool::new(layout.page_record_bytes, intake, intake).unwrap();
let (copier, gpu) = SimulatedGpu::shared_mapped(&geometry).unwrap();
let mut store = DiskStore::new(
record::DirectoryLock::acquire(&directory).unwrap(),
IDENTITY, FINGERPRINT, 1 << 30, geometry, records,
Box::new(Staged::new(Some(pool.clone()), copier, DiskThread::start("coalesce-burst").unwrap())),
).unwrap();
The same 14-17-line construction appears at :8316-8329, :8407-8420, :8531-8544, :8655-8668, :8770-8783, :8850-8863, :8934-8947, :8985-8998, :9183-9199, :9236-9252, each preceded by the same two pool lines (:8313-8314, :8403-8404, :8527-8528, :8647-8648, :8767-8768, :8847-8848, :8931-8932, :8982, :9180-9181, :9230-9231), and three tests repeat the same records vec (:8306-8309, :8763-8766, :8843-8846).
Smaller version — two helpers (~24 lines) and every site becomes one or two lines:
fn staged_store(directory: &Path, name: &str, geometry: Geometry,
records: Vec<Scanned>, intake: usize,
copier: Box<dyn Copier>) -> (DiskStore, SlabPool) { /* the block above */ }
fn scanned_tree(directory: &Path, fixture: &AncestorBranchFixture) -> Vec<Scanned> { /* parent + children */ }
Nothing is lost: each test keeps its own directory, its own counters and its own assertions; only the construction is shared.
2. Should fix — the demand-index scheduler (~65-80 lines) only reorders which new window a leader starts
selene/src/disk_store.rs:1732-1755 build_pending_demand, :1757-1793 pick_next_pending_plan (with its best: Option<(demand, plan_index)> scan), the demand: Option<&mut HashMap<WindowKey, usize>> parameter threaded through attach_pending (:1711-1730), and the two decrement sites (:1939, :1991-1995).
Coalescing does not depend on it. find_best_existing_window_for (:1665-1681) already scans every unstarted plan of the arriving record for a reusable in-flight window, and plan_windows(.., true) guarantees aligned (first, count) equality, so a later arriver attaches regardless of which window the leader chose to start first. The table is also provably empty for the common case: build_pending_demand returns immediately when device_inbound.len() <= 1 (:1736), i.e. every single-restore caller — which the PR description itself calls out as "single-restore callers skip demand indexing".
Smaller pick_next_pending_plan (the free-slot filter plus first unstarted plan, ~12 lines) — the point is that the picker becomes a position() over the existing filters:
fn pick_next_pending_plan(&self, id: JobId) -> Option<usize> {
let record = self.device_inbound.get(&id)?;
let free = self.resources.free_slots();
let row_slots = lock(&self.resources.transfers).layout().row_slots();
record.plans.iter().enumerate().position(|(i, plan)| {
!record.started[i] && plan.count + if plan.row { row_slots } else { 0 } <= free
})
}
then delete build_pending_demand, the demand argument on attach_pending, and both decrement blocks.
What is lost is only arrival-order relaxation across concurrent restores — which could show in the staggered row of the PR's benchmark table (3.76x staggered vs 4.22x simultaneous). Measure it before cutting. If the staggered number regresses, the cheap replacement is a single peer_demand > 0 lookup in the existing window_index (:1229) instead of a per-pump HashMap<WindowKey, usize> rebuilt over every pending plan of every live fetch.
3. Should fix — the close-drain test duplicates the burst test (~70 lines)
selene/src/disk_store.rs:8830-8906 staged_close_drains_active_coalesced_fetches_cleanly and :8293-8384 concurrent_burst_coalesces_shared_ancestor_opens_and_window_reads build the same fixture (write_shared_ancestor_tree, scanned vec, intake-sized SlabPool, SimulatedGpu::shared_mapped, DiskStore::new, per-branch InboundTicket, poll_all_fetches), assert the same counters (disk_opens, disk_window_reads, coalesced_windows, pool free slots, no pins), and run the same per-page and per-row equality loops. They differ in BRANCHES/PARENT_PAGES and in whether store.close() is called before polling.
One test with for close_early in [false, true], BRANCHES = 4, PARENT_PAGES = 3 * WINDOW_PAGES, and the in_flight().1 == BRANCHES / close() / stats().fetched lines inside if close_early, gives exactly the counts the close test asserts (disk_opens() == 1 + BRANCHES, coalesced_windows() == 3 * (BRANCHES - 1)). The 4-aligned-parent-window shape stays covered by different_skip_pages_coalesce_aligned_windows_to_exact_gpu_pages (:8510, 3 * WINDOW_PAGES + 7).
4. Should fix — ObservedTransport and the recomputed rate (~60-75 lines)
selene/src/disk_store.rs:9110-9160 is a 51-line struct ObservedTransport { inner: Staged, samples: Arc<Mutex<Vec<(u64, Duration)>>> } whose DiskTransport impl delegates all eight methods one-for-one to Staged; the only non-delegating body is poll (:9140-9150), which copies TransportEvent::InboundWindowSample { bytes, elapsed } into the log. The test then reconstructs the rate from that log (:9324-9328) for the sole purpose of comparing store.stats().inbound_rate with itself (:9346-9350).
Delete the wrapper and the sample plumbing (single_samples :9176, the samples: fields :9196/:9249, the asserts :9225, :9313-9319), and keep the guarantees that actually test the stated property:
staged.disk_window_reads() == 2(already asserted at:9310) — one physical read per aligned window, so followers did not inflate it;- hoist the existing 5%-tolerance comparison between
rate_after_physical_reads(:9280) and the final rate (:9336-9345) out of theif let, so it runs for both passes.
Only the absolute rate value for the non-staggered pass is lost, and stats.inbound_rate > 0.0 && is_finite() (:5726) already covers that.
5. Should fix — HeaderIdentity re-implements Header's identity rules (~50 added, net ~22)
selene/src/disk_store.rs:1001-1050 adds HeaderIdentity(Arc<Header>), whose only purpose is to be a Hash key inside SegmentKey (:1052-1056) and hence WindowKey (:1058-1064). Its 47-line hand-written Hash (:1014-1050) re-states the field list of Header's own PartialEq (selene/src/shared/record.rs:136-152) and deliberately skips version, destructuring with .. (:1030) — so a field added to Header can be hashed differently from how it is compared, and the compiler will not say so. The Arc::ptr_eq fast path in PartialEq (:1008) buys nothing: equal Arcs are equal by value.
Smaller version: put the Hash impl once, next to the PartialEq it must agree with, and drop the wrapper.
// selene/src/shared/record.rs, after `impl Eq for Header {}` (line 154)
impl std::hash::Hash for Header { /* the same field list as `eq`, ~28 lines */ }
// selene/src/disk_store.rs
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct SegmentKey { path: Arc<Path>, expected: Arc<Header> }
plus HeaderIdentity(Arc::new(..)) at :2444 → Arc::new(..) and (*key.segment.expected.0).clone() at :1964 → (*key.segment.expected).clone(). Net ~22 lines and one fewer definition of which Header fields are identity.
6. Nit — pump_device_inbound walks every record's active-window list twice (~12 lines)
selene/src/disk_store.rs:1897-1909 (Pass 1) removes entries whose upload_done is set; :2144-2196 (Pass 5b) walks the same list again with if active.upload_submitted { continue; } and submits an upload for each. Nothing between them reads record.done/record.bytes; the only shared input, has_window_credit → active.len(), is changed by reaping only downwards, which merely lets Pass 4 start fewer windows for one pump and is picked up on the next step.
Folding the reap into the head of a single "reap-and-upload" loop at the Pass 5b site deletes one full traversal, its active_len copy, and the self.device_inbound[&id].active[index] re-lookup per upload. Lowest-confidence item here: confirm the pump interleaving is acceptable (the tests that count polls loop, so one extra pump is tolerated).
7. Nit — poll_all_fetches duplicates crate::testing::poll_until (~10-16 lines)
selene/src/disk_store.rs:8215-8232 and selene/src/testing.rs:25-37 are the same helper: poll into a Vec<StoreEvent> until a condition within a deadline, returning the events. The file already imports use crate::testing::poll_until; (:2829) and uses it at :3940, :7609, :7859, :7904 and elsewhere. The one difference: poll_until takes Fn(&StoreEvent) -> bool (not FnMut), so counting to expected needs a Cell in the closure at the six call sites (:8347, :8476, :8583, :8687, :8803, :8961). Saving is modest; a thin local wrapper is defensible.
8. Nit — Owner::HostInbound(JobId, usize) and HostInbound::segments carry a list that always has one element (~8 lines)
selene/src/disk_store.rs:265-267, :749-750. The only constructor is read_into (:1351, :1359-1360), which builds Owner::HostInbound(id, 0) and HostInbound::new(vec![segment], ...), so the index is always 0. Owner::HostInbound(JobId) with segment: Segment removes the vec![], the segments.get_mut(segment) at :789, and the .iter() / [plan.segment] indirections at :865, :882, :890, :924, :974, :987. Segment::settled is unchanged. (The segments: Vec<Segment> inside InboundRecord on the device path is genuinely multi-element and must stay.)
9. Nit — the docs state the physical-vs-logical split twice (~5 lines)
docs/prefix-cache-offload.md:362-366 (§2.4) and :1528-1531 (§4 measurement notes) say the same thing: StoreStats.bytes_in counts logical restored bytes while inbound_rate comes from physical staging-window reads. Keep the §4 note where the measurement table is; drop the §2.4 sentences. §2.4 also restates the module doc at selene/src/disk_store.rs:9-27 clause for clause (shared handle, slots pinned until every upload, close before Fetched, at most one extra partial window); the module doc next to the code is the one to keep.
10. Nit — one provably dead term in Staged::close's max (~2-4 lines)
selene/src/disk_store.rs:2522-2528:
let internal = self.owners.len()
.max(self.maintenance.len())
.max(self.shared_segments.len())
.max(self.shared_windows.len());
SharedWindow owns no disk job id, so .max(self.shared_windows.len()) can never raise the count. Every maintenance id is inserted into owners first (:2468, :2485), and a SharedSegment id is in owners at :1968 as soon as its Open is submitted, so the segment term only matters while a segment is still Unopened. Safe shorter form: self.owners.len().max(self.maintenance.len()).max(self.shared_segments.len()) — the shared_windows term goes outright; whether the remaining terms can go too (if the Unopened case is covered by the store-level store_jobs count) is for the author to confirm.
Left behind, and checked and found sound (do not re-raise)
- Nothing is left dead by this change.
Destination,InPhase,InboundRecord::apply_transfer,InboundRecord::submit_uploadand the device branch of the old inbound record are all deleted inside this same diff (they replacedisk_store.rs:614-1000on main). The only pre-existing helper whose call sites the diff rewrites isplan_windows, and all four sites are updated::1349(false),:2435(true),:6262(false),:8235(true). plan_windows(.., align_to_window)and theWindowKey/window_indexO(1) lookup are themselves subtractions already taken earlier on this branch in response to review (PR comment "S4 & S5", 2026-11-25 02:41) — they replaced a hand-written 5-tuple key and a per-pumpPathBufclone. Not proposed again.TransportEvent::InboundWindowSample(:97-101) needs all three of its sites:DiskStore::apply(:3632-3635) is the only consumer and must return beforestats.progress += 1;shard.rs:476'sunreachable!is genuinely unreachable becauseSharded::absorb_local(:722-725) andPeer::forward(:1148-1150) both filter the variant andcontinue. There is no smaller route fromStagedtoDiskStore::inbound_rate, sinceDiskStoreonly observesTransportEvents.- The diagnostic counters
disk_opens/disk_window_reads/coalesced_windowsand thedisk_read_countedflags are already gated at 13#[cfg(any(test, feature = "test-support"))]sites, and each getter (:1279-1295) is used by several tests — no dead instrumentation. Resources::free_slots(:236-239) is a one-line accessor with callers; not worth cutting.- No core re-export or on-disk format change, as the description says.
Open questions
- Demand preference vs the staggered benchmark (finding 2): the PR reports
3.76xstaggered vs4.22xsimultaneous onQwen3.8-27B-NVFP4. That difference is the only thing the demand table can buy. It should be measured with the table removed before the 65-80 lines come out; the fallback is a boolean test overwindow_index. - The
Unopenedshared-segment case inStaged::close(finding 10): whether it is meant to be counted byinternalor is already covered bystore_jobs— the author should confirm before more terms come out. poll_all_fetchesvspoll_until(finding 7): verified thatpoll_untiltakesFn(&StoreEvent) -> booland returns the accumulated buffer, so the duplication is real; theCellneeded at six call sites is why it stays a nit.
Caveat
No toolchain, GPU or test execution was available in this review environment: every finding above is established by reading the source at head 0c04b1e2, not by running the suites.