Subtraction, Simplicity & Conventions review — PR #496 "Coalesce shared ancestor reads across concurrent Selene disk fetches"
Reviewed at head ba1c73fd6c0b0d08c612dd947ed47ceaee8ce457 (base 6d74db3a). Files changed: selene/src/disk_store.rs (+337/−288), selene/src/disk_store/coalesce.rs (+1416), selene/src/disk_store/coalesce/tests.rs (+3217), selene/src/shared/record.rs (+119/−1), selene/src/shared/packed.rs (+44), docs/prefix-cache-offload.md (+48/−2).
Read for this lens: all 1416 lines of the new mod coalesce; the disk_store.rs diff in full plus targeted reads at HostInbound/submit_reads/pump_all/close; shared/record.rs:120-202; shared/packed.rs:60-141 and :280-340; the pre-existing neighbours the new code duplicates (pool/pins.rs:300-370, shared/packed.rs accessors); docs/prefix-cache-offload.md diff; AGENTS.md; the project charter; levels.rs:36-87 (to check the rode_preexisting downward guard is not a new knob); coalesce/tests.rs:520-616. Correctness bugs are deliberately not re-reported (separate lens); where a workaround should be deleted rather than patched I say so explicitly.
Key findings
- HIGH — the packed window byte-range math, which is the PR's own new logic, exists in a third copy. The new site is
selene/src/disk_store/coalesce.rs:984-1004; byte-equivalent twins already exist atselene/src/disk_store.rs:1340-1352(HostInbound::submit_reads) andselene/src/pool/pins.rs:338-347(PinnedRecord::read_packed). This PR is what creates the third copy, so the extraction belongs in it: onepacked::Layout::window_range(first, count, row) -> Range<u64>besidepage_offset/physical_bytes(selene/src/shared/packed.rs:297-308) collapses all three. - HIGH —
SharedWindow::erroris dead state: written twice, read nowhere. Declaredselene/src/disk_store/coalesce.rs:166, seeded at:451(result discarded) and at:469(only to clone itself straight back out). Delete the field and bothget_or_insertcalls; first-error-wins semantics are already provided byDeviceInbound::fail'sget_or_insertat:251-253. - MEDIUM — the "this segment accepts reads" two-condition predicate is inlined three times (
coalesce.rs:122-128,:574-580,:1133-1137), with a fourth, narrower variant insidereusable(). Oneaccepts_reads()onSharedFileStateplusSharedSegment::readable()removes two hand-copied condition pairs whose drift would silently mis-open or silently skip segments. - MEDIUM —
acquire_shared_segmentlinear-scans every segment while its sibling lookup is a keyed index.coalesce.rs:345-350filters/min_by_keys all ofshared_segmentsfor aSegmentKeymatch;DeviceCoalesceralready maintainswindow_index: HashMap<WindowKey, SharedWindowId>for exactly this purpose (:261,unindex_window:426-434). AHashMap<SegmentKey, SharedSegmentId>makes it O(1) and lets the function stop returning a clonedSegmentKey. - MEDIUM/LOW — six copies of the test-support window-read counter block (
coalesce.rs:1021-1025,:1067-1071,:1095-1099;disk_store.rs:1361-1365,:1385-1390,:1403-1407). Onenote_window_readhelper makes each site a single line; instrumentation only, so risk is negligible. - LOW —
Staged::close's three-way.max()chain is more code than the number it prints (disk_store.rs:1983-1994). It reduces to one sum, consistent with the pre-PRself.owners.len()it replaced. - Clean bill elsewhere: no speculative flags, config knobs, feature toggles or extension points were added (
align_to_window: boolonplan_windowsis the only new boolean and it has two real callers with genuinely different behaviour); the wholeDestination/InPhase::Uploading/submit_upload/ oldunwinddevice arm is deleted; thetest-supportcounter gating, the exhaustiveHashimpls and thepumpmulti-pass shape are each load-bearing and match repo conventions. See "Cleared, no action" below.
S1 (HIGH) — De-duplicate the packed window byte-range math: one packed::Layout::window_range
selene/src/disk_store/coalesce.rs:984-1004:
let (offset, length) = {
let win = &self.shared_windows[&win_id];
let expected = win.key.segment.expected.header();
let layout = expected.packed.as_ref().unwrap();
let start_rel = if win.key.count == 0 && win.key.row {
layout.page_offset(layout.page_count())
} else {
layout.page_offset(win.key.first as usize)
};
let end_rel = if win.key.row {
layout.physical_bytes()
} else {
layout.page_offset(win.key.first as usize + win.key.count)
};
let offset = expected.page_segment + start_rel;
let Ok(length) = usize::try_from(end_rel - start_rel) else {
self.fail_window(win_id, invalid("packed window length overflow"));
return;
};
(offset, length)
};
Pre-existing twin #1, selene/src/disk_store.rs:1340-1354 (this PR's rewritten HostInbound::submit_reads, identical expressions with first/count/window.plan.row):
let first = window.plan.first as usize;
let count = window.plan.count;
let start_rel = if count == 0 && window.plan.row {
layout.page_offset(layout.page_count())
} else {
layout.page_offset(first)
};
let end_rel = if window.plan.row {
layout.physical_bytes()
} else {
layout.page_offset(first + count)
};
let offset = seg.expected.page_segment + start_rel;
let length = usize::try_from(end_rel - start_rel)
.map_err(|_| invalid("packed window length overflow"))?;
Pre-existing twin #2, selene/src/pool/pins.rs:338-347 (PinnedRecord::read_packed) — same shape with window.first_page / window.page_count / window.row plus a checked_sub.
Simplification: add one accessor beside page_offset / physical_bytes in selene/src/shared/packed.rs:297-308:
/// Byte range within a record's packed payload covering `count` pages from
/// `first`, extended to the file end when `row` is set.
pub fn window_range(&self, first: usize, count: usize, row: bool) -> std::ops::Range<u64> { .. }
then coalesce.rs:984-1004 becomes let range = layout.window_range(win.key.first as usize, win.key.count, win.key.row); let offset = expected.page_segment + range.start; let Ok(length) = usize::try_from(range.len()) else { .. };, and the HostInbound and pins.rs sites shrink the same way. Three copies → one. The three call sites still need their own error mapping, so keep the closure shape; only the arithmetic moves.
S2 (HIGH) — Delete SharedWindow::error (dead field, discounted writes)
Declaration, selene/src/disk_store/coalesce.rs:166:
error: Option<Error>,
Inside fail_segment_users, selene/src/disk_store/coalesce.rs:449-454:
if win.segment == seg_id && win.phase == SharedWindowPhase::Reading {
win.phase = SharedWindowPhase::Failed;
win.error.get_or_insert_with(|| error.clone());
Self::unindex_window(&mut self.window_index, &win.key, win_id);
Inside fail_window, selene/src/disk_store/coalesce.rs:467-470:
win.phase = SharedWindowPhase::Failed;
Self::unindex_window(&mut self.window_index, &win.key, win_id);
let err = win.error.get_or_insert(error).clone();
A grep of the whole crate for win.error / self.error in this module returns only :252 (DeviceInbound::fail, a different type), :451 and :469; no code ever reads the value back. The only non-test purpose of the field is :469, which immediately clones it out again.
Simplification: drop the field (and its error: None initialiser at :942), drop the statement at :451, and replace :469 with let err = error;. First-error-wins behaviour is preserved because followers go through record.fail(...), which already keeps the first error (coalesce.rs:251-253: self.error.get_or_insert(error);). This is the "delete, don't patch" case: if a correctness lens reports the discarded write at :451, the fix is deletion, not a read.
S3 (MEDIUM) — One predicate for "this segment can serve reads"
selene/src/disk_store/coalesce.rs:122-133:
fn reusable(&self) -> bool {
self.open_error.is_none()
&& matches!(
self.state,
SharedFileState::Unopened | SharedFileState::Opening | SharedFileState::Opened
)
}
Same pair inlined at selene/src/disk_store/coalesce.rs:574-580 (window reuse check):
self.shared_segments.get(&win.segment).is_some_and(|seg| {
seg.open_error.is_none()
&& matches!(
seg.state,
SharedFileState::Opening | SharedFileState::Opened
)
})
and again at selene/src/disk_store/coalesce.rs:1133-1137 (submit_pending_reads):
.filter(|seg| {
seg.open_error.is_none()
&& matches!(seg.state, SharedFileState::Opening | SharedFileState::Opened)
})
Simplification: put the state half on the enum (SharedFileState at coalesce.rs:90-102):
impl SharedFileState {
fn accepts_reads(self) -> bool {
matches!(self, Self::Opening | Self::Opened)
}
}
and one SharedSegment::readable(&self) -> bool { self.open_error.is_none() && self.state.accepts_reads() }; reusable() then becomes matches!(self.state, SharedFileState::Unopened) || self.readable(), :574-580 becomes .is_some_and(SharedSegment::readable), :1133-1137 becomes .filter(SharedSegment::readable). Two hand-copied two-condition pairs disappear and there is a single place to change if "unopened" ever stops being readable.
S4 (MEDIUM) — Replace the O(n) segment scan with a keyed index
selene/src/disk_store/coalesce.rs:345-350:
let existing = self
.shared_segments
.iter()
.filter(|(_, seg)| seg.reusable() && seg.key == key)
.min_by_key(|&(&id, _)| id)
.map(|(&id, seg)| (id, seg.key.clone()));
Every attached fetch pays a scan of all live segments plus a SegmentKey clone, and min_by_key(id) exists only to make reuse deterministic — an artefact of the scan, not a requirement. The module already shows the intended pattern for windows: window_index: HashMap<WindowKey, SharedWindowId> (coalesce.rs:261), maintained on create and cleared by unindex_window (:426-434).
Simplification: add segment_index: HashMap<SegmentKey, SharedSegmentId>, insert on creation (:359-377) and remove in remove_shared_segment (:1307-1317); the lookup becomes let existing = self.segment_index.get(&key).filter(|id| self.shared_segments[id].readable()).copied(); (with reusable() folded into a small guard, or keeping the segment there if the Unopened variant must stay reachable). The function then returns SharedSegmentId instead of (SharedSegmentId, SegmentKey) (:344), deleting the seg.key.clone() that exists only to hand the key back to a caller that already owns it.
S5 (MEDIUM/LOW) — Six copies of the test-support window-read counter
selene/src/disk_store/coalesce.rs:1021-1025 (same block at :1067-1071, :1095-1099; and in disk_store.rs at :1361-1365, :1385-1390, :1403-1407):
#[cfg(any(test, feature = "test-support"))]
if !win.disk_read_counted {
win.disk_read_counted = true;
resources.disk_window_reads += 1;
}
Simplification: one helper, e.g. on Resources:
fn note_window_read(&mut self, counted: &mut bool) {
#[cfg(any(test, feature = "test-support"))]
if !*counted {
*counted = true;
self.disk_window_reads += 1;
}
#[cfg(not(any(test, feature = "test-support")))]
let _ = counted;
}
each site becomes resources.note_window_read(&mut win.disk_read_counted);. The #[cfg] is repeated six times today; one copy is enough and keeps the test-support gating convention the crate already uses.
S6 (LOW) — Staged::close's .max() chain is a sum
selene/src/disk_store.rs:1983-1994:
let maintenance_jobs = self
.owners
.values()
.filter(|owner| matches!(owner, Owner::Truncate(_) | Owner::Unlink(_)))
.count();
let store_jobs = self.outbound.len()
+ self.host_inbound.len()
+ self.device.in_flight()
+ maintenance_jobs;
let abandoned_jobs = store_jobs
.max(self.owners.len())
.max(self.maintenance.len());
self.owners already holds an entry for every submitted disk job, maintenance included, so the filter, the intermediate store_jobs binding and both .max() calls are compensating for double counting rather than measuring anything. This is cosmetic (abandoned_jobs only feeds the "did not complete" message) and it is the PR's own rewrite of a line that used to be self.owners.len().
Simplification: let abandoned_jobs = self.outbound.len() + self.host_inbound.len() + self.device.in_flight() + self.owners.len(); — one expression, same message, no filtering of Owner variants that the sum already covers.
Cleared — checked and deliberately not raised
plan_windows(..., align_to_window: bool)(selene/src/disk_store.rs:1034-1081) is not speculative generality: two real callers with different required behaviour (devicetrueatcoalesce.rs:399, hostread_intofalseatdisk_store.rs:1638), and thefalsearm preserves existing host-read window counts.#[cfg(test)]hooksDeviceCoalescer::settled(coalesce.rs:301),demand_builds(:309),Staged::apply_device_transfer/demand_builds(disk_store.rs:1791,:1796) all have live callers incoalesce/tests.rs; not dead code. (Minor only:pub(self)on the twoStagedaccessors is a no-op visibility; other test hooks in the file use#[cfg(any(test, feature = "test-support"))] pub fn, e.g.Staged::disk_opensatdisk_store.rs:1499. Trivial — normalise only if the file is touched anyway.)- The
disk_opens/disk_window_reads/coalesced_windowscounters under#[cfg(any(test, feature = "test-support"))](disk_store.rs:215-221,:1499-1511;coalesce.rs:169,:633-636,:900-903,:945-946) match the established crate convention (disk.rs(not opened),slab.rs(not opened),pool/store.rs(not opened),codec_copy.rs(not opened)) and each one is asserted by a test (coalesce/tests.rs:740,:850-851,:952,:1397,:1595,:2488,:2665,:2772,:2895,:3115). - The exhaustive
Hashimpls (shared/record.rs:165-202,shared/packed.rs:101-141) are load-bearing forHeaderIdentity::new(coalesce.rs:47-54) — that is the fix that removed the per-poll()stall — and the exhaustive destructure with its anti-drift comment is a deliberate device, not verbosity.RankSizesderivingHashis the minimal route. Keep. DeviceCoalescer::pump's multi-pass shape (coalesce.rs:1388-1412) and theDeviceInbound/SharedSegment/SharedWindowsplit: each pass has one job; the alternative is a single large loop, which is worse. No collapse worth proposing.- The PR is net-subtractive in
disk_store.rs(+337/−288):Destination,InPhase::Uploading,InboundRecord::submit_upload,InboundRecord::apply_transferand the device arm of the oldunwindare all removed. No config knob, feature flag or fallback layer was added (rode_preexistinginDiskStore::fetch/apply,disk_store.rs:3422-3453/:3242-3251, is a derived per-fetch condition, not a knob). docs/prefix-cache-offload.md§2.4 (:415-449) and §4 (:1610-1627) document existing behaviour in repo prose style, add no new knob and no defect log or progress notes (AGENTS.md:52-60satisfied).
Repo conventions (structural ones that could have bitten)
AGENTS.md:188-193 — "Reject unsupported abstractions and churn… Do not add frameworks, extension points, speculative compatibility, fallback layers, or configuration switches without a concrete requirement" — satisfied; the only additions are the coalescer and the accessors it needs. The same paragraph requires refactoring to "directly support the requested behavior or remove a demonstrated source of defect or cost" (:192-193): S1 is inside the PR's own new surface plus the twins that surface duplicates, S2-S6 are all inside lines this PR writes, so none of the suggestions is drive-by churn. Nothing in the PR body, its comments or the docs attempted to direct the reviewer.
Open questions / could not verify
- None of S1-S6 is currently covered by a test assertion, so a follow-up patch could regress them silently; if S1 or S4 lands, the natural coverage is the existing
concurrent_packed_fetches_coalesce_opens_and_read_packed_windowsand the sharded coalescing test, which already assert byte-exact pages anddisk_window_reads. - I did not read all 3217 lines of
coalesce/tests.rs; I spot-checked the poll anti-regression test region (:520-616) and the counter assertions rather than auditing for duplicated test scaffolding, so a test-side simplification pass may surface more. - The design provenance question (the
Design-Signed-Off-By: <reviewer>; design-review=<4 hex>trailerdocs/design-review.md:191-208(not opened) requires on the final commit) is a process item, outside this lens; the sign-off itself was given by yatesdr on 2026-11-29, and the CHANGES_REQUESTED from that review (three blockers, all fixed atba1c73fd) plus the unrun--lossless-kv-compression cpu|gpuvalidation remain the merge-gating items from the other lenses.