Skip to content

Coalesce shared ancestor reads across concurrent Selene disk fetches - #496

Merged
yatesdr merged 2 commits into
NVIDIA:mainfrom
FujitsuPolycom:selene-disk-ancestor-coalescing
Nov 29, 2026
Merged

yatesdr merged 2 commits into
NVIDIA:mainfrom
FujitsuPolycom:selene-disk-ancestor-coalescing

Conversation

@FujitsuPolycom

@FujitsuPolycom FujitsuPolycom commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Why

When concurrent requests restore distinct branch checkpoints sharing a disk-resident ancestor prefix, Helios deduplicates inbound restore tickets by endpoint key, so each branch submits its own GPU restore (Staged::fetch) in selene/src/disk_store.rs. Before this change, each restore opened every ancestor record file independently and staged private 64-page windows, repeating O_DIRECT opens, reads, and checksum verification once per branch.

Published record files are immutable and stay pinned in DiskStore across every referencing restore. Coalescing belongs in Staged rather than DiskThread because DiskThread sees only file offsets and raw buffers and finishes once direct I/O completes, whereas shared SlabPool staging slots and v4 ReadPacked payload buffers must remain pinned until every attached follower's asynchronous Copier decode or GPU upload completes.

What

  • Shared device-inbound state machine (selene/src/disk_store.rs, selene/src/disk_store/coalesce.rs):
    • Before: Staged ran every host and GPU inbound read through an isolated per-fetch InboundRecord, opening each segment and staging private 64-page windows independently.
    • After: caller-owned host reads (Staged::read_into using plan_windows(..., false) and Staged::read_into_packed storing (Header, Arc<Vec<u8>>) in completed_packed_reads for CompositeStore) remain on private HostInbound. Device fetches (Staged::fetch, plan_windows(..., true)) delegate to DeviceCoalescer in selene/src/disk_store/coalesce.rs, slicing on WINDOW_PAGES (64-page) file boundaries and sharing one open file handle per SegmentKey and one SharedWindow per WindowKey (O(1) window_index lookup) across both raw v1–v3 SlabPool staging windows and v4 packed ReadPacked buffers (which allocate zero SlabPool slots and retain Arc<Vec<u8>> until every follower's Copier decode and upload completes).
  • Exhaustive Header/packed::Layout hashing with cached digest and lazy demand indexing (selene/src/shared/packed.rs, selene/src/shared/record.rs, selene/src/disk_store/coalesce.rs):
    • Before: Header and packed::Layout had no Hash implementation; hashing an entire packed::Layout (up to 8,200 PackedUnits on TP8 1,024-page records) or eagerly rebuilding demand on full-credit poll() ticks would stall the worker thread.
    • After: packed::Layout implements Eq and exhaustive Hash over Layout, PackedOffer, and PackedUnit; RankSizes derives Hash; Header implements exhaustive Hash beside PartialEq (omitting only encoding version); HeaderIdentity::new(Arc<Header>) precomputes a deterministic u64 digest once with DefaultHasher::new(), HeaderIdentity::hash hashes only that cached u64, and HeaderIdentity::eq short-circuits on digest mismatch and Arc::ptr_eq before comparing full Header values; and start_new_windows builds demand lazily only when a fetch holds free window credit and needs to start a new window (skipping demand indexing when at most one fetch is active).
  • Tight-pool shared-ancestor holdback (selene/src/disk_store/coalesce.rs):
    • Before: skipping any unstarted plan whose Layout::record_slots exceeded currently free slots allowed a sibling on a tight 2 * (64 + row_slots) pool to grab leftover slots for a small private tail instead of waiting for a 64-page shared ancestor window, fragmenting slots and forcing re-reads.
    • After: pick_next_pending_plan computes reachable_free = free + self.staged_slots() + outbound_slots and holds back lower-demand windows whenever a higher-peer_demand shared window fits within reachable_free. Because in-flight staged windows drain without allocating new slots, waiting never deadlocks when no staged slots can free or under external pool retention.
  • End-to-end DiskStore::inbound_rate and per-fetch bytes_in (selene/src/disk_store.rs):
    • Before: DiskStore::inbound_rate observed every completed fetch's (bytes, started.elapsed()), which would let staggered coalesced followers riding pre-existing windows overstate bandwidth.
    • After: StoreStats.bytes_in continues counting per-fetch payload bytes restored across completed fetches (raw bytes for v1–v3 records and compressed payload bytes for v4 packed records, credited once per completed fetch including coalesced followers), while StoreStats.inbound_rate observes end-to-end uncompressed checkpoint bytes (layout.record_bytes(chain.pages)) over full fetch wall time (covering Open, slot queueing, disk read, codec decode, GPU upload, and all Sharded ranks) in the same units as HostHit::estimated_seconds and worth_fetching(). Restores submitted while an in-flight restore already reads a shared segment (rode_preexisting) skip inbound_rate.started() and observe inbound_rate only downward (when (logical_bytes / elapsed) < inbound_rate.get()), so fast coalesced followers riding pre-existing staged windows never inflate bandwidth while continuous overlapping streams, mid-stream slowdowns, and bursts whose leader fails still push inbound_rate down without letting Rate::get() drift upward to the 3.0 GB/s seed, and slow disks still recover upward when throughput improves. No DiskTransport or shard.rs rate-sampling plumbing and no TransportEvent change are added.
  • Failure isolation and docs (selene/src/disk_store/coalesce.rs, docs/prefix-cache-offload.md): private child or transient follower GPU upload errors fail only that restore; shared open, read, or packed-payload content errors (is_packed_content_error, marked with with_record_read()) fail all attached restores after in-flight I/O drains so DiskStore::apply drops the corrupt endpoint's lookup row. The last user of a shared segment waits for disk close (disk_settled) before emitting Fetched, and Staged::close reports abandoned transport jobs separately from leaked shared staging entries. Diagnostic counters are gated under test-support, and docs/prefix-cache-offload.md (sections 2.4 and 4) documents raw and v4 packed coalescing, tight-pool holdback, and end-to-end rate accounting. No core re-export, record format, wire protocol, or TransportEvent change is required.

Result

Overlapping GPU restores open a shared ancestor file once and read each aligned 64-page raw or v4 packed window once while staged (windows already released before a later restore attaches are read again). As an expected bound, single-restore callers skip demand indexing (device_inbound.len() <= 1) and pay at most one extra partial window per segment when skip_pages % 64 != 0.

On x86_64 Linux (--release selene tests over io_uring + ext4, rustc 1.100.0, comparing cb3db468 vs ba1c73fd, reproducible with cargo test --locked --release --manifest-path selene/Cargo.toml --features test-support --lib poll_at_full_window_credit_with_large_packed_header_avoids_demand_rebuild_and_rehashing -- --nocapture), full-credit (2/2) Staged::poll() latency across 1,000 polls drops:

Shape (PackedUnits) Concurrent Fetches Before Mean / p99 (cb3db468) After Mean / p99 (ba1c73fd) Speedup (Mean) Credit-Regained Demand Pass (ba1c73fd)
TP1, 512 pages (513) 1 0.283 µs / 0.323 µs 0.252 µs / 0.274 µs 1.12x 26.642 µs
TP1, 512 pages (513) 8 1,354.937 µs / 1,561.375 µs 0.693 µs / 0.701 µs 1,955x 31.396 µs
TP8, 512 pages (4,104) 1 0.278 µs / 1.507 µs 0.256 µs / 0.274 µs 1.09x 23.816 µs
TP8, 512 pages (4,104) 8 10,347.821 µs / 11,234.217 µs 0.664 µs / 0.679 µs 15,584x 31.298 µs
TP8, 1,024 pages (8,200) 1 0.310 µs / 1.361 µs 0.253 µs / 0.274 µs 1.23x 25.612 µs
TP8, 1,024 pages (8,200) 8 44,447.427 µs / 48,825.259 µs 0.745 µs / 1.392 µs 59,661x 39.897 µs

Prior live flare run A/B on NVIDIA GB10 (SM121) comparing main before v4 packed records (c0c4f798) against 0c04b1e2 with --lossless-kv-compression off and --prefix-cache-memory 0 --prefix-cache-disk /tmp/selene-disk (--max-concurrency 16 --prefix-cache-disk-limit 40G on Qwen3.8-27B-NVFP4; --max-concurrency 8 --prefix-cache-disk-limit 24G on Qwen3.8-Flash-Next), warming one ~61K-token shared prefix plus 8 child branches (~256 unique tail tokens each), restarting flare run for empty VRAM, and sending 8 concurrent /v1/chat/completions follow-ups (ingress-to-first-token TTFT; read-reduction ratios are ratios of tabulated means):

  • Qwen3.8-27B-NVFP4 (TP1, 60.5K, 2 interleaved repeats): physical NVMe reads drop 18,177.5 -> 4,306.7 MB (2,274 MB single restore — 472 pages at 128 tokens/page plus 101 MB continuation row, so 18,177.5 MB is 8x full copies; 4.22x, -76.3%), median TTFT 7,974.6 -> 5,662.8 ms (-29.0%) simultaneous; and 18,194.2 -> 4,843.6 MB (3.76x, -73.4%), TTFT 6,883.6 -> 5,951.9 ms (-13.5%) at +25 ms stagger.
  • Qwen3.8-Flash-Next (TP1, 61.0K): NVMe reads drop 7,944.9 -> 1,981.1 MB (4.01x, -75.1%, TTFT 3,327.5 -> 3,225.0 ms) simultaneous, and 7,958.0 -> 2,251.5 MB (3.53x, -71.7%, TTFT 3,137.7 -> 3,049.9 ms) at +25 ms stagger.

Recommended merge order with companion PR #497 (Selene pipeline prioritization and tighter 2 * (64 + row_slots) intake pools): merge #497 first, then rebase #496 onto main so Staged::pump_all retains MAINTENANCE_DEFER_LIMIT = 8 and runs host_inbound and pump_device_inbound ahead of outbound and maintenance.

Evidence

  • Verified on x86_64 Linux (O_DIRECT + io_uring, ext4, rustc 1.100.0) on exact git archive ba1c73fd6c0b0d08c612dd947ed47ceaee8ce457 (tree 0f5524389c086223a243a59388d58bd9ad17458b, base 6d74db3a; merges cleanly against origin/main 9031847a, selene/src/shard.rs diff 0 bytes):
    • cargo check --locked --release --manifest-path selene/Cargo.toml --all-targets: passed, 0 warnings (both with and without --features test-support).
    • cargo test --locked --release --manifest-path selene/Cargo.toml --features test-support: 522 lib + 1 mixed_codec_root passed, 0 failed, 0 ignored, including:
      • header_identity_caches_digest_and_matches_header_equality and poll_at_full_window_credit_with_large_packed_header_avoids_demand_rebuild_and_rehashing
      • packed_restore_inbound_rate_includes_decode_delay_and_worth_fetching_rejects, sharded_inbound_rate_reflects_end_to_end_multi_rank_wall_time, coalesced_restores_keep_inbound_rate_end_to_end_and_bytes_in_logical, overlapping_shared_stream_tracks_slowdown_and_recovers_without_drift, and leader_private_failure_with_slow_follower_updates_inbound_rate_and_rejects
      • tight_pool_waits_for_shared_ancestor_instead_of_starting_private_tail (row_slots = 1 / 130 slots and row_slots = 8 / 144 slots, asserting disk_opens == 3, disk_window_reads == 5, coalesced_windows == 3) and tight_pool_wait_never_deadlocks_without_releasable_staged_slots
      • sharded_concurrent_fetches_coalesce_across_rank_zero_and_peer (local TCP Sharded + Peer via shard::serve, confirming Rank 0 disk_opens == 5 / disk_window_reads == 7 / coalesced_windows == 9 and Peer Rank 1 simultaneous live slab-address sharing)
      • 4-way v4 packed coalescing and corrupt-packet record_read invalidation, misaligned follower partial-tail+row parity, private vs shared failure isolation, and Staged::close draining.
    • cargo test --locked --release --manifest-path selene-manager/Cargo.toml --test client --test offload: 85 + 2 passed, 0 failed, 0 warnings.
    • cargo check --locked --manifest-path helios/Cargo.toml --features runtime-core,server --all-targets: passed (0 warnings in touched crates).
    • pytest tests/preparation/test_core_boundary.py tests/test_design_review_hook.py: 22 passed, 0 failed.
  • Prior SM121 GPU evidence at 0c04b1e2 against main before v4 packed records (c0c4f798, raw v3 records / --lossless-kv-compression off): helios offload:: (FLARE_RUN_CUDA_TESTS=1 --include-ignored) passed all 21 single-GPU SM121 tests (split_pools requires 2 local GPUs); live SM121 parity across 5 cold-VRAM restart repeats (seed = 1234..1238, 60,534 tokens, top_logprobs = 5) on Qwen3.8-27B-NVFP4 TP1 produced identical FP32 top-5 logprobs and token IDs vs main (c0c4f798) on all 5 repeats; and 4 concurrent decode streams spilling checkpoints over 30 s on Qwen3.8-Flash-Next TP1 had 0 errors (100.0 -> 100.6 tok/s).
  • Not covered: post-fix SM121 flare run re-measurement on ba1c73fd, live SM121 --lossless-kv-compression (cpu/gpu) serving, multi-host RoCE serving, 2-GPU split_pools, discrete PCIe GPUs, Windows serving, and live warm-plus-disk (--prefix-cache-memory > 0) or PooledStore HTTP serving (CompositeStore + DiskStore CUDA transfers are covered in helios offload::).

Discord: Dooner

@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 496. The case file is kept up to date with all findings, and should be read by agents working on this code base.
Case File Intake Report

To opt out, include #autobot:ignore in the PR or any comment.

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review for Agents.

Recommendation: Changes Requested

The approach belongs in the repo — a measured, served-workload win with no new flags, no format change, failure isolation preserved, and the shared-window lifetime work holds up. One result in the PR's own evidence must be settled first; the rest is metering, docs and duplication.

Blockers:

  • Settle the 61.3K retrieval result or declare it inconclusive. The description reports 8/9 on main vs 7/9 at head on a temperature=0 retrieval prompt and draws no conclusion. Re-run several times on both revisions, report variance and the differing fact; if the gap holds, fix it — the narrow plausible site is plan_aligned_windows' offset/row mapping for a follower attaching to a window it did not create.

Should fix:

  • inbound_rate is now measured on logical bytes and the error does not decay. Every follower credits the whole shared window to its own record (:1829), so the sample divides coalesced elapsed time into a ~4x byte count; hit() prices restores off it (:3587) and worth_fetching gates on it (store.rs:423-438), and Rate only decays below its seed (levels.rs:69-76). Sample once per physical window; keep bytes_in logical and documented; add a 1-vs-8-restore rate test.
  • Docs and rustdoc claim more than the mechanism. §2.4 (docs:337-342) needs the two limits the description discloses, the immutable+pinned invariant, WINDOW_PAGES file-boundary alignment, and the real write_from/read_into signatures; the module doc still says "at most WINDOWS_IN_FLIGHT windows" and "Nothing here waits" (disk_store.rs:14-24); the allocate rustdoc now sits on free_slots (:228-234).
  • Benchmark predates head; expected costs are stated as results. Re-run one simultaneous and one staggered TP1 trial at f9c9191 (or label the table's commit), and mark "existing users pay per-pump demand indexing…" as an expected bound that applies only to multi-fetch pumps (:1651-1653).
  • One planner, one window key. plan_aligned_windows (:700) is plan_windows (:672) plus one clamp; the sharing key (path, header, first, count, row) is hand-written five times (:1368, :1578, :1647, :1710, :1890/:1996). Name it WindowKey and index it — that also removes the per-pump PathBuf clones and the O(windows×plans) scan.
  • De-duplicate the attach loop and record the design call. Pass 2 and Pass 4 repeat the credit predicate and attach loop (:1845-1861, :1874-1903) — extract has_window_credit/attach_pending; and get recorded maintainer sign-off for putting a second inbound lifecycle inside Staged rather than in the disk thread that already owns the handle.

Nits:

4 nits — Staged::close counts leaked windows into "N disk transport jobs did not complete" (:2485-2489); test-only counters use allow(dead_code) instead of cfg(test) and live outside StoreStats (:192-200); dead state (PlanState::Done, single-element Vec<Segment>, duplicated window fields/ids) and a positional 4-tuple GatedCopier; naming-axis mixing plus a 60-word doc sentence.

Full evidence, per-angle detail and the list of what was checked and found sound are in the case file.

To opt out, include #autobot:ignore in your post or comment.

@FujitsuPolycom

Copy link
Copy Markdown
Contributor Author

Updated this branch to 0c04b1e2 (over c0c4f798) and refreshed the PR description to match. Summary of changes in review order:

  • B1 (Qwen3.8-27B-NVFP4 ~61K retrieval parity & misaligned follower test):
    • 5-repeat SM121 check (0c04b1e2 vs main c0c4f798): Flare does not support greedy temperature = 0 (helios/src/model.rs); helios/src/server/request.rs clamps "temperature": 0 in the benchmark client into the core's positive sampling range, and the initial single-pass script used distinct per-build prompt nonces (producing different turn-1 assistant texts and positive-temperature sampling trajectories). Warming one shared 60,534-token checkpoint to disk and running 5 cold-VRAM restart repeats (seed = 1234..1238, top_logprobs = 5) against that checkpoint produced identical FP32 top-5 logprobs and token IDs across all 5 repeats (main vs 0c04b1e2: 6/9 == 6/9, 8/9 == 8/9, 7/9 == 7/9, 9/9 == 9/9, 4/9 == 4/9), with first-token top-5 logprobs matching in-VRAM GPU hits ("9" -0.756374 vs "3" -1.256374).
    • Unit test: Added misaligned_follower_attaching_to_shared_partial_tail_and_row_matches_private_restore (selene/src/disk_store.rs), verifying byte-equal SimulatedGpu pages and row state when a follower with skip_pages = 13 attaches to shared windows created by a leader (skip_pages = 0), covering both a partial <64-page ancestor tail and a partial leaf chunk with row = true.
  • S1 (Physical inbound_rate vs logical bytes_in): Added TransportEvent::InboundWindowSample { bytes, elapsed } (selene/src/disk_store.rs, forwarded on rank 0 in selene/src/shard.rs and ignored on peer ranks) summing disk::Reply.elapsed per physical window read so DiskStore::inbound_rate observes one physical disk sample per window while StoreStats.bytes_in stays logical. Added coalesced_restores_keep_inbound_rate_physical_and_bytes_in_logical (1 vs 8 simultaneous and staggered restores) and verified live on SM121 (6.07 GB/s single vs 7.71 GB/s 8-way simultaneous and 6.02 GB/s 8-way staggered on Qwen3.8-27B-NVFP4).
  • S2 (Docs, module contract, and rustdoc): Updated docs/prefix-cache-offload.md (§2.4 and §4) with the current write_from / read_into signatures, WINDOW_PAGES file-boundary alignment, the immutable-record + index-pin + close-before-Fetched invariant, failure isolation scope, physical inbound_rate vs logical bytes_in, and the two coalescing limits. Updated selene/src/disk_store.rs's module doc and restored Resources::allocate's rustdoc above allocate with a dedicated doc line on free_slots.
  • S3 (Head-commit benchmarks & expected-cost bound): Re-measured the Result table at 0c04b1e2 vs main (c0c4f798) on Qwen3.8-27B-NVFP4 TP1 (18,177.5 -> 4,306.7 MB, 4.22x, TTFT 7,974.6 -> 5,662.8 ms simultaneous; 18,194.2 -> 4,843.6 MB, 3.76x, 6,883.6 -> 5,951.9 ms staggered) and Qwen3.8-Flash-Next TP1 (7,944.9 -> 1,981.1 MB, 3.99x simultaneous; 7,958.0 -> 2,251.5 MB, 3.52x staggered), moved un-rerun multi-host RoCE serving to Not covered, and labeled the single-restore / unaligned-skip_pages cost as an expected bound noting build_pending_demand's device_inbound.len() <= 1 fast path.
  • S4 & S5 (plan_windows, WindowKey O(1) lookup, and attach_pending): Unified plan_windows(segments, align_to_window: bool) with a doc comment explaining why caller-owned read_into keeps segment-relative packing (align_to_window = false); added HeaderIdentity(Arc<Header>), SegmentKey (Arc<Path>), WindowKey, window_index: HashMap<WindowKey, SharedWindowId>, and HashMap<WindowKey, usize> demand counts; and extracted has_window_credit / attach_pending across the existing-window and new-window attachment loops in pump_device_inbound.
  • S6 (Staged vs DiskThread rationale): Documented in Why: DiskThread sees only file offsets and raw host addresses and finishes once direct I/O and xxh3 complete, whereas a shared window's SlabPool slots must stay pinned until every attached follower's asynchronous Copier GPU upload completes, which Staged owns. Also verified on pending_row_reads FIFO matching: push_back runs only inside submit_disk's Ok(()) arm, so a failed submission never enqueues an unmatched entry.
  • Nits & suite verification: Included owners, shared_segments, and shared_windows in Staged::close's abandoned count; gated disk_opens, disk_window_reads, coalesced_windows, and disk_read_counted under #[cfg(any(test, feature = "test-support"))] (0 warnings without test-support); replaced PlanState with started: Vec<bool>; and removed duplicate path/expected fields on SharedWindow and DeviceSegmentRef. At 0c04b1e2, 476 Linux selene tests, 13 Windows IOCP tests, 21 single-GPU SM121 helios offload:: tests (FLARE_RUN_CUDA_TESTS=1 --include-ignored), and test_core_boundary.py passed.

Ready for another look at 0c04b1e2.

@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 496.
Case File Intake Report

To opt out, include #autobot:ignore in the PR or any comment.

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review for Agents.

Recommendation: Changes Requested

Non-blocking: no blocker remains, but five should-fix items (one layering, one maintainability, one arithmetic, one docs, one process sign-off) are worth landing before or with the merge.

Blockers:

None.

Should fix:

  • Take the rate sample off the cross-rank completion enum. TransportEvent::InboundWindowSample (disk_store.rs:97-101) carries no JobId yet joins the enum documented as "Completion the transport reports to the disk store" (:83), forcing unreachable!() in Kind::of (shard.rs:476-478) upheld by two hand-written guards (shard.rs:722-725, :1148-1150) and making CompositeStore::poll bump stats.progress — and so re-run spill_parked + disk.maintain() — once per physical window (composite.rs:1376, gate :1418-1428). Carry it out of band (a Staged drain method or a field on Fetched).
  • Move HeaderIdentity's hand-written Hash next to the equality it tracks. It hashes 14 fields through a .. pattern (disk_store.rs:1014-1050, .. at :1030) against Header's exhaustive PartialEq in another module (shared/record.rs:136-152); a new Header field silently drops out of the hash and coalescing stops with no test failure. Give Header a Hash impl (or hash only PrefixKey) and add an a == b ⇒ hash(a) == hash(b) test.
  • Call Layout::record_slots instead of restating it. The admission guard in pick_next_pending_plan recomputes pages + row_slots by hand (disk_store.rs:1767-1777) while the allocator it predicts uses record_slots (geometry.rs:180-182, disk_store.rs:245). One-line change, hoisted beside free.
  • Split the §2.4 bullet and stop stating the metrics contract twice. docs/prefix-cache-offload.md:337-366 is one ~250-word paragraph carrying ~12 behaviours, and the bytes_in/inbound_rate statement repeats at :1528-1531. Mechanism prose in §2.4, limits/failure scope as bullets, metrics only in §4.
  • Get the design decision recorded. The Staged-vs-DiskThread argument in Why is sound; ask a maintainer to record the choice to put a second inbound lifecycle inside Staged (AGENTS.md:204-206 (not opened)). No code change.

Nits:

5 nits


Full report, with citations, severity rationale, what was resolved since the last head f9c9191, the verified-sound list and open questions, follows in the report body. Evidence for every finding is in the case file (https://autobot.eidonix.com/api/v1/cases/774e16ea-5f84-4ff8-9166-74ab6876cc37.html). No toolchain, GPU or test run was available to this review: every finding is established from source at head 0c04b1e2.

To opt out, include #autobot:ignore in your post or comment.

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review for Agents.

Autobot Review

Full Review for Agents.

Recommendation: Ready To Merge

No new commits since the last review — 0c04b1e2 is still head, so the previous "Changes Requested" post is superseded, not overtaken by new code. Re-weighing those items: none can make a released build wrong, so none is treated as a merge gate. This belongs in the repo — a measured win on a served workload (27B simultaneous 18,177.5 → 4,306.7 MB physical reads, TTFT 7,974.6 → 5,662.8 ms), in the right layer (Selene's disk tier), with no new flag, no per-model branch, no on-disk format and no wire change. Every earlier blocker is resolved: parity settled by 5 cold-VRAM repeats (identical FP32 top-5 logprobs and token IDs), inbound_rate physical with bytes_in logical (live 6.07 GB/s single vs 7.71 GB/s 8-way), benchmarks re-measured at this head, one plan_windows plus WindowKey.

Blockers:

  • None.

Should fix:

  • Take the rank-local rate sample off the cross-rank completion enum. TransportEvent::InboundWindowSample (disk_store.rs:97-101) is the one variant of six with no JobId, in an enum documented as "Completion the transport reports to the disk store" (:83). It forces two unreachable!()s (shard.rs:476-478, disk_store.rs:3638) upheld by hand-written guards (shard.rs:722-725, :1148-1150), and makes CompositeStore::poll bump stats.progress — re-running spill_parked + disk.maintain() — once per physical window (composite.rs:1376, gate :1420-1428). → Carry it out of band (a Staged drain method or a field on Fetched) and keep it out of the composite progress count.
  • Move HeaderIdentity's hand-written Hash beside the equality it tracks. It hashes Header's fields through a .. pattern (disk_store.rs:1014-1050) against PartialEq defined in another module (shared/record.rs:136-152), with no test pinning agreement. Precisely: a mismatch here fails safe — a coarser hash costs bucket collisions in window_index, never wrong results — but main has already added a packed field to Header's equality that this branch omits, so the drift is live. → Implement Hash for Header in record.rs and let SegmentKey/WindowKey derive; add an a == b ⇒ hash(a) == hash(b) test.
  • Call Layout::record_slots instead of restating it. The admission guard recomputes pages + row_slots by hand (disk_store.rs:1777) while the allocator it predicts uses record_slots (geometry.rs:180-182, disk_store.rs:245). → One line, hoisted beside free; a guard must use the allocator's own arithmetic.
  • Split the §2.4 bullet and state the metrics contract once. docs/prefix-cache-offload.md:337-366 is one ~250-word paragraph carrying ~12 behaviours, burying the two limits a reviewer needs; the bytes_in/inbound_rate contract repeats at :1528-1531. → Mechanism in §2.4, limits and failure scope as short bullets, metrics only in §4.
  • Record the design decision (process, no code change). The Staged-vs-DiskThread argument in Why is sound, but a second inbound lifecycle inside Staged is an invariant-level choice that AGENTS.md:201-206 (not opened) says a maintainer must record explicitly — a PR Why is not that record. → Ask a maintainer to sign off.

Nits:

10 nits — inbound_rate now prices restores optimistically and CompositeStore measures another quantity under the name; Staged::close reports a non-job count as a job count (:2522-2544); memory.rs:1336-1367 is now the last copy of the WINDOW_PAGES splitter this PR unified; two settled() predicates plus three repeated unindex blocks and two identical detach closures; one-element HostInbound vec with an always-zero owner index; SharedSegment.id/SharedWindow.id duplicating their map keys; a dead demand.is_empty() guard (:1781-1787); test-only residue (disk_read_counted flags, GatedCopier 4-tuple); ~90-110 lines of duplicated test setup, the ObservedTransport wrapper and the duplicated close-drain test; and four description/docs wording items (sample scope, Flash-Next 3.99x/3.52x vs 4.010/3.535, undisclosed arrival-order relaxation, "no re-export or format change").


Full report — per-finding requests, resolutions since the last head, the verified-sound list and open questions — is in the case file. No toolchain, GPU or test run was available: every finding is established from source at 0c04b1e2, and the head carries no CI checks. Nothing in the PR or docs attempted to direct the reviewer.

To opt out, include #autobot:ignore in your post or comment.

FujitsuPolycom added a commit to FujitsuPolycom/flare-local-inference that referenced this pull request Nov 27, 2026
Why

When concurrent requests restore distinct branch checkpoints sharing a
disk-resident ancestor prefix, Helios deduplicates inbound restore tickets by
endpoint key, so each branch submits its own GPU restore (`Staged::fetch`) in
`selene/src/disk_store.rs`. Before this change, each restore opened every
ancestor record file independently and staged private 64-page windows, repeating
`O_DIRECT` opens, reads, and checksum verification once per branch.

Published record files are immutable and stay pinned in `DiskStore` across every
referencing restore. Coalescing belongs in `Staged` rather than `DiskThread`
because `DiskThread` sees only file offsets and raw buffers and finishes once
direct I/O completes, whereas shared `SlabPool` staging slots and v4
`ReadPacked` payload buffers must remain pinned until every attached follower's
asynchronous `Copier` decode or GPU upload completes.

What

- Separate private host and shared GPU read paths (`selene/src/disk_store.rs`):
  caller-owned host reads (`Staged::read_into` using `plan_windows(..., false)`,
  and `Staged::read_into_packed` storing `(Header, Arc<Vec<u8>>)` in
  `completed_packed_reads` for `CompositeStore`) remain on a private
  `HostInbound` path. GPU restores (`Staged::fetch`, `plan_windows(..., true)`)
  slice on 64-page (`WINDOW_PAGES`) file boundaries and share one open file
  handle per `SegmentKey` (`Arc<Path>`, `HeaderIdentity(Arc<Header>)`) and one
  `SharedWindow` per `WindowKey` (`O(1)` `window_index` lookup) across both raw
  v1-v3 `SlabPool` staging windows and v4 `packed` `ReadPacked` windows (which
  allocate zero `SlabPool` slots and retain `Arc<Vec<u8>>` until all followers'
  `Copier` decode and upload jobs finish).
- Exhaustive `Header` and `packed::Layout` hashing (`selene/src/shared/packed.rs`,
  `selene/src/shared/record.rs`, `selene/src/disk_store.rs`): implement `Eq` and
  `Hash` on `packed::Layout` with exhaustive destructures over `Layout`,
  `PackedOffer`, and `PackedUnit`; derive `Hash` on `RankSizes`; implement
  `Hash` on `Header` beside `PartialEq` (omitting only encoding `version`); and
  delegate `HeaderIdentity::hash` to `Header::hash` while retaining the
  `Arc::ptr_eq` fast path on `PartialEq`.
- Reference-counted windows and demand indexing (`selene/src/disk_store.rs`):
  active restores attach via `has_window_credit` / `attach_pending` within their
  two-window (`WINDOWS_IN_FLIGHT`) credit before finished windows release;
  `pick_next_pending_plan` sizes raw windows with `Layout::record_slots` and
  requires zero slots for v4 `packed` segments; `build_pending_demand`
  short-circuits when at most one restore is active; and the last segment user
  waits for disk close (`disk_settled`) before emitting `Fetched`.
- Out-of-band physical `inbound_rate` and logical `bytes_in`
  (`selene/src/disk_store.rs`, `selene/src/shard.rs`): record one
  `(bytes, elapsed)` sample per completed shared window read in
  `Staged::inbound_samples`, drain it out of band via
  `DiskTransport::drain_inbound_samples` (forwarded on rank 0 in `Sharded`,
  discarded on peers in `Peer::forward`), and observe it in `DiskStore` without
  adding a variant to `TransportEvent` or incrementing `StoreStats.progress`.
  `CompositeStore` continues to update its end-to-end `disk_inbound_rate` from
  `read_into` and `read_into_packed` completions.
- Failure isolation and docs (`docs/prefix-cache-offload.md`): private child or
  transient follower GPU upload errors fail only that restore; shared open,
  read, or packed-payload content errors (`is_packed_content_error`, converted
  via `with_record_read()`) fail all attached restores after in-flight I/O
  drains so `DiskStore::apply` drops the corrupt endpoint's lookup row.
  `Staged::close` reports abandoned transport jobs separately from leaked shared
  staging entries. Diagnostic counters are gated under `test-support`, and
  `docs/prefix-cache-offload.md` (sections 2.4 and 4) documents raw and v4
  packed coalescing and rate accounting. No core re-export, record format, or
  `TransportEvent` variant change is required.

Result

Overlapping GPU restores open a shared ancestor file once and read each aligned
64-page raw or v4 packed window once while staged (windows already released
before a later restore attaches are read again). As an expected bound,
single-restore callers skip demand indexing (`device_inbound.len() <= 1`) and
pay at most one extra partial window per segment when `skip_pages % 64 != 0`.

Live `flare run` A/B on NVIDIA GB10 (SM121) comparing pre-`NVIDIA#504` `main`
(`c0c4f798`) against `0c04b1e2` with `--lossless-kv-compression` off (identical
raw physical windowing, I/O, and upload schedule to this rebased commit when
compression is `off`) and `--prefix-cache-memory 0 --prefix-cache-disk
/tmp/selene-disk` (`--max-concurrency 16 --prefix-cache-disk-limit 40G` on
`Qwen3.8-27B-NVFP4`; `--max-concurrency 8 --prefix-cache-disk-limit 24G` on
`Qwen3.8-Flash-Next`). Each trial warms one ~61K-token shared prefix plus 8
child branches (~256 unique tail tokens each) to disk, restarts `flare run` so
GPU memory starts empty, and sends 8 concurrent `/v1/chat/completions`
follow-ups (ingress-to-first-token TTFT; read-reduction ratios are ratios of
tabulated means):
- `Qwen3.8-27B-NVFP4` (TP1, `60.5K`, 2 interleaved repeats): physical NVMe reads
  drop `18,177.5 -> 4,306.7 MB` (`2,274 MB` single restore — `472` pages at
  `128` tokens/page plus `101 MB` continuation row, so `18,177.5 MB` is `8x`
  full copies; `4.22x`, `-76.3%`), median TTFT `7,974.6 -> 5,662.8 ms`
  (`-29.0%`) simultaneous; and `18,194.2 -> 4,843.6 MB` (`3.76x`, `-73.4%`),
  TTFT `6,883.6 -> 5,951.9 ms` (`-13.5%`) at `+25 ms` stagger. `inbound_rate`
  stays physical (`6.07 GB/s` single vs `6.02-7.71 GB/s` 8-way).
- `Qwen3.8-Flash-Next` (TP1, `61.0K`): NVMe reads drop `7,944.9 -> 1,981.1 MB`
  (`4.01x`, `-75.1%`, TTFT `3,327.5 -> 3,225.0 ms`) simultaneous, and `7,958.0 ->
  2,251.5 MB` (`3.53x`, `-71.7%`, TTFT `3,137.7 -> 3,049.9 ms`) at `+25 ms`
  stagger (`inbound_rate` `7.17-9.01 GB/s` single).

Recommended merge order with companion PR `NVIDIA#497`: merge `NVIDIA#497` first, then
rebase `NVIDIA#496` onto `main` so `Staged::pump_all` retains
`MAINTENANCE_DEFER_LIMIT = 8` and runs `host_inbound` and `pump_device_inbound`
ahead of `outbound` and `maintenance`.

Evidence

- Verified at this commit over `main` (`6d74db3a`): on x86_64 Linux WSL
  (`O_DIRECT` + `io_uring`, `rustc 1.100.0`), `cargo check --locked --release
  --manifest-path selene/Cargo.toml --all-targets` (`0` warnings with and
  without `test-support`), `cargo test --locked --release --manifest-path
  selene/Cargo.toml --features test-support` (`513 passed, 0 failed` unit + `1
  passed` in `mixed_codec_root`, covering 4-way v4 `packed` ancestor coalescing
  and corrupt-packet `record_read` propagation in
  `concurrent_packed_fetches_coalesce_opens_and_read_packed_windows`,
  `packed::Layout` and `Header` hash-equality agreement in
  `header_eq_implies_same_hash`, out-of-band `drain_inbound_samples` /
  `progress` preservation, misaligned follower partial-tail+row parity, private
  vs shared failure isolation, and `Staged::close` draining), `cargo check
  --locked --manifest-path helios/Cargo.toml --features runtime-core,server
  --all-targets`, and `pytest tests/preparation/test_core_boundary.py
  tests/test_design_review_hook.py` (`22 passed, 0 failed`). On Windows IOCP
  (`stable-x86_64-pc-windows-msvc`), `12` coalescing, window-planning, and
  header-hashing tests plus `mixed_codec_root` passed.
- Verified at pre-rebase commit `0c04b1e2` against `main` (`c0c4f798`, raw v3
  records / `--lossless-kv-compression` off): `selene --features test-support`
  passed `476` tests on ARM64 Linux (DGX Spark GB10); `helios` `offload::`
  (`FLARE_RUN_CUDA_TESTS=1 --include-ignored`) passed all `21` single-GPU SM121
  tests (`split_pools` requires 2 local GPUs); live SM121 parity across 5
  cold-VRAM restart repeats (`seed = 1234..1238`, `60,534` tokens,
  `top_logprobs = 5`) on `Qwen3.8-27B-NVFP4` TP1 produced identical FP32 `top-5
  logprobs` and token IDs vs `main` (`c0c4f798`) on all 5 repeats (`6/9, 8/9,
  7/9, 9/9, 4/9`, matching in-VRAM GPU step-0 `top-5 logprobs`; cross-seed
  variation reflects positive-temperature sampling, as `helios` clamps request
  `temperature` into the core's positive sampling range and Flare does not
  support greedy `temperature = 0`); and 4 concurrent decode streams spilling
  checkpoints over 30 s on `Qwen3.8-Flash-Next` TP1 had `0` errors (`100.0 ->
  100.6 tok/s`).
- Not covered: live SM121 `--lossless-kv-compression` (`cpu`/`gpu`) serving (v4
  `packed` window coalescing is covered by `selene` unit tests), rerunning the
  raw SM121 `flare run` A/B after rebasing onto `6d74db3a`, multi-host RoCE
  serving, 2-GPU `split_pools`, discrete PCIe GPUs, Windows serving, and live
  warm-plus-disk (`--prefix-cache-memory > 0`) or `PooledStore` HTTP serving
  (`CompositeStore` + `DiskStore` CUDA transfers are covered in `helios`
  `offload::`).

Discord: Dooner

Design-Signed-Off-By: Antigravity (Gemini 4 Carbon); design-review=eb2f
Signed-off-by: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com>
@FujitsuPolycom
FujitsuPolycom force-pushed the selene-disk-ancestor-coalescing branch from 0c04b1e to cb3db46 Compare November 27, 2026 05:58
FujitsuPolycom added a commit to FujitsuPolycom/flare-local-inference that referenced this pull request Nov 27, 2026
…head

Why

Disk-only prefix-cache offload (`--prefix-cache-memory 0` with
`--prefix-cache-disk`, default `--lossless-kv-compression off`) incurred five
host and coordination costs: (1) opening a raw v1-v3 record file
(`selene/src/disk.rs`) issued two sequential `O_DIRECT` reads (4 KiB header,
then page checksums); (2) `xxh3` page hashing ran serially on the single disk
thread across up to 64 pages (`268 MB` at `4.19 MB`/page); (3) `Staged::pump_all`
(`selene/src/disk_store.rs`) submitted unlinks/truncates and outbound writes
ahead of interactive restores; (4) while waiting on an inbound restore with an
idle GPU, Helios's worker (`helios/src/server/runtime.rs`) slept up to `2 ms`
and multi-host disk peers (`selene/src/shard.rs`) slept `1 ms` instead of waking
on socket readability; and (5) on integrated-memory GPUs
(`CU_DEVICE_ATTRIBUTE_INTEGRATED`), disk-only offload scaled registered host
intake with concurrency (`2 * max_active * row_slots + 128`, up to `8.2 GiB`
needed on `Qwen3.8-27B-NVFP4` at `--max-concurrency 16`), carving GPU KV cache
out of shared RAM even though paged disk streaming stages at most two windows
(`2 * (64 + row_slots)` slots).

What

- Single-read raw open (`selene/src/disk.rs`): preserve `NVIDIA#504`'s v4 packed
  `Header::read_metadata` open branch, and on raw v1-v3 `O_DIRECT` opens read
  the 4 KiB header and expected checksum segment in one transfer when
  `expected.tail_pages <= MAX_TAIL_PAGES` (`CHECKSUM_SCRATCH_BYTES = 1 MiB`),
  falling back to a 4 KiB header-only read on failure while preserving retry
  I/O errors, truncated-file checks, and shared scratch span helpers.
- Scoped parallel page hashing (`selene/src/disk.rs`): cache `parallel_cpus`
  once at `Worker::new` and hash raw batches of >= `HASH_PARALLEL_MIN_PAGES`
  (`4`) pages across `parallel_cpus.min(MAX_HASH_THREADS).min(buffers.len())`
  `std::thread::scope` threads (`MAX_HASH_THREADS = 4`) when `parallel_cpus >=
  HASH_PARALLEL_MIN_CPUS` (`4`), with `0` idle helper threads, Linux
  `SCHED_BATCH` inheritance via `clone`, inline recomputation on helper spawn
  or unwind failure, and fault hooks folded into `Faults` under
  `cfg(any(test, feature = "test-support"))` (zero test-only parameters on
  shipped signatures).
- Bounded restore-first submission and wakeup (`disk_store.rs`,
  `helios/src/server/runtime.rs`, `shard.rs`): order `Staged::pump_all` as
  inbound restores, then outbound writes, then maintenance while submitting one
  reserved maintenance job ahead of inbound and outbound after
  `MAINTENANCE_DEFER_LIMIT` (`8`) consecutive passes where queued maintenance
  lost free disk-queue space; poll `Worker::idle_wait` at `50 us` during
  active/waiting inbound restores; and wake Unix disk peers via `libc::poll`
  (`POLLIN`).
- Bounded integrated disk-only intake (`selene/src/offload.rs`,
  `helios/src/offload/mod.rs`, `helios/src/runtime_core/{memory,model}.rs`,
  `docs/prefix-cache-offload.md`): pass explicit `PrepareInputs` (no `Default`
  or unused `prepare`/`core` wrappers), unify `disk_enabled()`,
  `headroom_inner`, private `target_intake_slots`, and parameterless
  `Prepared::intake_warning()` (`required_intake` + `sized_concurrency`), and
  target `intake_slots(layout, 1)` (`2 * (64 + row_slots)`) on integrated
  disk-only hosts without shrink warnings while preserving `NVIDIA#504` lossless KV
  compression. No core re-export or record-format change is required.

Result

Live `flare run` A/B on NVIDIA GB10 (SM121) measured `NVIDIA#497` standalone
(`cd5a366b`) against pre-`NVIDIA#504` `main` (`c0c4f798`) with `--prefix-cache-memory
0 --prefix-cache-disk /tmp/selene-disk` and default `--lossless-kv-compression
off` (the raw v3 `.ckpt` path, whose runtime execution is unchanged by rebasing
onto `6d74db3a` and removing test-only signature plumbing; ingress-to-first-token
TTFT; bandwidth is rank-0 `flare_host_cache_inbound_bytes_per_second`):
- `Qwen3.8-27B-NVFP4` (TP1, `--max-concurrency 16 --prefix-cache-disk-limit
  40G`, 3 interleaved repeats): intake drops `7.3 GiB` (`1,877` slots, shrink
  warning) -> `1.0 GiB` (`252` slots, `0` warnings), raising GPU KV cache `64.4
  -> 71.6 GiB` (`+7.2 GiB` / `+235.5K` tokens); median single-restore bandwidth
  and TTFT improve `7.05 -> 8.02 GB/s` (`348.0 -> 301.7 ms`, `-13.3%`; wall
  `353.5 -> 306.5 ms`) at `30.0K` and `6.28 -> 8.68 GB/s` (`+38.2%`, `551.8 ->
  447.6 ms`, `-18.9%`; wall `561.7 -> 455.4 ms`) at `61.1K`; `NVIDIA#497` standalone
  8-way `61.1K` cold-restart burst mean median TTFT drops `8,156.1 -> 6,963.4
  ms` (`-14.6%`, 2 interleaved repeats; the `NVIDIA#496 + NVIDIA#497` combination is
  unmeasured).
- Isolated `std::thread::scope` `xxh3` (`cd5a366b` with `MAX_HASH_THREADS = 1`
  at `selene/src/disk.rs:157` and no other change vs unmodified `cd5a366b` with
  `MAX_HASH_THREADS = 4`, 3 interleaved repeats on `Qwen3.8-27B-NVFP4`):
  parallel hashing alone improves median TTFT `486.8 -> 447.6 ms` (`-8.1%`,
  `7.73 -> 8.68 GB/s`, `+12.3%`, faster on all 3 repeats: `[447.6, 432.7,
  451.2]` vs `[479.9, 557.5, 486.8] ms`) at `61.1K` and `322.4 -> 301.7 ms`
  (`7.55 -> 8.02 GB/s`) at `30.0K`. `HASH_PARALLEL_MIN_PAGES = 4` and
  `HASH_PARALLEL_MIN_CPUS = 4` assign at least one page per thread at the
  4-thread cap and leave cores for serving threads on narrow hosts (not swept
  separately).
- `Qwen3.8-Flash-Next` (TP1, `--max-concurrency 8 --prefix-cache-disk-limit
  24G`, `cd5a366b` vs `c0c4f798`): intake drops `1.9 -> 0.3 GiB` (`2,288 -> 398`
  slots), raising GPU KV cache `23.28 -> 24.98 GiB` (`+1.70 GiB` / `+127.0K`
  tokens); bandwidth improves `5.67 -> 7.05 GB/s` (`372.1 -> 355.6 ms`) at
  `30.0K` and `6.65 -> 8.35 GB/s` (`+25.6%`, `458.0 -> 413.8 ms`, `-9.7%`) at
  `61.0K`; `NVIDIA#497` standalone 8-way burst median TTFT drops `3,327.5 -> 3,078.5
  ms` (`-7.5%`).

What it costs: up to three short-lived scoped `xxh3` helpers during >=4-page
raw batches (`0` idle helpers), `50 us` `Worker::idle_wait` polling during
active/waiting inbound restores (`969.9 -> 1,069.2 ms/s` `/proc/<pid>/stat`
server CPU across 8-way `Qwen3.8-27B-NVFP4` bursts: `+99.3 ms/s` / ~`0.10` of
20 Grace cores combined; the `50 us` poll's CPU share and latency contribution
are unisolated from scoped `xxh3` helpers), two-window serialization for
concurrent unique-prefix restores and outbound stores on integrated disk-only
hosts, and up to `8` passes of maintenance deferral.

Companion PR (NVIDIA#496): merge `NVIDIA#497` first, then rebase `NVIDIA#496` onto `main` so
`Staged::pump_all` retains `MAINTENANCE_DEFER_LIMIT = 8` (submitting one
reserved maintenance job first after `8` deferred passes) and runs
`host_inbound` + `pump_device_inbound` ahead of `outbound` and `maintenance`.

Evidence

- Rebased crate and Python checks over `origin/main` (`6d74db3a`): `selene
  --features test-support` (`510` lib + `1` integration passed, `0` warnings),
  `selene-manager --test client --test offload` (`85 + 2` passed), `helios
  --features runtime-core,server` (`0` warnings; `phase_tests::idle_wait` and
  `offload::pool::tests` passed), `6` targeted Windows IOCP `selene` tests, and
  `pytest tests/preparation/test_core_boundary.py`.
- Prior SM121 GPU unit and live checks (at `cd5a366b`, `--lossless-kv-compression
  off`): `helios` `offload::` (`FLARE_RUN_CUDA_TESTS=1 --include-ignored`, `21`
  single-GPU SM121 tests passed; `split_pools` requires 2 local GPUs);
  corrupting a multi-page `.ckpt` payload on `Qwen3.8-27B-NVFP4` incremented
  `fetch_failed_total` (`1`), launched `0` `restore` graphs, and recomputed
  identical `top-5 logprobs` and tokens; under `--prefix-cache-disk-limit 6G`
  (`4` concurrent restores + `3` fresh `30K` stores), disk bytes peaked at
  `6.38 GB` (`<= 6 GiB`) and settled at `6.37 GB` with `0` `retry_abandoned`
  and `0` `io_error` drops (`2` normal `end_of_chain` evictions); four
  concurrent decode streams spilling checkpoints over 30 s on
  `Qwen3.8-Flash-Next` had `0` errors (`100.0 -> 95.9 tok/s`).
- Not covered: live `--lossless-kv-compression` (`cpu`/`gpu`) serving,
  post-rebase SM121 `flare run` re-measurement, isolated `50 us`
  `Worker::idle_wait` A/B, `NVIDIA#496 + NVIDIA#497` combined serving, multi-host RoCE
  serving, 2-GPU `split_pools`, discrete PCIe GPUs, Windows serving, and live
  warm-plus-disk (`--prefix-cache-memory > 0`) or `PooledStore` HTTP serving
  (`CompositeStore` + `DiskStore` CUDA transfers are covered in `helios`
  `offload::`).

Discord: Dooner

Design-Signed-Off-By: Antigravity (Gemini 4 Carbon); design-review=eb2f
Signed-off-by: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com>
@FujitsuPolycom

Copy link
Copy Markdown
Contributor Author

Rebased onto main (6d74db3a, post-#504 lossless KV compression) at cb3db468, ported v4 packed record coalescing onto SharedSegment / SharedWindow, and addressed all Round 2 review suggestions and description clarifications:

  1. Ported #504 v4 packed record support and added packed ancestor coalescing (selene/src/disk_store.rs, selene/src/shared/packed.rs, selene/src/shared/record.rs):
    • Preserved Source::HostPacked, write_packed, read_into_packed (HostDestination::Packed populating completed_packed_reads before TransportEvent::Fetched), take_packed_read, codec_receive_profiles, decode_counters, StoreStats.decode, and all #504/#523/#524 tests on HostInbound / OutboundRecord / DiskStore.
    • Extended DeviceInbound / SharedSegment / SharedWindow to coalesce v4 packed windows (Operation::ReadPacked) alongside raw v1–v3 SlabPool windows: packed windows allocate 0 SlabPool slots in pick_next_pending_plan and Pass 4, submit one shared ReadPacked job per aligned 64-page window, retain packed_buf: Option<Arc<Vec<u8>>> across all attached followers' PinnedPacket / Window::restore_pinned Copier decode-and-upload jobs until sweep_shared_windows, and map is_packed_content_error failures via with_record_read() so DiskStore::apply drops corrupt lookup rows.
    • Verified in concurrent_packed_fetches_coalesce_opens_and_read_packed_windows (4 concurrent branch fetches sharing a 3-window v4 packed ancestor over a 1-slot SlabPool, asserting 5 opens, 7 ReadPacked reads, 9 coalesced follower attachments, byte-exact GpuMemory pages and rows, 0 leaked slots/pins, and shared corrupt-packet Checksum::Stored -> is_record_read() row invalidation) plus packed_disk_round_trip_restart_mixed_profiles_and_compaction, packed_composite_spills_v4_and_promotes_across_restart, and mixed_codec_root.
  2. Moved physical window-read rate samples off TransportEvent (selene/src/disk_store.rs, selene/src/shard.rs):
    • Removed TransportEvent::InboundWindowSample and both unreachable!() arms. Staged now buffers (bytes, elapsed) samples in inbound_samples and exposes DiskTransport::drain_inbound_samples (forwarded on rank 0 in Sharded, discarded on peers in Peer::forward), which DiskStore::poll drains into inbound_rate without touching TransportEvent or incrementing CompositeStore's stats.progress. Verified in coalesced_restores_keep_inbound_rate_physical_and_bytes_in_logical (stats.progress equals completed restore events only).
  3. Implemented exhaustive Hash on Header and packed::Layout beside PartialEq (selene/src/shared/packed.rs, selene/src/shared/record.rs, selene/src/disk_store.rs):
    • Added Eq and exhaustive Hash on packed::Layout (Layout, PackedOffer, and PackedUnit), derived Hash on RankSizes, implemented exhaustive Hash on Header (version: _ excluded to match PartialEq, packed included), and delegated HeaderIdentity::hash directly to Header::hash. Verified in header_eq_implies_same_hash across raw and v4 packed headers.
  4. Used Layout::record_slots in pick_next_pending_plan and cleaned up Staged::close / docs / description nits (selene/src/disk_store.rs, docs/prefix-cache-offload.md):
    • Hoisted the transfers lock once in pick_next_pending_plan and called layout.record_slots(plan.count, plan.row) (0 slots when packed).
    • Reported abandoned_jobs separately from leaked_shared staging entries in Staged::close. (Note on staggered_arrival_attaches_out_of_order_to_in_flight_windows: coalesced_windows() >= 2 is already a bound, while disk_window_reads() + coalesced_windows() == 10 is an exact conservation identity across the two 5-window restores because every logical window is either started once or attached once.)
    • Split docs/prefix-cache-offload.md §2.4 into mechanism, invariants, and limits/failure-scope sub-bullets covering both raw and v4 packed windows, consolidated bytes_in / inbound_rate / CompositeStore.disk_inbound_rate in §4, clarified the Qwen3.8-27B-NVFP4 single-restore size (2,274 MB: 472 pages at 128 tokens/page + 101 MB row, so 18,177.5 MB is 8x full copies) and Flash-Next mean ratios (4.01x / 3.53x), and stated the #497 -> #496 merge order explicitly.

Verification at cb3db468 (over main 6d74db3a):

  • x86_64 Linux WSL (rustc 1.100.0): cargo check --locked --release --manifest-path selene/Cargo.toml --all-targets (0 warnings with and without test-support), cargo test --locked --release --manifest-path selene/Cargo.toml --features test-support (513 passed, 0 failed unit + 1 passed in mixed_codec_root), cargo check --locked --manifest-path helios/Cargo.toml --features runtime-core,server --all-targets, and pytest tests/preparation/test_core_boundary.py tests/test_design_review_hook.py (22 passed, 0 failed).
  • Windows IOCP (stable-x86_64-pc-windows-msvc): 12 coalescing, window-planning, and header-hashing tests + mixed_codec_root passed.
  • Remaining limits: live SM121 --lossless-kv-compression (cpu/gpu) serving, rerunning the raw SM121 flare run A/B after rebasing onto 6d74db3a, multi-host RoCE serving, 2-GPU split_pools, discrete PCIe GPUs, Windows serving, and live warm-plus-disk (--prefix-cache-memory > 0) or PooledStore HTTP serving (CompositeStore + DiskStore CUDA transfers were covered at 0c04b1e2 by the 21/21 SM121 helios offload:: suite).

Ready for another look at cb3db468 (and for explicit maintainer sign-off on the Staged shared-window lifecycle).

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Ready To Merge

All prior blocker and should-fix items are resolved in code at cb3db468; coalescing sits in the right layer with no flag, per-model branch, record-format or wire change. What remains is one recorded maintainer decision, one rate-naming/unit mismatch, and a purely subtractive cleanup worth ~360–400 lines.

  • Blockers: 0
  • Should fix: 2
  • Subtractive suggestions: 5
  • Nits: 12

Have your agent review the Full Review for complete findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

@yatesdr yatesdr left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the thorough work here and for porting the coalescing path cleanly onto post-#504 v4 packed records.

Design sign-off: Placing the shared-segment / shared-window coalescing lifecycle in Staged (rather than DiskThread) is the right boundary and I'm signing off on that choice — SlabPool staging slots and v4 packed_buf: Arc<Vec<u8>> must remain pinned across every follower's async Copier decode/upload, failure isolation preserves #343's is_record_read() semantics, and waiting for disk_settled() on the last segment user preserves DiskStore's index-pin invariant.

Before merging, there are a few unintended consequences that need to be addressed:

1. Worker-thread CPU stall from per-poll eager build_pending_demand and uncached packed::Layout hashing (blocker)

In selene/src/disk_store.rs, HeaderIdentity::hash (:1442) delegates directly to Header::hash (selene/src/shared/record.rs:165-202), which hashes the full packed::Layout (selene/src/shared/packed.rs:94-134 — every PackedUnit in offer.units, offsets, and pages). Three hot paths in pump_device_inbound() hash WindowKey repeatedly:

  • Eager demand-map rebuild on every poll() (disk_store.rs:2460-2468): if self.resources.free_slots() > 0 || any_packed builds demand even when zero active fetches have window credit (active.len() == WINDOWS_IN_FLIGHT), which is almost every poll tick (especially paired with #497's 50 µs idle_wait). Line 2479 already lazily calls demand.get_or_insert_with(|| self.build_pending_demand()) inside while self.has_window_credit(id).
  • Full packed::Layout re-hashing per lookup: On a large v4 packed ancestor (e.g., 1,024 pages × TP8 = 8,192 PackedUnits, >600 KB of heap data), each lookup in build_pending_demand, find_best_existing_window_for, and pick_next_pending_plan re-hashes the entire layout on the main Helios worker thread (and on every peer's Peer::run loop).

Requested fix:

  • Cache a precomputed deterministic u64 hash once in HeaderIdentity::new(Arc<Header>) (e.g., via DefaultHasher::new(), which uses fixed keys so a == b => hash(a) == hash(b)) and hash only that cached u64 in HeaderIdentity::hash.
  • Remove the eager build_pending_demand() block (:2460-2468) and rely on let mut demand = None; + the existing lazy get_or_insert_with at :2479.

2. Switching DiskStore::inbound_rate to rank-0 disk-read-only breaks worth_fetching() / restore_wait.defer() pricing (blocker)

DiskStore::inbound_rate feeds DiskStore::hit() (:4394) -> HostHit::estimated_seconds -> worth_fetching() and restore_wait.defer() in helios/src/server/runtime.rs. Changing it from end-to-end restore wall time to rank-0 per-window DiskThread reply.elapsed via inbound_samples / drain_inbound_samples has several unintended effects:

  • v4 packed records (--lossless-kv-compression cpu|gpu): disk::Worker::read_packed uses buffered File::open + read_exact_at (not O_DIRECT). Page-cache hits report RAM-copy speeds while omitting CPU/GPU codec decode and GPU H2D upload completely. Because Rate only decays upward toward its seed and never downward (selene/src/levels.rs:69-75), inflated rates stick and systematically underprice restores.
  • Raw v1–v3: Excludes Open (header + checksums), slot queueing, and GPU H2D upload (for instance, in the PR's own Qwen3.8-27B table, inbound_rate reports 7.71 GB/s / ~295 ms estimated for a 2,274 MB restore during a 5.66 s median-TTFT burst).
  • Sharded multi-host: Peer::forward (selene/src/shard.rs:1213-1214) discards peer samples and Sharded::drain_inbound_samples (:1005-1012) only drains rank 0's local Staged, leaving worth_fetching() blind to slow or degraded peer NVMe/links.
  • 3-sample median noise & split with CompositeStore: Emitting one sample per window lets tiny partial tail or 4 KiB row-only windows dominate Rate's 3-sample median, while CompositeStore::disk_inbound_rate still measures end-to-end read_into / read_into_packed time.

Requested fix: Keep DiskStore::inbound_rate measuring end-to-end restore latency (including Open, codec decode, GPU upload, and all Sharded ranks) rather than disk-thread-only window reads. To avoid inflating the estimate on late-attaching followers that ride already-staged windows, only observe end-to-end (bytes, job.started.elapsed()) for restores that did not ride pre-existing windows (or measure elapsed from the earliest attached shared window's start). That also eliminates the drain_inbound_samples plumbing across DiskTransport, Sharded, and Peer, and keeps docs/prefix-cache-offload.md §4 consistent with CompositeStore.

3. pick_next_pending_plan skipping shared windows on tight pools (interaction with #497)

In pick_next_pending_plan (disk_store.rs:2320), skipping any unstarted plan whose layout.record_slots(plan.count, plan.row) > free allows a fetch to grab leftover slots for a small private child tail (peer_demand = 0) instead of waiting for a 64-page shared ancestor (peer_demand > 0).

Under #497's 2 * (64 + row_slots) integrated-GPU pool (e.g., 178 slots when row_slots ≈ 25), as soon as the first sibling finishes uploading a 64-page ancestor window while slower siblings still pin it (free = 50), that sibling skips the next 64-page shared ancestor window and spends its window credit + slots on its private tail (29 slots). That fragments the pool, delays 64 + row_slots windows, and can desynchronize siblings so they miss coalescing the next shared ancestor window.

Requested fix: Avoid bypassing a higher-peer_demand shared window just to run a lower-demand (peer_demand == 0) private window when free is temporarily below a full window; wait for slots to free so siblings stay synchronized on the shared ancestor.

Minor / maintainability & validation notes

  • selene/src/disk_store.rs grows from ~8K to ~10.8K lines with pump_device_inbound at ~538 lines in one function; consider extracting the shared device-inbound state machine into a private submodule (e.g., disk_store/coalesce.rs) and splitting pump_device_inbound's passes into small methods.
  • Please add unit coverage for #496 + #497-style tight 2 * (64 + row_slots) pool coalescing and multi-rank Sharded coalescing, and verify live serving with --lossless-kv-compression (cpu/gpu) once #1 and #2 are updated.

@yatesdr

yatesdr commented Nov 29, 2026

Copy link
Copy Markdown
Collaborator

Following up with empirical measurements of all three items on NVIDIA GB10 (DGX Spark, ARM64 Cortex-X925, --release selene tests over real NVMe + io_uring + O_DIRECT) at cb3db468:

1. Per-poll() worker-thread stall on v4 packed records

Measuring Staged::poll() while all active fetches are healthy and at full 2/2 window credit (zero new windows can start):

v4 Packed Ancestor fetches = 1 (mean / p99) fetches = 8 (mean / p99) Slowdown
TP1, 512 pages (513 PackedUnits) 0.9 µs / 0.9 µs 1.47 ms / 2.23 ms 1,634×
TP8, 512 pages (4,104 PackedUnits) 0.4 µs / 0.6 µs 9.73 ms / 9.74 ms 24,335×
TP8, 1024 pages (8,200 PackedUnits) 0.4 µs / 0.4 µs 49.33 ms / 49.59 ms 123,325×

Every poll() on the Helios worker thread (and on each Peer::run loop) stalls for 1.5–49.3 ms doing wasted hashing while disk/GPU work is in flight.

2. DiskStore::inbound_rate vs worth_fetching() pricing

  • v4 packed (buffered ReadPacked + omitted decode/upload): Restoring a 128-page (33.6 MB raw / 414 KB compressed) v4 checkpoint with a 150 ms decode/upload delay took 166.1 ms wall time (202.5 MB/s effective), while PR Coalesce shared ancestor reads across concurrent Selene disk fetches #496 reported inbound_rate = 14,057.7 MB/s (69.4× inflation) and hit.estimated_seconds = 2.39 ms. Against a 100 ms prefill (worth_fetching threshold 50 ms), worth_fetching() returned true despite the real restore being slower than prefill.
  • Raw Sharded (omitted Open + upload + peer sync): Over a local TCP Sharded + Peer pair (with zero artificial peer read delay), a 128-page (2.1 MB) restore took 17.0 ms end-to-end (123.7 MB/s), while rank 0's inbound_rate reported 1,669.7 MB/s (13.5× inflation, hit.estimated_seconds = 1.26 ms).

3. Tight #497 pool (2 * (64 + row_slots)) skips shared ancestor and drops coalescing

With intake_slots(&layout, 1) = 130 slots (row_slots = 1) and a 3-window shared ancestor + 2 branches (1-page + row private tails):

  • Minor upload skew on W0 caused Job 1 to skip shared ancestor W2 (peer_demand = 1) and start its private child tail C1 (peer_demand = 0), dropping free_slots to 0.
  • Job 2 then read and swept W2 while Job 1's credits were occupied, forcing W2 to be re-read from disk (disk_window_reads = 6 vs 5 ideal; coalesced_windows = 2 vs 3 ideal).

Happy to re-run these checks and validate on GB10 once the fixes are pushed.

@flare-autobot flare-autobot added area:caching Prefix/KV reuse, cache retention, and model or payload cache behavior. area:selene Selene shared prefix-cache pool, protocol, manager, and transfers. performance Performance, latency, throughput, or memory-efficiency investigation or improvement. triage:review Proposed change needs code review; this does not imply merge readiness. labels Nov 29, 2026
Why

When concurrent requests restore distinct branch checkpoints sharing a
disk-resident ancestor prefix, Helios deduplicates inbound restore tickets by
endpoint key, so each branch submits its own GPU restore (`Staged::fetch`) in
`selene/src/disk_store.rs`. Before this change, each restore opened every
ancestor record file independently and staged private 64-page windows, repeating
`O_DIRECT` opens, reads, and checksum verification once per branch.

Published record files are immutable and stay pinned in `DiskStore` across every
referencing restore. Coalescing belongs in `Staged` rather than `DiskThread`
because `DiskThread` sees only file offsets and raw buffers and finishes once
direct I/O completes, whereas shared `SlabPool` staging slots and v4
`ReadPacked` payload buffers must remain pinned until every attached follower's
asynchronous `Copier` decode or GPU upload completes.

What

- Shared device-inbound state machine (`selene/src/disk_store.rs`,
  `selene/src/disk_store/coalesce.rs`):
  - Before: `Staged` ran every host and GPU inbound read through an isolated
    per-fetch `InboundRecord`, opening each segment and staging private 64-page
    windows independently.
  - After: caller-owned host reads (`Staged::read_into` using
    `plan_windows(..., false)` and `Staged::read_into_packed` storing
    `(Header, Arc<Vec<u8>>)` in `completed_packed_reads` for `CompositeStore`)
    stay on private `HostInbound`. Device fetches (`Staged::fetch`,
    `plan_windows(..., true)`) delegate to `DeviceCoalescer` in
    `selene/src/disk_store/coalesce.rs`, slicing on `WINDOW_PAGES` (64-page)
    file boundaries and sharing one open file handle per `SegmentKey` and one
    `SharedWindow` per `WindowKey` (`O(1)` `window_index` lookup) across both
    raw v1-v3 `SlabPool` staging windows and v4 `packed` `ReadPacked` buffers
    (which allocate zero `SlabPool` slots and retain `Arc<Vec<u8>>` until every
    follower's `Copier` decode and upload completes).
- Exhaustive `Header`/`packed::Layout` hashing with cached digest and lazy
  demand indexing (`selene/src/shared/packed.rs`, `selene/src/shared/record.rs`,
  `selene/src/disk_store/coalesce.rs`):
  - Before: `Header` and `packed::Layout` had no `Hash` implementation; hashing
    an entire `packed::Layout` (up to 8,200 `PackedUnit`s on TP8 1,024-page
    records) or eagerly rebuilding `demand` on full-credit `poll()` ticks
    would stall the worker thread.
  - After: `packed::Layout` implements `Eq` and exhaustive `Hash` over `Layout`,
    `PackedOffer`, and `PackedUnit`; `RankSizes` derives `Hash`; `Header`
    implements exhaustive `Hash` beside `PartialEq` (omitting only encoding
    `version`); `HeaderIdentity::new(Arc<Header>)` precomputes a deterministic
    `u64` digest once with `DefaultHasher::new()`, `HeaderIdentity::hash`
    hashes only that cached `u64`, and `HeaderIdentity::eq` short-circuits on
    digest mismatch and `Arc::ptr_eq` before comparing full `Header` values;
    and `start_new_windows` builds `demand` lazily only when a fetch holds free
    window credit and needs to start a new window (skipping demand indexing
    when at most one fetch is active).
- Tight-pool shared-ancestor holdback (`selene/src/disk_store/coalesce.rs`):
  - Before: skipping any unstarted plan whose `Layout::record_slots` exceeded
    currently free slots allowed a sibling on a tight `2 * (64 + row_slots)`
    pool to grab leftover slots for a small private tail instead of waiting for
    a 64-page shared ancestor window, fragmenting slots and forcing re-reads.
  - After: `pick_next_pending_plan` computes `reachable_free = free +
    self.staged_slots() + outbound_slots` and holds back lower-demand windows
    whenever a higher-`peer_demand` shared window fits within `reachable_free`.
    Because in-flight staged windows drain without allocating new slots,
    waiting never deadlocks when no staged slots can free or under external
    pool retention.
- End-to-end `DiskStore::inbound_rate` and per-fetch `bytes_in`
  (`selene/src/disk_store.rs`):
  - Before: `DiskStore::inbound_rate` observed every completed fetch's
    `(bytes, started.elapsed())`, which would let staggered coalesced followers
    riding pre-existing windows overstate bandwidth.
  - After: `StoreStats.bytes_in` continues counting per-fetch payload bytes
    restored across completed fetches (raw bytes for v1-v3 records and
    compressed payload bytes for v4 packed records, credited once per completed
    fetch including coalesced followers), while `StoreStats.inbound_rate`
    observes end-to-end uncompressed checkpoint bytes
    (`layout.record_bytes(chain.pages)`) over full fetch wall time (covering
    `Open`, slot queueing, disk read, codec decode, GPU upload, and all
    `Sharded` ranks) in the same units as `HostHit::estimated_seconds` and
    `worth_fetching()`. Restores submitted while an in-flight restore already
    reads a shared segment (`rode_preexisting`) skip `inbound_rate.started()`
    and observe `inbound_rate` only downward (when `(logical_bytes / elapsed) <
    inbound_rate.get()`), so fast coalesced followers never inflate bandwidth
    while continuous overlapping streams, mid-stream slowdowns, and bursts
    whose leader fails still push `inbound_rate` down without drifting to the
    3.0 GB/s seed, and slow disks can still recover upward when throughput
    improves. No `DiskTransport` or `shard.rs` rate-sampling plumbing and no
    `TransportEvent` change are added.
- Failure isolation and docs (`selene/src/disk_store/coalesce.rs`,
  `docs/prefix-cache-offload.md`): private child or transient follower GPU
  upload errors fail only that restore; shared open, read, or packed-payload
  content errors (`is_packed_content_error`, marked with `with_record_read()`)
  fail all attached restores after in-flight I/O drains so `DiskStore::apply`
  drops the corrupt endpoint's lookup row. The last user of a shared segment
  waits for disk close (`disk_settled`) before emitting `Fetched`, and
  `Staged::close` reports abandoned transport jobs separately from leaked
  shared staging entries. Diagnostic counters are gated under `test-support`,
  and `docs/prefix-cache-offload.md` (sections 2.4 and 4) documents raw and v4
  packed coalescing, tight-pool holdback, and end-to-end rate accounting. No
  core re-export, record format, wire protocol, or `TransportEvent` change is
  required.

Result

Overlapping GPU restores open a shared ancestor file once and read each aligned
64-page raw or v4 packed window once while staged (windows already released
before a later restore attaches are read again). As an expected bound,
single-restore callers skip demand indexing (`device_inbound.len() <= 1`) and
pay at most one extra partial window per segment when `skip_pages % 64 != 0`.

On x86_64 Linux (`--release` `selene` tests over `io_uring` + ext4, `rustc
1.100.0`, 1,000 full-credit polls), full-credit (2/2) `Staged::poll()` mean
latency with 8 concurrent v4 packed fetches drops from `1,354.937 us` ->
`0.693 us` (`1,955x`, p99 `0.701 us`, credit-regained demand pass `31.396 us`)
at TP1 512 pages (`513` `PackedUnit`s), `10,347.821 us` -> `0.664 us`
(`15,584x`, p99 `0.679 us`, demand pass `31.298 us`) at TP8 512 pages (`4,104`
`PackedUnit`s), and `44,447.427 us` -> `0.745 us` (`59,661x`, p99 `1.392 us`,
demand pass `39.897 us`) at TP8 1,024 pages (`8,200` `PackedUnit`s), with zero
demand rebuilds at full credit. Single-fetch full-credit mean latency stays at
`0.252-0.256 us` (`23.8-26.6 us` demand pass).

Live `flare run` A/B on NVIDIA GB10 (SM121) comparing `main` before v4 packed
records (`c0c4f798`) against `0c04b1e2` with `--lossless-kv-compression` off
and `--prefix-cache-memory 0 --prefix-cache-disk /tmp/selene-disk`
(`--max-concurrency 16 --prefix-cache-disk-limit 40G` on `Qwen3.8-27B-NVFP4`;
`--max-concurrency 8 --prefix-cache-disk-limit 24G` on `Qwen3.8-Flash-Next`).
Each trial warms one ~61K-token shared prefix plus 8 child branches (~256
unique tail tokens each) to disk, restarts `flare run` so GPU memory starts
empty, and sends 8 concurrent `/v1/chat/completions` follow-ups (ingress-to-
first-token TTFT; read-reduction ratios are ratios of tabulated means):
- `Qwen3.8-27B-NVFP4` (TP1, `60.5K`, 2 interleaved repeats): physical NVMe reads
  drop `18,177.5 -> 4,306.7 MB` (`2,274 MB` single restore — `472` pages at
  `128` tokens/page plus `101 MB` continuation row, so `18,177.5 MB` is `8x`
  full copies; `4.22x`, `-76.3%`), median TTFT `7,974.6 -> 5,662.8 ms`
  (`-29.0%`) simultaneous; and `18,194.2 -> 4,843.6 MB` (`3.76x`, `-73.4%`),
  TTFT `6,883.6 -> 5,951.9 ms` (`-13.5%`) at `+25 ms` stagger.
- `Qwen3.8-Flash-Next` (TP1, `61.0K`): NVMe reads drop `7,944.9 -> 1,981.1 MB`
  (`4.01x`, `-75.1%`, TTFT `3,327.5 -> 3,225.0 ms`) simultaneous, and `7,958.0 ->
  2,251.5 MB` (`3.53x`, `-71.7%`, TTFT `3,137.7 -> 3,049.9 ms`) at `+25 ms`
  stagger.

Recommended merge order with companion PR `NVIDIA#497` (Selene pipeline
prioritization and tighter `2 * (64 + row_slots)` intake pools): merge `NVIDIA#497`
first, then rebase `NVIDIA#496` onto `main` so `Staged::pump_all` retains
`MAINTENANCE_DEFER_LIMIT = 8` and runs `host_inbound` and `pump_device_inbound`
ahead of `outbound` and `maintenance`.

Evidence

- Verified on x86_64 Linux (`O_DIRECT` + `io_uring`, ext4, `rustc 1.100.0`) on
  the exact archived tree over `main` (`6d74db3a`; merges cleanly against
  `origin/main` `9031847a`):
  - `cargo check --locked --release --manifest-path selene/Cargo.toml
    --all-targets` (`0` warnings, with and without `test-support`).
  - `cargo test --locked --release --manifest-path selene/Cargo.toml --features
    test-support`: `522` lib + `1` `mixed_codec_root` passed, `0` failed,
    including `HeaderIdentity` cached-digest equality, full-credit large packed
    header `poll()` latency and zero-demand-rebuild verification (reproducible
    with `--lib
    poll_at_full_window_credit_with_large_packed_header_avoids_demand_rebuild_and_rehashing
    -- --nocapture`), end-to-end `inbound_rate` and `worth_fetching()` pricing
    on delayed v4 packed and multi-rank `Sharded` + `Peer` restores, staggered
    follower non-inflation, continuous overlapping shared-stream aging,
    mid-stream slowdown, and slow-to-fast upward recovery, leader private
    failure with slow follower rate update and `worth_fetching()` rejection,
    tight `2 * (64 + row_slots)` pool shared-ancestor holdback
    (`disk_window_reads == 5`, `coalesced_windows == 3`) and deadlock freedom
    under external pool retention and concurrent outbound stores, multi-rank
    `Sharded` + `Peer` coalescing, 4-way v4 packed coalescing and
    corrupt-packet `record_read` invalidation, misaligned follower
    partial-tail+row parity, private vs shared failure isolation, and
    `Staged::close` draining.
  - `cargo test --locked --release --manifest-path selene-manager/Cargo.toml
    --test client --test offload`: `85 + 2` passed, `0` failed.
  - `cargo check --locked --manifest-path helios/Cargo.toml --features
    runtime-core,server --all-targets`: passed (`0` warnings in touched crates).
  - `pytest tests/preparation/test_core_boundary.py
    tests/test_design_review_hook.py`: `22` passed, `0` failed.
- Prior SM121 GPU evidence at `0c04b1e2` against `main` before v4 packed
  records (`c0c4f798`, raw v3 records / `--lossless-kv-compression` off):
  `helios` `offload::` (`FLARE_RUN_CUDA_TESTS=1 --include-ignored`) passed all
  `21` single-GPU SM121 tests (`split_pools` requires 2 local GPUs); live SM121
  parity across 5 cold-VRAM restart repeats (`seed = 1234..1238`, `60,534`
  tokens, `top_logprobs = 5`) on `Qwen3.8-27B-NVFP4` TP1 produced identical FP32
  `top-5 logprobs` and token IDs vs `main` (`c0c4f798`) on all 5 repeats; and 4
  concurrent decode streams spilling checkpoints over 30 s on
  `Qwen3.8-Flash-Next` TP1 had `0` errors (`100.0 -> 100.6 tok/s`).
- Not covered: live SM121 `--lossless-kv-compression` (`cpu`/`gpu`) serving,
  post-fix SM121 `flare run` re-measurement, multi-host RoCE serving, 2-GPU
  `split_pools`, discrete PCIe GPUs, Windows serving, and live warm-plus-disk
  (`--prefix-cache-memory > 0`) or `PooledStore` HTTP serving (`CompositeStore`
  + `DiskStore` CUDA transfers are covered in `helios` `offload::`).

Discord: Dooner

Design-Signed-Off-By: Antigravity (Gemini 4 Neon); design-review=eb2f
Signed-off-by: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com>
@FujitsuPolycom
FujitsuPolycom force-pushed the selene-disk-ancestor-coalescing branch from cb3db46 to ba1c73f Compare November 29, 2026 04:04
FujitsuPolycom added a commit to FujitsuPolycom/flare-local-inference that referenced this pull request Nov 29, 2026
…head

Why

Disk-only prefix-cache offload (`--prefix-cache-memory 0` with
`--prefix-cache-disk`, default `--lossless-kv-compression off`) incurred five
host and coordination costs: (1) opening a raw v1-v3 record file
(`selene/src/disk.rs`) issued two sequential `O_DIRECT` reads (4 KiB header,
then page checksums); (2) `xxh3` page hashing ran serially on the single disk
thread across up to 64 pages (`268 MB` at `4.19 MB`/page); (3) `Staged::pump_all`
(`selene/src/disk_store.rs`) submitted unlinks/truncates and outbound writes
ahead of interactive restores; (4) while waiting on an inbound restore with an
idle GPU, Helios's worker (`helios/src/server/runtime.rs`) slept up to `2 ms`
and multi-host disk peers (`selene/src/shard.rs`) slept `1 ms` instead of waking
on socket readability; and (5) on integrated-memory GPUs
(`CU_DEVICE_ATTRIBUTE_INTEGRATED`), disk-only offload scaled registered host
intake with concurrency (`2 * max_active * row_slots + 128`, up to `8.2 GiB`
needed on `Qwen3.8-27B-NVFP4` at `--max-concurrency 16`), carving GPU KV cache
out of shared RAM even though paged disk streaming stages at most two windows
(`2 * (64 + row_slots)` slots).

What

- Single-read raw open (`selene/src/disk.rs`): preserve `NVIDIA#504`'s v4 packed
  `Header::read_metadata` open branch, and on raw v1-v3 `O_DIRECT` opens read
  the 4 KiB header and expected checksum segment in one transfer when
  `expected.tail_pages <= MAX_TAIL_PAGES` (`CHECKSUM_SCRATCH_BYTES = 1 MiB`),
  falling back to a 4 KiB header-only read on failure while preserving retry
  I/O errors, truncated-file checks, and shared scratch span helpers.
- Scoped parallel page hashing (`selene/src/disk.rs`): cache `parallel_cpus`
  once at `Worker::new` and hash raw batches of >= `HASH_PARALLEL_MIN_PAGES`
  (`4`) pages across `parallel_cpus.min(MAX_HASH_THREADS).min(buffers.len())`
  `std::thread::scope` threads (`MAX_HASH_THREADS = 4`) when `parallel_cpus >=
  HASH_PARALLEL_MIN_CPUS` (`4`), with `0` idle helper threads, Linux
  `SCHED_BATCH` inheritance via `clone`, inline recomputation on helper spawn
  or unwind failure, and fault hooks folded into `Faults` under
  `cfg(any(test, feature = "test-support"))` (zero test-only parameters on
  shipped signatures).
- Bounded restore-first submission and wakeup (`disk_store.rs`,
  `helios/src/server/runtime.rs`, `shard.rs`): order `Staged::pump_all` as
  inbound restores, then outbound writes, then maintenance while submitting one
  reserved maintenance job ahead of inbound and outbound after
  `MAINTENANCE_DEFER_LIMIT` (`8`) consecutive passes where queued maintenance
  lost free disk-queue space; poll `Worker::idle_wait` at `50 us` during
  active/waiting inbound restores; and wake Unix disk peers via `libc::poll`
  (`POLLIN`).
- Bounded integrated disk-only intake & `NVIDIA#589` unified-memory budget integration
  (`selene/src/offload.rs`, `helios/src/offload/mod.rs`,
  `helios/src/runtime_core/{memory,model}.rs`, `docs/prefix-cache-offload.md`):
  pass explicit `PrepareInputs` (`max_active`, `input_staging`, `shard`,
  `integrated`) into `headroom_with_inputs`, `headroom_with_inputs_for_budget`,
  `prepare_with_inputs`, and `prepare_with_inputs_budget` (deleting unused
  `prepare` and dead `core: &Path`), unify `disk_enabled()`, `headroom_inner`,
  private `target_intake_slots`, and parameterless `Prepared::intake_warning()`
  (`required_intake` + `sized_concurrency`), preserve `options.pool_only()` so a
  degraded disk directory under `--prefix-cache-pool --prefix-cache-memory 0`
  remains restore-only against `NVIDIA#589`'s `planned_offload_host`, and target
  `intake_slots(layout, 1)` (`2 * (64 + row_slots)`) on integrated disk-only
  hosts without shrink warnings across `NVIDIA#589`'s small-SoC headroom scaling,
  explicit `--memory-limit` budgets, pre-planned post-KV `planned_offload_host`,
  and `HOST_NUMA` split-mapping fallback while preserving `NVIDIA#504` lossless KV
  compression. No core re-export or record-format change is required.

Result

Live `flare run` A/B on NVIDIA GB10 (SM121) measured `NVIDIA#497` standalone
(`cd5a366b`) against pre-`NVIDIA#504` `main` (`c0c4f798`) with `--prefix-cache-memory
0 --prefix-cache-disk /tmp/selene-disk` and default `--lossless-kv-compression
off` (the raw v3 `.ckpt` path, whose default GB10 disk-only execution is
unchanged by rebasing onto `ba3afb13` / `NVIDIA#589` because GB10 128 GiB exceeds the
16 GiB small-SoC threshold and disk-only intake targets the same two-window
floor; ingress-to-first-token TTFT; bandwidth is rank-0
`flare_host_cache_inbound_bytes_per_second`):
- `Qwen3.8-27B-NVFP4` (TP1, `--max-concurrency 16 --prefix-cache-disk-limit
  40G`, 3 interleaved repeats): intake drops `7.3 GiB` (`1,877` slots, shrink
  warning) -> `1.0 GiB` (`252` slots, `0` warnings), raising GPU KV cache `64.4
  -> 71.6 GiB` (`+7.2 GiB` / `+235.5K` tokens); median single-restore bandwidth
  and TTFT improve `7.05 -> 8.02 GB/s` (`348.0 -> 301.7 ms`, `-13.3%`; wall
  `353.5 -> 306.5 ms`) at `30.0K` and `6.28 -> 8.68 GB/s` (`+38.2%`, `551.8 ->
  447.6 ms`, `-18.9%`; wall `561.7 -> 455.4 ms`) at `61.1K`; `NVIDIA#497` standalone
  8-way `61.1K` cold-restart burst mean median TTFT drops `8,156.1 -> 6,963.4
  ms` (`-14.6%`, 2 interleaved repeats; combining this change with concurrent
  ancestor-restore read coalescing in companion PR `NVIDIA#496` is unmeasured).
- Isolated `std::thread::scope` `xxh3` (`cd5a366b` with `MAX_HASH_THREADS = 1`
  at `selene/src/disk.rs:157` and no other change vs unmodified `cd5a366b` with
  `MAX_HASH_THREADS = 4`, 3 interleaved repeats on `Qwen3.8-27B-NVFP4`):
  parallel hashing alone improves median TTFT `486.8 -> 447.6 ms` (`-8.1%`,
  `7.73 -> 8.68 GB/s`, `+12.3%`, faster on all 3 repeats: `[447.6, 432.7,
  451.2]` vs `[479.9, 557.5, 486.8] ms`) at `61.1K` and `322.4 -> 301.7 ms`
  (`7.55 -> 8.02 GB/s`) at `30.0K`. `HASH_PARALLEL_MIN_PAGES = 4` and
  `HASH_PARALLEL_MIN_CPUS = 4` assign at least one page per thread at the
  4-thread cap and leave cores for serving threads on narrow hosts (not swept
  separately).
- `Qwen3.8-Flash-Next` (TP1, `--max-concurrency 8 --prefix-cache-disk-limit
  24G`, `cd5a366b` vs `c0c4f798`): intake drops `1.9 -> 0.3 GiB` (`2,288 -> 398`
  slots), raising GPU KV cache `23.28 -> 24.98 GiB` (`+1.70 GiB` / `+127.0K`
  tokens); bandwidth improves `5.67 -> 7.05 GB/s` (`372.1 -> 355.6 ms`) at
  `30.0K` and `6.65 -> 8.35 GB/s` (`+25.6%`, `458.0 -> 413.8 ms`, `-9.7%`) at
  `61.0K`; `NVIDIA#497` standalone 8-way burst median TTFT drops `3,327.5 -> 3,078.5
  ms` (`-7.5%`).
- Expected interaction with `NVIDIA#589` (`ba3afb13`): on unified-memory GPUs with an
  explicit `--memory-limit`, disk-only intake remains bounded at
  `intake_slots(layout, 1)` so unlocked unified RAM expands GPU KV cache rather
  than concurrency-scaled staging, while warm+disk (`--prefix-cache-memory > 0`)
  and pool-only capture retain `NVIDIA#589`'s pre-planned host budget and small-SoC
  scaling.

What it costs: up to three short-lived scoped `xxh3` helpers during >=4-page
raw batches (`0` idle helpers), `50 us` `Worker::idle_wait` polling during
active/waiting inbound restores (`969.9 -> 1,069.2 ms/s` `/proc/<pid>/stat`
server CPU across 8-way `Qwen3.8-27B-NVFP4` bursts: `+99.3 ms/s` / ~`0.10` of
20 Grace cores combined; the `50 us` poll's CPU share and latency contribution
are unisolated from scoped `xxh3` helpers), two-window serialization for
concurrent unique-prefix restores and outbound stores on integrated disk-only
hosts, and up to `8` passes of maintenance deferral.

Companion PR (NVIDIA#496, concurrent ancestor-restore open and window coalescing):
merge `NVIDIA#497` first, then rebase `NVIDIA#496` onto `main` so `Staged::pump_all` retains
`MAINTENANCE_DEFER_LIMIT = 8` (submitting one reserved maintenance job first
after `8` deferred passes) and runs `NVIDIA#496`'s private `host_inbound` and shared
`pump_device_inbound` queues ahead of `outbound` and `maintenance`.

Evidence

- Rebased crate and Python checks over `origin/main` (`ba3afb13`, `NVIDIA#589`) on
  x86_64 Linux (`O_DIRECT` + `io_uring`): `selene --features test-support`
  (`514` lib + `1` `mixed_codec_root` integration passed, `0` warnings; also
  `cargo check --release` without `test-support`, `0` warnings), `selene-manager
  --features test-support --test client --test offload` (`85 + 2` passed, `0`
  warnings), `helios --features runtime-core,server --lib -- offload::
  runtime_core::memory::tests runtime_core::model::tests
  server::runtime::phase_tests` (`144` passed, `14` GPU-only ignored, `0`
  warnings in touched files, covering `NVIDIA#497` + `NVIDIA#589` small-SoC,
  `--memory-limit`, and degraded-disk restore-only pool coexistence), and
  `pytest tests/preparation/test_core_boundary.py
  tests/test_design_review_hook.py` (`22` passed).
- Prior SM121 GPU unit and live checks (at `cd5a366b`, `--lossless-kv-compression
  off`): `helios` `offload::` (`FLARE_RUN_CUDA_TESTS=1 --include-ignored`, `21`
  single-GPU SM121 tests passed; `split_pools` requires 2 local GPUs);
  corrupting a multi-page `.ckpt` payload on `Qwen3.8-27B-NVFP4` incremented
  `fetch_failed_total` (`1`), launched `0` `restore` graphs, and recomputed
  identical `top-5 logprobs` and tokens; under `--prefix-cache-disk-limit 6G`
  (`4` concurrent restores + `3` fresh `30K` stores), disk bytes peaked at
  `6.38 GB` (`<= 6 GiB`) and settled at `6.37 GB` with `0` `retry_abandoned`
  and `0` `io_error` drops (`2` normal `end_of_chain` evictions); four
  concurrent decode streams spilling checkpoints over 30 s on
  `Qwen3.8-Flash-Next` had `0` errors (`100.0 -> 95.9 tok/s`).
- Not covered: live `--lossless-kv-compression` (`cpu`/`gpu`) serving,
  post-rebase SM121 `flare run` re-measurement, live Jetson Orin GA10B /
  `--memory-limit` GPU serving, isolated `50 us` `Worker::idle_wait` A/B,
  `NVIDIA#496 + NVIDIA#497` combined serving, multi-host RoCE serving, 2-GPU `split_pools`,
  discrete PCIe GPUs, Windows serving, and live warm-plus-disk
  (`--prefix-cache-memory > 0`) or `PooledStore` HTTP serving (`CompositeStore`
  + `DiskStore` CUDA transfers were covered at `cd5a366b` in `helios`
  `offload::`).

Discord: Dooner

Design-Signed-Off-By: Antigravity (Gemini 4); design-review=c3a9
Signed-off-by: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com>
@FujitsuPolycom

Copy link
Copy Markdown
Contributor Author

@yatesdr Thank you for the detailed review, the empirical GB10 trial, and the confirmation on keeping coalescing in Staged. I updated the branch to ba1c73fd6c0b0d08c612dd947ed47ceaee8ce457 (atop 6d74db3a, merging cleanly with origin/main 9031847a) to address all three blockers, extract the state machine into a private submodule, and add the requested Sharded and tight-pool unit tests.

1. Per-poll() worker-thread CPU stall on v4 packed records

  • Fix (selene/src/disk_store/coalesce.rs):
    • HeaderIdentity::new(Arc<Header>) now precomputes a deterministic u64 digest once with DefaultHasher::new(). HeaderIdentity::hash hashes only that cached u64, and HeaderIdentity::eq short-circuits on self.hash == other.hash && (Arc::ptr_eq(&self.header, &other.header) || *self.header == *other.header).
    • Deleted the eager build_pending_demand() pass before the credit loop; start_new_windows initializes let mut demand = None; and populates it lazily inside while self.has_window_credit(id) only when a fetch needs to start a new window (and skips demand indexing when device_inbound.len() <= 1).
  • Tests & --release micro-benchmark (ba1c73fd vs cb3db468, x86_64 Linux io_uring + ext4, rustc 1.100.0, 1,000 full-credit poll() ticks):
    • Added header_identity_caches_digest_and_matches_header_equality and poll_at_full_window_credit_with_large_packed_header_avoids_demand_rebuild_and_rehashing (asserting demand_builds stays unchanged across all 1,000 full-credit polls; reproducible via --lib poll_at_full_window_credit_with_large_packed_header_avoids_demand_rebuild_and_rehashing -- --nocapture):
Shape (PackedUnits) Concurrent Fetches Before Mean / p99 (cb3db468) After Mean / p99 (ba1c73fd) Speedup (Mean) Credit-Regained Demand Pass (ba1c73fd)
TP1, 512 pages (513) 1 0.283 µs / 0.323 µs 0.252 µs / 0.274 µs 1.12x 26.642 µs
TP1, 512 pages (513) 8 1,354.937 µs / 1,561.375 µs 0.693 µs / 0.701 µs 1,955x 31.396 µs
TP8, 512 pages (4,104) 1 0.278 µs / 1.507 µs 0.256 µs / 0.274 µs 1.09x 23.816 µs
TP8, 512 pages (4,104) 8 10,347.821 µs / 11,234.217 µs 0.664 µs / 0.679 µs 15,584x 31.298 µs
TP8, 1,024 pages (8,200) 1 0.310 µs / 1.361 µs 0.253 µs / 0.274 µs 1.23x 25.612 µs
TP8, 1,024 pages (8,200) 8 44,447.427 µs / 48,825.259 µs 0.745 µs / 1.392 µs 59,661x 39.897 µs

2. End-to-end DiskStore::inbound_rate (v4 packed and Sharded inflation)

  • Fix (selene/src/disk_store.rs, selene/src/shard.rs, docs/prefix-cache-offload.md):
    • Removed DiskTransport::drain_inbound_samples, Staged::inbound_samples, DiskStore::observe_inbound_samples, Sharded::drain_inbound_samples, and Peer::forward sample discarding (selene/src/shard.rs is back to 0 diff against main).
    • Restored end-to-end DiskStore::inbound_rate on Inbound: DiskStore::fetch captures started = Instant::now() before self.transport.fetch(...), records read_nodes (segments with pages > 0 || row) and logical_bytes = self.layout.record_bytes(chain.pages as u64) (uncompressed checkpoint bytes matching HostHit::bytes and HostHit::estimated_seconds = bytes / inbound_rate.get() for both raw and v4 packed records), and marks rode_preexisting when any currently in-flight Inbound shares a node in read_nodes.
    • Restores with rode_preexisting == true skip self.inbound_rate.started() and observe self.inbound_rate downward only ((job.logical_bytes as f64 / elapsed.as_secs_f64()) < self.inbound_rate.get()). Fast coalesced followers riding pre-existing staged windows never inflate bandwidth; continuous overlapping streams, mid-stream slowdowns, and bursts whose leader fails still push inbound_rate down without letting Rate::get() drift upward to the 3.0 GB/s seed; and keeping started() skipped on rode_preexisting preserves normal 2x / 10 s upward recovery when a slow disk recovers during overlapping traffic.
    • StoreStats.bytes_in continues counting per-fetch payload bytes restored across completed fetches (raw bytes for v1–v3 records and compressed payload bytes for v4 packed records, credited once per completed fetch including coalesced followers). Updated docs/prefix-cache-offload.md §4 to match CompositeStore::disk_inbound_rate and document both metrics accurately.
  • Tests (selene/src/disk_store/coalesce/tests.rs):
    • packed_restore_inbound_rate_includes_decode_delay_and_worth_fetching_rejects: 128 × 256 KiB logical v4 packed restore with a 150 ms DelayedCopier yields end-to-end ~200 MB/s, estimated_seconds >= 0.14, and worth_fetching() rejects against a 100 ms prefill.
    • sharded_inbound_rate_reflects_end_to_end_multi_rank_wall_time: local-TCP Sharded + Peer with an 80 ms delay on Peer rank 1 reflects full multi-rank wall time (estimated_seconds >= 0.075) and rejects against a 100 ms prefill.
    • coalesced_restores_keep_inbound_rate_end_to_end_and_bytes_in_logical: verifies end-to-end rate with an 80 ms upload hold and confirms simultaneous and staggered late followers riding pre-existing windows do not inflate inbound_rate while bytes_in credits per-fetch payload bytes.
    • overlapping_shared_stream_tracks_slowdown_and_recovers_without_drift: verifies continuous daisy-chained overlapping restores (rode_preexisting = true) prevent upward drift to 3.0 GB/s after aging inbound_rate, track mid-stream slowdowns (worth_fetching() rejects), prevent fast coalesced followers from inflating inbound_rate, and preserve 2x / 10 s upward recovery when throughput improves.
    • leader_private_failure_with_slow_follower_updates_inbound_rate_and_rejects: corrupts only the leader's private child on a cold DiskStore while a slow coalesced follower (150 ms) succeeds, verifying inbound_rate drops from 3.0 GB/s and worth_fetching() rejects against a 100 ms prefill.

3. Shared-ancestor holdback on tight 2 * (64 + row_slots) intake pools

  • Fix (selene/src/disk_store/coalesce.rs, selene/src/disk_store.rs, docs/prefix-cache-offload.md):
    • pick_next_pending_plan now computes reachable_free = free + self.staged_slots() + outbound_slots and tracks max_reachable_shared_demand across unstarted plans with peer_demand > 0 && needed <= reachable_free. It returns a fitting lower-demand plan only when best_demand >= max_reachable_shared_demand; otherwise it returns None and waits for in-flight staged slots to drain.
    • Because staged_slots + outbound_slots belong to in-flight windows that complete without allocating new slots—and when staged_slots + outbound_slots == 0, reachable_free == free—holding back never deadlocks, including under external warm-slot retention (CompositeStore / MemoryStore).
    • Documented this rule in docs/prefix-cache-offload.md §2.4.
  • Tests (selene/src/disk_store/coalesce/tests.rs):
    • tight_pool_waits_for_shared_ancestor_instead_of_starting_private_tail: exercises both row_slots = 1 (130-slot pool, 1-page + row private tails) and row_slots = 8 (144-slot pool, 4-page + row private tails) under W0 upload skew, verifying Job 1 waits instead of starting private C1, final disk_opens == 3, disk_window_reads == 5, coalesced_windows == 3, and byte-exact GPU pages/rows.
    • tight_pool_wait_never_deadlocks_without_releasable_staged_slots: covers both external retention holding 120/130 slots (staged_slots + outbound_slots == 0, private tails still make progress and the shared ancestor coalesces once slots release) and a concurrent 65-slot outbound store alongside two tight-pool shared-ancestor fetches on a 130-slot pool (coalesced_windows == 2, zero deadlock).

4. Submodule extraction, Sharded coalescing coverage, and verification

  • Extracted the device-inbound coalescing state machine out of selene/src/disk_store.rs (10,856 -> 8,062 lines) into selene/src/disk_store/coalesce.rs (1,416 lines) and selene/src/disk_store/coalesce/tests.rs (3,217 lines), breaking DeviceCoalescer::pump into 9 single-purpose pass methods (reap_completed_uploads, detach_unwinding_windows, attach_existing_windows, sweep_shared_windows, start_new_windows, submit_pending_reads, submit_pending_uploads, close_idle_segments, complete_finished_fetches).
  • Added sharded_concurrent_fetches_coalesce_across_rank_zero_and_peer: runs local-TCP Sharded + Peer via production shard::serve with 4 concurrent branches sharing a 3-window ancestor, confirming coalescing on Rank 0 (disk_opens == 5, disk_window_reads == 7, coalesced_windows == 9), simultaneous live slab-address sharing on Peer Rank 1 via CoalesceProbeCopier, and byte-exact GPU pages/rows on both ranks.
  • Verified on exact git archive ba1c73fd6c0b0d08c612dd947ed47ceaee8ce457 (x86_64 Linux O_DIRECT + io_uring, ext4, rustc 1.100.0):
    • cargo check --locked --release --manifest-path selene/Cargo.toml --all-targets (0 warnings with and without test-support)
    • cargo test --locked --release --manifest-path selene/Cargo.toml --features test-support: 522 lib + 1 mixed_codec_root passed, 0 failed, 0 ignored
    • cargo test --locked --release --manifest-path selene-manager/Cargo.toml --test client --test offload: 85 + 2 passed, 0 failed, 0 warnings
    • cargo check --locked --manifest-path helios/Cargo.toml --features runtime-core,server --all-targets: passed (0 warnings in touched crates)
    • pytest tests/preparation/test_core_boundary.py tests/test_design_review_hook.py: 22 passed, 0 failed
    • git merge-tree --write-tree 9031847aacbc0037ac54c3ef854083c43b34124a ba1c73fd6c0b0d08c612dd947ed47ceaee8ce457: clean (exit=0)

Remaining limits

  • I have not yet re-run live SM121 flare run measurements on ba1c73fd (or live SM121 --lossless-kv-compression cpu/gpu serving, multi-host RoCE, 2-GPU split_pools, discrete PCIe GPUs, Windows serving, or warm+disk / PooledStore HTTP serving); the live SM121 A/B and parity numbers in the PR body remain explicitly scoped to 0c04b1e2 against main before v4 packed records (c0c4f798). A combined merge test with companion PR #497 (ca863852) was last run at 54c70eca (prior to the 6-line downward-only rate observation guard in DiskStore::apply, which does not touch Staged::pump_all).

I have updated the PR description as well so it stands on its own. Could you please take another look at ba1c73fd6c0b0d08c612dd947ed47ceaee8ce457?

@flare-autobot flare-autobot added triage:validation Proposed implementation needs acceptance evidence; no claim that a reported defect is fixed. and removed triage:review Proposed change needs code review; this does not imply merge readiness. labels Nov 29, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Ready To Merge

All three empirical GB10 blockers from the 2026-11-29 review (cb3db468) are cleanly fixed at ba1c73fd, with zero new correctness, concurrency, or safety defects found across the full coalesce.rs state machine and disk_store.rs diff. The Staged-layer boundary is signed off by @yatesdr and unit coverage now exercises v4 packed decode-delay pricing, local-TCP Sharded + Peer coalescing, and tight-pool holdback — but run the requested live GB10 serving check at ba1c73fd before pressing merge.

  • Blockers: 0 · Should fix: 1 · Subtract/Simplify: 3 · Nits: 1
Walkthrough
  • selene/src/disk_store/coalesce.rs (new, +1,416): DeviceCoalescer with HeaderIdentity (cached u64 digest + Arc::ptr_eq fast path), SegmentKey interning in acquire_shared_segment, O(1) WindowKey lookup via window_index, lazy build_pending_demand (skipped when device_inbound.len() <= 1 or no fetch has window credit), tight-pool holdback in pick_next_pending_plan (reachable_free = free + staged_slots + outbound_slots), shared-vs-private failure isolation, and 9 focused passes in pump.
  • selene/src/disk_store.rs (+337/−288): Narrows InboundRecord to private HostInbound (HostDestination::{Slots, Packed}), delegates Staged::fetch to DeviceCoalescer with plan_windows(..., true) file-boundary alignment, removes all out-of-band InboundWindowSample plumbing, and restores end-to-end DiskStore::inbound_rate (logical_bytes = layout.record_bytes(chain.pages)) with a rode_preexisting downward-only guard (:3242-3251, 3422-3455).
  • selene/src/shared/packed.rs (+44) & selene/src/shared/record.rs (+119/−1): Derive Eq/exhaustive Hash on packed::Layout (PackedOffer, PackedUnit, offsets, pages) and Header (matching PartialEq, omitting encoding version), derive Hash on RankSizes, and add header_eq_implies_same_hash for v4 packed headers.
  • selene/src/disk_store/coalesce/tests.rs (new, +3,217): 19 tests covering HeaderIdentity caching and full-credit poll() CPU cost across TP1/TP8 512–1024-page packed headers, aligned/misaligned coalescing, private-vs-shared failure isolation, end-to-end inbound_rate, local-TCP Sharded + Peer coalescing, tight 2 * (64 + row_slots) pool holdback and deadlock freedom, and 4-way v4 packed coalescing.
  • docs/prefix-cache-offload.md (+48/−2): Updates §2.4 (:418-449) with current host/device signatures, WINDOW_PAGES alignment, index-pin/close-before-Fetched invariant, tight-pool holdback, and failure/coalescing limits; §4 (:1613-1627) documents end-to-end inbound_rate, rode_preexisting, per-fetch bytes_in, and CompositeStore::disk_inbound_rate.
Merge Risk: Medium · up to ba1c73fd
  • Replaces Staged's device-inbound restore path (selene/src/disk_store.rs) with a 1,416-line DeviceCoalescer state machine coordinating shared file handles, SlabPool staging windows, and v4 packed Arc<Vec<u8>> payload buffers across concurrent fetches and async Copier uploads.
  • Live SM121/GB10 serving at ba1c73fd — specifically --lossless-kv-compression cpu|gpu — has not been re-run (served A/B numbers remain from 0c04b1e2 against pre-v4 main c0c4f798), and companion PR #497 also edits Staged::pump_all (merge #497 first, then rebase #496).
  • Risk is well-contained: zero unsafe blocks, record formats / wire protocols / TransportEvent / FetchSegment / selene/src/shard.rs unchanged, private failures isolated from shared record_read failures, and Fetched waits for disk_settled() on the last segment user; referenced packed buffers leak only if transfers.close() times out (disk_store.rs:2006-2008, coalesce.rs:313-319).
Pre-merge checks: ✅ 2 passed · ⚠️ 2 warnings
  • ✅ Security / malicious screen: No prompt injection, external network exfiltration, or unsafe code introduced (coalesce.rs has zero unsafe blocks; all changed files inspected).
  • ✅ Charter & value fit: Directly removes redundant NVMe opens/reads/checksums on concurrent shared-prefix restores in the right layer (Staged, signed off by @yatesdr) with no model-specific branches, flags, or format/wire changes.
  • ⚠️ Related / duplicate / conflict check: No duplicate PR; cleanly preserves merged #504/#523/#524 v4 packed paths, but companion PR #497 (ca863852) also edits Staged::pump_all in selene/src/disk_store.rs — merge #497 first and rebase #496 so MAINTENANCE_DEFER_LIMIT = 8 and restore-first ordering are preserved.
  • ⚠️ Tests & verification evidence: Unit/TCP Sharded suite (522 selene lib + 1 mixed_codec_root, 85 + 2 selene-manager, helios check, 22 pytest) and the full-credit poll() microbenchmark (0.25–0.75 µs) are fresh at ba1c73fd, but live SM121/GB10 serving validation at ba1c73fd — including --lossless-kv-compression cpu|gpu requested in @yatesdr's review — is not yet run (disclosed in Not covered).

Have your agent review the Full Review for complete verified findings, file:line citations, and suggested changes.

To opt out, include #autobot:ignore in your post or comment.

yatesdr pushed a commit that referenced this pull request Nov 29, 2026
…head (#497)

Why

Disk-only prefix-cache offload (`--prefix-cache-memory 0` with
`--prefix-cache-disk`, default `--lossless-kv-compression off`) incurred five
host and coordination costs: (1) opening a raw v1-v3 record file
(`selene/src/disk.rs`) issued two sequential `O_DIRECT` reads (4 KiB header,
then page checksums); (2) `xxh3` page hashing ran serially on the single disk
thread across up to 64 pages (`268 MB` at `4.19 MB`/page); (3) `Staged::pump_all`
(`selene/src/disk_store.rs`) submitted unlinks/truncates and outbound writes
ahead of interactive restores; (4) while waiting on an inbound restore with an
idle GPU, Helios's worker (`helios/src/server/runtime.rs`) slept up to `2 ms`
and multi-host disk peers (`selene/src/shard.rs`) slept `1 ms` instead of waking
on socket readability; and (5) on integrated-memory GPUs
(`CU_DEVICE_ATTRIBUTE_INTEGRATED`), disk-only offload scaled registered host
intake with concurrency (`2 * max_active * row_slots + 128`, up to `8.2 GiB`
needed on `Qwen3.8-27B-NVFP4` at `--max-concurrency 16`), carving GPU KV cache
out of shared RAM even though paged disk streaming stages at most two windows
(`2 * (64 + row_slots)` slots).

What

- Single-read raw open (`selene/src/disk.rs`): preserve `#504`'s v4 packed
  `Header::read_metadata` open branch, and on raw v1-v3 `O_DIRECT` opens read
  the 4 KiB header and expected checksum segment in one transfer when
  `expected.tail_pages <= MAX_TAIL_PAGES` (`CHECKSUM_SCRATCH_BYTES = 1 MiB`),
  falling back to a 4 KiB header-only read on failure while preserving retry
  I/O errors, truncated-file checks, and shared scratch span helpers.
- Scoped parallel page hashing (`selene/src/disk.rs`): cache `parallel_cpus`
  once at `Worker::new` and hash raw batches of >= `HASH_PARALLEL_MIN_PAGES`
  (`4`) pages across `parallel_cpus.min(MAX_HASH_THREADS).min(buffers.len())`
  `std::thread::scope` threads (`MAX_HASH_THREADS = 4`) when `parallel_cpus >=
  HASH_PARALLEL_MIN_CPUS` (`4`), with `0` idle helper threads, Linux
  `SCHED_BATCH` inheritance via `clone`, inline recomputation on helper spawn
  or unwind failure, and fault hooks folded into `Faults` under
  `cfg(any(test, feature = "test-support"))` (zero test-only parameters on
  shipped signatures).
- Bounded restore-first submission and wakeup (`disk_store.rs`,
  `helios/src/server/runtime.rs`, `shard.rs`): order `Staged::pump_all` as
  inbound restores, then outbound writes, then maintenance while submitting one
  reserved maintenance job ahead of inbound and outbound after
  `MAINTENANCE_DEFER_LIMIT` (`8`) consecutive passes where queued maintenance
  lost free disk-queue space; poll `Worker::idle_wait` at `50 us` during
  active/waiting inbound restores; and wake Unix disk peers via `libc::poll`
  (`POLLIN`).
- Bounded integrated disk-only intake & `#589` unified-memory budget integration
  (`selene/src/offload.rs`, `helios/src/offload/mod.rs`,
  `helios/src/runtime_core/{memory,model}.rs`, `docs/prefix-cache-offload.md`):
  pass explicit `PrepareInputs` (`max_active`, `input_staging`, `shard`,
  `integrated`) into `headroom_with_inputs`, `headroom_with_inputs_for_budget`,
  `prepare_with_inputs`, and `prepare_with_inputs_budget` (deleting unused
  `prepare` and dead `core: &Path`), unify `disk_enabled()`, `headroom_inner`,
  private `target_intake_slots`, and parameterless `Prepared::intake_warning()`
  (`required_intake` + `sized_concurrency`), preserve `options.pool_only()` so a
  degraded disk directory under `--prefix-cache-pool --prefix-cache-memory 0`
  remains restore-only against `#589`'s `planned_offload_host`, and target
  `intake_slots(layout, 1)` (`2 * (64 + row_slots)`) on integrated disk-only
  hosts without shrink warnings across `#589`'s small-SoC headroom scaling,
  explicit `--memory-limit` budgets, pre-planned post-KV `planned_offload_host`,
  and `HOST_NUMA` split-mapping fallback while preserving `#504` lossless KV
  compression. No core re-export or record-format change is required.

Result

Live `flare run` A/B on NVIDIA GB10 (SM121) measured `#497` standalone
(`cd5a366b`) against pre-`#504` `main` (`c0c4f798`) with `--prefix-cache-memory
0 --prefix-cache-disk /tmp/selene-disk` and default `--lossless-kv-compression
off` (the raw v3 `.ckpt` path, whose default GB10 disk-only execution is
unchanged by rebasing onto `ba3afb13` / `#589` because GB10 128 GiB exceeds the
16 GiB small-SoC threshold and disk-only intake targets the same two-window
floor; ingress-to-first-token TTFT; bandwidth is rank-0
`flare_host_cache_inbound_bytes_per_second`):
- `Qwen3.8-27B-NVFP4` (TP1, `--max-concurrency 16 --prefix-cache-disk-limit
  40G`, 3 interleaved repeats): intake drops `7.3 GiB` (`1,877` slots, shrink
  warning) -> `1.0 GiB` (`252` slots, `0` warnings), raising GPU KV cache `64.4
  -> 71.6 GiB` (`+7.2 GiB` / `+235.5K` tokens); median single-restore bandwidth
  and TTFT improve `7.05 -> 8.02 GB/s` (`348.0 -> 301.7 ms`, `-13.3%`; wall
  `353.5 -> 306.5 ms`) at `30.0K` and `6.28 -> 8.68 GB/s` (`+38.2%`, `551.8 ->
  447.6 ms`, `-18.9%`; wall `561.7 -> 455.4 ms`) at `61.1K`; `#497` standalone
  8-way `61.1K` cold-restart burst mean median TTFT drops `8,156.1 -> 6,963.4
  ms` (`-14.6%`, 2 interleaved repeats; combining this change with concurrent
  ancestor-restore read coalescing in companion PR `#496` is unmeasured).
- Isolated `std::thread::scope` `xxh3` (`cd5a366b` with `MAX_HASH_THREADS = 1`
  at `selene/src/disk.rs:157` and no other change vs unmodified `cd5a366b` with
  `MAX_HASH_THREADS = 4`, 3 interleaved repeats on `Qwen3.8-27B-NVFP4`):
  parallel hashing alone improves median TTFT `486.8 -> 447.6 ms` (`-8.1%`,
  `7.73 -> 8.68 GB/s`, `+12.3%`, faster on all 3 repeats: `[447.6, 432.7,
  451.2]` vs `[479.9, 557.5, 486.8] ms`) at `61.1K` and `322.4 -> 301.7 ms`
  (`7.55 -> 8.02 GB/s`) at `30.0K`. `HASH_PARALLEL_MIN_PAGES = 4` and
  `HASH_PARALLEL_MIN_CPUS = 4` assign at least one page per thread at the
  4-thread cap and leave cores for serving threads on narrow hosts (not swept
  separately).
- `Qwen3.8-Flash-Next` (TP1, `--max-concurrency 8 --prefix-cache-disk-limit
  24G`, `cd5a366b` vs `c0c4f798`): intake drops `1.9 -> 0.3 GiB` (`2,288 -> 398`
  slots), raising GPU KV cache `23.28 -> 24.98 GiB` (`+1.70 GiB` / `+127.0K`
  tokens); bandwidth improves `5.67 -> 7.05 GB/s` (`372.1 -> 355.6 ms`) at
  `30.0K` and `6.65 -> 8.35 GB/s` (`+25.6%`, `458.0 -> 413.8 ms`, `-9.7%`) at
  `61.0K`; `#497` standalone 8-way burst median TTFT drops `3,327.5 -> 3,078.5
  ms` (`-7.5%`).
- Expected interaction with `#589` (`ba3afb13`): on unified-memory GPUs with an
  explicit `--memory-limit`, disk-only intake remains bounded at
  `intake_slots(layout, 1)` so unlocked unified RAM expands GPU KV cache rather
  than concurrency-scaled staging, while warm+disk (`--prefix-cache-memory > 0`)
  and pool-only capture retain `#589`'s pre-planned host budget and small-SoC
  scaling.

What it costs: up to three short-lived scoped `xxh3` helpers during >=4-page
raw batches (`0` idle helpers), `50 us` `Worker::idle_wait` polling during
active/waiting inbound restores (`969.9 -> 1,069.2 ms/s` `/proc/<pid>/stat`
server CPU across 8-way `Qwen3.8-27B-NVFP4` bursts: `+99.3 ms/s` / ~`0.10` of
20 Grace cores combined; the `50 us` poll's CPU share and latency contribution
are unisolated from scoped `xxh3` helpers), two-window serialization for
concurrent unique-prefix restores and outbound stores on integrated disk-only
hosts, and up to `8` passes of maintenance deferral.

Companion PR (#496, concurrent ancestor-restore open and window coalescing):
merge `#497` first, then rebase `#496` onto `main` so `Staged::pump_all` retains
`MAINTENANCE_DEFER_LIMIT = 8` (submitting one reserved maintenance job first
after `8` deferred passes) and runs `#496`'s private `host_inbound` and shared
`pump_device_inbound` queues ahead of `outbound` and `maintenance`.

Evidence

- Rebased crate and Python checks over `origin/main` (`ba3afb13`, `#589`) on
  x86_64 Linux (`O_DIRECT` + `io_uring`): `selene --features test-support`
  (`514` lib + `1` `mixed_codec_root` integration passed, `0` warnings; also
  `cargo check --release` without `test-support`, `0` warnings), `selene-manager
  --features test-support --test client --test offload` (`85 + 2` passed, `0`
  warnings), `helios --features runtime-core,server --lib -- offload::
  runtime_core::memory::tests runtime_core::model::tests
  server::runtime::phase_tests` (`144` passed, `14` GPU-only ignored, `0`
  warnings in touched files, covering `#497` + `#589` small-SoC,
  `--memory-limit`, and degraded-disk restore-only pool coexistence), and
  `pytest tests/preparation/test_core_boundary.py
  tests/test_design_review_hook.py` (`22` passed).
- Prior SM121 GPU unit and live checks (at `cd5a366b`, `--lossless-kv-compression
  off`): `helios` `offload::` (`FLARE_RUN_CUDA_TESTS=1 --include-ignored`, `21`
  single-GPU SM121 tests passed; `split_pools` requires 2 local GPUs);
  corrupting a multi-page `.ckpt` payload on `Qwen3.8-27B-NVFP4` incremented
  `fetch_failed_total` (`1`), launched `0` `restore` graphs, and recomputed
  identical `top-5 logprobs` and tokens; under `--prefix-cache-disk-limit 6G`
  (`4` concurrent restores + `3` fresh `30K` stores), disk bytes peaked at
  `6.38 GB` (`<= 6 GiB`) and settled at `6.37 GB` with `0` `retry_abandoned`
  and `0` `io_error` drops (`2` normal `end_of_chain` evictions); four
  concurrent decode streams spilling checkpoints over 30 s on
  `Qwen3.8-Flash-Next` had `0` errors (`100.0 -> 95.9 tok/s`).
- Not covered: live `--lossless-kv-compression` (`cpu`/`gpu`) serving,
  post-rebase SM121 `flare run` re-measurement, live Jetson Orin GA10B /
  `--memory-limit` GPU serving, isolated `50 us` `Worker::idle_wait` A/B,
  `#496 + #497` combined serving, multi-host RoCE serving, 2-GPU `split_pools`,
  discrete PCIe GPUs, Windows serving, and live warm-plus-disk
  (`--prefix-cache-memory > 0`) or `PooledStore` HTTP serving (`CompositeStore`
  + `DiskStore` CUDA transfers were covered at `cd5a366b` in `helios`
  `offload::`).

Discord: Dooner

Design-Signed-Off-By: Antigravity (Gemini 4); design-review=c3a9

Signed-off-by: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com>
Merging NVIDIA#497 onto main changed `Staged::pump_all` to prioritize
interactive inbound restores ahead of background writes and
starvation-guarded maintenance, and added tests referencing
`Staged::inbound`, which this branch split into `device`
(`pump_device_inbound`) and `host_inbound` (`pump_host_inbound`).

- Resolved the `Staged::pump_all` conflict in `selene/src/disk_store.rs`
  by retaining NVIDIA#497's maintenance starvation guard and pumping
  `pump_device_inbound()` and `host_inbound` ahead of `outbound` and
  `maintenance`.
- Updated the three `staged.inbound[&JobId(12)]` assertions (and
  comment) in NVIDIA#497's `staged_pump_all_prioritizes_inbound_ahead_of_outbound_and_maintenance`
  test to `staged.host_inbound`.

Both interactive coalesced device restores and host-buffer reads now
keep priority ahead of background writes and maintenance without
starving maintenance or breaking compilation.

Validated on Linux (GB10 `cn6`):
- `cargo check --manifest-path selene/Cargo.toml --all-targets --features codec,rdma`: passed with 0 warnings.
- `cargo test --release --manifest-path selene/Cargo.toml --features codec`: 534/534 lib + 1/1 `mixed_codec_root` passed.
- `cargo test --release --manifest-path selene-manager/Cargo.toml --test offload --test packed`: 2/2 `offload` + 9/9 `packed` passed.

Design-Signed-Off-By: derek <derek.yates@live.com>; design-review=2e5b

@yatesdr yatesdr left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All three review concerns are addressed, and the post-#497 merge in Staged::pump_all and staged_pump_all_prioritizes_inbound_ahead_of_outbound_and_maintenance is resolved and verified (selene --features codec 534/534 + 1/1, selene --features codec,rdma 0 warnings, selene-manager offload 2/2 + packed 9/9). Merging now.

@yatesdr
yatesdr merged commit f725658 into NVIDIA:main Nov 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:caching Prefix/KV reuse, cache retention, and model or payload cache behavior. area:selene Selene shared prefix-cache pool, protocol, manager, and transfers. performance Performance, latency, throughput, or memory-efficiency investigation or improvement. triage:validation Proposed implementation needs acceptance evidence; no claim that a reported defect is fixed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants