Review of PR #496 — lens: conventions and duplication
Head 0c04b1e2, base main c0c4f798. No new commits since the previous round. Changed files: selene/src/disk_store.rs (+3313/−931), selene/src/shard.rs (+10/−0), docs/prefix-cache-offload.md (+35/−2).
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 (one purpose per document), :72-140 (why/what/benefit/evidence, untested scope), :188-193 (reject unsupported abstractions and churn — "Refactoring must directly support the requested behavior or remove a demonstrated source of defect or cost"), :201-207 (maintainer decision required for an architectural invariant); docs/design-review.md (not opened):74 ("account for duplicate representations"), principle 6 (explicit lifetimes); .agents/skills/repo-prose/SKILL.md (not opened):71, :84 (ordinary readable sentences).
Methods note: no toolchain or GPU was available to me, so nothing was compiled or run. Every finding below is established from source, with line numbers verified at the head commit.
Key findings
Nothing here blocks the merge. The coalescing design itself is well placed, and — importantly for this lens — it does not reinvent an existing mechanism: it is genuinely new machinery for a genuinely new job. What this lens does find is three places where a new construct departs from a pattern the crate already established, or duplicates a contract owned elsewhere:
- The only hand-written
Hashinselene/srcmirrorsHeader'sPartialEq, which lives in a different module and has already grown a field the hash silently omits (should fix). - A rate sample placed inside the cross-rank completion enum, which forces
unreachable!()and duplicated skip guards inshard.rsand inflatesCompositeStore's maintenance trigger (should fix). - Hand-rolled slot arithmetic and a per-candidate mutex where
Layout::record_slots, the very helper the guarded allocator uses, already exists (should fix).
Plus six nits: one surviving third copy of the WINDOW_PAGES splitter, a misleading telemetry string, two settled() predicates, three repeated idioms in the shared-window code, a positional test 4-tuple, and a doc bullet that both overpacks and states the metrics contract twice.
Also worth recording: six findings from my earlier round are resolved at this head, and I correct one claim from my earlier report (HeaderIdentity's .. fails safe — it costs hash collisions, not correctness).
Correction to my previous round
My earlier report claimed that HeaderIdentity's .. rest-pattern means "a new Header field silently drops out of the hash and coalescing stops, with no test failing". That is the wrong direction, and it is worth stating precisely:
HashMapsoundness needsa == b ⇒ hash(a) == hash(b).Header'sPartialEq(selene/src/shared/record.rs:136-152) is exhaustive; the hash covers fewer fields, so adding a field toPartialEqwhile the hash omits it keeps the implication true. The hash merely becomes coarser and colliding entries are still separated byeq. Effect: bucket collisions / slowerwindow_index(disk_store.rs:1229, lookups at:1646-1663) — not lost coalescing.- The genuinely unsound direction is the reverse: a field included in
hashbut excluded fromPartialEq, i.e. the privateversionfield (shared/record.rs:118-119, documented as "not semantic identity"). Today it is excluded from both, correctly. - The omission is nonetheless live, not hypothetical:
mainhas since addedpub packed: Option<Arc<packed::Layout>>toHeader(main'sshared/record.rs:127) and compares it inPartialEq(main:146). This branch'shash(14 fields,..atdisk_store.rs:1030) does not hash it.
So finding 1 stands as a conventions/robustness issue, not as a correctness bug.
Should fix
1. The only hand-written Hash in selene/src, mirroring an equality contract owned in another module
File: selene/src/disk_store.rs:1001-1050 (impl :1014-1050; .. at :1030).
Precedent: selene/src/shared/record.rs:136-154 — impl PartialEq for Header (exhaustive) and impl Eq; derives everywhere else for key types: SegmentKey (disk_store.rs:1052), WindowKey (:1058), SharedSegmentId/SharedWindowId (:995/:998), levels.rs:9 (not opened), plan.rs:22 (not opened), store.rs:17/:115, shard.rs:441, slab.rs:36 (not opened), pool/types.rs:12 (not opened). A grep for impl (std::hash::)?Hash for across selene/src returns exactly this one hit, which is how I know it is the crate's sole manual hash.
HeaderIdentity(Arc<Header>) implements PartialEq by delegation (:1006-1010), then hashes fourteen-plus fields by hand. Two consequences:
- The contract is split across modules. Adding or reclassifying a
Headerfield is a compile error inrecord.rsand silent here. The..makes the omission invisible in review — andpackedonmainis already the case in point. - Nothing tests the agreement. No assertion in the suite would fail if
hashandPartialEqdiverged in the unsound direction.
Fix: implement Hash next to Header's PartialEq in shared/record.rs (or hash the canonical encoding already used by shard::shape, shard.rs:1242-1249 via Header::canonical_encoding, record.rs:260/:348), and add a test that equal headers hash equally. That removes the cross-module mirror outright rather than merely moving it.
2. A rate sample placed in the cross-rank completion enum
File: selene/src/disk_store.rs:83 (doc: "Completion the transport reports to the disk store"), variant :97-101.
TransportEvent::InboundWindowSample { bytes, elapsed } is the only non-completion in an enum documented as completions, and it is not tied to a job id. Four consumers must special-case it, two of them with unreachable!():
Kind::of,shard.rs:476-478—unreachable!("window rate samples stay local to rank zero").Sharded::absorb_local,shard.rs:722-725— hand-written skip guard.Peer::forward,shard.rs:1148-1150— the same skip guard, which must stay in sync with the previous one by hand.DiskStore::apply,disk_store.rs:3632-3638— early return plus a secondunreachable!()arm.
And one consumer mis-accounts for it: CompositeStore::poll (composite.rs:1376) bumps stats.progress += 1 for every transport event before the maintenance gate at :1418-1429 (spill_parked + disk.maintain()), so each completed physical window can now trigger a maintenance pass.
Precedent for out-of-band progress/rate signalling in this crate: Budget::progress / DiskBudget::progress (selene/src/input.rs:80-81, :146-148) and StoreStats.progress (store.rs:201-202) — a counter the owner reads, not a variant of a completion enum. TransportEvent's other variants all carry id: JobId and a Result; this one carries neither.
Fix: drain the sample from Staged directly — a take_window_samples() beside the existing take_packed_read-style accessors — or carry it on Fetched. Either removes both unreachable!()s, both hand-written guards, and the per-physical-window maintenance amplification at once.
3. Hand-rolled slot arithmetic where Layout::record_slots exists
File: selene/src/disk_store.rs:1767-1777 — let needed = plan.count + if plan.row { layout_row_slots } else { 0 };
Precedent: selene/src/geometry.rs:180-182:
pub fn record_slots(&self, pages: usize, row: bool) -> usize {
pages + usize::from(row) * self.row_slots()
}
This is the exact expression, and it is what the allocator this guard is predicting already uses: Resources::allocate (disk_store.rs:245), and at :6403, :6618, :7531, :7626, :7701, composite.rs:810/:1167, memory.rs:468/:1856/:3883/:4064. So the guard and the allocation it guards can drift apart if the layout formula ever changes — precisely the class of drift the helper exists to prevent.
There is a second, smaller problem in the same lines: lock(&self.resources.transfers).layout() is taken once per call but is placed before the for loop over plans, so pick_next_pending_plan acquires the transfers mutex on every candidate-plan scan iteration even though the value it reads is loop-invariant.
Fix: hoist lock(&self.resources.transfers).layout() once beside free and call layout.record_slots(plan.count, plan.row).
Nits
N1. The last surviving third copy of the WINDOW_PAGES splitter. selene/src/memory.rs:1336-1367, fn windows(...). This PR unified the two disk-side copies into one plan_windows(..., align_to_window) (disk_store.rs:682-727) — a good change. But the same policy now lives in two homes: chunk into windows of WINDOW_PAGES, row attached to the last window, row-only window when the page count is zero, empty link → none. If the two drift, the host-tier and disk-tier window boundaries disagree, which is exactly the sort of defect the unification was removing. Either call windows from the disk path or give it a shared home.
N2. Staged::close reports a non-job count as a job count. selene/src/disk_store.rs:2522-2545 computes abandoned as a .max() chain over owners, maintenance, shared_segments and shared_windows, then reports "{abandoned} disk transport jobs did not complete". After this PR the maximum can come from shared_windows — pinned staging slots, not jobs — so the message names the wrong unit and an operator reading a shutdown log will mis-size the leak. Either split the message or rename the unit.
N3. Two different settled() predicates with the same name. Segment::settled (:662-664) says "file unopened or closed"; SharedSegment::settled (:1106-1109) says "no disk jobs outstanding". Two predicates, one name, adjacent concepts — a reader has to check the receiver type to know which semantic they are getting. Rename one (closed() / drained()).
N4. Three repeated window-index removals and two identical follower-detach closures. The "unindex if the index still points at me" body appears three times (:1525-1527, :1543-1545, :1837-1839). The self.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 stating it three times is how it will eventually be stated wrong once. Extract fn 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 retain closure appears twice identically (:1813-1816 in detach_unwinding_windows, :1900-1904 in Pass 1 of pump_device_inbound), matching on the (record, plan_index) pair that is WindowFollower's identity (:1119-1123) and is constructed a third time at :1690-1695; a matches/remove method on WindowFollower would define the identity once. The two detach paths differ deliberately in byte crediting — only Pass 1 does record.bytes += win.read_bytes (:1901), because detach_unwinding_windows detaches from a record that is being failed — and that asymmetry deserves a one-line comment so the next reader does not "fix" the duplication by unifying them.
N5. GatedCopier::wrap returns a positional 4-tuple. selene/src/disk_store.rs:8092-8122 defines (SharedCopier, Arc<Mutex<bool>>, Arc<Mutex<VecDeque<copier::Reply>>>, Arc<Mutex<Option<JobId>>>); five call sites destructure positionally and three discard the tail with _ (:8406, :8530, :8984; :8650 is (copier, _, _, fail_job); :9234 ignores the tail entirely). Precedent in this crate for test fixtures returning named handles: selene/src/testing.rs:178 (not opened) (StoppedCopier), :225 (SimulatedGpu::shared_mapped/shared). A named struct with hold/held/fail fields would let each site say which gate it wants and would not renumber every site when a gate is added. Test-only, no production impact. If composite.rs's tests ever need it, it belongs beside StoppedCopier in selene/src/testing.rs (not opened), not in a #[cfg(test)] block at disk_store.rs:8092.
N6. §2.4's new bullet is one ~250-word paragraph carrying a dozen facts, and it states the metrics contract a second time. docs/prefix-cache-offload.md:337-366; duplicate at :1528-1531. The bullet runs from :337 (write_from(id, header, …)) to :366 (estimates.) as a single 30-line block carrying signatures, handle sharing, alignment, slot lifetime, the read_into separation, the immutability/pin invariant, close-before-Fetched, demand scheduling, reuse limits, the extra-partial-window bound, failure-isolation scope, and two metrics. The content is now accurate and complete, but .agents/skills/repo-prose/SKILL.md:84 (not opened) ("Use ordinary readable sentences") and :71 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. Separately, the StoreStats.bytes_in / inbound_rate sentences (:362-366) restate the §4 measurement table (:1528-1531); one contract in two homes is the duplication this lens exists to catch. Suggested split: 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.
Resolved since my earlier round (recorded so the fixes are not lost)
- Diagnostic counters
disk_opens/disk_window_reads/coalesced_windows(:200-208) anddisk_read_counted(:742,:1139) are now#[cfg(any(test, feature = "test-support"))], followingselene/src/disk.rs:309/:321/:437, instead of the earlierallow(dead_code)workaround. SegmentKey/WindowKey+window_index(:1052-1064,:1229) replaced the five-times hand-written identity tuple and theO(windows × plans)scan; lookups are nowO(1)(find_reusable_window,:1646-1663).plan_aligned_windowswas folded back into a singleplan_windows(..., align_to_window)(:682-727) rather than a second near-copy of the splitter.- The pass-2/pass-4 attach loop is extracted into
has_window_credit(:1683) /attach_pending(:1711) rather than duplicated. - The immutability/pin invariant I asked for in §2.4 is now stated (
:346-350), andWINDOW_PAGESis named at:342/:356rather than "64-page". debug_assert!at:1950matches existingseleneusage (memory.rs:534,composite.rs:647).
Checked and sound (not findings)
- No pre-existing coalescing or shared-handle mechanism was duplicated.
shard::Shardedhas only a plainfetch(shard.rs:900);selene/srchas no earlier shared-window or shared-open abstraction to reuse. The closest existing pair type,FileSpan { path, header }(selene/src/pool/pins.rs:165-183(not opened)), serves pinning, not staging, and could not be reused without contorting it. Onmainthere is no shared-window machinery at all (main'splan_windowsdisk_store.rs:1001-1024,InboundRecord/InWindow:1033-1054, a singleDestinationenum). Staged::read_intostaying on the private path is the right call, and it is stated in both code (plan_windows(..., false)at:1349, comment at:679-681) and doc (:345-346) — consistent withdocs/design-review.md(not opened) principle 6: caller-owned host reads have no follower to share a window with, so packing fullWINDOW_PAGESjobs without extra splits is correct.Resources::free_slots()(:236-239) is new but not a duplicate; it follows the shape of the existingdisk_space()/transfer_space()accessors.- Failure isolation (
fail_segment_users:1509,fail_window:1538,record.fail:1211) follows the file's existing per-record error handling rather than introducing a second error-propagation style.
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 instead that the enum gained a rank-0-local variant. The benchmark table is labelled at head with repeat counts and concurrency settings, and the "Not covered" list (multi-host RoCE, 2-GPU split_pools, discrete PCIe, Windows serving, live CompositeStore/PooledStore) satisfies AGENTS.md:103-112.
Open questions and what could not be settled
- Can
HeaderderiveHash? It has a privateversionfield excluded fromPartialEq(shared/record.rs:118-119); that exclusion is correctly reproduced in the new hash, and aHashimpl matching it is implementable. Whether disk metadata headers should carryPartialEq/Hashat all — versus a content digest, whichpool/pins.rs:165-183(not opened) andvocab.rs:30(not opened) suggest is idiomatic here — is a maintainer call, not a test. - Hash/eq agreement is untested. Nothing in the suite would fail if
HeaderIdentity::hashandHeader'sPartialEqdiverged in the unsound direction. A property test (a == b ⇒ hash(a) == hash(b)over a syntheticHeader) would settle it, and should be written if the manual impl is kept. - The
CompositeStoremaintenance amplification is unquantified. The code showscomposite.rs:1376bumping progress for every transport event and:1418-1424gatingspill_parked+disk.maintain()on it; the PR's benchmark table does not report maintenance-run counts, so the practical cost of the new event is not measured. A counter on the maintenance gate would settle it. - Architectural sign-off (AGENTS.md:201-207). The Why argument for putting a second inbound lifecycle inside
Stagedrather thanDiskThreadis sound —DiskThreadsees only file offsets and finishes atxxh3, whereas shared slots must stay pinned until every follower'sCopierfinishes — but a second inbound lifecycle in one type is an architectural choice a maintainer should explicitly acknowledge. - Not read in full: the ~5,300-line test module (
disk_store.rs:5100-9358). I read the new fixtures (GatedCopier::wrap:8092-8125,write_shared_ancestor_tree:8136ff,poll_all_fetches:8172ff), the new coalescing tests around:8299-9350, and every assertion touching the reviewed constructs. Multi-host/RoCE, 2-GPUsplit_pools, Windows serving and liveCompositeStore/PooledStoreGPU paths are untested here, as the description itself states.