Review of PR #496 — lens: conventions and duplication
Head reviewed: 0c04b1e2 (base main c0c4f798). Files changed: selene/src/disk_store.rs, selene/src/shard.rs, docs/prefix-cache-offload.md (+3358/−933).
Rules applied: charter line 9 ("Solve the right problem in the right place… look for the smallest footprint in shared code"), lines 24, 35, 42-43; AGENTS.md:52-60 (document purposes), :72-140 (why/what/benefit/evidence and untested scope), :188-193 (reject unsupported abstractions); docs/design-review.md:74 ("account for duplicate representations"); .agents/skills/repo-prose/SKILL.md:71 (not opened), :84.
No toolchain or GPU was available in this environment, so nothing was compiled or run; every finding below is established from the code at the head commit, with the precedent it departs from cited. The substantive good news is that six findings from my earlier review round are genuinely resolved at this head — the duplication that mattered most (the twin plan_windows/plan_aligned_windows splitters and the five-times-repeated window identity tuple) is gone, and the three items below are new problems created by those fixes.
Key findings
- A
Hashimpl that duplicates an equality contract defined in another module (disk_store.rs:1014-1050vsshared/record.rs:136-152). The only hand-writtenHashinselene/src, and the one place where adding aHeaderfield breaks coalescing silently rather than at compile time. - A rate sample placed inside the completion enum (
disk_store.rs:97-101), whose cost is paid by every consumer: twounreachable!()s, two forwarding guards that must stay in sync, and aCompositeStoreprogress counter that now triggers a maintenance pass on every physical window read (composite.rs:1376, gate:1418-1424). - A hand-rolled restatement of
Layout::record_slots(disk_store.rs:1777), where the geometry helper already exists (geometry.rs:180-182) and is used by the allocator the check guards (disk_store.rs:245). memory.rs::windows()is now the last surviving third copy of theWINDOW_PAGESsplitter, and the only remaining duplication in the lens (nit now that the disk-side pair is unified).- Everything else is cosmetic: two same-named
settled()predicates, a shutdownabandonedcount that no longer matches its message, three repeated unindex blocks and two repeated follower-detach closures, a positional test-fixture tuple, and one over-long documentation bullet that states the metrics contract twice.
Should fix
1. HeaderIdentity hand-writes Hash over Header's fields, duplicating the equality contract 1,200 lines away in another module
File: selene/src/disk_store.rs:1001-1050 (the manual impl is :1014-1050; the destructure ends with .. at :1030). Precedent: selene/src/shared/record.rs:136-152 (impl PartialEq for Header, exhaustive field list, impl Eq at :154; Header defined :116-134).
HeaderIdentity(Arc<Header>) implements PartialEq by delegation (Arc::ptr_eq fast path, else *self.0 == *other.0, :1006-1010) and then writes Hash by hand, destructuring Header and hashing fourteen fields one at a time (identity, fingerprint, flags, key, parent, bucket, page_tokens, tail_pages, ranks element-wise, page_segment, row_segment, row_checksum, created).
The contract it must mirror lives in a different module: impl PartialEq for Header at shared/record.rs:136-152. The destructure here ends in .., and the equality list there is exhaustive. Adding a field to Header therefore produces a compile error in record.rs but not here: the new field silently drops out of the hash, two headers that compare equal hash differently, window_index.get(&key) (disk_store.rs:1229, lookups at :1650) misses, and coalescing silently stops working — a performance regression with no test failure, since nothing in the suite pins hash/eq agreement.
This is also a convention departure, not just a hazard. A repository-wide search for impl (std::hash::)?Hash for in selene/src returns exactly one hit: this one. The crate's precedent is to derive: PrefixKey derives PartialEq, Eq, Hash, PartialOrd, Ord (selene/src/vocab.rs:30), RankSizes derives PartialEq, Eq (shared/record.rs:89), DiskRecord derives (disk_store.rs:72), and the PR's own SegmentKey/WindowKey derive PartialEq, Eq, Hash (:1052, :1058). The manual impl exists only because Header itself does not derive Hash.
Fix: move the hashing next to the equality it must track — #[derive(Hash)] on Header in shared/record.rs (keeping the private version field out, as PartialEq already does at record.rs:118-119), or define a record::HeaderKey digest beside Header. HeaderIdentity then shrinks to the Arc wrapper plus the ptr_eq fast path, and the two contracts cannot drift.
2. TransportEvent::InboundWindowSample is a rate sample inserted into the enum documented as the transport's completions
File: selene/src/disk_store.rs:83-110 (variant at :97-101). Consumers: disk_store.rs:3632-3638, selene/src/shard.rs:476-478 (guards at :722-724, :1148-1150), selene/src/composite.rs:1373-1386.
The enum's own doc comment (:83) reads "Completion the transport reports to the disk store". The new variant is not a completion: it carries { bytes, elapsed } for one shared staging window's physical read. Every consumer now has to special-case it:
DiskStore::apply(:3632-3638) must early-return beforeself.stats.progress += 1, and thematchneedsTransportEvent::InboundWindowSample { .. } => unreachable!()to remain exhaustive.shard::Kind::of(shard.rs:466-486) cannot encode it:shard.rs:476-478isunreachable!("window rate samples stay local to rank zero"). That panic is load-bearing on two separate guards which must stay in sync —absorb_local(shard.rs:722-724) pushes the sample toself.eventsandcontinues, andPeer::forward(shard.rs:1148-1150) skips it. Any future path that hands a sample toKind::ofpanics. The enum's own convention for an unrepresentable kind is an error, not a panic:shard.rs:462returnsErr(invalid("unknown prefix record event kind")).- The wire
Kindenum (shard.rs:441-464) has no code for it, so the variant exists only on rank 0 — a "rank-0-local" concept expressed as a variant of a shared enum.
Concrete, verified cost beyond ergonomics: CompositeStore's poll loop drains transport events and does self.stats.progress += 1 for every event before dispatch (composite.rs:1376). That counter is documented as "Completion and capacity-release events" (selene/src/store.rs:202), and it gates the maintenance pass at composite.rs:1418-1424 (maintenance_progress != progress → spill_parked(...) + self.disk.maintain()). With this PR, each physical 64-page window read bumps progress and therefore re-runs both, once per window per restore — exactly the maintenance cadence this PR is trying to keep off the hot path.
Fix: carry the sample out of band rather than as a completion variant — a dedicated drain method, or a field on the existing Fetched event for the coalesced case, or the precedent the crate already has for a rate signal that is not an event: Budget::progress() (selene/src/input.rs:146-152 (not opened)), a counter the store reads. Whatever form it takes, exclude it from CompositeStore's stats.progress — composite.rs:1376 should count completions only.
Note that the physical-rate mechanism itself is correct and I am not flagging it: DiskStore::apply observes inbound_rate from disk::Reply.elapsed at :3632-3634, Fetched no longer observes it (:3652-3671), and the two rank guards do keep peer ranks from double-counting. The finding is about where the signal is carried, which is exactly what the description's "no format change" phrasing overlooks — see the description note at the end.
3. pick_next_pending_plan restates Layout::record_slots instead of calling it
File: selene/src/disk_store.rs:1766-1777. Precedent: Layout::record_slots at selene/src/geometry.rs:180-182 (pages + usize::from(row) * self.row_slots()), row_slots at :173-178.
let free = self.resources.free_slots();
let layout_row_slots = self.resources.pool.as_ref()
.map(|_| lock(&self.resources.transfers).layout().row_slots())?;
...
let needed = plan.count + if plan.row { layout_row_slots } else { 0 };
record_slots(pages, row) already encodes this formula, and it is the crate's single definition of what a record costs in staging slots: its callers include Resources::allocate (disk_store.rs:245), memory.rs:468, composite.rs:810 and :1167. The admission guard here (needed > free, :1778) exists to predict whether allocate will succeed; expressing the prediction with a different formula means the guard can disagree with the allocator, and it will the moment record_slots learns to account for anything beyond pages + row.
Secondary cost: lock(&self.resources.transfers) is taken once per call — i.e. per candidate record per pump iteration — and then taken again immediately afterwards by allocate (:1987).
Fix: let needed = lock(&self.resources.transfers).layout().record_slots(plan.count, plan.row);, hoisted next to free outside the plan loop.
Nits
4. memory.rs::windows() is now the last surviving third copy of the WINDOW_PAGES splitter
Files: selene/src/memory.rs:1333-1367 vs selene/src/disk_store.rs:679-727.
This PR removed the duplication that mattered — plan_aligned_windows is folded back into one plan_windows(segments, align_to_window) (disk_store.rs:679-727, doc at :679-681 explaining why read_into passes false at :1349 and fetch passes true at :2438-2442). What remains is the third expression of the same policy in memory.rs::windows(): pages.chunks(WINDOW_PAGES) (:1344), row attached only to the last chunk (row: if last { row.clone() } else { None }, :1353), a row-only record getting exactly one window (:1356-1365), and an empty link getting none (empty chunks falls through). That is the same three-way rule plan_windows encodes at :689-700 and :719. Its output type differs (VecDeque<copier::Job> vs Vec<WindowPlan>), so full convergence is a refactor rather than a rename; the minimum is a comment on plan_windows naming memory::windows as its twin (in both directions) and a test pinning the shared policy, since design-review.md:74 asks a change to account for duplicate representations.
5. Staged::close's abandoned count no longer matches its message, and two settled() predicates share a name
File: selene/src/disk_store.rs:2513-2544 (message at :2540-2544); :662-664 vs :1106-1109.
internal is .max() over owners.len(), maintenance.len(), shared_segments.len() and shared_windows.len() (:2522-2527), and abandoned = store_jobs.max(internal) (:2528), reported as "{abandoned} disk transport jobs did not complete within {:?}" (:2541-2543). shared_segments/shared_windows are map sizes, not jobs: one leaked shared window in an otherwise idle store yields abandoned == 1 and a claim that a disk transport job did not complete, while four abandoned outbound jobs plus six leaked windows reports six. maintenance_jobs is also counted twice — it is derived from owners (:2513-2517) and owners.len() is folded into internal. Previously the number was owners.len(), one entry per owned disk job (i.e. what the message says).
Separately, Segment::settled (:661-664, "has this file handle reached a terminal state", used at :882, :987) and SharedSegment::settled (:1106-1109, "have this shared segment's disk jobs drained", used at :2250, :2266, :2283) are two different lifetime predicates with the same name in the same file. Rename one (file_settled / drained) so a reader knows which lifetime is being tested.
Fix: keep the error message counting owners.len(), and if leaked staging state is worth catching, report it with its own message ("{n} shared windows/segments leaked").
6. Three repeated unindex blocks and two repeated follower-detach closures
File: selene/src/disk_store.rs
- The "unindex this window, but only if the index still points at it" body appears verbatim three times:
:1525-1527(fail_segment_users),:1543-1545(fail_window),:1837-1839(sweep_shared_windows). Theself.window_index.get(&win.key) == Some(&win_id)guard is the subtle part — it stops a newer window that reused the key from being unindexed — and it is stated three times. Extractfn unindex_window(&mut self, key: &WindowKey, id: SharedWindowId). The file's own pattern for this is small named predicates:SharedSegment::settled/reusable(:1097-1110). - The follower-detach
retainclosure appears twice identically::1813-1816(detach_unwinding_windows) and:1900-1904(Pass 1 ofpump_device_inbound), matching on the(record, plan_index)pair. That pair isWindowFollower's identity (:1119-1123) and is constructed a third time at:1690-1695. GiveWindowFolloweramatches/removemethod so the identity is one definition. - Worth a one-line comment: the two detach paths differ deliberately in byte crediting — only Pass 1 credits
record.bytes += win.read_bytes(:1901), becausedetach_unwinding_windowsis detaching from a record that is being failed.
7. GatedCopier::wrap returns a positional 4-tuple where the crate's fixture precedent uses named handles
File: selene/src/disk_store.rs:8092-8122. Precedent: selene/src/testing.rs:178 (not opened) (StoppedCopier), :225 (SimulatedGpu::shared_mapped/shared returning a named two-element handle).
type GatedCopierParts = (SharedCopier, Arc<Mutex<bool>>, Arc<Mutex<VecDeque<copier::Reply>>>, Arc<Mutex<Option<JobId>>>); all five call sites destructure positionally and three discard the last two fields with _ (:8406, :8530, :8984; :8650 is (copier, _, _, fail_job); :9234 ignores the tail entirely). A named struct with fields (hold, held, fail) would let each site say which gate it wants, and adding a gate would not renumber every site. Test-only, no production impact. If the fixture is ever needed by composite.rs's tests it belongs beside StoppedCopier in selene/src/testing.rs (not opened).
8. §2.4's new bullet is one 250-word paragraph carrying nine facts, and it states the metrics contract a second time
File: docs/prefix-cache-offload.md:337-366; duplicate at :1528-1531.
The bullet added by this PR runs from :337 (write_from(id, header, …)) to :366 (estimates.) — a single 30-line, ~250-word block carrying signatures, handle sharing, alignment, slot lifetime, the read_into isolation, the immutability/pin invariant, close-before-Fetched, demand scheduling, reuse limits, the extra-partial-window bound, failure-isolation scope, and the two metrics. Its content is now accurate and complete (my earlier finding about the missing immutability invariant is resolved: :346-350 states it, and :342/:356 name WINDOW_PAGES rather than "64-page" — good). But .agents/skills/repo-prose/SKILL.md:84 (not opened) ("Use ordinary readable sentences") and :71 ("if understanding any sentence requires 'you had to be there'") argue against a paragraph this dense, and AGENTS.md:52-60 gives a document one purpose at a time — this mixes mechanism, correctness invariant, scheduling heuristic and metrics.
The StoreStats.bytes_in / inbound_rate sentences (:362-366) are also stated a second time in the §4 measurement table (:1528-1531). One contract in two homes is the duplication this lens exists to catch. Keep the behavioural half in §2.4 (admission prices bandwidth from physical reads, so the row matters), move the measurement statement to §4, and leave a pointer.
Checked and sound — not findings
- No pre-existing coalescing or shared-handle mechanism was duplicated.
shard::Shardedhas only a plainfetch(selene/src/shard.rs:900); there is no earlier shared-window or shared-open abstraction inselene/srcthat this reinvents. The closest existing pair type,FileSpan { path, header }(selene/src/pool/pins.rs:165-183), serves a different purpose (pinning, not staging) and could not have been reused without contorting it. Staged::read_intostaying on the private path is the right call, and it is stated in both code (plan_windows(..., false)at:1349,:679-681) and doc (:345-346). It is consistent withdocs/design-review.mdprinciple 6 (explicit lifetimes): caller-owned host reads have no follower to share a window with.Resources::free_slots()(:236-239) is new but not a duplicate; it follows the shape of the existingdisk_space()/transfer_space()accessors.SegmentKey/WindowKeywith thewindow_index(:1052-1064,:1229) are the pattern the rest of the file should follow, andfind_reusable_window(:1646-1663) is now an O(1) index lookup — a real improvement over the linear scan in the earlier revision.- The
debug_assert!at:1950matches existingseleneusage (memory.rs:534,composite.rs:647). - The three diagnostic counters (
disk_opens,disk_window_reads,coalesced_windows,:200-208) are correctly#[cfg(any(test, feature = "test-support"))], following the crate precedent (selene/src/disk.rs:309(not opened),:321,:437) rather than theallow(dead_code)workaround in the earlier revision. (Whether they should instead be operator-visible inStoreStats—selene/src/store.rs:185-244, "counters every store maintains", surfaced by/metrics— is a product question, not a convention violation; I mention it only as a prompt.) - Failure isolation (
fail_segment_users:1509,fail_window:1538,record.fail:1211) matches the description and follows the file's existing per-record error handling.
Description accuracy (AGENTS.md:72-140)
Four of the five "What" bullets match the code exactly (host/GPU read-path split, reference-counted windows with has_window_credit/attach_pending, physical inbound_rate with logical bytes_in, failure isolation, cfg-gated counters). One overstates: "No core re-export or format change is required" — true for re-exports, but TransportEvent is a public enum in a public module and gains a variant (disk_store.rs:97-101), which is precisely what forces the unreachable!() at shard.rs:476-478. Say the enum gained a rank-0-local variant instead. The benchmark and "Not covered" sections do satisfy AGENTS.md:103-112.
Open questions and what could not be settled
- Can
HeaderderiveHash? It has a private__-styleversionfield excluded fromPartialEq(shared/record.rs:118-119); that exclusion is correctly reproduced in the new hash, andHashcan be implemented to match. Whether the maintainers wantPartialEq/Hashon disk metadata headers at all (as opposed to a content digest) is a design call — the PR's alternative is to key on an existing digest, whichpool/pins.rs:165-183andvocab.rs:30suggest is idiomatic here. Settling that needs a maintainer, not a test. - Hash/eq agreement is untested. Nothing in the suite would fail if
HeaderIdentity::hashandHeader'sPartialEqdiverged; a property test (a == b ⇒ hash(a) == hash(b)over a syntheticHeader) would settle it, and would have to be written if the manual impl is kept. - The
CompositeStoremaintenance amplification has not been measured. Code showscomposite.rs:1376bumps progress for every transport event and:1418-1424gatesspill_parked+disk.maintain()on it; the benchmark table in the description does not report maintenance-run counts, so the practical cost is unquantified. A counter on the maintenance gate would settle it. - Not covered by reading: I did not read the full ~5,300-line test module (
disk_store.rs:5100-9358); I read the new fixtures (:8092-8125GatedCopier::wrap,:8136ffwrite_shared_ancestor_tree,:8172ffpoll_all_fetches) and grepped every assertion touching the constructs reviewed. Multi-host/RoCE, 2-GPUsplit_pools, Windows serving and liveCompositeStore/PooledStorepaths are untested here, as the description itself states.