Subtractive scratchpad · NVIDIA/hyperflare-inference #496

Raw Markdown for agents: https://autobot.eidonix.com/p/c1427d80-8f14-4def-8d79-9f18054934e0.md

#1 [high] Should fix: HeaderIdentity (≈50 lines) duplicates Header's identity rules; move Hash onto Header

selene/src/disk_store.rs:1001-1050 adds HeaderIdentity(Arc<Header>) with PartialEq (ptr_eq || ==), Eq, and a 47-line hand-written Hash that destructures Header with .., hashes ranks.len() then each RankSizes, and deliberately skips version. Its purpose is only to be a Hash key in SegmentKey (1052-1056) and thus WindowKey (1058-1064). Header (selene/src/shared/record.rs:116-154) derives Clone, Debug and defines its own PartialEq (136-152) that includes exactly the fields the Hash lists minus version.

Smaller version: put the Hash impl once, beside the Eq it must agree with, and delete the wrapper:

Net ≈ -22 lines plus one fewer type, and there is then one definition of "which Header fields are identity". Today a field added to Header must be added in two places (record.rs:136 and disk_store.rs:1016) and the .. pattern means the compiler will not complain if it is missed, so WindowKey hashing can silently disagree with the expected comparison it is paired with. Nothing in the file needs the ptr_eq fast path (identical Arcs are equal by value anyway).

#3 [high] Should fix: demand-index scheduling (~80 lines) only reorders which new window starts first

selene/src/disk_store.rs:1732-1793 build_pending_demand (24 lines) + pick_next_pending_plan (37 lines), plus the demand: Option<&mut HashMap<WindowKey, usize>> parameter threaded through attach_pending (:1711-1730) and the demand.as_mut() decrement blocks at :1991-1995 and :1939, ≈80 lines total, exist only to reorder which new window a leader starts first: prefer plans whose WindowKey another live fetch also needs. Coalescing itself does not depend on it — attach_pending/find_best_existing_window_for (:1665-1681) already scans every unstarted plan for any reusable in-flight window regardless of order, and plan_windows(.., true) guarantees aligned (first, count) equality. Selecting the first unstarted plan (what main did) coalesces exactly the same windows, just possibly a little later.

Evidence the machinery is often dead: build_pending_demand returns empty for device_inbound.len() <= 1 (:1736) — i.e. every single-restore caller, and pick_next_pending_plan then degenerates to first-unstarted.

Smaller version: delete build_pending_demand, the demand parameter and both decrement sites; pick_next_pending_plan becomes the free-slot filter plus "first unstarted plan", about 12 lines; attach_pending loses its second argument. ≈65-80 lines removed. What is lost is only arrival-order relaxation across concurrent restores, which the PR measures as part of the staggered TTFT gain (3.76x vs 4.22x simultaneous); if the staggered number regresses, keep the preference as a single peer_demand > 0 boolean test over the existing window_index instead of a per-pump HashMap of every pending key.

#6 [high] Summary: subtraction totals for PR 496 and what must stay

Sizes measured from the PR diff for PR #496 (head 0c04b1e2, base c0c4f798): docs/prefix-cache-offload.md +35/-2, selene/src/disk_store.rs +3313/-931, selene/src/shard.rs +10/-0. Total +3358/-933. Of disk_store.rs, the new test module additions are roughly +900 lines (the six coalescing tests :8234-9357 plus GatedCopier/write_shared_ancestor_tree/poll_all_fetches fixtures), so the production change is roughly +2400/-930.

Confirmed subtractions, ranked by lines saved (details in notes 1-5):

  1. Demand-index scheduling: ~65-80 lines.
  2. Merge the close-drain test into the burst test: ~70 lines.
  3. HeaderIdentity wrapper + manual Hash: ~50 lines (net ~22 after moving Hash onto Header, but one duplicate definition of identity goes).
  4. Fold Pass 1 into Pass 5b: ~12 lines.
  5. Nits: duplicated docs paragraph ~5, four-way max in close ~4, single-segment Vec ~8: ~17 lines.

Total ≈ 215-230 lines removable, i.e. about 6% of the change and about 9% of the non-test production lines. The rest of the change is load-bearing: the shared-segment/shared-window state machine, the reference counts that keep SlabPool slots alive across every follower's upload, the failure isolation, and the InboundWindowSample event + shard.rs forwarding are each required by a stated goal and cannot be dropped without losing the measured 3.5-4.2x read reduction.

Judgement for the report: the change is not minimal but it is not padded either — the biggest single saving is the demand-index scheduler, which is the only block in the change whose removal loses nothing except start order. Everything else is Nit-to-Should fix housekeeping. I did not find a part of the change that serves no purpose, duplicates an existing repository helper beyond plan_windows/Header Hash, or leaves a superseded path behind: Destination, InPhase, InboundRecord::submit_upload and the device branch of the old InboundRecord are all deleted in this same diff, and the old plan_windows single call site is replaced.

#8 [high] Research summary

Reviewed PR #496 (head 0c04b1e, +3358/-933 across disk_store.rs, shard.rs and docs) strictly for subtraction. Seven scratchpad notes hold the findings with file:line citations, line savings and smaller replacements; note 6 has the ranked totals.

Headline: the change is large but mostly load-bearing — the shared segment/window state machine, the reference counts that keep SlabPool slots pinned across every follower's upload, the failure isolation and the InboundWindowSample plumbing are each required by a stated goal, and the old Destination/InPhase/submit_upload device path is fully deleted in the same diff, so nothing is left dead. The confirmed removable total is roughly 215–230 lines (~6% of the change), dominated by three items: the per-pump demand table and demand-aware plan picker (~65–80 lines, whose only effect is which new window a leader starts first — attach scanning already coalesces regardless of order); folding the close-drain test into the burst test, which builds the same fixture and asserts the same counters (~70 lines); and the HeaderIdentity wrapper with its 47-line hand-written Hash, which duplicates Header's own identity rules and should move onto Header next to the PartialEq it must agree with (~50 lines added, ~22 net). Remaining nits: duplicated docs paragraph (§2.4 and §4 say the same thing), a four-way max in Staged::close where one term is provably dead, a one-element Vec in HostInbound, and one redundant traversal of the active-window list per pump.

#2 [medium] Should fix: close-drain test duplicates the burst test (~70 lines)

selene/src/disk_store.rs:8294-8384 concurrent_burst_coalesces_shared_ancestor_opens_and_window_reads (BRANCHES=6, PARENT_PAGES=3WINDOW_PAGES+5, CHILD_PAGES=3, intake pool, SimulatedGpu, 6 fetches, poll_all_fetches, then assert disk_opens/disk_window_reads/coalesced_windows, pool.free_slots, no pins, per-page and row equality) and :8831-8906 staged_close_drains_active_coalesced_fetches_cleanly (BRANCHES=4, PARENT_PAGES=3WINDOW_PAGES, CHILD_PAGES=4, same pool/SimulatedGpu/poll pattern, plus in_flight().1 == BRANCHES, store.close() before polling, and stats().fetched) are the same test with a different close placement.

Smaller version: one test, for close_early in [false, true], with const BRANCHES: usize = 4; const PARENT_PAGES: usize = 3 * WINDOW_PAGES; and the in_flight/close lines inside if close_early. Assertions become: disk_opens() == 1 + BRANCHES, coalesced_windows() == 3 * (BRANCHES - 1) (the exact count the close test already asserts and the burst test would reach with 3 parent windows), pool free, no pins, per-page/row equality (already identical loops). Saves the whole second fixture+setup+teardown.

≈70 lines. Nothing lost: the close-drain assertions are the union of both, and the burst test's 4-parent-window shape is already covered by different_skip_pages_coalesce_aligned_windows_to_exact_gpu_pages (8510) which uses 3*WINDOW_PAGES+7.

#4 [medium] Nits: duplicated docs paragraph, four-way max in close, one-element Segment Vec

  1. docs/prefix-cache-offload.md:362-366 and again :1528-1531 state the same fact twice in one document ("StoreStats.bytes_in counts logical checkpoint bytes restored to GPU destinations across completed fetches, whereas DiskStore updates StoreStats.inbound_rate from physical staging-window disk reads once per window so coalesced followers do not inflate admission bandwidth estimates"). Keep the §4 measurement note (it sits in the measurement table) and drop the §2.4 sentences, ~5 lines. Also §2.4 (:337-366) now restates the module doc at selene/src/disk_store.rs:9-27 almost clause for clause (shared handle, pinned slots until every upload, close before Fetched, at most one extra partial window); one of the two is enough, and the module doc is the one next to the code.

  2. selene/src/disk_store.rs:2522-2528 Staged::close: internal is .max() over owners.len(), maintenance.len(), shared_segments.len(), shared_windows.len(). Every shared segment's disk job id is already in owners (:1968) and every maintenance job's id too (:2468, :2485), and shared windows own no id at all, so the last two maxima cannot raise the count: internal is owners.len().max(maintenance.len()) — 2 lines instead of 6.

  3. selene/src/disk_store.rs:265 Owner::HostInbound(JobId, usize): HostInbound always holds exactly one segment (read_into builds vec![segment] at :1360, and it is the only constructor), so the usize segment index is always 0 and segments: Vec<Segment> is a single Segment. Making it Owner::HostInbound(JobId) and segment: Segment removes the vec![], the .get_mut(segment) in apply_disk (:789) and the iter() in apply_disk/pump/unwind (:865, :882, :974) — ~8 lines, and Segment::settled keeps working.

#7 [medium] Correction to close() max finding: shared_windows max is dead, shared_segments only for Unopened

Correction to note 4 item 2 (verified against the code): every Owner::SharedSegment id is inserted in owners at :1968 and every maintenance id at :2468/:2485, before the job enters maintenance; SharedWindow owns no disk id at all. So .max(self.shared_windows.len()) can never raise the count, and .max(self.shared_segments.len()) only can when some segment is still Unopened (no Open submitted yet, hence nothing on the disk thread to abandon). Safe shorter form: let internal = self.owners.len().max(self.maintenance.len()).max(self.shared_segments.len()); — or keep shared_segments only for the Unopened case and drop shared_windows outright (:2522-2528, ~2 lines).

#9 [medium] Verified sound: no superseded code left behind; event variant and counters are needed

Checked and found sound (do not raise as findings, but the report should say these were checked):

#5 [low] Nit: pump_device_inbound walks every record's active windows twice

selene/src/disk_store.rs:1897-1909 (Pass 1), :2144-2196 (Pass 5b): both walk a healthy record's active list.

Smaller version: in Pass 1, when upload_done is false and !upload_submitted, submit the upload there (the win.phase == Read guard is the same test), then drop Pass 5b's first two if arms. The constraint is that Pass 5b must run after Pass 5a (disk reads), and Pass 1 runs before it — so instead of merging into Pass 1, Pass 1 can be folded into the head of a single "reap-and-upload" loop placed where Pass 5b is today: the "reap finished uploads" work does not need to happen before Pass 2/4 (those only consult started, active.len() and the shared windows, all unchanged by reaping). That deletes one of the two full traversals plus its active_len/index bookkeeping, ≈12 lines and one device_inbound[&id].active[index] re-lookup per upload.

Verification: nothing between Pass 1 and Pass 5b reads record.done or record.bytes — has_window_credit reads active.len(), which reaping changes, but reaping frees credit and lower credit only makes Pass 4 start fewer windows this pump, and pump_all runs every step, so it is caught next poll. Worth checking that the loop still terminates in one pump for the tests that count polls (staggered_arrival_attaches_out_of_order_to_in_flight_windows polls in a loop, so it tolerates an extra pump). Lower confidence than the other findings: merge only if the interleaving above is confirmed acceptable.

#10 [low] Nit (unverified): poll_all_fetches may duplicate crate::testing::poll_until

selene/src/disk_store.rs:8215-8232 adds poll_all_fetches(store, expected, deadline) -> Vec<StoreEvent> in the test module: it loops store.poll(&mut events), asserts the deadline, and returns the events once len() == expected. The crate already has crate::testing::poll_until (selene/src/testing.rs:25), which this very file imports (use crate::testing::poll_until; at :2829) and uses in dozens of tests for exactly this "poll until a predicate within a deadline" shape.

Savings if it is genuinely subsumed: ~16 lines, by calling poll_until(&mut store, deadline, |e| matches!(e, StoreEvent::Fetched { .. })) and asserting the event count afterwards, or by keeping only the assert helper. It is used by 5 of the new tests (:8347, :8476, :8583, :8687, :8803, :8961).

Caveat that keeps this a Nit and that the report must state: I did not read selene/src/testing.rs:25's exact signature, so I could not confirm it returns the accumulated Vec<StoreEvent> or counts events the way these tests need (several tests assert events.len() == expected and iterate for per-branch byte checks). Verify the signature before acting; drop the finding if poll_until only returns a bool or discards the buffer.