#1 [high] Should fix: HeaderIdentity (≈50 lines) duplicates Header's identity rules; move Hash onto Header
selene/src/disk_store.rs:1001-1050 adds HeaderIdentity(Arc<Header>) with PartialEq (ptr_eq || ==), Eq, and a 47-line hand-written Hash that destructures Header with .., hashes ranks.len() then each RankSizes, and deliberately skips version. Its purpose is only to be a Hash key in SegmentKey (1052-1056) and thus WindowKey (1058-1064). Header (selene/src/shared/record.rs:116-154) derives Clone, Debug and defines its own PartialEq (136-152) that includes exactly the fields the Hash lists minus version.
Smaller version: put the Hash impl once, beside the Eq it must agree with, and delete the wrapper:
- selene/src/shared/record.rs after line 154:
impl std::hash::Hash for Header { fn hash<H: Hasher>(&self, state: &mut H) { self.identity.hash(state); self.fingerprint.hash(state); /* same field list */ } }(~28 lines). - disk_store.rs:
#[derive(Clone, Debug, PartialEq, Eq, Hash)] struct SegmentKey { path: Arc<Path>, expected: Arc<Header> }; deleteHeaderIdentityentirely (struct + 3 impls, 50 lines); dropHeaderIdentity(Arc::new(..))at :2444 and(*key.segment.expected.0).clone()at :1964.
Net ≈ -22 lines plus one fewer type, and there is then one definition of "which Header fields are identity". Today a field added to Header must be added in two places (record.rs:136 and disk_store.rs:1016) and the .. pattern means the compiler will not complain if it is missed, so WindowKey hashing can silently disagree with the expected comparison it is paired with. Nothing in the file needs the ptr_eq fast path (identical Arcs are equal by value anyway).
#3 [high] Should fix: demand-index scheduling (~80 lines) only reorders which new window starts first
selene/src/disk_store.rs:1732-1793 build_pending_demand (24 lines) + pick_next_pending_plan (37 lines), plus the demand: Option<&mut HashMap<WindowKey, usize>> parameter threaded through attach_pending (:1711-1730) and the demand.as_mut() decrement blocks at :1991-1995 and :1939, ≈80 lines total, exist only to reorder which new window a leader starts first: prefer plans whose WindowKey another live fetch also needs. Coalescing itself does not depend on it — attach_pending/find_best_existing_window_for (:1665-1681) already scans every unstarted plan for any reusable in-flight window regardless of order, and plan_windows(.., true) guarantees aligned (first, count) equality. Selecting the first unstarted plan (what main did) coalesces exactly the same windows, just possibly a little later.
Evidence the machinery is often dead: build_pending_demand returns empty for device_inbound.len() <= 1 (:1736) — i.e. every single-restore caller, and pick_next_pending_plan then degenerates to first-unstarted.
Smaller version: delete build_pending_demand, the demand parameter and both decrement sites; pick_next_pending_plan becomes the free-slot filter plus "first unstarted plan", about 12 lines; attach_pending loses its second argument. ≈65-80 lines removed. What is lost is only arrival-order relaxation across concurrent restores, which the PR measures as part of the staggered TTFT gain (3.76x vs 4.22x simultaneous); if the staggered number regresses, keep the preference as a single peer_demand > 0 boolean test over the existing window_index instead of a per-pump HashMap of every pending key.
#6 [high] Summary: subtraction totals for PR 496 and what must stay
Sizes measured from the PR diff for PR #496 (head 0c04b1e2, base c0c4f798): docs/prefix-cache-offload.md +35/-2, selene/src/disk_store.rs +3313/-931, selene/src/shard.rs +10/-0. Total +3358/-933. Of disk_store.rs, the new test module additions are roughly +900 lines (the six coalescing tests :8234-9357 plus GatedCopier/write_shared_ancestor_tree/poll_all_fetches fixtures), so the production change is roughly +2400/-930.
Confirmed subtractions, ranked by lines saved (details in notes 1-5):
- Demand-index scheduling: ~65-80 lines.
- Merge the close-drain test into the burst test: ~70 lines.
HeaderIdentitywrapper + manual Hash: ~50 lines (net ~22 after moving Hash ontoHeader, but one duplicate definition of identity goes).- Fold Pass 1 into Pass 5b: ~12 lines.
- Nits: duplicated docs paragraph ~5, four-way max in
close~4, single-segmentVec~8: ~17 lines.
Total ≈ 215-230 lines removable, i.e. about 6% of the change and about 9% of the non-test production lines. The rest of the change is load-bearing: the shared-segment/shared-window state machine, the reference counts that keep SlabPool slots alive across every follower's upload, the failure isolation, and the InboundWindowSample event + shard.rs forwarding are each required by a stated goal and cannot be dropped without losing the measured 3.5-4.2x read reduction.
Judgement for the report: the change is not minimal but it is not padded either — the biggest single saving is the demand-index scheduler, which is the only block in the change whose removal loses nothing except start order. Everything else is Nit-to-Should fix housekeeping. I did not find a part of the change that serves no purpose, duplicates an existing repository helper beyond plan_windows/Header Hash, or leaves a superseded path behind: Destination, InPhase, InboundRecord::submit_upload and the device branch of the old InboundRecord are all deleted in this same diff, and the old plan_windows single call site is replaced.
#8 [high] Research summary
Reviewed PR #496 (head 0c04b1e, +3358/-933 across disk_store.rs, shard.rs and docs) strictly for subtraction. Seven scratchpad notes hold the findings with file:line citations, line savings and smaller replacements; note 6 has the ranked totals.
Headline: the change is large but mostly load-bearing — the shared segment/window state machine, the reference counts that keep SlabPool slots pinned across every follower's upload, the failure isolation and the InboundWindowSample plumbing are each required by a stated goal, and the old Destination/InPhase/submit_upload device path is fully deleted in the same diff, so nothing is left dead. The confirmed removable total is roughly 215–230 lines (~6% of the change), dominated by three items: the per-pump demand table and demand-aware plan picker (~65–80 lines, whose only effect is which new window a leader starts first — attach scanning already coalesces regardless of order); folding the close-drain test into the burst test, which builds the same fixture and asserts the same counters (~70 lines); and the HeaderIdentity wrapper with its 47-line hand-written Hash, which duplicates Header's own identity rules and should move onto Header next to the PartialEq it must agree with (~50 lines added, ~22 net). Remaining nits: duplicated docs paragraph (§2.4 and §4 say the same thing), a four-way max in Staged::close where one term is provably dead, a one-element Vec in HostInbound, and one redundant traversal of the active-window list per pump.
#12 [high] Should fix: eight new coalescing tests rebuild the same store (~90-110 lines)
The new test module constructs the identical store boilerplate at 10 sites in selene/src/disk_store.rs (head 0c04b1e2):
- :8316-8329
concurrent_burst_coalesces_... - :8407-8420
staggered_arrival_attaches_out_of_order_... - :8531-8544
different_skip_pages_coalesce_... - :8655-8668
private_failure_isolation_... - :8770-8783
shared_ancestor_failure_propagates_... - :8850-8863
staged_close_drains_... - :8934-8947 (the private baseline store inside
misaligned_follower_...) - :8985-8998 (the coalesced store in the same test)
- :9183-9199 and :9236-9252 (the two
ObservedTransportstores incoalesced_restores_keep_inbound_rate_...)
Each block is 14-17 lines and differs only in the directory, the DiskThread::start(name) label, and which copier is passed:
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();
preceded in every case 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();, :8313-8314, :8403-8404, :8527-8528, :8647-8648, :8767-8768, :8847-8848, :8931-8932, :8982, :9180-9181, :9230-9231) and, at :8306-8309, :8763-8766, :8843-8846, a five-line records vec built from the fixture (vec![scanned(parent)] + loop over children with index age).
Smaller version, ~18 lines, once in the test module:
fn staged_store(
directory: &Path,
name: &str,
geometry: Vec<CacheGeometry>,
records: Vec<Scanned>,
intake: usize,
copier: SharedCopier,
) -> (DiskStore, SlabPool) {
let layout = Layout::new(&geometry).unwrap();
let pool = SlabPool::new(layout.page_record_bytes, intake, intake).unwrap();
let store = DiskStore::new(
record::DirectoryLock::acquire(directory).unwrap(),
IDENTITY, FINGERPRINT, 1 << 30, geometry, records,
Box::new(Staged::new(Some(pool.clone()), copier, DiskThread::start(name).unwrap())),
).unwrap();
(store, pool)
}
fn scanned_tree(directory: &Path, fixture: &AncestorBranchFixture) -> Vec<Scanned> { /* ~6 lines */ }
Each site becomes let (mut store, pool) = staged_store(&directory, "coalesce-burst", geometry, records, crate::offload::intake_slots(&layout, 1), copier); (1-2 lines), and the three repeated records blocks become scanned_tree(&directory, &fixture).
Saving: about 13 lines x 10 sites = ~130 removed, ~24 added for the two helpers => roughly 90-110 lines net. No coverage is lost: every test keeps its own directory, its own counters and its own assertions; only the constructor repetition goes. This is the largest single subtraction left in the change and it is pure test-fixture duplication, not behaviour.
#13 [high] Should fix: ObservedTransport wrapper (~51 lines) recomputes a rate the store already reports
selene/src/disk_store.rs:9110-9160 defines ObservedTransport, a struct { inner: Staged, samples: Arc<Mutex<Vec<(u64, Duration)>>> } that implements all eight DiskTransport methods as pure delegation (self.inner.store(...), self.inner.fetch(...), ...) except poll, where it copies every TransportEvent::InboundWindowSample { bytes, elapsed } into the log. 51 lines of pass-through for one observation.
The test then rebuilds the rate from those samples (:9324-9328) purely to assert that store.stats().inbound_rate equals it (:9346-9350) - i.e. it feeds Rate the same samples Rate already received and compares the result with itself. The staggered pass already snapshots the real store rate at :9280 (rate_after_physical_reads = Some(store.stats().inbound_rate)) and compares the final rate to it at :9336-9345 with the same 5% tolerance; because no follower ever emits a sample, that comparison is the physical-vs-logical check, and it can be hoisted out of the if let for both passes.
Smaller version: delete ObservedTransport (:9110-9160), the samples shells (single_samples :9176, samples: Arc::clone(...) :9196, :9225, recorded_samples :9235, :9249) and the sample assertions/expected-rate block (:9313-9328), and assert instead:
let staged = store.transport_mut().staged().unwrap();
assert!(settled(staged));
assert_eq!(staged.disk_window_reads(), 2); // already there, :9310
assert_eq!(staged.coalesced_windows(), 2 * (CONCURRENT as u64 - 1));
if let Some(before) = rate_before_followers { /* existing 5% comparison, both passes */ }
For the single-restore half of the test the physical-read count is available the same way, via private/store.transport_mut().staged().unwrap().disk_window_reads() == 2beforeclose(); the loss is only the absolute inbound_ratevalue for the non-staggered pass, which the pre-existingstats.inbound_rate > 0.0 && is_finite()` test (:5726) and the staggered comparison still cover.
Saving: 51 (wrapper) + ~25 (sample plumbing and the recomputed expected rate) => about 60-85 lines. Net of the 3 lines that replace them, ~60-75.
#14 [high] Addendum: revised totals ~370-410 lines; two large test-fixture cuts found
Addendum to note #6/#11 after re-reading the whole test module at head 0c04b1e2:
Two subtractions found this round, both inside the ~+900 lines of new tests, and both larger than anything previously recorded:
staged_store+scanned_treehelpers replace 10 copies of the same 14-17 lineDiskStore::new(... Staged::new(Some(pool.clone()), copier, DiskThread::start(..)))block and 3 copies of the samerecordsvec: ~90-110 lines (note #12).- Delete
ObservedTransport(:9110-9160, 51 lines of pure delegation) and the sample plumbing that recomputes from its log aRatethe store has already computed; assert onstaged.disk_window_reads()instead: ~60-75 lines (note #13).
Revised totals, ranked by lines saved (all confirmed against the code):
| # | Where | Lines | Severity |
|---|---|---|---|
| 1 | 10x store boilerplate -> staged_store/scanned_tree |
~90-110 | Should fix |
| 2 | Demand-index scheduling (:1732-1793, :1711-1730, :1926-1942, :1991-1995) | ~65-80 | Should fix |
| 3 | Merge staged_close_drains_... (:8830-8906) into concurrent_burst_... (:8293-8384) |
~70 | Should fix |
| 4 | ObservedTransport + sample recomputation (:9110-9160, :9176, :9225, :9313-9328) |
~60-75 | Should fix |
| 5 | HeaderIdentity + hand-written Hash (:1001-1050, :2444, :1964) |
~50 added, net ~22 | Should fix |
| 6 | Pass 1 / Pass 5b double traversal (:1897-1909, :2144-2196) | ~12 | Nit |
| 7 | poll_all_fetches (:8215-8232) vs crate::testing::poll_until (testing.rs:25-37) |
~10-16 | Nit |
| 8 | Owner::HostInbound(JobId, usize) single-element Vec<Segment> (:265, :1351-1360, :789, :865-987) |
~8 | Nit |
| 9 | Duplicated docs paragraph (prefix-cache-offload.md:362-366 vs :1528-1531) | ~5 | Nit |
| 10 | Dead .max(self.shared_windows.len()) in Staged::close (:2522-2528) |
~2-4 | Nit |
New total: roughly 370-410 lines, about 11-12% of the change and ~42% of the new test lines. With the four test-side cuts (~250 of it) the change is materially smaller and loses no coverage: each remaining test keeps its own directory, counters and assertions.
Still cleared (unchanged): no superseded code left behind (Destination, InPhase, InboundRecord::apply_transfer/submit_upload, and the device branch of the old inbound record are deleted in this diff); plan_windows' only old call site is updated; TransportEvent::InboundWindowSample and its three shard.rs sites are needed for the stated physical-rate goal; the #[cfg(any(test, feature = "test-support"))] gating on the three counters is already tight.
#15 [high] Research summary
Verdict: make it smaller first — the change is +3358/−933 in 3 files, and about 370–410 lines of it can go without losing anything the project needs.
Two large cuts found this round, both in the ~+900 lines of new tests, and both bigger than anything previously recorded:
- 10 copies of the same store boilerplate (~90–110 lines). Every new coalescing test rebuilds the identical 14–17-line
DiskStore::new(record::DirectoryLock::acquire…, IDENTITY, FINGERPRINT, 1 << 30, geometry, records, Box::new(Staged::new(Some(pool.clone()), copier, DiskThread::start(name))))plus the same twoSlabPoollines, and three tests repeat the samerecordsvec from the fixture. Onestaged_storehelper and onescanned_treehelper replace all of it; each test keeps its own directory, counters and assertions. - A 51-line pass-through transport (
ObservedTransport, :9110-9160). It delegates all eightDiskTransportmethods toStagedonly to logInboundWindowSample, and the test then rebuilds from those samples aRatethe store has already computed, to compare the store's rate with itself. The staggered pass already snapshotsstore.stats().inbound_ratebefore followers arrive and bounds the final value within 5%; asserting onstaged.disk_window_reads()gives the same physical-vs-logical guarantee in ~60–75 fewer lines.
The earlier findings stand and are now ranked below them: the per-pump demand table and demand-aware picker (~65–80 lines that only reorder which new window a leader starts; attach_pending already coalesces regardless of order, and the table is provably empty for every single-restore caller); merging the close-drain test into the burst test (~70 lines, identical fixture and assertions differing only in when close() runs); HeaderIdentity and its hand-written 47-line Hash duplicating Header's identity rules (50 added, ~22 net); then five nits (~40 lines: the Pass 1/Pass 5b double traversal, poll_all_fetches vs crate::testing::poll_until, the single-element Vec<Segment> behind Owner::HostInbound, a docs paragraph stated twice, and a dead term in Staged::close's max).
Nothing is left dead behind the change: Destination, InPhase, InboundRecord::apply_transfer, submit_upload and the old device branch are all deleted in this same diff, plan_windows' one old call site is updated, and the InboundWindowSample event plus its three shard.rs sites are required by the stated physical-rate goal. The rest of the production change — the shared segment/window state machine and the reference counts that pin SlabPool slots until every follower's upload finishes — is load-bearing for the measured 3.5–4.2x read reduction. Findings and line counts are in scratchpad notes #12, #13 and #14, with the earlier ranked report in #11.
#16 [high] Final consolidated report input for PR 496 (head 0c04b1e2)
PR #496 — subtraction review, final
PR: https://github.com/NVIDIA/hyperflare-inference/pull/496, head 0c04b1e2, base c0c4f798. Size: +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, ~+900 is the new test module (:8094-9357), so the production change is ~+2400/-930.
Verdict
Make it smaller first. Removable: ~370-410 lines (~11-12% of the change; ~42% of the new test lines). The change is not padded — the shared segment/window state machine, the reference counts pinning SlabPool slots until every follower's upload finishes, the private-vs-shared failure isolation, and the InboundWindowSample plumbing to 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 and one scheduler whose only effect is start order.
Ranked findings (lines saved, then severity)
- ~90-110 | Should fix — 10 copies of the same store boilerplate in the tests. :8316-8329, :8407-8420, :8531-8544, :8655-8668, :8770-8783, :8850-8863, :8934-8947, :8985-8998, :9183-9199, :9236-9252 each rebuild
DiskStore::new(record::DirectoryLock::acquire(&directory).unwrap(), IDENTITY, FINGERPRINT, 1 << 30, geometry, records, Box::new(Staged::new(Some(pool.clone()), copier, DiskThread::start(name).unwrap()))).unwrap()(14-17 lines), 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 :8313-8314, :8403-8404, :8527-8528, :8647-8648, :8767-8768, :8847-8848, :8931-8932, :8982, :9180-9181, :9230-9231), and three tests repeat the samerecordsvec (:8306-8309, :8763-8766, :8843-8846). Replace with two helpers (~24 lines):fn staged_store(directory, name, geometry, records, intake, copier) -> (DiskStore, SlabPool)andfn scanned_tree(&Path, &AncestorBranchFixture) -> Vec<Scanned>. Each site becomes 1-2 lines. No coverage lost: every test keeps its own directory, counters and assertions. - ~65-80 | Should fix — per-pump demand table + demand-aware picker.
build_pending_demand:1732-1755,pick_next_pending_plan:1757-1793, thedemand: Option<&mut HashMap<WindowKey, usize>>argument onattach_pending:1711-1730, and the decrement sites :1939 and :1991-1995. Only effect: reorder which new window a leader starts. Coalescing is independent —find_best_existing_window_for:1665-1681 already scans every unstarted plan for a reusable in-flight window, andplan_windows(.., true)guarantees aligned(first,count)equality. Provably idle for the common case:build_pending_demandreturns empty whendevice_inbound.len() <= 1(:1736). Smallerpick_next_pending_plan:
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] && record.count_or(plan) + if plan.row { row_slots } else { 0 } <= free
})
}
(adapt the size expression; the point is the picker becomes a position() over the free-slot filter). Only arrival-order relaxation goes; that shows in the staggered row of the PR table (3.76x vs 4.22x), so measure before cutting; the cheap fallback is a single peer_demand > 0 lookup in window_index instead of a HashMap.
3. ~70 | Should fix — close-drain test duplicates the burst test. staged_close_drains_active_coalesced_fetches_cleanly :8830-8906 vs concurrent_burst_coalesces_shared_ancestor_opens_and_window_reads :8293-8384: same fixture (write_shared_ancestor_tree, scanned, intake-sized SlabPool, SimulatedGpu::shared_mapped, DiskStore::new, per-branch InboundTicket, poll_all_fetches), same counter assertions, same per-page and row equality loops; they differ only in BRANCHES/PARENT_PAGES and when store.close() runs. 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 :8510 (3*WINDOW_PAGES+7).
4. ~60-75 | Should fix — ObservedTransport and the recomputed rate. :9110-9160 is a 51-line DiskTransport that delegates all eight methods to Staged only to copy InboundWindowSample{bytes,elapsed} into a log; the test then rebuilds the rate from that log (:9324-9328) purely to compare store.stats().inbound_rate with itself (:9346-9350). Delete the wrapper and the sample shells (single_samples :9176, samples: :9196/:9249, asserts :9225/:9313-9319), assert staged.disk_window_reads() == 2 (already at :9310) and hoist the existing 5%-tolerance comparison between rate_after_physical_reads (:9280) and the final rate (:9336-9345) 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() (:5726) still covers it.
5. ~50 added, net ~22 | Should fix — HeaderIdentity re-implements Header's identity. :1001-1050: wrapper whose only purpose is to be the Hash key inside SegmentKey :1052-1056 / WindowKey :1058-1064. Its 47-line hand-written Hash re-states Header's PartialEq (selene/src/shared/record.rs:136-152) with a .. pattern (:1030) that hides a missed field, so hashing can silently disagree with the expected comparison it is paired with. Put the Hash impl once beside the PartialEq (record.rs after :154), make SegmentKey { path: Arc<Path>, expected: Arc<Header> } derive Hash, drop the wrapper, HeaderIdentity(Arc::new(..)) at :2444 -> Arc::new(..), (*key.segment.expected.0).clone() at :1964 -> (*key.segment.expected).clone(). The Arc::ptr_eq fast path buys nothing (equal Arcs are equal by value).
6. ~12 | Nit — Pass 1 and Pass 5b walk every record's active list twice. Pass 1 :1897-1909 reaps upload_done; Pass 5b :2144-2196 walks the same list with if active.upload_submitted { continue; } and submits uploads. Folding the reap into the head of one reap-and-upload loop at the Pass 5b site removes a traversal, the active_len copy and the self.device_inbound[&id].active[index] re-lookup per upload. Lowest-confidence item: confirm the pump interleaving (the tests that count polls loop, so an extra pump is tolerated).
7. ~10-16 | Nit — poll_all_fetches :8215-8232 duplicates crate::testing::poll_until (selene/src/testing.rs:25-37), already imported and used at :3940, :7609, :7859, :7904... Verified signature: takes impl 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). Modest saving; a thin local wrapper is defensible.
8. ~8 | Nit — Owner::HostInbound(JobId, usize) and HostInbound::segments carry a list that always has one element. :265-267, :749-750; the only constructor is read_into :1351/:1359-1360 building Owner::HostInbound(id, 0) and HostInbound::new(vec![segment], ...). Owner::HostInbound(JobId) + segment: Segment removes the vec![], segments.get_mut(segment) :789, and the .iter()/[plan.segment] indirections at :865, :882, :890, :924, :974, :987. (InboundRecord's multi-element Vec<Segment> on the device path is genuinely multi and must stay.)
9. ~5 | Nit — docs state the physical-vs-logical split twice. docs/prefix-cache-offload.md:362-366 and :1528-1531 say the same thing; keep the §4 measurement note, drop the §2.4 sentences. §2.4 also restates the module doc at disk_store.rs:9-27 clause for clause.
10. ~2-4 | Nit — dead term in Staged::close's max. :2522-2528 internal = owners.len().max(maintenance.len()).max(shared_segments.len()).max(shared_windows.len()). SharedWindow owns no disk job id, so the last term can never raise the count; maintenance ids are inserted into owners at :2468/:2485 first; a SharedSegment id is in owners at :1968 once Open is submitted, so the segment term only matters while Unopened. Safe: drop the shared_windows term (~2 lines); the Unopened case should be confirmed with the author.
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. The only pre-existing helper with rewritten call sites isplan_windows, and all four sites are updated (:1349false, :2435true, :6262false, :8235true). TransportEvent::InboundWindowSample(:97-101) needs its three sites:DiskStore::apply:3632-3635 is the only consumer and must return beforestats.progress += 1;shard.rs:476'sunreachable!is genuinely unreachable becauseabsorb_local:722-725 andPeer::forward:1148-1150 both filter the variant. There is no smaller route fromStagedtoDiskStore::inbound_rate.- Diagnostic counters
disk_opens/disk_window_reads/coalesced_windowsand thedisk_read_countedflags are already gated at 13#[cfg(any(test, feature = "test-support"))]sites; each getter (:1279-1295) is used by several tests (10, 6, 10 call sites respectively).Resources::free_slots:236-239 is a one-line accessor with callers. - No new core re-export or on-disk format change.
Caveat to state in the report
No toolchain, GPU or test run was available: every finding is established from source at head 0c04b1e2. The demand-order removal (finding 2) is the only item whose absence could show in the PR's staggered benchmark; it should be measured, not assumed.
#18 [high] Report of 2026-11-27, run 1181 — PR 496 re-reviewed at rebased head cb3db468
PR #496 subtraction review — head cb3db468 (rebased onto main 6d74db3a)
Size at this head (pr_files): 5 files, +8470/−5627 for selene/src/disk_store.rs, +44 packed.rs, +119/−1 record.rs, +11 shard.rs, +38/−2 docs/prefix-cache-offload.md. Production disk_store.rs is ~4.8k lines of change; the new test module is :9352-10856 (~1.5k lines).
Verdict: make it smaller first. ~360-400 lines removable (~7-8% of the change, ~25% of the new test lines).
All findings re-verified in the code at this head. Ranked by lines saved.
1. Should fix — ~100-115 | 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() at :9499-9512, :9593-9606, :9716-9729, :9839-9852, :9954-9967, :10034-10047, :10169-10182, :10370-10386, :10423-10439 (9 identical blocks, 13-17 lines each), each preceded by the same two lines let intake = crate::offload::intake_slots(&layout, N); let pool = SlabPool::new(layout.page_record_bytes, intake, intake).unwrap(); (:9496, :9589, :9712, :9831, :9951, :10031, :10115, :10367, :10418), plus the same parent+children records vec (vec![scanned(parent)] + loop) at :9489-9492, :9584-9588, :10027-10030, :9947-9950, :9826-9830, :9707-9711.
Smaller: one helper + a scanned_tree helper (~24 lines total):
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> { ... }
Each site becomes 1 line; nothing lost (each test keeps its own directory, counters, assertions).
2. Should fix — ~65-80 | demand table + demand-aware picker only reorders window start order
build_pending_demand :2273-2294, pick_next_pending_plan :2299-2331, the demand: Option<&mut HashMap<WindowKey, usize>> arg on attach_pending :2250-2253 with decrement blocks :2261-2266 and :2541-2545. Coalescing is done by find_best_existing_window_for :2204-2220 + find_reusable_window :2185-2202, which already attach to any live window regardless of start order (plans are aligned by plan_windows(.., true) :3101-3105). The table is empty by construction for device_inbound.len() <= 1 (:2275).
Smaller: delete the table, the parameter and both decrements; picker becomes
fn pick_next_pending_plan(&self, id: JobId) -> Option<usize> {
let record = self.device_inbound.get(&id)?;
let free = self.resources.free_slots();
let layout = lock(&self.resources.transfers);
let layout = layout.layout();
record.plans.iter().enumerate().position(|(i, plan)| {
!record.started[i]
&& (record.segments[plan.segment].segment.expected.packed.is_some()
|| layout.record_slots(plan.count, plan.row) <= free)
})
}
Caveat to state: only arrival-order relaxation goes; the staggered benchmark row (3.53x vs 4.01x) should be re-measured if cut.
3. Should fix — ~70-75 | close-drain test duplicates the burst test
staged_close_drains_active_coalesced_fetches_cleanly :10014-10090 vs concurrent_burst_coalesces_shared_ancestor_opens_and_window_reads :9476-9570: same write_shared_ancestor_tree fixture, same intake pool, same SimulatedGpu::shared_mapped, same per-branch tickets, same counter assertions (disk_opens() == 1 + BRANCHES), same per-page/row equality loops. They differ in constants and in whether store.close() runs before polling (:10064-10065).
Smaller: 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. The 4-aligned-window shape stays covered by different_skip_pages_coalesce_aligned_windows_to_exact_gpu_pages :9694 (3*WINDOW_PAGES+7).
4. Should fix — ~55-65 | ObservedTransport wrapper recomputes a rate the store already reports
:10290-10347 is a 58-line DiskTransport delegating all twelve methods to Staged, only to copy (bytes, elapsed) window samples into a log; the test then rebuilds Rate from that log (:10499-10514) purely to compare store.stats().inbound_rate with a value derived from the same samples it was fed (:10531-10535). The real physical-vs-logical check is already rate_after_physical_reads vs final rate (:10466, :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; assert staged.disk_window_reads() == 2 (already :10496), the coalesced count (:10497), bytes_in, and hoist the existing 5% 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; stats.inbound_rate > 0.0 && is_finite() still covers it.
5. Nit — ~20 | HeaderIdentity wrapper is no longer needed
Now that Header: Hash lives beside its PartialEq (selene/src/shared/record.rs:165-202, added by this PR) and RankSizes/packed::Layout derive it, struct HeaderIdentity(Arc<Header>) with its manual PartialEq/Eq/Hash (:1440-1456) only exists to be the SegmentKey field (:1459-1462). Make SegmentKey { path: Arc<Path>, expected: Arc<Header> } and derive; delete the wrapper (:1440-1456, 17 lines) 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: equal Arcs are equal by value and hash equal.
6. Nit — ~14 | poll_all_fetches :9398-9415 duplicates crate::testing::poll_until (selene/src/testing.rs:24-37)
poll_until(store, deadline, |e| matches!(e, StoreEvent::Fetched{..})) already stops on the wanted event; counting to N needs a Cell in the closure at the 7 call sites (:9530, :9662, :9766, :9986, :10231, :10741, :10834). Saves the 18-line helper net of ~4 added.
7. Nit — ~12 | HostInbound::segments is always a one-element Vec<Segment>
Owner::HostInbound(JobId, usize) (:276) plus HostInbound::new(vec![segment], ..) (:1824, :1863-1867) — the only two constructors pass exactly one segment. Owner::HostInbound(JobId) and segment: Segment removes the index, the Vec, segments.get_mut(segment) (:1143), and the [window.plan.segment] indirections at :1227, :1278, :1324, :1413, :1426. (Device-side Vec<DeviceSegmentRef> is genuinely multi and must stay.)
8. Nit — ~10 | Staged::close's abandoned-job arithmetic is over-built
:3183-3195: maintenance_jobs (filter over owners), store_jobs (sum of three maps + that count) and store_jobs.max(self.owners.len()).max(self.maintenance.len()). Every maintenance job is already in owners (:3134, :3151) and every store job inserts an owner, so self.owners.len() alone counts abandoned disk jobs; maintenance.len() never exceeds it. Replace the four bindings with let abandoned_jobs = self.owners.len(); and keep the leaked_shared count as is.
9. Nit — ~12 | Pass 1 and Pass 5b walk each record's active list twice
Pass 1 :2422-2444 reaps upload_done windows; Pass 5b :2768-2862 walks the same list with if active.upload_submitted { continue; }. One reap-and-upload loop at the Pass 5b site removes a traversal, the active_len copy (:2769-2772) and the self.device_inbound[&id].active[index] re-lookup per upload.
10. Nit — ~5 | docs state the physical-vs-logical contract twice
docs/prefix-cache-offload.md:445-448 (§2.4 "See section 4 for StoreStats.bytes_in/…") and :1612-1618 (§4) say the same thing; keep §4. §2.4 also restates disk_store.rs:13-27 module doc clause by clause.
Cleared (do not re-raise)
- No code left behind:
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 anddrain_inbound_samples(:150, itsStagedimpl :3165-3167,Sharded:shard.rs, discarded inPeer::forward) is now the only route toDiskStore::inbound_rate(:3649-3655). Allplan_windowscall sites updated (:1851false, :3101true, tests).Header/packed::Layouthashing includes thepackedfield, so the earlier drift risk is fixed. TransportEventis unchanged; no re-export or on-disk format change;CompositeStore'sdisk_inbound_ratepath is outside this diff.- Test-only counters (
disk_opens/disk_window_reads/coalesced_windows) are#[cfg(any(test, feature = "test-support"))]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 callers. - Load-bearing and must stay: the shared segment/window state machine (:1488-1562, :2418-2955), reference counts (
disk_referenced/upload_referenced/followers), private-vs-shared failure isolation (:2040-2154), theFetched-after-disk_settledrule (:2894-2944), theinbound_samplesdrain, and the packed-window path.
Caveat
No toolchain, GPU or test run was available; every finding is from source at cb3db468. Finding 2 is the only one whose absence could show in the staggered benchmark row.
#19 [high] Research summary
Re-reviewed PR #496 at its rebased head cb3db468 (+8470/−5627 in selene/src/disk_store.rs, +44 packed.rs, +119/−1 record.rs, +11 shard.rs, +38/−2 docs/prefix-cache-offload.md), strictly for subtraction, and recorded the findings in scratchpad entry #18.
Verdict: make it smaller first. About 360–400 lines can go (~7–8% of the change, ~25% of the new test module at :9352-10856) with no behaviour or coverage lost. Ranked: nine copies of the same DiskStore::new(… Staged::new(SlabPool …)) fixture plus the same scanned-records vec in the new tests (~100–115, replaceable by two helpers); the per-pump demand table and demand-aware pick_next_pending_plan (~65–80, whose only effect is which new window a leader starts — coalescing is done by find_best_existing_window_for, and the table is empty for a single restore); the close-drain test duplicating the burst test (~70, one test with for close_early in [false, true]); the pass-through ObservedTransport plus the recomputed Rate (~55–65); then nits — the now-redundant HeaderIdentity wrapper (~20, since this PR put Hash on Header beside its PartialEq), the local poll_all_fetches vs crate::testing::poll_until (~14), the always-one-element HostInbound.segments (~12), the over-built abandoned-job arithmetic in Staged::close (~10), the double walk of each record's active list (~12), and a doc paragraph stated twice (~5).
Cleared: nothing is left dead behind the change — Destination, InPhase, the old device inbound branch and TransportEvent::InboundWindowSample are all deleted in this same diff, the two unreachable!()s are gone, and the earlier Header hash drift is fixed. The shared segment/window state machine, its reference counts, the private-vs-shared failure isolation, the Fetched-after-disk_settled rule and the out-of-band inbound_samples plumbing are load-bearing and must stay. No toolchain, GPU or test run was available; every finding is from source at cb3db468, and only the demand-index cut could show in the PR's staggered benchmark row.
#2 [medium] Should fix: close-drain test duplicates the burst test (~70 lines)
selene/src/disk_store.rs:8294-8384 concurrent_burst_coalesces_shared_ancestor_opens_and_window_reads (BRANCHES=6, PARENT_PAGES=3WINDOW_PAGES+5, CHILD_PAGES=3, intake pool, SimulatedGpu, 6 fetches, poll_all_fetches, then assert disk_opens/disk_window_reads/coalesced_windows, pool.free_slots, no pins, per-page and row equality) and :8831-8906 staged_close_drains_active_coalesced_fetches_cleanly (BRANCHES=4, PARENT_PAGES=3WINDOW_PAGES, CHILD_PAGES=4, same pool/SimulatedGpu/poll pattern, plus in_flight().1 == BRANCHES, store.close() before polling, and stats().fetched) are the same test with a different close placement.
Smaller version: one test, for close_early in [false, true], with const BRANCHES: usize = 4; const PARENT_PAGES: usize = 3 * WINDOW_PAGES; and the in_flight/close lines inside if close_early. Assertions become: disk_opens() == 1 + BRANCHES, coalesced_windows() == 3 * (BRANCHES - 1) (the exact count the close test already asserts and the burst test would reach with 3 parent windows), pool free, no pins, per-page/row equality (already identical loops). Saves the whole second fixture+setup+teardown.
≈70 lines. Nothing lost: the close-drain assertions are the union of both, and the burst test's 4-parent-window shape is already covered by different_skip_pages_coalesce_aligned_windows_to_exact_gpu_pages (8510) which uses 3*WINDOW_PAGES+7.
#4 [medium] Nits: duplicated docs paragraph, four-way max in close, one-element Segment Vec
-
docs/prefix-cache-offload.md:362-366 and again :1528-1531 state the same fact twice in one document ("
StoreStats.bytes_incounts logical checkpoint bytes restored to GPU destinations across completed fetches, whereasDiskStoreupdatesStoreStats.inbound_ratefrom physical staging-window disk reads once per window so coalesced followers do not inflate admission bandwidth estimates"). Keep the §4 measurement note (it sits in the measurement table) and drop the §2.4 sentences, ~5 lines. Also §2.4 (:337-366) now restates the module doc at selene/src/disk_store.rs:9-27 almost clause for clause (shared handle, pinned slots until every upload, close beforeFetched, at most one extra partial window); one of the two is enough, and the module doc is the one next to the code. -
selene/src/disk_store.rs:2522-2528
Staged::close:internalis.max()overowners.len(),maintenance.len(),shared_segments.len(),shared_windows.len(). Every shared segment's disk job id is already inowners(:1968) and every maintenance job's id too (:2468, :2485), and shared windows own no id at all, so the last two maxima cannot raise the count:internalisowners.len().max(maintenance.len())— 2 lines instead of 6. -
selene/src/disk_store.rs:265
Owner::HostInbound(JobId, usize):HostInboundalways holds exactly one segment (read_intobuildsvec![segment]at :1360, and it is the only constructor), so theusizesegment index is always 0 andsegments: Vec<Segment>is a singleSegment. Making itOwner::HostInbound(JobId)andsegment: Segmentremoves thevec![], the.get_mut(segment)inapply_disk(:789) and theiter()inapply_disk/pump/unwind(:865, :882, :974) — ~8 lines, andSegment::settledkeeps working.
#7 [medium] Correction to close() max finding: shared_windows max is dead, shared_segments only for Unopened
Correction to note 4 item 2 (verified against the code): every Owner::SharedSegment id is inserted in owners at :1968 and every maintenance id at :2468/:2485, before the job enters maintenance; SharedWindow owns no disk id at all. So .max(self.shared_windows.len()) can never raise the count, and .max(self.shared_segments.len()) only can when some segment is still Unopened (no Open submitted yet, hence nothing on the disk thread to abandon). Safe shorter form: let internal = self.owners.len().max(self.maintenance.len()).max(self.shared_segments.len()); — or keep shared_segments only for the Unopened case and drop shared_windows outright (:2522-2528, ~2 lines).
#9 [medium] Verified sound: no superseded code left behind; event variant and counters are needed
Checked and found sound (do not raise as findings, but the report should say these were checked):
- Nothing in the repository 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 the same diff (see the diff hunks replacing disk_store.rs:614-1000 on main). The only pre-existing helper whose call sites the diff rewrites isplan_windows, and both call sites are updated (read_into :1349 withfalse, fetch :2435 withtrue), plus the two plan-shape tests (:6262 withfalse, :8235 withtrue). plan_windows(.., align_to_window)merging the previously separate aligned planner and theWindowKey/window_indexO(1) lookup are additions this branch already made in response to the earlier review (PR comment 2026-11-25 02:41, "S4 & S5"). They replaced a hand-written 5-tuple key and a per-pump PathBuf clone, so they are net subtractions already taken; do not propose them again.TransportEvent::InboundWindowSample(disk_store.rs:97-101) needs its three call sites:DiskStore::apply(:3631-3638) is the only consumer and mustreturnbeforestats.progress += 1;shard.rs:476unreachable!is genuinely unreachable because both forwarding paths filter the variant first (Sharded::absorb_local:722-725 pushes it toself.eventsandcontinues;Peer::forward:1148-1150continues). It is one enum variant plus 2 match arms and 10 forwarding lines; there is no smaller way to get a per-physical-window sample fromStagedtoDiskStore::inbound_ratebecauseDiskStoreonly seesTransportEvents. Keep.Resources::free_slots(:236-239) is a one-line accessor with two callers (:1766, :1926/:1936) andMapOrstyle matching the file; not worth cutting.- Test-only counters
disk_opens/disk_window_reads/coalesced_windowsand thedisk_read_countedflags are already#[cfg(any(test, feature = "test-support"))](13 cfg sites) and the getterspub fn disk_opens()/disk_window_reads()/coalesced_windows()(:1279-1295) are each used by 4-9 tests, so no dead instrumentation.
#20 [medium] Addendum: framing for PR 496 at cb3db468 — diff size includes the #504 packed port
Addendum for the final report on PR #496 (head cb3db468), to be read with note #18.
Scope framing:
- The head is rebased onto main 6d74db3a, which already contains #504/#523/#524 lossless KV compression. The PR's diff therefore shows selene/src/disk_store.rs at +8470/−5627, selene/src/shared/record.rs +119/−1, selene/src/shared/packed.rs +44, selene/src/shard.rs +11, docs +38/−2 — but part of the record.rs/packed.rs additions are the v4
packedsupport re-ported across the rebase (author's comment at 2026-11-27 06:01 UTC lists "ported #504 v4 packed record support"), not new coalescing logic. State the numbers as the diff's own figures and note the mixture, rather than implying all of it is the coalescing feature. - The orientation packet reports 5 files, +8682/−5630 for the whole PR; pr_files at this head gives the per-file split quoted above. Use both with their sources.
Also worth stating plainly in the report:
- The author's own round-2 response (comment 2026-11-27) says every Round 2 review suggestion was addressed, including moving the rate sample off
TransportEventand movingHashontoHeader. My re-check at this head confirms those two are now satisfied (see cleared list in note #18), so the findings that survive are the test-fixture duplication, the demand scheduler, and the small nits — none of them items the author already fixed. - Merge-order note (author): land #497 first, then rebase #496. Relevant only as context; no subtraction follows from it.
- Charter hooks for the verdict: charter line 9 ("smallest footprint in shared code") and line 42 (supported-matrix review) — the cuts proposed remove duplication inside Selene's disk tier without changing behaviour or dropping a covered case.
#5 [low] Nit: pump_device_inbound walks every record's active windows twice
selene/src/disk_store.rs:1897-1909 (Pass 1), :2144-2196 (Pass 5b): both walk a healthy record's active list.
- Pass 1 removes entries with
upload_doneset. - Pass 5b walks the same entries again with
if active.upload_submitted { continue; }and submits an upload for each.
Smaller version: in Pass 1, when upload_done is false and !upload_submitted, submit the upload there (the win.phase == Read guard is the same test), then drop Pass 5b's first two if arms. The constraint is that Pass 5b must run after Pass 5a (disk reads), and Pass 1 runs before it — so instead of merging into Pass 1, Pass 1 can be folded into the head of a single "reap-and-upload" loop placed where Pass 5b is today: the "reap finished uploads" work does not need to happen before Pass 2/4 (those only consult started, active.len() and the shared windows, all unchanged by reaping). That deletes one of the two full traversals plus its active_len/index bookkeeping, ≈12 lines and one device_inbound[&id].active[index] re-lookup per upload.
Verification: nothing between Pass 1 and Pass 5b reads record.done or record.bytes — has_window_credit reads active.len(), which reaping changes, but reaping frees credit and lower credit only makes Pass 4 start fewer windows this pump, and pump_all runs every step, so it is caught next poll. Worth checking that the loop still terminates in one pump for the tests that count polls (staggered_arrival_attaches_out_of_order_to_in_flight_windows polls in a loop, so it tolerates an extra pump). Lower confidence than the other findings: merge only if the interleaving above is confirmed acceptable.
#10 [low] Nit (unverified): poll_all_fetches may duplicate crate::testing::poll_until
selene/src/disk_store.rs:8215-8232 adds poll_all_fetches(store, expected, deadline) -> Vec<StoreEvent> in the test module: it loops store.poll(&mut events), asserts the deadline, and returns the events once len() == expected. The crate already has crate::testing::poll_until (selene/src/testing.rs:25), which this very file imports (use crate::testing::poll_until; at :2829) and uses in dozens of tests for exactly this "poll until a predicate within a deadline" shape.
Savings if it is genuinely subsumed: ~16 lines, by calling poll_until(&mut store, deadline, |e| matches!(e, StoreEvent::Fetched { .. })) and asserting the event count afterwards, or by keeping only the assert helper. It is used by 5 of the new tests (:8347, :8476, :8583, :8687, :8803, :8961).
Caveat that keeps this a Nit and that the report must state: I did not read selene/src/testing.rs:25's exact signature, so I could not confirm it returns the accumulated Vec<StoreEvent> or counts events the way these tests need (several tests assert events.len() == expected and iterate for per-branch byte checks). Verify the signature before acting; drop the finding if poll_until only returns a bool or discards the buffer.