Code review summary report · NVIDIA/hyperflare-inference #496

Raw Markdown for agents: https://autobot.eidonix.com/p/843ebe6d-3a89-4d79-9452-a6dcefc6f591.md

PR #496 review — "Coalesce shared ancestor reads across concurrent Selene disk fetches"

Head reviewed: 0c04b1e2 · Base: main c0c4f798 · Files: selene/src/disk_store.rs (+3313/−931), selene/src/shard.rs, docs/prefix-cache-offload.md (+35/−2) · 3 files, +3358/−933. Case file: https://autobot.eidonix.com/api/v1/cases/774e16ea-5f84-4ff8-9166-74ab6876cc37.html Lenses applied: architecture/scope, conventions & duplication, simplicity, correctness, prose. Five reviewers, no toolchain or GPU available — every finding below is established from source at the head commit, not from a build or run.

Key findings


Blockers

None. No correctness defect, no compatibility break, and no scope violation was found in the changed paths.


Should Fix

S1. A rank-local rate sample was added to the cross-rank completion enum, and it amplifies the composite's maintenance cadence

Finding. TransportEvent::InboundWindowSample { bytes, elapsed } (selene/src/disk_store.rs:97-101) was added to the enum whose own doc comment reads "Completion the transport reports to the disk store" (:83), where every other variant is a job completion carrying a JobId. This variant carries no id: it is a per-window bandwidth sample for Staged's own inbound Rate, produced inside Staged::apply_shared_disk when a shared window's physical reads finish (:1619) and consumed by a short-circuit at the top of DiskStore::apply (:3632-3635), with a unreachable!() immediately below to keep the match exhaustive (:3638).

Because the same enum is what shard::Sharded serialises between ranks, Kind::of now has to panic on it (selene/src/shard.rs:476-478: unreachable!("window rate samples stay local to rank zero")), while the enum's own convention for an unrepresentable kind is an error, not a panic (Err(invalid("unknown prefix record event kind")), shard.rs:462). That panic is upheld only by two hand-written matches! guards that must stay in sync: Sharded::absorb_local pushes the sample straight into self.events and continues (shard.rs:722-725), and Peer::forward skips it (shard.rs:1148-1150). Anything else that maps Kind::of over a Sharded's event list panics — including the existing test helper events.sort_by_key(|event| Kind::of(event).1) (selene/src/shard/tests.rs:339), which survives today only because those tests issue stores and unlinks and no fetch. Disk-store test code has to filter the variant by hand (disk_store.rs:6341) and match it out of the stream explicitly (:9145).

Concrete, verified cost beyond ergonomics. CompositeStore::poll does self.stats.progress += 1 for every transport event before dispatch (selene/src/composite.rs:1375-1376). That counter is documented as "Completion and capacity-release events" (selene/src/store.rs:202) and gates the maintenance pass: maintenance_progress != progress → spill_parked(...) + self.disk.maintain() (composite.rs:1418-1428). With this change each physical WINDOW_PAGES (64-page) window read bumps progress and therefore re-runs both, once per window per restore — the opposite of the hot-path relief this PR is after. DiskStore::apply deliberately does not bump progress for this variant (disk_store.rs:3632-3636), so the two stores' progress counters now advance at different rates for the same work.

Request. Carry the sample out of band rather than as a completion variant — any of: a Staged drain method over a pair of window byte/elapsed accumulators (the store already reads Staged state directly for in_flight() and pool()), 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)). Whichever shape, exclude it from CompositeStore's stats.progress (composite.rs:1376 should count completions only). A test asserting Kind::of is total over every TransportEvent, or a property test over the enum, would settle the panic path permanently; today only reading the two guards shows it.

Why. This is "solve the right problem in the right place" and "reject unsupported abstractions" (charter line 9; AGENTS.md:188-193 (not opened)). A variant with no job id is not a transport completion, and adding it makes the cross-rank protocol mapper responsible for a rank-local statistic: Kind::of goes from total to partially defined over its own input domain, and its totality now depends on two guards far from it. The fix needs no new machinery. Note the mechanism is correct and is not in question — observing a physical rate, the vanished per-record observe, and the two rank guards all behave as intended; the finding is about where the signal is carried. It is also what the description's "No core re-export or format change is required" overlooks: TransportEvent is a public enum in a public module and gained a variant.

S2. HeaderIdentity hand-writes Hash, duplicating an equality contract defined in another module

Finding. HeaderIdentity(Arc<Header>) implements PartialEq by delegation with an Arc::ptr_eq fast path (selene/src/disk_store.rs:1006-1010), then writes Hash by hand: it destructures Header, hashes fourteen fields one at a time plus each RankSizes (:1014-1050; the destructure ends in .. at :1030). The contract it must mirror is exhaustive and lives ~1,200 lines away in a different module — impl PartialEq for Header (selene/src/shared/record.rs:136-152), Header defined :116-134, impl Eq :154, private version excluded at :118-119 and correctly excluded here too.

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) misses (disk_store.rs:1229, lookups at :1650), and coalescing silently stops working — a performance regression with no test failure, because nothing in the suite pins hash/eq agreement.

It is also a convention departure, not merely a hazard: a repository-wide search for impl (std::hash::)?Hash for in selene/src returns exactly this one hit. The crate derives instead — PrefixKey derives PartialEq, Eq, Hash, PartialOrd, Ord (selene/src/vocab.rs:30), RankSizes derives (shared/record.rs:89), DiskRecord derives (disk_store.rs:72), and this PR's own SegmentKey/WindowKey derive (:1052, :1058). The manual impl exists only because Header does not derive Hash. Separately, HeaderIdentity restates Header identity where a per-record unique key already exists: Header.key is a PrefixKey, which derives Hash, and the path is derived from it.

Request. Move the hashing next to the equality it must track — impl Hash for Header in shared/record.rs with the same field list and version still excluded — and let SegmentKey/WindowKey derive; HeaderIdentity then disappears and the two contracts cannot drift. Minimum acceptable alternative if the author prefers the wrapper: impl Hash for HeaderIdentity { fn hash<H: Hasher>(&self, state: &mut H) { self.0.key.hash(state) } } — Hash need only be consistent with Eq, not complete; collisions cost a bucket because PartialEq still compares the whole header — plus a comment saying why the full field list was chosen. Either way, add the missing a == b ⇒ hash(a) == hash(b) property test.

Why. A Hash that must be hand-kept in step with an equality defined elsewhere, written with a non-exhaustive pattern so the compiler cannot help, is exactly the duplicate representation docs/design-review.md:74 (not opened) asks a change to account for — and the failure mode is silent and performance-only, which is the class of bug this PR's own benchmark exists to catch.

S3. pick_next_pending_plan restates Layout::record_slots instead of calling it

Finding. selene/src/disk_store.rs:1760-1793 computes a candidate window's slot cost by hand:

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 };

Layout::record_slots(pages, row) already encodes exactly this — pages + usize::from(row) * self.row_slots() (selene/src/geometry.rs:180-182, row_slots :173-178) — and it is the crate's single definition of what a record costs in staging slots: Resources::allocate uses it (disk_store.rs:245), as do memory.rs:468 and composite.rs:810/:1167. This guard exists to predict whether allocate will succeed (:1778); expressing the prediction with a different formula means the guard can disagree with the allocator, and it will the moment record_slots accounts for anything beyond pages + row. Secondary cost: lock(&self.resources.transfers) is taken once per candidate record per pump iteration here and then immediately again by allocate.

Request. let needed = lock(&self.resources.transfers).layout().record_slots(plan.count, plan.row);, hoisted next to free outside the plan loop; also drop the dead if demand.is_empty() guard at :1781-1787 (see Nit 3).

Why. A guard that predicts the allocator must use the allocator's own arithmetic; two formulas for one cost is a latent mismatch, and the helper already exists.

S4. The new §2.4 bullet is one ~250-word paragraph and states the metrics contract twice

Finding. docs/prefix-cache-offload.md:337-366 is a single 30-line bullet carrying roughly twelve facts: the write_from/read_into signatures, the shared open handle, WINDOW_PAGES file-boundary alignment, per-follower GPU upload, slot lifetime, read_into independence, the immutability/pin invariant, close-before-Fetched, sibling-demand scheduling, the live-window limit, the extra-partial-window bound, error scope, and the two metrics. Its content is now accurate and complete — every earlier doc ask is met, including the missing immutability invariant and the WINDOW_PAGES naming. What remains is shape and duplication: .agents/skills/repo-prose/SKILL.md:71 (not opened)/:84 ask for ordinary readable sentences and no "you had to be there" density, and AGENTS.md:52-60 (not opened) gives a document one purpose at a time, whereas this mixes mechanism, correctness invariant, scheduling heuristic and metrics. The bytes_in/inbound_rate contract is also stated twice — docs:362-366 and again nearly verbatim at :1528-1531 in §4 — and one contract in two homes is what drifts.

Request. Keep one paragraph of mechanism in §2.4 (shared handle; aligned WINDOW_PAGES fan-out to every attached upload; independent read_into), move failure scope and the two limits ("sharing covers only live windows"; "at most one extra partial window when skip_pages % WINDOW_PAGES != 0") to a short bullet list in the style of :333-336, keep the metrics statement only in §4 (:1528-1531) and leave a pointer from §2.4.

Why. This is the paragraph a future reader will trust to learn the transport's contract; a run-on makes three distinct behaviours read as one mechanism, and duplicated prose drifts (AGENTS.md:43-49 (not opened) prose review; design-review principle 16, write without hidden context).

S5. Record the design decision for the new shared inbound lifecycle (process, not code)

Finding. The change replaces Staged's single inbound lifecycle — the invariant behind the old "Nothing here waits" text — with two (host vs device) inside shared cache machinery: a five-state shared-file machine, reference-counted shared windows with separate disk and upload counts, out-of-order plan completion via started: Vec<bool>, and a close-only-when-settled rule (selene/src/disk_store.rs:1066-1160, :1824-2278). The PR Why now argues the choice on technical grounds — DiskThread sees only file offsets and raw host addresses and finishes once direct I/O and xxh3 complete, whereas SlabPool slots must stay pinned until every follower's asynchronous Copier upload completes — which discharges the design-review ask in substance. What remains is that an invariant this central not be settled implicitly by merge (AGENTS.md:204-206 (not opened)).

Request. Get a recorded maintainer sign-off on doing the coalescing inside Staged rather than inside the disk thread that already owns the file handle. No code change is requested.

Why. The technical content held up under review, but a change of this shape to shared cache invariants should rest on a recorded decision rather than on review-time inference.


Nits

N1. inbound_rate now measures pure disk-thread time, so estimated_seconds prices restores optimistically

disk::Reply.elapsed is set only around worker.execute(job) (selene/src/disk.rs:447-450) — one O_DIRECT read plus xxh3, with no wait for a free slot, no copier queue time and no GPU upload. Before this revision the rate was observed as record bytes over job.started.elapsed() from DiskStore::fetch to Fetched, spanning queueing and the upload; that field is gone and the Fetched arm now only does stats.bytes_in += bytes (disk_store.rs:3669). Since hit() divides by the rate (estimated_seconds: bytes as f64 / self.inbound_rate.get().max(1.0), :3625) and worth_fetching/worth_transfer gate on it (selene/src/store.rs:422-438), restore estimates are now optimistic by the staging/upload share even for a single restore — the opposite direction from the inflation this revision fixed. CompositeStore prices its disk part on its own disk_inbound_rate observed from read_into completions over disk_started.elapsed() (composite.rs:994-1004), so the two stores measure different quantities under one name. Request: either document inbound_rate explicitly as device read bandwidth and keep a separate end-to-end restore estimate for estimated_seconds, or include the per-record wait in the sample.

N2. Staged::close's abandoned count no longer matches its message, and two settled() predicates share a name

internal is a .max() over owners.len(), maintenance.len(), shared_segments.len() and shared_windows.len() (disk_store.rs:2522-2527), and abandoned = store_jobs.max(internal) (:2528), reported as "{abandoned} disk transport jobs did not complete within {:?}" (:2541-2544). Map sizes are 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, file handle reached a terminal state) and SharedSegment::settled (:1106-1109, disk jobs drained) are two different lifetime predicates with the same name in one file. Request: count owners.len() in the message and, if leaked staging state is worth catching, report it with its own message ("{n} shared windows/segments leaked"); rename one of the two settled()s.

N3. Dead guard, plus three verbatim unindex blocks, two identical detach closures, and id fields duplicating their map keys

N4. memory.rs::windows() is now the last third copy of the WINDOW_PAGES splitter, and two fixture shapes break crate precedent

N5. PR description nits


Resolved since the previous round at f9c9191 (reported here for closure, not re-raised)


Checked and sound (no action requested)


Open questions and what could not be settled