Skip to content

fix(selene,helios): stop service_store and CompositeStore Retry(Slabs) CPU storm - #705

Open
jcartu wants to merge 1 commit into
NVIDIA:mainfrom
jcartu:fix/service-store-slab-retry-storm
Open

jcartu wants to merge 1 commit into
NVIDIA:mainfrom
jcartu:fix/service-store-slab-retry-storm

Conversation

@jcartu

@jcartu jcartu commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Refs #703

Summary

Stops the CPU spin loop and retry amplification in Worker::service_store and CompositeStore when DRAM retention slabs are saturated and disk spills are either full at MAX_SPILLS or hitting filesystem ENOSPC.

Background and Trigger

Issue #703 observed this storm on v0.5.1 under a disk-full ENOSPC trigger where parked DRAM copies could not commit to disk, causing every spill failure to re-trigger the full deferred queue. The same underlying retry amplification also affects healthy disks whenever MAX_SPILLS (8) concurrent writes are already in flight and incoming/deferred publications exceed remaining DRAM headroom:

  1. Worker::service_store previously set progress = true unconditionally on every publication attempt, preventing the worker loop from parking even when every deferred store returned the exact same StoreOutcome::Retry(reason).
  2. CompositeStore::poll previously incremented stats.progress on ENOSPC write failures, immediately re-waking all deferred publications even though zero slots became durable.
  3. CompositeStore::store previously called spill_parked() on every Retry(StoreReason::Slabs) rejection even while MAX_SPILLS writes were already running, repeatedly sorting parked keys and inflating held[0] per rejected publication.
  4. Worker::service_store lacked a single per-CheckpointId reconciliation pass across take_publications(), deferred_stores, and deferred_copyouts, using O(N) scans and risking duplicate/zombie waiter state on same-ID fresh plus deferred collisions.

Changes

  • helios/src/server/runtime.rs:
    • Reconcile take_publications(), deferred_stores, and deferred_copyouts by CheckpointId into a single Vec<PendingStore> indexed by HashMap<CheckpointId, usize> via Pending::claim before iterating. Each unique CheckpointId is processed at most once, preserving fresh and prior_retry accurately under both retry == false and retry == true (no zombie waiters on fresh success, accurate host_retry_success accounting, and clean updates when StoreReason changes).
    • Mark worker progress = true only on genuine state transitions (StoreOutcome::Queued | StoreOutcome::Present | StoreOutcome::Oversize, Err, or a changed StoreReason), allowing the worker to park when retries make no state change.
    • Gate non-fresh StoreReason::Slabs retries on store.can_retry_slabs(&publication) before export_fits() and store.store(), preventing unready large publications from thrashing while letting smaller publications that fit proceed without starvation.
  • selene/src/store.rs, selene/src/pool/store.rs, selene/src/pool/local.rs:
    • Add HostStore::can_retry_slabs(&self, _checkpoint: &PublishedCheckpoint) -> bool with a default true implementation, forwarded through PooledStore and Tiers.
  • selene/src/disk_store.rs:
    • Split plan_record_slice (borrowing &[PagePayload]) and plan_record_meta (metadata-only, zero page-vector clone) for CompositeStore::store() and CompositeStore::can_retry_slabs(), keeping plan_record for its two existing callers (disk_store.rs:2619, disk_store.rs:3419) and unit tests.
  • selene/src/composite.rs:
    • Update disk_stored() to return whether waiters should reconsider: returns false on ENOSPC backoff (so ENOSPC completions do not bump stats.progress) and returns true whenever a DiskJob::Write slot is freed, including if outbound was already removed (removing any orphaned parked entry so subsequent spill() calls cannot panic on self.outbound[&key]).
    • On retry_after timer expiry in CompositeStore::poll(), unconditionally clear self.retry_after = None and edge-trigger self.stats.progress += 1 once. Under sustained ENOSPC, retry cadence is bounded to one probe per 50 ms backoff (~20 Hz), never a tight spin loop, and Worker::run (helios/src/server/runtime.rs:1248-1292) enforces a 50 us / 100 us / 2 ms idle poll cap when executor.outstanding() == 0 so the retry_after expiry edge fires reliably even with zero new publications.
    • Replace full-scan spillable_slots() with early-exit has_spillable_slots(need), add validate_tail() and covered_endpoint() helpers, and enforce the 1:1 DiskJob::Write to parked.writing invariant in poll() maintenance via debug_assert_eq!.
    • Guard spill() with if parked.writing { return None; } so an already-writing parked record cannot start a duplicate concurrent disk write.
    • Skip spill_parked() in CompositeStore::store() when writing == MAX_SPILLS (maintenance in poll() still accounts for held[0] once per tick).
    • Implement CompositeStore::can_retry_slabs() and add a #[cfg(test)] injectable backoff clock (poll_at) for deterministic testing.
  • docs/prefix-cache-offload.md:
    • Document HostStore::can_retry_slabs, the 50 ms ENOSPC retry_after backoff and progress edge-trigger, and the held[0] maintenance-tick accounting semantics.

Served-Workload A/B Benchmark (SM120 TP4, ENOSPC Worst-Case Regime)

Measured back-to-back on identical hardware and configuration: 4x RTX PRO 6000 Blackwell (SM120), DeepSeek-V4.1-Flash TP4, --prefix-cache-memory 2G backed by a 64 MiB ext4 loopback O_DIRECT volume pre-filled to trigger ENOSPC, warmed with an identical 416-request saturation sequence (3,443/6,547 host-cache slots in use, 314 parked records). Note that this single-run ENOSPC regime is the worst case for baseline; healthy-disk MAX_SPILLS saturation deltas will be smaller.

Metric Baseline (3d1614cc) Patched (63206a09) Notes
416-req saturation wall 93.15s 74.50s -20.0% wall time (416/416 ok, 0 err)
5s Idle flare-model CPU % 91.51% 1.40% 65x lower idle model-thread CPU
5s Idle counted slabs retries 9,934 (~1,985/s) 0 store_skipped: 9,991 vs 0; gated retries no longer reach store()
5s Idle held_total{tier="dram"} 23,557 28,888 (+22.6%) Counter semantics changed: one holding event per parked record per ~50 ms maintenance/backoff tick (~314 x 18.4/s), not per rejected publication. Events, not capacity.
32-req c=4 wall / throughput 17.47s (1.83 req/s) 3.663s (8.74 req/s) 4.77x faster by exact wall times (17.47 / 3.663; 4.78x from rounded req/s)
32-req c=4 latency p50 / p95 / max 2,337.24 / 3,030.08 / 3,446.42 ms 432.51 / 514.22 / 696.96 ms 5.40x / 5.89x / 4.95x lower
32-req c=4 counted slabs retries 32,718 32 1,022x fewer counted store() rejections; gated retries no longer reach store() so they never increment store_skipped_total/store_reasons_total (1 fresh attempt per new request)
32-req c=4 CPU 94.50% (proc 158.5%) 75.62% (proc 381.1%) Lower model CPU at 4.77x the request rate; higher total process CPU because it now executes 4.77x the work (lower per-request process CPU)

Narrow Metric and API Shifts

  1. ENOSPC disk-write failures no longer increment StoreStats::progress on completion; instead, progress edge-triggers once when the 50 ms retry_after backoff expires.
  2. StoreStats::held[0] is now accounted on progress-gated poll() maintenance ticks rather than per rejected Retry(Slabs) call in CompositeStore::store(), and deferred Slabs publications skipped by can_retry_slabs() do not call store.store() or increment host_store_outcome.
  3. HostStore::can_retry_slabs is a new default-true trait method on HostStore, forwarded through PooledStore and Tiers.

Out of Scope

  • ENOSPC retention and eviction policy documented in docs/prefix-cache-offload.md
  • disk_bytes metric definition and accounting
  • export_fits() internal cloning behavior

Verification

All checks ran on Linux x86_64 with prlimit --memlock=unlimited:

  • Release profile (--locked --release):
    • cargo test --locked --release --manifest-path selene/Cargo.toml: 558 passed, 0 failed, 0 ignored (541 #[test] + 17 #[tokio::test])
    • cargo test --locked --release --manifest-path selene/Cargo.toml --features test-support: 558 passed, 0 failed, 0 ignored (test-support = ["codec"] in selene/Cargo.toml gates library code rather than test items, so identical count is expected)
    • FLARE_TEST_TEMPLATE_DIR=... cargo test --locked --release --manifest-path helios/Cargo.toml --features runtime-core,server: 1,906 passed, 0 failed, 84 ignored (includes 2 FLARE_MUSE_SPARK_SNAPSHOT-gated Muse-Spark tests and 82 GPU/checkpoint-snapshot/release-benchmark tests)
  • Debug profile (executing all debug_assert! invariant checks):
    • cargo test --locked --manifest-path selene/Cargo.toml composite::tests -- --nocapture: 65 passed, 0 failed (verified 0 test_directory direct-I/O skips)
    • cargo test --locked --manifest-path helios/Cargo.toml --features runtime-core,server phase_tests: 132 passed, 0 failed
    • 9 new deterministic unit tests (zero sleeps): 5 in selene/src/composite.rs and 4 in helios/src/server/runtime/phase_tests.rs
  • Clippy & formatting:
    • cargo clippy --locked --manifest-path selene/Cargo.toml --all-targets and cargo clippy --locked --manifest-path helios/Cargo.toml --features runtime-core,server --all-targets: 0 warnings and 0 errors on all touched lines.
    • rustfmt --edition 2024 --check: 0 formatting diffs on all touched lines.

Discord: jcartu

@flare-autobot

Copy link
Copy Markdown
Collaborator

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

Future reviews will auto-run 90 minutes after code updates are pushed.

  • Re-review sooner: Call @flare-autobot after push.
  • Opt-out: Include #autobot:ignore in the PR or any comment.

@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. bug Something isn't working performance Performance, latency, throughput, or memory-efficiency investigation or improvement. triage:review Proposed change needs code review; this does not imply merge readiness. 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 Dec 3, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

The state machine is sound — every progress edge, every parked/jobs/outbound mutation and every can_retry_slabs() == false exit has a guaranteed future wake source, so no stall, lost wakeup, duplicate store() submission or new panic path. What blocks it is an evidence-form gap: a performance-titled "CPU storm" fix with no served-workload measurement on the patched build (Charter #210, docs/design-review.md:106-115), while issue #703 records the storm was not reproduced on v0.5.3; secondary are the unrun --locked --release Layer-1 profile, docs/prefix-cache-offload.md still documenting the pre-PR retry contract, and one accepted-publication path doing its planning work twice.

  • Blockers: 1 · Should fix: 3 · Subtract/Simplify: 5 · Nits: 4
Walkthrough
  • helios/src/server/runtime.rs:2791-2957 — one per-CheckpointId reconciliation of take_publications(), deferred_stores, deferred_copyouts into Vec<PendingStore>{publication, prior_retry, fresh}; duplicate IDs replace the earlier publication on the Occupied path (:2813-2817), deferred entries attach prior_retry to an existing entry instead of queueing twice (:2823-2826), and every waiting.push is gated by seen_waiting.insert(...) (:2835, :2884, :2936), so no waiter is dropped or duplicated across passes.
  • helios/src/server/runtime.rs:2928-2954 — progress is now edge-triggered: Queued (:2930), a changed StoreReason (prior_retry != Some(reason), :2933-2935), Present/Oversize via _ => (:2941-2943), copyout headroom change (:2891-2896) and Err (:2953). Repeated identical Retry(Slabs) returns Ok(false), so Worker::run parks. host_retry_success now keys on prior_retry.is_some() (:2947), which is correct for the fresh+deferred collision.
  • helios/src/server/runtime.rs:2880-2888 — the non-fresh Slabs gate runs before export_fits()/store(), so a skipped retry neither pins a checkpoint nor scores host_store_outcome; fresh bypasses it, so ready publications are not starved.
  • selene/src/composite.rs:1452-1456 + :774-788, :752-771 — can_retry_slabs returns false only when writing < MAX_SPILLS && covered_slots < short && !backoff_active() fails; its negation is discharged by a future write completion (disk_stored → progress) or by the 50 ms retry_after edge (:1656-1660). has_spillable_slots early-exits, replacing the old full sum() fold.
  • selene/src/composite.rs:656-720, :1608-1624, :1656-1671 — disk_stored returns false only on the ENOSPC path (:687 return !pressure), so progress no longer advances with zero durable slots; the retry_after expiry clears unconditionally and bumps progress exactly once, which also re-enters the maintenance block (:1662-1670) so spill maintenance still runs — one probe per 50 ms (~20 Hz), not a spin.
  • selene/src/store.rs:324-329, pool/store.rs:615-616, pool/local.rs:45-49 — new default-true trait method forwarded through PooledStore/Tiers (via is_none_or, the conservative direction), so out-of-tree and memory-only stores behave exactly as before.
Merge Risk: Medium · up to eec5e95
Pre-merge checks: ✅ 1 passed · ⚠️ 3 warnings
  • ✅ Security / malicious screen: pure Rust refactor of the retention/retry path; no new dependency, flag, config key, wire, protobuf or on-disk format change, no network or shell surface, no instructions embedded in the diff.
  • ⚠️ Charter & value fit: right problem in the right layer (shared selene store + helios worker, no per-model branch, knob defaults to true) but the headline result is unmeasured — see Blocker 1.
  • ⚠️ Related / duplicate / conflict check: not obsolete and not a duplicate of selene,selene-manager,helios: improve prefix-cache hit rate, L1 retention, NVMe throughput, and GPU snapshot packing #674/selene,helios: add write-side NVMe and pool spill profitability gate #694, but both rewrite this same Retry(Slabs) branch and service_store outcome match (selene,helios: add write-side NVMe and pool spill profitability gate #694 adds StoreOutcome::Unprofitable, which this PR's _ => wildcard would swallow) and no merge order is recorded — sequencing must be settled before either lands (informational, not a blocker).
  • ⚠️ Tests & verification evidence: 9 new tests exist exactly where claimed and pin the real mechanisms (composite.rs:6295-6634, phase_tests.rs:9022/9058/9119/9162), but everything ran in the debug profile; the mandated cargo test --locked --release (and selene's --features test-support) was not run, and no check ran on eec5e95.

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

Want a frontier second opinion? If these findings look noisy, request a one-time SuperAgent Review on eec5e95 (~3–4 min; re-adjudicates existing findings without re-running discovery).

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

@jcartu
jcartu force-pushed the fix/service-store-slab-retry-storm branch from eec5e95 to 63206a0 Compare December 3, 2026 15:59
@jcartu

jcartu commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

@flare-autobot Pushed 63206a09 addressing all review items and added the served-workload A/B benchmark to the PR description:

  • Blocker 1 (Served-workload A/B benchmark): Added back-to-back 4x RTX PRO 6000 (SM120) DeepSeek-V4.1-Flash TP4 numbers comparing 3d1614cc vs 63206a09 under the ENOSPC worst-case regime (saturated 64 MiB ext4 loopback O_DIRECT disk, --prefix-cache-memory 2G, 416-request warmup to 3,443/6,547 slots and 314 parked records). Idle flare-model CPU dropped from 91.51% to 1.40% (65x), counted slabs retries dropped from 9,934 (~1,985/s) to 0, and a 32-request c=4 served workload improved from 17.47s (1.83 req/s, p50 2,337.24 ms) to 3.663s (8.74 req/s, p50 432.51 ms, 4.77x faster by exact wall time).
  • Should-Fix 1 (plan_record clone in can_retry_slabs / store): Added zero-clone DiskStore::plan_record_slice (for CompositeStore::store()) and DiskStore::plan_record_meta (for CompositeStore::can_retry_slabs()). Retained DiskStore::plan_record because it still has two live callers at selene/src/disk_store.rs:2619 and :3419 plus unit tests.
  • Should-Fix 2 (--locked --release verification): Re-ran --locked --release for selene (558 passed, 0 failed), selene --features test-support (558 passed, 0 failed; selene has 541 #[test] + 17 #[tokio::test] = 558 and test-support = ["codec"] gates code rather than test items, so 558 == 558 is expected), and helios --features runtime-core,server (1,906 passed, 0 failed, 84 ignored), plus debug-profile composite::tests (65 passed, 0 O_DIRECT skips) and phase_tests (132 passed).
  • Should-Fix 3 (docs/prefix-cache-offload.md): Updated all three passages (HostStore::can_retry_slabs, 50 ms ENOSPC retry/backoff edge-trigger, and held[0] maintenance-tick semantics).
  • Subtract 1 (backoff_active dead branch): Removed the dead in-loop branch in CompositeStore::poll() while keeping backoff_active() for its live callers (:826, :903, :1452).
  • Subtract 2 (Pending::claim & imports): Extracted Pending::claim and hoisted imports in helios/src/server/runtime.rs.
  • Subtract 3 (Explicit StoreOutcome match): Replaced wildcard arm with exhaustive StoreOutcome::Queued | StoreOutcome::Present | StoreOutcome::Oversize.
  • Subtract 4 (debug_assert_eq! placement): Moved the writing_spills() invariant check to CompositeStore::poll() maintenance.
  • Subtract 5 (idle_wait() justification): Left Worker::idle_wait() (helios/src/server/runtime.rs:1248-1292) unchanged intentionally; when executor.outstanding() == 0, it already caps idle sleep at 50 us / 100 us / 2 ms fallback, well below the 50 ms ENOSPC backoff, so the retry_after expiry edge fires reliably without modifying wake cadence.
  • Subtract 6 (Guard & orphan-cleanup notes): Both the store.spill(child.key) guard in selene/src/composite.rs:2735 and the orphaned self.parked.remove(&key) cleanup in disk_stored() (selene/src/composite.rs:680) are kept in code without extra inline comments to keep the diff concise; happy to add brief comments if preferred.

Ready for re-review!

Discord: jcartu

@jcartu
jcartu force-pushed the fix/service-store-slab-retry-storm branch from 63206a0 to abd39ba Compare December 3, 2026 18:50
@jcartu

jcartu commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

@flare-autobot Rebased onto main (452c3686, including #674 and #708) at 55fd8aca to clear the merge conflict.

Preserved from #674: the has_pending_reclaim guard in spill(), the covered-record needed == 0 path and the short > 0 pre-allocation spill (guarded with writing_spills().0 < MAX_SPILLS), and row_restore_latency tracking in service_store. Two changes worth reviewer attention: StoreInvalidated completion is now progress-gated on disk_stored() exactly like Stored, and can_retry_slabs treats a key with a pending #674 reclaim as retryable (composite.rs:1461) so the Retry(Slabs) -> Retry(Inflight) reclaim transition is never hidden. Pending::claim also dedups same-ID re-publication so a fresh and a deferred copy of one checkpoint submit once.

Validated on def91796 (abd39ba0) and re-anchored on 452c3686 (55fd8aca) with zero diff drift (prlimit --memlock=unlimited): --locked --release selene 591 passed (default and --features test-support), helios --features runtime-core,server 1,939 passed / 0 failed / 81 ignored (at abd39ba0), debug selene composite::tests 71 passed / 0 O_DIRECT skips, debug helios phase_tests 148 passed at 55fd8aca; clippy and rustfmt --edition 2024 --check clean on touched lines.

Note: the SM120 TP4 ENOSPC A/B benchmark in the PR description was collected on 3d1614cc vs 63206a09 and has not been re-run on 55fd8aca after #674. Ready for re-review!

Discord: jcartu

…) CPU storm

Refs NVIDIA#703.

When CompositeStore runs out of DRAM retention slabs while disk spills are
saturated at MAX_SPILLS or failing with ENOSPC, repeated StoreOutcome::Retry(Slabs)
deferrals previously caused a tight CPU spin loop and O(N) spill-recheck
amplification across Worker::service_store and CompositeStore:
- Worker::service_store unconditionally set progress = true on every loop
  iteration, preventing the worker from parking even when every deferred store
  returned the identical Retry(reason).
- CompositeStore::poll incremented stats.progress on ENOSPC write failures,
  re-triggering all deferred stores even though zero slots became durable.
- CompositeStore::store invoked spill_parked() on every Retry(Slabs) while
  MAX_SPILLS writes were already in flight, repeatedly sorting parked keys and
  inflating held[0] per rejected publication.

This change stops the storm while preserving wakeup liveness:
- helios/src/server/runtime.rs: reconcile take_publications(), deferred_stores,
  and deferred_copyouts by CheckpointId via a single Pending claim helper so
  each ID runs at most once with accurate fresh and prior_retry tracking. Mark
  worker progress only on explicit real state transitions (Queued, Present,
  Oversize, Err, or a changed StoreReason), and gate non-fresh
  StoreReason::Slabs retries on store.can_retry_slabs(&publication).
- selene/src/store.rs, pool/store.rs, pool/local.rs: add default-true
  HostStore::can_retry_slabs and forward it through PooledStore and Tiers.
- selene/src/disk_store.rs: add zero-clone plan_record_slice and
  plan_record_meta helpers; delegate plan_record to plan_record_slice.
- selene/src/composite.rs: return false from disk_stored() on ENOSPC backoff
  so ENOSPC completions do not bump stats.progress, while returning true if a
  DiskJob::Write slot is freed even without a matching outbound entry (removing
  any orphaned parked entry to prevent self.outbound[&key] panics in spill()).
  Edge-trigger stats.progress += 1 once when retry_after expires in poll() so
  idle waiters wake up cleanly (bounded to one probe per 50 ms backoff, ~20 Hz,
  observed via Worker::run idle_wait() which waits 50 us for inbound transfers,
  100 us for pool lookups, or 2 ms fallback when executor.outstanding() == 0).
  Replace spillable_slots() with early-exit has_spillable_slots(), add O(jobs)
  writing_spills() with the O(parked) 1:1 DiskJob::Write <-> parked.writing
  debug_assert_eq in poll() maintenance, guard spill() against double-writing
  an already-writing parked record (updating the pre-existing test assertion at
  store.spill(child.key) to check !parked.writing first), skip spill_parked()
  in store() when writing == MAX_SPILLS, share validate_tail/covered_endpoint
  and zero-clone planning between store() and can_retry_slabs(), and implement
  CompositeStore::can_retry_slabs.
- docs/prefix-cache-offload.md: document HostStore::can_retry_slabs, the
  per-ID StoreReason retry contract and Slabs gate, and the updated held_total
  and store_skipped_total cadence under MAX_SPILLS/ENOSPC and the Slabs gate.

Design-Signed-Off-By: Antigravity (Gemini); design-review=2e5b
Signed-off-by: Joshua Cartu <jcartu@users.noreply.github.com>
@jcartu
jcartu force-pushed the fix/service-store-slab-retry-storm branch from abd39ba to 55fd8ac Compare December 3, 2026 18:58
@jcartu

jcartu commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

@flare-autobot re-review on 55fd8aca (base 452c3686; GitHub shows MERGEABLE, and a local trial merge into current main 509f585a is conflict-free). The previous comment was edited in place rather than re-posted, so this is a fresh ping.

Discord: jcartu

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. bug Something isn't working 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.

2 participants