Review of PR #496 — Coalesce shared ancestor reads across concurrent Selene disk fetches
Lens: D, simplicity — what can be deleted. Reviewed at head 0c04b1e2 (base c0c4f798), files selene/src/disk_store.rs (+3313/−931), selene/src/shard.rs, docs/prefix-cache-offload.md (+35/−2).
Key findings
Verdict: clean. No blocking, no should-fix findings in this lens. Seven nits, each a small deletion.
Nothing in the change is a fallback layer, configuration switch, speculative abstraction or compatibility path that AGENTS.md 188-193 would reject. The split between a private caller-owned host read path (read_into, pump_host_inbound) and a coalescing device path (fetch → pump_device_inbound) is exactly what the PR says it is; read_into's observable behaviour is unchanged; slot release has one owner; the eight passes of pump_device_inbound each carry an ordering argument the others depend on, so their shape is not churn.
Every ask I made in the previous review round is implemented at this commit (listed under "Resolved" below), including the two I most wanted: one window planner and one attach helper. What remains is polish:
- the 30-line §2.4 doc paragraph that repeats §4;
- the single-segment host inbound modelled as a
Vecwith an always-zero index; HeaderIdentity's 37-line hand-writtenHash;Staged::closereporting amaxof unrelated counts as a job count;- two
idfields duplicating theirHashMapkeys; - a dead
demand.is_empty()guard; - two
disk_read_countedflags that exist only for a test counter.
Rules cited
- Charter, line 9: "Solve the right problem in the right place… Look for the smallest footprint in shared code, or a way to solve it without new code at all."
AGENTS.md188-193 ("Contribution scope and rejection criteria"): "Do not add frameworks, extension points, speculative compatibility, fallback layers, or configuration switches without a concrete requirement… Refactoring must directly support the requested behavior or remove a demonstrated source of defects or cost."AGENTS.md194-199: validation must exercise the real behaviour — "source-text checks and mocks that bypass the behavior cannot establish runtime correctness."AGENTS.md43-49 (required prose review) anddocs/design-review.md(not opened) principle 1 ("Keep Helios as simple as possible"), principle 7 ("Published checkpoints are immutable"), principle 12 ("Validate the real path and report evidence honestly"), principle 16 (prose).- Charter line 42 (supported-matrix compatibility) and line 43 (no per-model special cases or flags) — checked, none added.
Findings
N1 (nit, fix-first) — docs/prefix-cache-offload.md:337-366 is one 30-line paragraph carrying nine behaviours, three of which are repeated in §4
Section 2.4 now contains a single paragraph that covers, in one breath: the write_from/read_into signatures, shared open handles per segment, WINDOW_PAGES-aligned window coalescing, per-follower GPU upload from shared slots, slot release ordering, independent read_into reads, the immutability/pin assumption, the last-user close-before-Fetched rule, sibling-demand scheduling, the "sharing only covers live windows" limit, the one-extra-partial-window bound, error scope, and the bytes_in vs inbound_rate split (362-366). Its last three sentences are then repeated almost word for word in §4 at docs/prefix-cache-offload.md:1528-1531:
On
DiskStore,StoreStats.bytes_incounts logical checkpoint bytes restored to GPU destinations across completed fetches, whileStoreStats.inbound_ratemeasures physical staging-window disk reads so coalesced follower restores do not overstate device read bandwidth.
Why it matters: this is the paragraph a future reader will trust to learn the transport's contract, and a 30-line run-on makes the three distinct behaviours — one open handle per record, one read per aligned window fanned out to every attached upload, and read_into staying independent — look like one mechanism. The doc's own style elsewhere is one behaviour per sentence, with bullets for lists (compare 333-336). Duplicated prose drifts: the next edit to one copy will not reach the other. AGENTS.md 43-49 requires the prose review, and principle 16 of docs/design-review.md (not opened) requires the doc to state what the code does.
Fix: keep one paragraph of mechanism in §2.4 (shared handle; aligned 64-page fan-out to every attached upload; independent read_into), move failure scope and the limits ("sharing covers only live windows"; "one extra partial window when skip_pages % WINDOW_PAGES != 0") to a short bullet list in the style of 333-336, and keep the bytes_in / inbound_rate statement only in §4 at 1528-1531.
N2 (nit) — selene/src/disk_store.rs:267, 658, 750, 822, 867, 882, 1351-1360 — the host inbound read is a Vec<Segment> with an always-zero index and a redundant counter
read_into inserts exactly one segment at index 0 (self.owners.insert(disk, Owner::HostInbound(id, 0)), 1351; one Segment built at 1352-1360), yet HostInbound.segments is a Vec<Segment> (750), apply_disk has to tolerate a missing segment with segments.get_mut(segment) returning early (789-791), and the pump loops over self.segments (865, 890, 974). Separately, Segment::reads_left (658) is decremented only at 822 and tested only at 867 — where self.done == self.plans.len() at 882 already says the same thing.
Why it matters: a one-element collection plus an index that is always 0 invites a reader to look for the multi-segment case, which cannot occur; and an error branch (get_mut miss) guards an impossible state. reads_left is a second, independent way to ask "are all plans done", and two ways to answer the same question drift.
Fix: struct HostInbound { segment: Segment, … } (no Vec), Owner::HostInbound(JobId) with no index at 267/1351/2334, drop the get_mut tolerance at 789-791, and drop reads_left (658, 822, 867) in favour of the existing done == plans.len() check at 882. The close then waits one extra pump — harmless. WindowPlan.segment becomes dead on the host path.
N3 (nit) — selene/src/disk_store.rs:1001-1050 — HeaderIdentity's hand-written 37-line Hash restates Header's PartialEq field list by hand
The impl lists fourteen fields plus a loop over ranks (1032-1048). It cannot simply derive: Header's version field is excluded from PartialEq (selene/src/shared/record.rs:118-119, list at 136-152), so a derived Hash would hash a field equality ignores and break the Hash/Eq contract. Correct as written — but it must be kept in step by hand every time Header gains or renames a field, and a missed field is a silent bucketing bug, not a compile error.
Why it matters: 37 lines of maintenance coupled to a struct in another module, for no behaviour the map needs. Hash need only be consistent with Eq, not complete.
Fix: impl Hash for HeaderIdentity { fn hash<H: Hasher>(&self, state: &mut H) { self.0.key.hash(state) } }. PrefixKey derives Hash (selene/src/vocab.rs:30-34) and is unique per record; the path is derived from the key. Hash collisions only cost a bucket — PartialEq still compares the whole header, so correctness is unchanged. If the author prefers to keep the full field list, a comment saying why it duplicates Header's PartialEq instead of deriving (the version exclusion) is the minimum.
N4 (nit) — selene/src/disk_store.rs:2513-2528, 2541-2544 — Staged::close reports a max over four unrelated lengths as a job count
let store_jobs = self.outbound.len() + self.host_inbound.len()
+ self.device_inbound.len() + maintenance_jobs;
let internal = self.owners.len()
.max(self.maintenance.len())
.max(self.shared_segments.len())
.max(self.shared_windows.len());
let abandoned = store_jobs.max(internal);
…
"{abandoned} disk transport jobs did not complete within {:?}"
internal takes the maximum of an owner-map size, a maintenance list, a segment map and a window map; the larger of that and a genuine job count is then printed as a count of "disk transport jobs".
Why it matters: the number in the error message is not any count in the system — it can be the number of windows or of maintenance entries. An operator reading a shutdown failure will chase the wrong quantity, and a diagnostic that cannot be trusted is worse than a boolean.
Fix: either report only the pinned store records (self.outbound.len() + self.host_inbound.len() + self.device_inbound.len(), which is the claim the message makes), or say busy() did not settle and list the four counts separately. Either deletes the max.
N5 (nit) — selene/src/disk_store.rs:1083, 1131 — SharedSegment.id and SharedWindow.id duplicate their HashMap keys
Both fields hold the key they are stored under (shared_segments: HashMap<SharedSegmentId, SharedSegment>, shared_windows: HashMap<SharedWindowId, SharedWindow>), and are read only to compare against a map key or to pick a minimum (1433-1434, 1525, 1543, 1837).
Why it matters: two fields plus an invariant ("id always equals the key") that nothing enforces and any future insert can break; a lookup by the wrong id would be silently wrong rather than impossible.
Fix: iterate for (&id, seg) in &self.shared_segments / for (&id, win) in &self.shared_windows at the four use sites and delete the two fields. Same code shape, one less invariant.
N6 (nit) — selene/src/disk_store.rs:1781-1787 — dead guard in pick_next_pending_plan
let peer_demand = if demand.is_empty() {
0
} else {
demand.get(&record.window_key(plan_index))
.map_or(0, |total| total.saturating_sub(1))
};
map_or(0, ..) on an empty map already yields 0.
Why it matters: four lines that cannot change the result; a reader stops to work out what the empty-map case protects.
Fix: let peer_demand = demand.get(&record.window_key(plan_index)).map_or(0, |t| t.saturating_sub(1));
N7 (nit) — selene/src/disk_store.rs:743, 1140 (+ 915, 939-940, 957-958, 2009, 2102-2103, 2130-2131) — two disk_read_counted flags exist only so a test counter counts windows rather than jobs
HostWindow.disk_read_counted and SharedWindow.disk_read_counted guard the disk_window_reads increment so it fires once per window instead of once per ReadPages/ReadRow submission (six cfg blocks across the two structs).
Why it matters: per-struct state carried in production builds solely to define a diagnostic counter's unit; nothing documents the unit at the counter, so a future reader has to reverse-engineer the flags to know what the number means.
Fix: one doc line on the disk_window_reads accessor — "one per window, not per ReadPages/ReadRow job" — and count jobs in the increment, deleting both fields and their six cfg blocks. If per-window accuracy matters to the assertions, keep the flag but state its purpose on the field.
Resolved since my previous review round (not re-reported)
All four of my earlier asks, plus two smaller items, are implemented at 0c04b1e2:
- One window planner.
plan_windows(segments, align_to_window)(679-727) serves both callers (read_into1349, device path 2435), with the flag documented at 679-681. The parallelplan_aligned_windowsand the duplicated test half are gone. - No
PlanState::Done. Nowstarted: Vec<bool>(1173, 1787), so the enum variant nothing branched on is gone. - One attach helper.
has_window_credit(1683-1687) andattach_pending(1711-1730) replace the duplicated credit closures and attach loops; Passes 2 and 4 are now one-line loops (1916-1918, 1931-1935). - Counters gated.
disk_opens/disk_window_reads/coalesced_windowscarry#[cfg(any(test, feature = "test-support"))]on fields and increments (200-208 and the increment sites), matching theFaultspattern inselene/src/disk.rs(not opened); the threeallow(dead_code)attributes are gone. SharedWindowidentity. It now holdssegment: SharedSegmentIdandkey: WindowKey(1130-1150);path/expectedand the per-windowPathBuf/Headerclone are gone, and the open job reuseskey.segment(1961-1965).- Description vs code. The earlier "existing users pay per-pump demand indexing" overstatement is fixed:
build_pending_demanddocuments and implements thedevice_inbound.len() <= 1fast path (1732-1738), and the PR description now discloses it as an expected bound.
Scale judgement
+3313/−931 in disk_store.rs is large, and is the natural simplicity question for this PR. I do not think it is churn under AGENTS.md 188-193:
- the host path must stay private and unshared —
CompositeStorecallsread_intowith caller-owned registered buffers, so those reads cannot be attached to a sharedSlabPoolwindow; - the device path genuinely needs per-file and per-window reference state to keep each follower's GPU upload and each failure independent, which is the whole point of the change;
- the eight passes of
pump_device_inboundeach carry an ordering argument the others depend on: attach (1913-1918) before sweep (1920-1922) and before starting new reads (1924-1929); reads (2031-2140) before uploads (2142-2196); close (2203-2226) before completingFetched(2228-2278).
That ordering is what makes the coalescing correct and each pass has the comment that justifies it, so I am not asking for a different shape — only for the deletions above. Duplication that is avoidable is what N1-N7 remove.
Checked and found clean
read_into's observable behaviour is unchanged: sameplan_windows(.., false)planning (1349); caller-buffer slicing moved fromDestination::HostintoHostWindow.pages/row(907-917); sub-window resubmission still gated bypages_submitted/row_submitted(922-968);unwindstill drains referenced replies and closes opened files before reporting (865-881, 970-992). The device path never toucheshost_inbound.- One release point for pooled slots:
sweep_shared_windows(1824-1843), gated onfollowers.is_empty() && disk_referenced == 0 && upload_referenced == 0;Resources::release(256-260) is idempotent throughslots.take(). No double release or leak path visible in the code, and every new test assertspool.free_slots() == pool.slot_count()— the right property rather than a mock. - Error scope matches the description: private child and follower-upload failures fail only that record (
apply_device_transfer1563-1565 →record.fail, thendetach_unwinding_windows); shared open/read failures go throughfail_segment_users/fail_windowwithwith_record_read(). - The instrumented event is not swallowed:
TransportEvent::InboundWindowSampleis handled beforestats.progress += 1inDiskStore::apply(3631-3638), forwarded on rank 0 bySharded(selene/src/shard.rs:719-724) and skipped on peer ranks (shard.rs:1145-1150), andcomposite.rs:300-311still routes every event throughdisk.applyunchanged. - Tests exercise the real path, not mocks: byte-exact
SimulatedGpupage and row assertions in every coalescing test (e.g. 8368-8379), and the counters asserted are physical increments at the realsubmit_disksites — satisfyingAGENTS.md194-199. The shared fixtureswrite_shared_ancestor_treeandpoll_all_fetchesare used by five of the seven new tests, so they are not scaffolding. pump_allordering (2291-2312) runs maintenance, outbound, host-inbound, then device, consistent with the PR's merge-order note against #497.- No switch, fallback or compatibility path was added by this change that
AGENTS.md188-193 would reject; no per-model branch or flag (charter line 43).
Open questions / could not settle from the code
- N7: whether the
disk_read_countedflags are load-bearing for any assertion beyonddisk_window_reads. They appear only in the counter increments and the tests reading the counter; if the counter's unit is documented, the flags can go with them. - N3: whether hashing only
PrefixKeyis acceptable to the author as a uniqueness argument, or whether a full-fieldHashis deliberately preferred for bucket spread. Only the author knows if the 37-line list was chosen for distribution rather than correctness; a one-line comment would settle it either way. - N2: if a future change intends host reads to span several segments, the
Vecmay be anticipating it. Nothing in the code today inserts more than one segment, andAGENTS.md188-193 asks against speculative extension points, but a stated intent would change the finding.
Boundary
The benchmark table, the FP32 logprob parity evidence, and the Rate decay behaviour in inbound_rate are outside this lens and left to the other reviewers. The one cross-lens observation worth passing on: AGENTS.md 194-199 is satisfied, since the coalescing assertions are physical counts and byte-exact SimulatedGpu comparisons rather than source-text checks.