Review — PR #496 "Coalesce shared ancestor reads across concurrent Selene disk fetches"
Head reviewed: 0c04b1e2 · Lens: Correctness — callers, configurations, resource lifetimes, error handling, concurrency, inactive and edge-case paths, state transitions, compatibility with existing data, formats and persisted state.
Files read in context: selene/src/disk_store.rs, selene/src/shard.rs (changed, +3358/−933 across 3 files), plus selene/src/composite.rs, geometry.rs, slab.rs, disk.rs, levels.rs (not opened), shared/record.rs as callers/dependencies, and docs/prefix-cache-offload.md §2.4 and §4.
Key findings
No blocking or should-fix correctness findings. Two nits.
The three issues I raised on the previous revision are fixed in code at this head — physical-vs-logical accounting, the Staged::close abandoned count, and misaligned-follower coverage — and I found no correctness defect in the changed paths I read. The two surviving nits:
- Nit —
selene/src/composite.rs:1376:CompositeStore::pollincrementsself.stats.progressfor every transport event before dispatch, includingTransportEvent::InboundWindowSample, whileDiskStore::applyearly-returns for that variant and deliberately does not bumpself.stats.progress(selene/src/disk_store.rs:3632-3636). The two stores' progress counters advance at different rates for the same work, and via themaintenance_progressgate (composite.rs:1418-1429) the new event re-triggersspill_parked+disk.maintain()once per physical window read, defeating the throttle it exists for. Safe (maintenance is idempotent and slot-consuming only when needed), but wasteful. - Nit —
selene/src/disk_store.rs:2113-2116with:1599-1611: a shared window whoseReadRowjob is skipped becausedisk_space()is exhausted stays inSharedWindowPhase::Readingwithpages_submitted == true,row_submitted == falseanddisk_referenced == 0, so it is neither sampled intoinbound_ratenor uploadable until a later pump submits the row. Correct, but the liveness invariant is load-bearing and undocumented.
Both were re-verified in code immediately before this report.
Previously raised items, re-checked at head — resolved
(1) Logical bytes leaking into inbound_rate (was should-fix). apply_shared_disk now emits exactly one TransportEvent::InboundWindowSample { bytes, elapsed } per completed physical shared window, at selene/src/disk_store.rs:1596-1620, carrying win.read_bytes and the summed disk::Reply.elapsed over that window's ReadPages/ReadRow jobs (:1597-1598), pushed to self.events at :1617-1620. DiskStore::apply handles that variant first and only feeds the rate sampler:
// disk_store.rs:3631-3636
pub fn apply(&mut self, event: TransportEvent, events: &mut Vec<StoreEvent>) {
if let TransportEvent::InboundWindowSample { bytes, elapsed } = event {
self.inbound_rate.observe(bytes, elapsed);
return;
}
self.stats.progress += 1;
stats.bytes_in remains logical: each attached follower credits the window's full byte count in Pass 1 (record.bytes += win.read_bytes, :1899-1905) and DiskStore::apply spends it at :3669. hit()'s estimated_seconds (:3625) is therefore priced from physical disk bandwidth — the right input for admission — while bytes_in keeps its historical logical meaning. docs/prefix-cache-offload.md §2.4 and §4 now state the split, and I checked those claims against the code. Rate::observe ignores zero-byte / zero-elapsed samples (selene/src/levels.rs:57-60 (not opened)), and the sample is only produced when win.read_bytes > 0 (:1605), so the zero cases are covered at both ends.
(2) Staged::close abandoned count (was nit). selene/src/disk_store.rs:2513-2528 now computes store_jobs = outbound + host_inbound + device_inbound + maintenance_jobs and internal = max(owners.len(), maintenance.len(), shared_segments.len(), shared_windows.len()), then abandoned = store_jobs.max(internal). Since internal >= owners.len(), the count can no longer under-report versus the old self.owners.len(). Behaviour on failure (error returned, pool retained) is unchanged.
(3) Misaligned-follower coverage. misaligned_follower_attaching_to_shared_partial_tail_and_row_matches_private_restore compares byte-equal SimulatedGpu pages and row against a private-store baseline for skip_pages = 13 attaching to a leader's already-created windows — the exact untested pair I flagged previously.
Correctness checks that came out sound
Slot and file lifetimes
- A shared window is freed only when
followers.is_empty() && disk_referenced == 0 && upload_referenced == 0(sweep_shared_windows,:1755-1771). Attach paths incrementfollowers; every disk submission doeswin.disk_referenced += 1(:2100,:2128); every GPU upload doesupload_referenced += 1;apply_shared_diskdecrementsdisk_referenced(:1594) and emits the sample only at zero, andapply_device_transferdecrementsupload_referencedbefore any release decision. A reply can therefore never arrive for a freed window, and no slot is released while aCopierupload is outstanding — the reason the PR puts coalescing inStagedrather thanDiskThread. - Segment (file handle) removal requires
active.is_empty()(Pass 5e,:2213-2230) andsegment_needs_disk_readsfalse, sodisk::Closeis submitted only after the last attached restore's I/O drained — matching the described "last segment user waits for disk close before emittingFetched". allocate(plan.count, plan.row)matchesrecord_slots/row_slots(selene/src/geometry.rs:173-188) and the free-slot precheck inpick_next_pending_plan, andplan.offset/countindexrecord.pagesandwin.buffers.pagesconsistently forWINDOW_PAGES-aligned windows.- Reply matching relies on per-id FIFO submission order in
disk::Jobrows;pending_page_reads/pending_row_readsare pushed at submit time (:2123-2124for rows), so matching is exact on Linuxio_uringand theO_DIRECTpath.
Failure isolation
- Private child / GPU upload errors fail one restore (
record.fail,:1563-1565). - Shared open / read errors fail every attached restore after in-flight I/O drains:
fail_segment_userscollectsseg.users(:1509-1519),fail_windowonly marksReadingwindows failed (:1475-1487), and the error propagates aswith_record_read()so only the lookup row is invalidated — persistent state is not corrupted by a transient read error.
Concurrency and demand indexing
build_pending_demandshort-circuits whendevice_inbound.len() <= 1(:1651), so a lone restore behaves exactly as before and the only cost is at most one extra partial window per segment whenskip_pages % WINDOW_PAGES != 0— the bound the description claims.has_window_credit/attach_pendingkeep every attach within the two-window (WINDOW_CREDITS) budget before a finished slot can release, so no follower is starved by a peer's window release.Staged::pump_allruns outbound, thenhost_inbound, thenpump_device_inbound(:2291-2312), consistent with the#497merge-order note.
Host path unchanged
HostInbound (Staged::read_into, plan_windows(..., false)) keeps private per-restore opens and unaligned packing (:682-727), and CompositeStore::start_read (selene/src/composite.rs:802-837) uses only that path. Live CompositeStore/PooledStore host serving therefore sees no behavioural change; only GPU restores go through shared windows. This matches the doc claim that caller-owned reads run independently and segment-relative.
Event plumbing for the new variant
Sharded::absorb_localforwards samples toself.eventswithout going throughKind::of(selene/src/shard.rs:718-728). Theunreachable!arm inKind::of(shard.rs:476-478) is genuinely unreachable becausePeer::forwardfilters first (shard.rs:1144-1153): peer ranks dropInboundWindowSample, and rank 0 — which owns theDiskStore— keeps and measures its own. That is exactly what the description claims, and it is the reason the physical rate survives on rank 0.CompositeStore::pollroutes the variant tostreamed_event→DiskStore::apply(composite.rs:1373-1385,:300-327); the composite's byte and rate deltas are computed fromfetched/bytes_indeltas, so they are unaffected by the extra rate-only event.
Compatibility with existing data
No record-file format, header layout, or re-export change appears in the diff. HeaderIdentity's hand-written Hash (selene/src/disk_store.rs:1014-1050) was checked field-by-field against Header's PartialEq (selene/src/shared/record.rs:136-152): every equality-relevant field is hashed (identity, fingerprint, flags, key, parent, bucket, page_tokens, tail_pages, ranks, page_segment, row_segment, row_checksum, created), with version excluded from both and documented non-semantic (record.rs:118-119). So a == b ⇒ hash(a) == hash(b) holds and the new SegmentKey/WindowKey hashing cannot alias two different records. Files written before this PR load unchanged.
Nits
N1 (nit) — selene/src/composite.rs:1376: composite progress counter now advances for rate samples
for event in transport_events.drain(..) {
self.stats.progress += 1;
match event { ... other => self.streamed_event(other, events) }
}
DiskStore::apply returns before self.stats.progress += 1 for InboundWindowSample (disk_store.rs:3632-3636). Through a CompositeStore, every coalesced window adds an extra tick to CompositeStore::stats.progress that the inner store does not count, so the two progress counters — used as a liveness/backpressure signal — diverge for exactly the workload this PR introduces. Worse than a counter skew: the gate at composite.rs:1418-1429 (self.maintenance_progress != progress) re-runs spill_parked + disk.maintain() once per physical window read, so the new event defeats the throttle it exists for. Safe (maintenance is idempotent and consumes slots only when needed), but wasteful under an 8-way coalesced burst. Fix: skip the increment when matches!(event, TransportEvent::InboundWindowSample { .. }), mirroring the early return.
N2 (nit) — selene/src/disk_store.rs:2113-2116: window can sit unsampled and unuploadable when the disk queue is full
if row_needed {
if !self.resources.disk_space() {
continue;
}
When ReadPages for a window was already submitted (pages_submitted == true, with disk_referenced returning to 0) but the ReadRow is deferred here, the window remains Reading with row_submitted == false and disk_referenced == 0. The completion handler's sample condition (:1599-1611) requires pages_submitted && row_submitted && disk_referenced == 0, so no InboundWindowSample is emitted and no follower upload is armed until a later pump re-enters and submits the row. Behaviour is correct (the window is not released — followers is non-empty — and re-entry finds row_needed still true), but a rate sample can be delayed under disk-queue saturation, and the invariant "phase == Reading ⇒ at least one of pages_submitted/row_submitted still pending, or a reply outstanding" is what keeps the loop live. A comment at :2113 stating that invariant would make future edits to the continue safe.
Open questions / not verified
#497rebase onStaged::pump_all. Both PRs base onmainand both touchpump_all; the description asserts either merge order works and that the second one will "runhost_inboundandpump_device_inboundahead of writes and maintenance". Not verifiable from this branch — someone must confirm the resolvedpump_allin whichever PR merges second still orders shared-window uploads before outbound writes and maintenance.- Windows IOCP and multi-host RoCE. The author reports 13 coalescing tests passing on Windows IOCP but notes full Windows
seleneremains gated on/dev/urandom(docs/TODO.txt); Windows and multi-host RoCE serving are listed as not covered. The new path has no platform-specific branch, but the FIFO-reply-matching assumption above should be spot-checked against the IOCP job executor. - 2-GPU
split_pools, discrete PCIe GPUs, liveCompositeStore/PooledStoreGPU serving — listed as not covered by the author and not exercised here; N1 is precisely the composite-served path. - What would settle the residual risk. Only a stress test that saturates
disk::QUEUE_DEPTHwhile a follower attaches to a window whose row read is still deferred (N2), and aCompositeStore-wrapped coalesced burst asserting the progress counter and maintenance-throttle behaviour (N1), would close the two nits by test rather than by inspection. - No toolchain, GPU or test run was available to me. Every statement above is from source at
0c04b1e2; the author's reported suites (476 tests on x86_64 and ARM64 Linux, 13 on Windows IOCP, 21 Helios SM121 tests) were not reproduced.
Note on charter fit (correctness-adjacent, for other lenses)
The change lands in the shared selene disk tier rather than in a per-model or per-topology branch, and adds no flag — consistent with the charter's "Solve the right problem in the right place" and "No per-model special cases or flags". No persisted format change means the "existing data, artifacts, and exported cores still load" requirement is satisfied by construction. The benchmark provenance (description now compares main c0c4f798 to the exact head 0c04b1e2) makes the reported read reductions attributable to the merged code, unlike the previous revision where numbers predated the demand-index edit.