Review of PR #496 — lens C: conventions and duplication
Verdict: should-fix issues only.
Rules applied: docs/design-review.md (principle 8, "account for duplicate representations", line 74; principle 16 prose/explanation scheme, lines 137–152; principle 12 evidence), the charter (line 9, "look for the smallest footprint in shared code"), and the crate's own precedents below. I read the complete diff (2 files, +2808/−914), each new construct in its surrounding code, and the existing mechanisms it parallels. No compiler or GPU was available here, so every finding is established from code, not from running anything.
Key findings
-
The PR adds a second copy of a window splitter instead of extending the existing one.
plan_aligned_windows(selene/src/disk_store.rs:697–738) isplan_windows(selene/src/disk_store.rs:670–695) with four lines changed: identical signatureimpl IntoIterator<Item = (u32, usize, bool)> -> Vec<WindowPlan>, identicalWindowPlanoutput, identical zero-page/row-only handling, and the only substantive difference is that the chunk end is clamped to the nextWINDOW_PAGESboundary (:721–722).selene/src/memory.rs:1333–1367 windows()is already a third expression of the same splitter (pages.chunks(WINDOW_PAGES), row attached to the last window, row-only gets one window, empty link gets none). The charter's "smallest footprint in shared code" is the governing rule; here the same rule for row placement and empty links now lives in three places, so a fix to one will silently diverge in the other two. -
The shared-window identity is re-expressed five times and never named. The tuple that decides whether two GPU restores may share a staged window —
(path, expected Header, first, count, row)— appears as: segment lookup inacquire_shared_segment(selene/src/disk_store.rs:1368–1373), field-by-field matching infind_reusable_window(selene/src/disk_store.rs:1578–1583), the demand-table key plus an innerVec<(Header, usize)>linear scan inbuild_pending_demand(selene/src/disk_store.rs:1647–1679), the same key reconstructed inpick_next_pending_plan(selene/src/disk_store.rs:1705–1718), and again in the two decrement blocks (selene/src/disk_store.rs:1890–1899 and around:1996). The PR already accepts the cost of naming things twice over (SharedSegmentIdselene/src/disk_store.rs:1003,SharedWindowId) in the same spirit; a singleWindowKeytype is the consistent next step, and it is also what makes the demand map indexable (finding 3).shared::record::HeaderderivesPartialEqbut notHash(selene/src/shared/record.rs:110–117), so the key needs a comparable digest, which is a design choice the PR makes implicitly in three different places rather than once. -
New steady-state cost that the description concedes but the code does not minimise.
build_pending_demandclones aPathBufper pending plan and again per bucket push (selene/src/disk_store.rs:1668),pick_next_pending_planclonesseg_ref.pathon every candidate lookup (selene/src/disk_store.rs:1710), and the decrement blocks clone it again (:1890, :1996).find_reusable_window(selene/src/disk_store.rs:1576–1599) scans every value inshared_windowsfor every pending plan of every record, and is called fromfind_best_existing_window_for(:1602–1624) inside the attach loop. This is a heap allocation and an O(windows × plans) scan per pump in ordinary serving, for every restore, not just the coalescing ones. The PR itself shows the indexed precedent it should follow:pending_page_readsis a keyed map added by this same change; aWindowKey -> SharedWindowIdindex beside it removes both the clones and the quadratic scan.
Angle: duplication and conventions (all findings)
1. plan_aligned_windows duplicates plan_windows — should fix
selene/src/disk_store.rs:700, compared with selene/src/disk_store.rs:672 and selene/src/memory.rs:1336.
// :672 fn plan_windows(segments: impl IntoIterator<Item = (u32, usize, bool)>) -> Vec<WindowPlan>
// :700 fn plan_aligned_windows(segments: impl IntoIterator<Item = (u32, usize, bool)>) -> Vec<WindowPlan>
Both walk segments with a running byte offset, emit WindowPlan { segment, index, first, count, offset, row }, attach the row to the last window of the segment, and handle pages == 0 && row and pages == 0 && !row. The bodies are line-for-line equivalent except that plan_aligned_windows computes next_boundary = ((cursor / WINDOW_PAGES) + 1) * WINDOW_PAGES and chunk_end = end.min(next_boundary) (:721–722) where plan_windows uses start = window * WINDOW_PAGES. Note that when first is already aligned the two functions produce identical output — the divergence exists only for misaligned skip_pages, which is exactly the case the new tests cover, so the duplicated logic is the logic most likely to change next.
The third copy, windows() at selene/src/memory.rs:1336–1367, is a different output type (VecDeque<Job>) but the same policy: pages.chunks(WINDOW_PAGES), row on the last chunk (let last = chunks.peek().is_none()), an extra row-only window when empty (:1356–1365). The doc comment on memory.rs:1333–1335 and on disk_store.rs:670–671 is the same sentence.
Why it matters: the row-on-last-window rule and the empty-link rule are correctness-bearing (design-review principle 7, complete committed state; principle 6, explicit lifetimes). Three copies means a change that fixes, say, a row-bearing window split in one path leaves the other two staging the row into the wrong window. The charter (line 9) asks for the smallest footprint in shared code; adding a Boolean or alignment mode to plan_windows and reusing it would have been smaller than the ~40 lines added here.
Fix: give plan_windows an alignment parameter (or an align_first bool / Option<u32> start) and delete plan_aligned_windows. If memory.rs::windows cannot share the WindowPlan type, at minimum keep the policy in one documented place and reference it from the other two.
2. Shared-window identity re-expressed five times, no WindowKey — should fix
selene/src/disk_store.rs:1368, :1578, :1647–1677, :1890, :1996.
:1368–1373— segment lookup matchespathandexpected.:1578–1583—find_reusable_windowfilters onwin.first == first && win.count == count && win.row == row && win.path == path && win.expected == *expected.:1647–1679— the demand key is(PathBuf, u32, usize, bool)with a separate innerVec<(Header, usize)>scanned with.find(|(hdr, _)| *hdr == seg_ref.expected).:1705–1718— the same key and the same inner scan reconstructed inpick_next_pending_plan.:1890–1899and the second decrement block near:1996— the key reconstructed yet again.
The PR does introduce named ids for the other two layers (SharedSegmentId at selene/src/disk_store.rs:1003, SharedWindowId), so the convention it establishes for identifiers is not carried to the key that ties them together. Header derives PartialEq only (selene/src/shared/record.rs:110–117), which is why the codebase is reduced to a Vec linear scan: there is no Hash-able form of the identity. Defining one type WindowKey { path: Arc<Path>, expected: HeaderDigest, first, count, row } makes the identity definition single-source and makes the demand map a plain HashMap<WindowKey, usize> with no inner scan.
Why it matters: the matching rule is what guarantees two restores share a window only when they are genuinely reading the same bytes of the same immutable file. Five hand-written copies of that predicate is how a follower ends up attached to a window for the wrong expected header after someone adds a field to WindowPlan. It also is the enabling change for finding 3.
Fix: introduce the key type next to SharedWindowId; use it in SharedSegment, SharedWindow, the demand map and both decrement sites.
3. Per-pump allocation and quadratic scan in the attach path — should fix
selene/src/disk_store.rs:1668, :1710, :1576–1599, :1890.
:1668—demand.entry((seg_ref.path.clone(), plan.first, plan.count, plan.row))clones aPathBufper pending plan, and:1674clones theHeaderper bucket push.:1710—demand.get(&(seg_ref.path.clone(), ...))allocates again per candidate plan on everypick_next_pending_plancall.:1890and:1996— the same clone in the decrement paths.:1576–1599—find_reusable_windowiteratesself.shared_windows.values()in full for each call, andfind_best_existing_window_for(:1602–1624) calls it once per pending plan of the record; it is invoked in the attach loop at:1885.
The PR's own description acknowledges the trade ("Existing users pay per-pump demand indexing when free slots exist"), but the implementation pays more than the indexing it describes: an allocation per plan per pump, plus a scan whose cost grows with the number of live windows times the number of plan windows. This is exactly the shape pending_page_reads (added in this diff) was introduced to avoid.
Fix: with finding 2's WindowKey, keep HashMap<WindowKey, SharedWindowId> alongside shared_windows and HashMap<WindowKey, usize> for demand; store Arc<Path> (or the segment id) in SegRef rather than a PathBuf so the key clone is a refcount bump.
Angle: test fixtures and instrumentation conventions
4. GatedCopier fixture placement and positional 4-tuple — nit
selene/src/disk_store.rs:8051–8080, GatedCopierParts at :8059–8064.
The crate's established home for copier/pool fixtures is selene/src/testing.rs: StoppedCopier (:178) and SimulatedGpu (:225), whose shared_mapped/shared constructors return a two-element pair. This diff instead defines GatedCopier and ReverseWindows (:7732) inside disk_store.rs's test module and returns a positional four-tuple of Arc<Mutex<...>> handles (SharedCopier, Arc<Mutex<bool>>, Arc<Mutex<VecDeque<copier::Reply>>>, Arc<Mutex<Option<JobId>>>) that every call site has to destructure in order. Additionally the six new coalescing tests repeat the same pool/store construction block (:8253–~8330 and five more) even though write_shared_ancestor_tree (:8136) and poll_all_fetches (:8172) already exist as helpers in the same module — one more helper (store_for_fixture) would remove the repetition the reviewer has to verify is identical each time.
Fix: a named struct with fields instead of the tuple; and either move GatedCopier beside StoppedCopier in selene/src/testing.rs or justify its locality. Low stakes, but the tuple is the kind of construct that decays as tests are added.
5. Test-only counters compiled into release, and not in StoreStats — nit
selene/src/disk_store.rs:192–200, accessors gated at :1214–1229, attribute pattern repeated three times.
#[cfg_attr(not(any(test, feature = "test-support")), allow(dead_code))]
disk_opens: u64,
No other member of selene/src uses cfg_attr(..., allow(dead_code)); the crate's own convention is to compile the whole test-only member out — selene/src/disk.rs:309, :321, :437 keep the faults: Faults field under #[cfg(any(test, feature = "test-support"))], with the same attribute on the construction site (:314–316, :444–445). Gating the three fields the same way removes three allow(dead_code) attributes, three += 1 increments from release builds, and the inconsistency of gating the accessor but not the field.
Separately: the crate's stated home for counters is StoreStats — "Counters every store maintains" (selene/src/store.rs:185–244), surfaced by /metrics with disk_records, disk_bytes, restores_by_tier and friends. A physical-open count and a physical-window-read count are precisely the numbers that let an operator confirm coalescing is happening in production (and the PR's headline claim is a physical-read reduction). Today they reach tests only. That is defensible for a first PR, but it is a convention departure worth naming: the PR adds operator-relevant counters outside the struct the crate declares for them.
Fix: gate the three fields with cfg(any(test, feature = "test-support")); consider a follow-up adding disk_opens / coalesced_windows to StoreStats.
6. Staged::close counts non-jobs as "disk transport jobs" — nit
selene/src/disk_store.rs:2485–2489, with busy() at :2344–2351.
let abandoned = (self.outbound.len() + self.host_inbound.len()
+ self.device_inbound.len() + self.maintenance.len())
.max(usize::from(self.busy()));
busy() is true when any of outbound, host_inbound, device_inbound, shared_segments, shared_windows, or owners is non-empty. A leaked shared window or segment alone therefore yields abandoned == 1 even though the four summed pipelines are all empty, and the message still says "{abandoned} disk transport jobs did not complete". The pre-change code counted owners.len(), i.e. owned disk jobs. Either count what the message claims (owned jobs, or the four job pipelines without the .max) or reword the message to what is counted. Diagnostics only, but this is the line a CI failure or a shutdown warning is read from.
7. Naming axis mixing in the two paths — nit
selene/src/disk_store.rs:746, :759, :1070, :1117.
The record split is named by destination (HostInbound :759, DeviceInbound :1117) but the window split is named by sharing discipline (HostWindow :746, SharedWindow :1070), and the phase enums follow suit (HostInPhase :741, SharedWindowPhase). A reader pairing the host and device paths has to check both axes to know that HostWindow is the private counterpart of SharedWindow. PrivateWindow/SharedWindow or HostWindow/DeviceWindow would keep one axis throughout. Cosmetic, but this file is 8,866 lines and the pairing is the whole point of the change.
Angle: prose conventions (repo-prose skill, design-review principle 16)
8. Section 2.4 states the rule without the invariant that licenses it — nit
docs/prefix-cache-offload.md:337–342, module doc selene/src/disk_store.rs:14–21.
The added sentence reads: "Concurrent fetch jobs reading the same record file share one open file handle and coalesce aligned 64-page windows while staged so one disk read fans out to each attached fetch's GPU upload before its staging slots are released; caller-owned read_into reads run independently." What a reader needs before accepting that one handle and one window can serve several uploads is the invariant that makes it safe — published record files are immutable and pinned in DiskStore for the duration of every restore referencing them — and it is not stated, in the doc or in the module doc comment, even though the PR description states it. That is the "no hidden context" requirement (design-review principle 16): the justification exists, but only in the pull-request conversation.
Also: the section says "aligned 64-page windows" while the doc elsewhere speaks of WINDOW_PAGES and "windows of at most 64 pages plus the multi-slot row" (docs/prefix-cache-offload.md:398). Naming WINDOW_PAGES at the point the alignment rule is introduced ties the two statements together and stops "64" from being a second source of truth.
Fix: one clause on immutability+pin in both places, and WINDOW_PAGES in place of "64-page" where the rule is introduced.
Checked and not a finding
- No pre-existing coalescing/shared-handle helper is being duplicated. The other transport,
shard::Sharded, has only a plainfetch(selene/src/shard.rs:900); there is no existing shared-handle or demand mechanism inselene/srcthat this change should have reused instead of writing. read_intostaying on the private path is the right convention call, not a missed coalescing opportunity: caller-owned registered buffers have caller-defined lifetimes, and keeping them off the shared path matches design-review principle 6 (explicit lifetimes, never reuse slots while queued work references them). The code and the doc agree on this.Resources::free_slots(selene/src/disk_store.rs:228–232) is a new small helper but follows the localdisk_space()/transfer_space()predicates directly above it (:210, :220); no existing helper already did this.debug_assert!at :1923 is consistent with selene usage elsewhere (selene/src/memory.rs:534, composite.rs:647).
Open questions and what could not be settled
- Whether
plan_windowsandmemory.rs::windowscan truly converge (different output types:Vec<WindowPlan>vsVecDeque<Job>) or only share the policy. A small unit test assertingplan_aligned_windowsequalsplan_windowswhenfirstis aligned would at least pin the relationship the duplication currently leaves implicit. - Whether
Headercan grow aHash/digest form cheaply (selene/src/shared/record.rs:110–117) — this determines whether finding 2'sWindowKeyis a small or a structural change. - Whether the maintainers want the new physical-I/O counters in
StoreStats(selene/src/store.rs:185). I could not runcargoor the suite here, so I cannot say whether theallow(dead_code)attributes are load-bearing for a warning-free release build; that is checkable withcargo build --release --manifest-path selene/Cargo.toml(not opened). - Not verifiable from the code: whether the benchmark numbers hold after the demand-index and close-count edits — the description itself discloses that the SM121 runs predate those edits, so finding 3's cost is unmeasured in the table.