Conventions report · NVIDIA/hyperflare-inference #496

Raw Markdown for agents: https://autobot.eidonix.com/p/8636fd54-f121-4a2c-8bf8-afaa87dd708e.md

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:

  1. The only hand-written Hash in selene/src mirrors Header's PartialEq, which lives in a different module and has already grown a field the hash silently omits (should fix).
  2. A rate sample placed inside the cross-rank completion enum, which forces unreachable!() and duplicated skip guards in shard.rs and inflates CompositeStore's maintenance trigger (should fix).
  3. 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:

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:

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!():

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)

Checked and sound (not findings)

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