Skip to content

selene,selene-manager,helios: improve prefix-cache hit rate, L1 retention, NVMe throughput, and GPU snapshot packing - #674

Merged
lukealonso merged 1 commit into
NVIDIA:mainfrom
yatesdr:perf/selene-prefix-cache-holistic
Dec 3, 2026
Merged

lukealonso merged 1 commit into
NVIDIA:mainfrom
yatesdr:perf/selene-prefix-cache-holistic

Conversation

@yatesdr

@yatesdr yatesdr commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

Why

Prefix-cache serving across Selene, selene-manager, and Helios hits four coupled bottlenecks under multi-turn, multi-instance, and large-KV-budget workloads:

  1. Missed pool hits on partially resident GPU prefixes & wasted host intake RAM: Requests with any GPU-resident prefix skipped deeper host/pool lookups even when the shared pool held a longer continuation. Local host caches also reserved pinned intake buffers even when local disk storage was disabled, and Prometheus metrics conflated committed on-disk records with uncommitted write reservations.
  2. Dropped L1 DRAM copies after pool handover: Local host DRAM evicted clean copies immediately upon pool handover instead of retaining them for fast local re-reads, and shutdown drain blocked teardown unnecessarily.
  3. Over-excluded GPU KV pages under handle-count limits (Snapshot aliasing admits only the largest cache plane, so a snapshot excludes ~3.16x its own page cost #451) & noisy restore pricing: Shared GPU snapshot-alias packing exceeded CUDA handle budgets on large-KV-budget deployments, excluding dozens of KV pages per checkpoint. Meanwhile, host-restore profitability relied on a wall-clock prefill EMA that mispriced restores under concurrency spikes or short incremental turns.
  4. Buffered packed NVMe writes, timer-polled waiters, and immediate clean arena eviction: Compressed v4 records bypassed O_DIRECT, blocked put waiters polled on ticks instead of waking on resource releases, clean records were evicted from manager RAM immediately after writeback, and duplicate in-flight put offers were not coalesced.

What

1. Resident-aware lookup, intake sizing, and telemetry (selene/, helios/)

  • Keep host and pool prefix lookup active when a deeper checkpoint can extend a partially resident GPU prefix.
  • Allocate zero local intake slots (flare_host_cache_intake_slots == 0) when local disk storage is disabled, eliminating unused pinned host RAM and shortening host-cache initialization.
  • Preflight doomed L1 evictions before scheduling writeback.
  • Separate ready on-disk inventory (flare_host_cache_disk_records, flare_host_cache_disk_bytes) from uncommitted reservations (flare_host_cache_disk_reserved_records, flare_host_cache_disk_reserved_bytes).
  • Export per-level pool restore rate gauges (flare_host_cache_pool_inbound_bytes_per_second{level}) across neighbour_gpu, host_dram, host_nvme, and remote_nvme.

2. L1 DRAM retention and non-blocking drain (selene/, helios/)

  • Retain clean persisted_in_pool records in L1 DRAM after pool handover with explicit clean_slots invariant tracking.
  • Decouple capture headroom from local intake sizing (capture_headroom_slots).
  • Drain pending prefix-cache writes on shutdown without blocking request teardown.

3. GPU snapshot-alias packing (#451), pressure-aware eviction, and restore pricing (helios/)

  • Pack shared GPU snapshot aliases with midpoint-ordered half-width spans and symmetric exponential+binary handle budgeting (helios/src/runtime_core/cache_memory.rs, helios/src/scheduler/cache_memory.rs), recovering GPU KV pages and snapshot capacity on handle-limited deployments.
  • Replace fixed eviction ordering with pressure-aware GPU cache eviction (evict_for_pressure) driven by page, snapshot, and backing-conflict pressure.
  • Price host restores using read-only scheduler prefill-delta estimates (estimate_prefill_delta_ns) paired with measured per-level pool restore rates instead of wall-clock prefill EMA, track row-restore latency separately (RowRestoreLatency), derive prefill duration from GPU timing with wall_ns fallback when GPU duration is absent, and record prefill-saved seconds directly in Metrics::host_lookup_cost.

4. Direct compressed I/O, event-driven waiters, clean arena retention, and offer coalescing (selene/, selene-manager/)

  • Write compressed v4 records using aligned whole-record O_DIRECT I/O (WriteRecord, WritePacked) with exact logical-length recovery and disk-invalidation propagation (StoreInvalidated).
  • Replace timer-polled put waits with event-driven wakeups (writeback_waiters, inflight_waiters) using coalesced WindowReleaseSignal notifications and a rotating, epoch-tracked scan (writeback_wake_epoch) that prevents duplicate checks and starvation across cursor wraparound.
  • Retain clean records in manager RAM after writeback and evict only coalescable buddy blocks under allocation pressure.
  • Resolve waiting put offers directly to Present when publication covers the offer while preserving independent waiter ownership and rechecking bucket, role promotion, fork count, and descendant coverage.

Scope Summary

+10,106 / -1,158 lines across 42 files (selene/, selene-manager/, helios/, tests/server/test_conditioned_input_cache.py, verification/helios-lifecycle/check.py, and docs in docs/api.md, docs/prefix-cache-offload.md, docs/runtime-core-design.md, and selene-manager/docs/operating.md).

Compatibility and Limitations

  • Core & on-disk compatibility: No Protobuf schema changes and no model core re-export required. Compressed v4 records remain readable across kvc=off, kvc=cpu, and kvc=gpu modes.
  • Multi-host TP rank-relay wire event: Adds internal rank-relay event Kind::StoreInvalidated = 4 (selene/src/shard.rs), requiring matching rank builds in multi-host TP deployments.
  • Startup validation for sub-page warm memory budgets: When local disk is disabled, memory budgets smaller than one page record (checkpoint_memory < page_record_bytes) now fail startup cleanly (selene/src/offload.rs) rather than failing later on a 0-byte slab allocation.
  • Public flare-selene API updates: Updates HostStore::begin_lookup, TierStore::retired, TierStore::pending_pool_drain, HostHit.pooled, StoreStats reserved/rate fields, worth_restore, and levels::POOL_LEVELS in lockstep with workspace callers.
  • Restore pricing fallback & lookup refresh: Retains a narrowed cold-start fallback prefill_rate EMA (sampled on single-lane prefill steps with >= 50% capacity fill) until PrefillPredictor observes prefill capacities, and issues a once-per-episode stale pool-lookup ticket refresh when GPU residency advances while waiting.
  • GPU VRAM recovery scope (Snapshot aliasing admits only the largest cache plane, so a snapshot excludes ~3.16x its own page cost #451): Snapshot-alias packing recovers capacity on handle-limited / large-KV-budget deployments (such as DeepSeek-V4.1-Flash TP4). Memory-limited deployments (such as GLM-5.3-Flash TP2 with 87.6 GiB weights and 6.74 GiB cache budget per GPU) remain bounded by physical VRAM rather than CUDA virtual handle count.
  • Multi-process packed puts: selene-manager continues to reject packed (kvc=gpu / kvc=cpu) puts from multi-process TP>=2 instances per the existing manager protocol contract; compressed storage is tested on local disk (--prefix-cache-disk) and single-process configurations.
  • O_DIRECT cold reads after restart: Because WritePacked uses O_DIRECT without populating the Linux kernel page cache, post-restart local-disk reads fetch directly from NVMe rather than kernel page-cache RAM.

Measured Results (SM120 — 4× RTX PRO 6000)

Apples-to-apples A/B comparison against 5d53040e on SM120 plus cross-node TCP validation against an aarch64 selene manager. Hardware benchmarks and live saturation runs were executed on pre-refactor commit 7d7dcdcb against 5d53040e (prior to #657, #666, #663, #667, #670, #660, #665, #683, and #684); this branch is cleanly rebased onto c513e46a (main) and re-verified across the full Linux unit/integration test suites and TLA+ mutation checks on HEAD (831c47c7):

A. GPU VRAM KV Capacity Recovery (DeepSeek-V4.1-Flash TP4, 24 prompts / 72 checkpoints)

Metric Baseline (5d53040e) This PR Delta
flare_snapshot_capacity 1,946 4,864 +2.50× (+2,918 slots)
flare_snapshot_backing_pages (72 ckpts) 5,917 (82.2/ckpt) 2,390 (33.2/ckpt) -59.6% (+3,527 KV pages / +451K tokens freed)
flare_free_kv_pages after 24 prompts 154,062 157,589 +3,527 pages
flare_host_cache_intake_slots (no local disk) 1,600 0 -0.9 GiB pinned RAM (init 12.7s → 0.6s)

B. NVMe Spill, Tight-Limit Eviction & Post-Restart Restore (Qwen3.8-Flash-Next TP1)

--prefix-cache-memory 256M, selene manager --memory 512M --nvme 1200M --staging 512M; 12 distinct ~6.9K-token prompts populate → restart flare (cold GPU, warm manager) → reverse reread of 6 prompts.

Metric Baseline (5d53040e) This PR Delta
flare_host_cache_intake_slots 4,448 0 -100%
Retained L1 DRAM (memory_records / bytes) 0 (0 B) 2 (220 MiB) Clean L1 retention active
selene_put_writeback_waits_total 87 6 -93.1%
Manager clean RAM retained (selene_records{tier="memory"}) 1 (220 MiB) 2 (439 MiB) +2.0×
Manager RAM hits on restart (selene_hits_total{tier="memory"}) 1 2 +2.0×
Manager NVMe write bytes 2.97 GB 2.63 GB -11.5%
Manager tight-limit NVMe evictions (selene_evictions_total) 10 8 -20.0% (0 NVMe errors)
Post-restart cache-hit tokens (6 prompts) 66.56% (4/6 hits) 83.23% (5/6 hits) +16.67 pts (+6,915 tokens)
Post-restart latency (mean / p50) 0.5449s / 0.5635s 0.3907s / 0.3217s -28.3% mean / -42.9% p50

C. Multi-Turn, Multi-Instance Traffic (2× GLM-5.3-Flash TP2, kvc=off + selene manager)

2 instances on GPUs 0,1 and 2,3, shared selene manager (2G mem / 6G NVMe), 6 sessions × 3 turns routed A → B → A.

Metric Baseline (5d53040e) This PR Delta
flare_host_cache_intake_slots per instance 504 0 -100%
Retained L1 DRAM across 2 instances 0 (0 B) 35 (3.65 GiB) Clean L1 retention active
flare_host_cache_bytes_out_total 5.91 GB 5.01 GB -15.3%
Manager NVMe write bytes 4.10 GB 3.02 GB -26.4%
Manager NVMe write time / throughput 11.06s (370.5 MB/s) 2.86s (1,054.8 MB/s) +2.85× throughput
selene_put_writeback_waits_total 293 11 -96.2%
Turn 3 latency (mean / p50) 0.9171s / 0.8614s 0.8456s / 0.7566s -7.8% mean / -12.2% p50

Once flare_host_cache_pool_inbound_bytes_per_second{level="neighbour_gpu"} measured 2.33 GB/s, prefill-delta pricing skipped 3 Turn-3 cross-GPU row restores that only added 1,428 tokens over an already GPU-resident 4,793-token Turn-1 prefix, saving 521 MiB of restore traffic and reducing Turn 3 median latency by 12.2%.

D. Compression Parity & Tight Disk Eviction (GLM-5.3-Flash TP2, --prefix-cache-disk-limit 1500M)

  • kvc=gpu: Byte-identical codec ratios on populate (2,425,749,504 → 1,601,203,363, 1.5150×) and post-restart reread (1,212,874,752 → 799,713,689, 1.5166×), 0 codec failures, 0 verify failures, 99.97% reread cache-hit tokens (0.4527s cold NVMe O_DIRECT read vs 2.313s cold prefill = 5.1× faster), on-disk footprint held at 1,334.7 MB under the 1500M limit.
  • kvc=cpu & cross-mode (off-over-cpu): Verified on GLM-5.3 TP2 (1.5621× ratio, 0.0 logprob diff, 0 verify failures).

E. Cross-Node TCP Validation (2× Qwen3.8-Flash-Next TP1 on SM120 ↔ aarch64 selene manager)

  • 0 deterministic generation mismatches across cross-node TCP restore (Instance A → remote manager → Instance B).
  • Partial-GPU resident extension achieved 88.95% cache-hit tokens (52,146 / 58,621, p50 = 0.7159s vs 1.8340s cold).
  • Remote manager persisted 2.84 GB to NVMe at 2,388.8 MB/s (0 NVMe errors, 0 quarantined bytes, 8 clean records / 1.54 GiB retained in manager RAM).

F. Live Saturation, Compression Under Load, and Fault-Injection Recovery (SM120, 7d7dcdcb)

All 284 requests across 10 saturation and fault-injection phases returned HTTP 200 (0 HTTP 500s, 0 crashes, 0 NVMe errors, 0 codec/verify failures, 0 deterministic text mismatches):

Scenario Stress / Fault Injected HTTP OK Measured Saturation & Recovery Behavior
2× Qwen3.8 TP1 → tight manager (256M RAM / 512M NVMe / 256M staging) 16-way storm: 40 unique ~6.9K-tok prompts + 14 interleaved hot re-reads (11.16s wall) → cooldown → 4 cross-instance reads 62 / 62 Triggered 47 outcome="budget" refusals, 82 wb_waits, 2,151 store_skipped, 9.53 GB written into 512 MB NVMe (45 evictions, 806.6 MB/s, 0 NVMe errors); interleaved hot re-reads stayed 100% cached (0.86s p50 vs 3.90s cold, 0 mismatches); post-storm recovery restored 100% cross-instance hits (0.107s p50, 0 mismatches).
Live selene manager SIGKILL + restart Hard-killed manager mid-run → 8 concurrent prompts (4w) during outage → restarted manager on same socket/root → 4 writes + 4 cross-instance reads 16 / 16 During outage: 8/8 HTTP 200 (1.06s p50), degraded to local GPU + L1 DRAM without stalling. After restart: both instances auto-reconnected, resumed NVMe persistence (750.8 MB/s), and achieved 100% cross-instance reuse (0.112s p50, 0 mismatches).
2× GLM-5.3 TP2 GPU VRAM & snapshot wall (kvc=off + manager) 10 sessions × 3 turns × 4-way concurrency + 12 × 8-way eviction burst 42 / 42 Completed all 3 turns (Turn 3 10/10 OK, 1.35s p50, 72.34% cached) and the 8-way burst (8 GPU snapshot evictions, 7.97 GB manager NVMe writes at 1,043.1 MB/s, 31 manager evictions, 0 NVMe errors, 1.59 GiB retained in L1 DRAM).
GLM-5.3 TP2 local disk 1000M cap (kvc=gpu vs cpu vs off) 24 unique prompts @ 6-way (~3.2–4.8× disk cap) + 6 re-reads across all 3 modes 30 / 30 each kvc=gpu: 15.53s wall, 801.2 MB (12 recs), 1 skipped, 0 codec/verify err; kvc=cpu: 15.58s wall, 900.7 MB (8 recs), 23 skipped, 0 codec/verify err; kvc=off: 15.39s wall, 975.4 MB (10 recs), 9 skipped. All 3 modes achieved 100% reread hits with 0 mismatches.
GLM-5.3 TP2 live corrupt + read-only disk (kvc=gpu) Truncated 4 on-disk compressed records to 8 KiB, cold restart, chmod -R a-w, 6 re-reads + 4 writes, then restored u+w + 4 writes 14 / 14 Corrupt records rejected cleanly and recomputed (0.65s p50); 1 intact record restored (4,678 cached tok); read-only writes shed cleanly (disk_records held at 2); after restoring u+w, disk caching resumed automatically without restart (2 → 10 records, 793 MB).
DeepSeek-V4.1 TP4 high-concurrency burst 64 unique prompts @ 16-way concurrency across 4× RTX PRO 6000 64 / 64 243,587 prompt tokens in 15.29s (15,931 tok/s), 192 GPU checkpoints (4,672 / 4,864 snapshots still free), 248 clean store_skipped backpressure drops, 0 NVMe errors.

Verification

All checks re-verified on rebased HEAD (831c47c7, atop c513e46a):

  • RUSTFLAGS="-D warnings" cargo check --locked --all-targets: clean across selene, selene-manager, helios (--features runtime-core,server), and flare.
  • selene unit tests (Linux debug): 585/585 passed.
  • selene-manager tests (Linux debug): 205/205 lib passed + 128/128 client & pool integration passed (client 86, pool_l0 20, pool_net 6, pool_relay 5, pool_store 11).
  • helios release lib tests (Linux, --features runtime-core,server): 1,838/1,838 runnable passed (excluding root-chmod and FLARE_TEST_TEMPLATE_DIR-gated template tests).
  • flare release tests (Linux): 254/254 passed (246 bin + 7 + 1 integration).
  • verification/helios-lifecycle/check.py --mutations (Linux): 8/8 TLA+ models + all Rust mutations passed (including 222,817 CacheOwnership, 365,508 ResponseLifecycle, 13,566 Speculation, 8,490 OffloadTransfer, 7,940 DispatchRing, 1,710 Lifecycle, 1,291 RankProtocol, and 68 CheckpointReservation observed Rust transitions).

Discord: D-Rock

@flare-autobot

Copy link
Copy Markdown
Collaborator

A case file has been opened for 674.
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:memory Memory budgets, allocation lifetimes, scratch sharing, and capacity. 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 Dec 2, 2026
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

The four prefix-cache subsystems are technically sound, well-tested (CI green on 7d7dcdc, 8/8 TLA+ models + mutation guards), and free of verified correctness or concurrency blockers — several upstream alarms (eviction spin loop, metric unit mismatch) were confirmed false. Open items: a decay-clock reset bug in RowRestoreLatency::start on failed fetches, undisclosed behavior/wire changes in the PR body, and headline A/B runs measured against 5d53040e rather than base 1fbcc3c9.

  • Blockers: 0 · Should fix: 2 · Subtract/Simplify: 5 · Nits: 1
Walkthrough
  • Resident-aware lookup, zero diskless intake & metric split (helios/src/server/runtime.rs, metrics.rs, selene/src/offload.rs, pool/store.rs, disk_store.rs): Forwards GPU-resident token offsets on pool lookups with a once-per-episode stale-ticket refresh (runtime.rs:3227-3243), allocates zero local intake slots when local disk is disabled (offload.rs:681-685), splits ready disk inventory from uncommitted reservations (disk_store.rs:2788-2929), and exports per-level flare_host_cache_pool_inbound_bytes_per_second{level} (metrics.rs:1408-1422).
  • L1 DRAM clean retention & non-blocking drain (selene/src/memory.rs, composite.rs, pool/store.rs): Retains persisted_in_pool records with invariant-checked clean_slots / reclaimable_clean_slots accounting (memory.rs:1060-1121), decouples capture headroom from disk streaming intake (offload.rs:233-240), narrows shutdown drain to pending_pool_drain() (pool/store.rs:309-313).
  • GPU snapshot-alias packing, pressure eviction & restore pricing (helios/src/runtime_core/cache_memory.rs, memory.rs, scheduler/cache_memory.rs, scheduler/checkpoints.rs, cache.rs): Admits exact half-width alias planes with midpoint-ordered chunks and symmetric exponential+binary handle budgeting (cache_memory.rs:67-85, 248-319, 654-777), adds evict_for_pressure (scheduler/cache_memory.rs:615-670), prices restores via read-only estimate_prefill_delta_ns (checkpoints.rs:441-481) paired with per-tier RowRestoreLatency (runtime.rs:285-351).
  • Direct packed NVMe writes, event-driven waiters, clean arena retention & offer coalescing (selene/src/disk.rs, shard.rs, selene-manager/src/store.rs, arena.rs, pool/): 4 KiB-aligned O_DIRECT whole-record writes with exact set_len truncation (disk.rs:848-949, 1353-1478), StoreInvalidated propagated across sharded ranks (shard.rs:470, 650-735), tick-polled put waits replaced with lossless WindowReleaseSignal + epoch-tracked rotating waiter scans (store.rs:1690-1776, 5277-5281, 5540-5620), clean manager RAM extents retained via buddy coalescing_block (arena.rs:163-200, store.rs:2445-2480), and matching in-flight put offers coalesced.
Merge Risk: Medium · up to 7d7dcdc
  • Large cross-crate cache-core blast radius (+11,210 / −704 across 40 files): Touches GPU VMM alias planning (helios/src/runtime_core/cache_memory.rs), scheduler eviction/pricing (helios/src/scheduler/), host offload/sharding/direct I/O (selene/), and manager arena/waiter scheduling (selene-manager/src/store.rs); every core invariant is backed by targeted unit/integration tests and debug assertions.
  • Operator-visible metric, startup, and wire-event changes: flare_host_cache_intake_slots drops to 0 without local disk, sub-page memory-only budgets now fail startup cleanly (selene/src/offload.rs:711-717), flare_host_cache_disk_{records,bytes} excludes uncommitted reservations (requires tests/server/test_conditioned_input_cache.py:144-149 update), and selene/src/shard.rs:470,484 adds rank-relay event code Kind::StoreInvalidated = 4.
  • Concurrent PR overlap: Open PRs #665 (helios/src/cache.rs, docs/prefix-cache-offload.md) and #659 (helios/src/runtime_core/cache_memory.rs) edit the same regions; merge order should be coordinated.
Pre-merge checks: ✅ 2 passed · ⚠️ 2 warnings
  • ✅ Security / malicious screen: No credential handling, external network exfiltration, unsafe bypasses, or prompt-injection issues found; unsafe slice construction in selene/src/disk.rs:878,1429 is bounded by caller-pinned slab/input lifetimes.
  • ⚠️ Charter & value fit: Strongly aligned with the prefix-caching goal, model-agnostic, and fixes open issue #451; however, A/B tables A–C compare against 5d53040e (4 commits behind base 1fbcc3c9, before #663 and #667), and several behavior changes are omitted from the PR description (charter Qwen3.8 Flash Next DFlash2: mixed prefill rounds, YaRN serving, and served measurements from a fork #210 / docs/design-review.md Principles 12 & 16).
  • ⚠️ Related / duplicate / conflict check: Directly addresses #451 (issue still open and un-updated); overlaps open PRs #665 (helios/src/cache.rs, docs/prefix-cache-offload.md) and #659 (helios/src/runtime_core/cache_memory.rs) with no agreed merge sequence.
  • ✅ Tests & verification evidence: CI passed on 7d7dcdc, verification/helios-lifecycle/check.py --mutations (8/8 TLA+ models + Rust mutations) passed, and new CPU/unit/integration tests cover each mechanism without process-global state leaks; SM120 GPU tables A–F are author-reported without attached raw logs.
Should fix: 2
  1. Re-baseline headline A/B evidence against 1fbcc3c9 and disclose omitted behavior changes in the PR description (docs/design-review.md Principles 12 & 16; charter #210):
    • A/B tables A–C compare against 5d53040e, 4 commits behind the PR base 1fbcc3c9 (#657, #666, #663, #667; #663 touches scheduler waiting-age pricing, #667 touches Orbit/GB10/multi-host peer exports; Table F ran on 7d7dcdcb). Re-verify the headline A/B against 1fbcc3c9 (or confirm #663/#667 caused no baseline shift) and update #451 with the midpoint half-width conflict-span conclusion.
    • Add explicit PR-body disclosure for: (a) sub-page warm memory budgets without local disk now failing startup (selene/src/offload.rs:711-717), (b) the new rank-relay wire event Kind::StoreInvalidated = 4 (selene/src/shard.rs:470,484) requiring matching rank builds in multi-host TP deployments, (c) retention and narrowed sampling of the fallback prefill_rate EMA (helios/src/server/runtime.rs:2793-2803, 3110-3115, 3334-3335) rather than complete removal, (d) once-per-episode stale pool-lookup ticket refresh (helios/src/server/runtime.rs:3227-3243), and (e) the documentation updates in docs/ and selene-manager/docs/operating.md.
  2. Prevent RowRestoreLatency::start from resurrecting a decayed latency median on failed fetches (helios/src/server/runtime.rs:302-304):
    • start() unconditionally overwrites bucket.last = Some(now) whenever bucket.median_seconds.is_some(). If a tier saw a slow spike long ago (estimate decayed toward zero via the 10 s half-life) and a new row-only restore fails synchronously (store.fetch(...) returns Err) or asynchronously (finish(&key, false) never calls observe()), bucket.in_flight returns to 0 while bucket.last stays reset to now — jumping estimate_seconds() back to 100% of the stale median for another recovery window.
    • Fix: Do not overwrite bucket.last in start() (estimate_seconds() already returns the undecayed median while bucket.in_flight > 0 at :341); refresh bucket.last only inside observe() (or on successful completion).
Subtract / Simplify: 5
  1. Collapse TierStore::retired and TierStore::retired_offered into one method (selene/src/store.rs:433-444, selene/src/memory.rs:1185-1189, 3612-3626, selene/src/pool/local.rs:120-137, selene/src/pool/cascade.rs:415): the trait default forwards retired_offered -> retired, while every real implementor overrides both and forwards retired -> retired_offered(&[]). Replace both with a single fn retired(&mut self, _key: PrefixKey, _tier: PoolTier, _how: Retirement, _offered: &[Retiring]) {} and pass &[] at non-cascade call sites.
  2. Deduplicate writeback_wake_cursor / writeback_wake_remaining bookkeeping (selene-manager/src/store.rs:1586-1594, :1743-1768, :1850-1858, :4161-4168, :4236-4243): the modulo/clamp cursor fixup is duplicated across six sites, and close_operations (:4237-4243) omits the removed_before_cursor adjustment that resolve_published_waiters (:1571-1591) and expire_waiters (:1826-1855) perform. Extract remove_writeback_waiter(index) and retain_writeback_waiters(predicate) helpers to own the invariant in one place.
  3. Pass transfer and prefill seconds directly to Metrics::host_lookup_cost (helios/src/server/runtime.rs:3408-3415, helios/src/server/metrics.rs:538-560): admit_with_host_store computes effective_rate = gained as f64 / prefill_saved_seconds (with f64::INFINITY for 0.0) and clones HostHit just to satisfy host_lookup_cost(&priced_hit, effective_rate), which divides missing / rate.max(1.0) right back into seconds (clamping when 0 < effective_rate < 1.0). Accepting (missing_tokens, transfer_seconds, prefill_saved_seconds) deletes the HostHit::clone(), the f64::INFINITY trick, and the round-trip distortion.
  4. Extract Incoming::clear_pool_lookup(&mut self) (helios/src/server/runtime.rs:1800-1803, :2614-2617, :3030-3033, :3044-3047, :3076-3079): five sites repeat the same four-field reset (pool_lookup, pool_lookup_started, pool_lookup_reissued, pool_plan); one helper removes the duplication and prevents leaving pool_lookup_reissued stale on future edits.
  5. Narrow is_role_preserving_compaction visibility and simplify the redundant branch (helios/src/cache.rs:646-654, :688-695): is_role_preserving_compaction is pub(crate) but only called at helios/src/cache.rs:637 — make it private. The three-arm let tokens = ... ladder at :688-695 can collapse to if role_preserving { 0 } else { self.protected_eviction_tokens(node, rank) }, provided the literal mutation match in verification/helios-lifecycle/check.py:517 ("let tokens = self.protected_eviction_tokens(node, rank);") is updated in the same commit (and coordinated with #665).
Nits: 1
  • Duplicated pool level ordering (selene/src/levels.rs:121-128, helios/src/server/metrics.rs:1415-1418): Ranking::rates() returns [f64; 4] positionally while metrics.rs hardcodes the matching label array ["neighbour_gpu", "host_dram", "host_nvme", "remote_nvme"]. Co-locating a Level::ALL / label constant prevents silent positional drift.
Dropped on verification: 8 upstream findings dismissed
  • F7 (zero-progress eviction can spin ensure_resources) — False: helios/src/scheduler.rs:1284-1289 explicitly checks if evicted.retired.is_empty() and returns Err(Error::admission(AdmissionError::Capacity, ...)).
  • F3 (host_transfer_ns unit mismatch / fabricated host_prefill_ns 0 ns) — False: helios/src/server/metrics.rs:917-925 exposes flare_host_cache_estimated_transfer_ns and flare_host_cache_estimated_prefill_ns (matching worth_restore), and estimate_prefill_delta_ns (helios/src/scheduler/checkpoints.rs:438-439) legitimately returns Some(0) when both offsets execute the exact same quantized prefill graph sequence. Real cleanup moved to Subtract / Simplify.
  • F1 (prefill_rate EMA correctness / bias toward restores) — Inverted math & overstated: excluding queue wait (observed_duration_ns) yields a higher prefill_rate, making gained / rate smaller and biasing worth_restore against marginal restores; the EMA is only a cold fallback until PrefillPredictor learns each prefill capacity on all prefill steps. Only the PR-description gap survives.
  • F2 (sub-page startup failure / dead intake_warning) — Misread design: without local disk intake is intentionally 0, so a shrinkage warning should not fire (verified in selene/src/offload/tests.rs:684-738); failing startup cleanly when checkpoint_memory < page_record_bytes avoids a 0-byte SlabPool mmap failure and is documented (docs/prefix-cache-offload.md:169-171) and tested (selene/src/offload/tests.rs:1494-1511). Only PR-body disclosure survives.
  • F4 (lost StoreEvent::Fetched pins RowRestoreLatency forever) — Overstated: Fetched is also the sole trigger for scheduler.finish_inbound (helios/src/server/runtime.rs:2850), so a store dropping it already leaks GPU pages/requests; suspending decay while a slow fetch is in flight is deliberate backpressure. Replaced by the verified bucket.last reset issue in start().
  • F6 (#[cfg(test)]-only invariant verifiers / plan_mapping_handles per-step rebuild) — Low-signal: the startup-only binary search runs only above RM_HANDLE_RANGE (524,288) and memoizes identical TP rank geometries (helios/src/runtime_core/cache_memory.rs:706-716); heavyweight verification helpers staying #[cfg(test)] is standard.
  • S4 (delete DiskThread::start_with_faults) — Low-value churn: it has 10 test call sites across 4 files (selene/src/disk.rs, selene/src/composite.rs, selene/src/disk_store.rs, selene/src/shard/tests.rs).
  • capture_headroom_slots .clamp(1, ...) suggestion — Buggy: proposed .clamp(1, retention_slots.max(1)) returns 1 instead of 0 when retention_slots == 0, breaking the explicit test at selene/src/offload/tests.rs:1528.
  • Dossier inaccuracies corrected: 5d53040e is 4 commits behind 1fbcc3c9 (not 6; #656/#638 predate it); eviction_candidate_within_budget (helios/src/cache.rs:711-718) was retained as a wrapper, not renamed away; helios/src/runtime_core/memory/codec_layout_tests.rs was modified, not newly added.

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
yatesdr force-pushed the perf/selene-prefix-cache-holistic branch from 7d7dcdc to 19ce4a7 Compare December 2, 2026 09:37
@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

The 19ce4a7b refresh cleanly resolved all five Round-1 Subtract / Simplify items and rewrote the PR body into the charter's four-part format; deeper inspection confirms the core mechanisms (GPU midpoint half-width alias packing, pressure-aware eviction, O_DIRECT packed writes, L1 DRAM retention, arena buddy coalescing, event-driven waiter wakeups) are sound, and several upstream alarms (including a claimed selene-manager pump() spin loop) were verified false. One verified Round-1 correctness bug remains unfixed (RowRestoreLatency::start resets its decay clock on failed fetches), plus the baseline/disclosure carry-over.

  • Blockers: 1 · Should fix: 1 · Subtract/Simplify: 2 · Nits: 3
Walkthrough
  • Resident-aware lookup, diskless intake sizing & metric split (helios/src/server/runtime.rs, metrics.rs, selene/src/offload.rs, pool/lookup.rs, pool/store.rs, disk_store.rs): Passes GPU-resident token offsets into begin_lookup with a once-per-episode stale-ticket reissue (runtime.rs:3210-3218), allocates zero local intake slots when local disk is disabled (offload.rs:676-680), separates ready on-disk records/bytes from uncommitted reservations (disk_store.rs:2784-2920), and exports per-level flare_host_cache_pool_inbound_bytes_per_second{level} (metrics.rs:1409-1430).
  • L1 DRAM clean retention & non-blocking shutdown drain (selene/src/memory.rs, composite.rs, pool/local.rs, pool/cascade.rs, pool/store.rs): Retains persisted_in_pool records in L1 DRAM with invariant-checked clean_slots / reclaimable_clean_slots tracking (memory.rs:923-1204) and narrows shutdown drain to pending_pool_drain() (memory.rs:3517-3527, pool/store.rs:309-351).
  • GPU snapshot-alias packing, pressure eviction & restore pricing (helios/src/runtime_core/cache_memory.rs, scheduler/cache_memory.rs, scheduler/checkpoints.rs, scheduler.rs, cache.rs, server/runtime.rs): Admits half-width alias planes with midpoint-ordered chunks and symmetric exponential+binary handle budgeting (runtime_core/cache_memory.rs:67-101, 240-367, 655-770), adds evict_for_pressure (scheduler/cache_memory.rs:593-649, scheduler.rs:1258-1291), and prices restores via read-only estimate_prefill_delta_ns (checkpoints.rs:441-490) paired with RowRestoreLatency (runtime.rs:257-344) while excluding row-only fetches from bulk bandwidth medians (memory.rs:1715-1743, disk_store.rs:3425-3434, pool/store.rs:376-379).
  • Direct compressed I/O, event-driven waiters, clean arena retention & offer coalescing (selene/src/disk.rs, shard.rs, selene-manager/src/store.rs, arena.rs, pool/claims.rs): Writes compressed v4 records via aligned O_DIRECT + exact set_len truncation (disk.rs:848-876, 1271-1447), propagates StoreInvalidated across sharded ranks (shard.rs:470, 653-734), replaces tick-polled put waits with coalesced WindowReleaseSignal wakeups (store.rs:5309-5365), epoch-tracked rotating waiter scans (store.rs:1588-1666), and filter_writeback_waiters (store.rs:1443-1475), retains clean manager RAM extents via Arena::coalescing_block (arena.rs:163-200, store.rs:2246-2269), and resolves covered waiting offers directly to Present (store.rs:1481-1523, 5792-5836).
Merge Risk: Medium · up to 19ce4a7
  • Large cross-crate cache-core footprint (+10,035 / -1,142 across 41 files): Touches GPU VMM alias planning (helios/src/runtime_core/cache_memory.rs), scheduler eviction/pricing (helios/src/scheduler/), host offload/sharding/direct I/O (selene/), and manager arena/waiter scheduling (selene-manager/src/store.rs); core state-machine invariants are backed by unit/integration tests and debug assertions.
  • Wire, startup, and API compatibility surface: Adds rank-relay event code Kind::StoreInvalidated = 4 (selene/src/shard.rs:470, 484), fails startup cleanly on sub-page memory-only budgets (selene/src/offload.rs:706-712), separates committed vs reserved disk gauges (docs/api.md:390-394), and updates HostStore::begin_lookup, TierStore::retired, TierStore::pending_pool_drain, HostHit, and StoreStats (selene/src/store.rs:100-103, 248-256, 377, 401-404, 433-440).
  • Concurrent PR overlap: Open PRs #665 (helios/src/cache.rs, docs/prefix-cache-offload.md (not opened)) and #659 (helios/src/runtime_core/cache_memory.rs) modify the same regions; merge ordering should be coordinated.
Pre-merge checks: ✅ 1 passed · ⚠️ 3 warnings
  • ✅ Security / malicious screen: No credential handling, external exfiltration, or prompt-injection vectors found; unsafe slice construction in selene/src/disk.rs:1277, 1321, 1404 is bounded by caller-pinned slab/buffer lifetimes.
  • ⚠️ Charter & value fit: Directly serves the prefix-caching goal, stays model-agnostic, and addresses #451; however, Tables A–C still compare against 5d53040e (4 commits behind 1fbcc3c9, before #663 and #667), benchmarks ran on 7d7dcdcb rather than 19ce4a7b, and three compatibility items remain undisclosed in the PR body (charter #210, docs/design-review.md (not opened) Principles 12 & 16).
  • ⚠️ Related / duplicate / conflict check: Addresses open issue #451 (still un-updated with the midpoint half-width conflict-span conclusion); overlaps open PRs #665 (helios/src/cache.rs, docs/prefix-cache-offload.md (not opened)) and #659 (helios/src/runtime_core/cache_memory.rs).
  • ⚠️ Tests & verification evidence: Unit/integration tests and verification/helios-lifecycle/check.py:515-528 mutation guard are updated and well-isolated, but no CI status is yet reported for the force-pushed head 19ce4a7b, and phase_tests.rs:8799-8801 misses the RowRestoreLatency::start failed-fetch regression.
Blockers (1)
  1. Fix RowRestoreLatency::start resetting the decay clock on failed fetches (helios/src/server/runtime.rs:301-303, carry-over from Round 1):
    • start() unconditionally overwrites bucket.last_median's timestamp (*last = now) whenever a prior median exists. When a row-only fetch fails synchronously (runtime.rs:3401-3407) or asynchronously (StoreEvent::Fetched { result: Err(_) } at runtime.rs:2825-2826), finish(&key, false) decrements bucket.in_flight to 0 and returns early without calling observe() (runtime.rs:313-315), leaving *last = now.
    • As a result, a historical slow spike that had already decayed toward zero via the 10 s half-life (runtime.rs:342) jumps back to 100% of median on every failed fetch, causing worth_restore() (runtime.rs:3346-3355) to reject healthy row-only restores for another recovery window. The existing test (helios/src/server/runtime/phase_tests.rs:8799-8801) only exercises start + finish(false) when last_median is None.
    • Fix: Delete lines 301-303 (if let Some((_, last)) = &mut bucket.last_median { *last = now; }) in RowRestoreLatency::start()—estimate_seconds() already holds median undecayed while bucket.in_flight > 0 (runtime.rs:339-341), and observe() updates last_median on successful completion. Add a regression test in phase_tests.rs that observes a median, ages last_median, runs start + finish(false), and asserts the decayed estimate is preserved.
Should Fix (1)
  1. Re-verify baseline A/B against 1fbcc3c9 (on 19ce4a7b) and disclose remaining compatibility changes in the PR body (carry-over from Round 1; charter #210, docs/design-review.md (not opened) Principles 12 & 16):
    • Headline Tables A–C compare against 5d53040e, four commits behind PR base 1fbcc3c9 (#657, #666, #663, #667), where #663 (8489d504) changes scheduler latency pricing directly affecting Tables B/C and #667 (1fbcc3c9) changes GB10/multi-host peer exports; hardware runs were also executed on pre-refactor 7d7dcdcb rather than 19ce4a7b. Re-baseline the headline A/B against 1fbcc3c9 (or confirm no baseline shift from #663/#667), confirm green CI on 19ce4a7b, and post the midpoint half-width conflict-span conclusion on #451.
    • Add concise bullets under Compatibility and Limitations for the three still-omitted changes: (a) new internal rank-relay event Kind::StoreInvalidated = 4 (selene/src/shard.rs:470, 484-485), requiring matching rank builds in multi-host TP deployments; (b) sub-page warm memory budgets without local disk now failing startup cleanly (selene/src/offload.rs:706-712); and (c) public flare-selene trait/struct updates (HostStore::begin_lookup, TierStore::retired, TierStore::pending_pool_drain, HostHit.pooled, StoreStats reserved/rate fields at selene/src/store.rs:100-103, 248-256, 377, 401-404, 433-440).
Subtract / Simplify (2)
  1. Deduplicate the "half the prefill" restore predicate (helios/src/server/runtime.rs:225-229, selene/src/store.rs:450-468): worth_restore(transfer_seconds, prefill_saved_seconds) in Helios duplicates the 0.5 * + is_finite() policy from selene::worth_transfer, which now has only test callers left. Expose worth_restore in selene/src/store.rs, express worth_transfer through it, and delete the duplicate in helios/src/server/runtime.rs.
  2. Group admit_with_host_store's 15 positional arguments (helios/src/server/runtime.rs:3285-3302): Remove #[allow(clippy::too_many_arguments)] by passing a small request-probe struct (spec, prefill_spans, conditioned_images, core_parameter_defs, core_parameters), which can also eliminate the duplicate PreparedImageInput::conditioned_input mapping at runtime.rs:1722-1725 and :3324-3327.
Nits (3)
  • Windows write_packed buffered fallback (selene/src/disk.rs:1408-1438, 1774-1784; eos/src/windows.rs:104-109): eos::windows::check_alignment returns io::ErrorKind::Unsupported when sector size does not divide 4096, while is_direct_unsupported returns false on #[cfg(not(unix))], making the buffered fallback at disk.rs:1423 unreachable on Windows. Matching ErrorKind::Unsupported | ErrorKind::InvalidInput in the non-Unix arm restores parity.
  • Per-level row-restore bucketing (helios/src/server/runtime.rs:257-268, selene/src/pool/store.rs:465, 479-480): RowRestoreSource keys on (pooled, Tier), which isolates local DRAM from pooled/NVMe sources as intended, but pools HostNvme and RemoteNvme (and NeighbourGpu and HostDram) together. Carrying Level on HostHit would separate all four pool levels.
  • Positional pool level ordering (selene/src/levels.rs:121-128, helios/src/server/metrics.rs:1418-1423): Ranking::rates() returns [f64; 4] positionally while metrics.rs hardcodes the matching label strings. Co-locating a shared (Level, &'static str) constant prevents silent index drift.
Dropped on verification (8)
  • Correctness F1 (Unbounded self-rearming spin loop in selene-manager/src/store.rs:5067-5072 & selene/src/disk.rs:533-535) — False: Verified in selene-manager/src/store.rs:1319-1329, :1749-2078, :3478-3570, :1610-1666, and :1668-1738 that begin_put and begin_get never leave or re-enqueue blocked operations in pending_puts / pending_gets (blocked puts move into inflight_waiters or writeback_waiters, or are rejected; expired waiters hit immediate rejection checks at :1387-1398 / :1407-1414), writeback_wake_remaining strictly decreases by up to WRITEBACK_WAKE_SCAN (32) per pump to 0, and control.rs:203-227 processes up to 64 client commands per pump before store.pump(). on_reply in selene/src/disk.rs:355-390, 533-535 is only enabled by selene-manager (DiskThread::start_with_wakeup), not by client DiskThread::start, and fires once per NVMe job completion.
  • Correctness F7 (has_pending_reclaim permanently blackholes keys in selene/src/disk_store.rs:2516-2518) — Speculative / misread design: DiskThread is an in-process thread that always replies to submitted jobs, synchronous submission errors immediately apply TransportEvent::Unlinked (disk_store.rs:3209-3217), and a broken peer in Sharded poisons the whole transport (shard.rs:589-671). Blocking re-capture while an unlink/truncate of the deterministic record::file_name(&key) path is in flight prevents file-path races, and maintenance is bounded by MAINTENANCE_IN_FLIGHT.
  • Correctness F8 (Unchecked -= on committed_records/committed_bytes at selene/src/disk_store.rs:2788-2792) — Low-signal: Consistent with all other exact accounting updates across disk_store.rs (:2846-2863, :2911-2912, :3154), guarded by was_ready and assert_disk_accounting() (:3565-3584).
  • Correctness F9 (Undocumented span shift in Metrics::host_lookup_cost) — Low-signal: The histograms are explicitly named flare_host_cache_estimated_transfer_ns and flare_host_cache_estimated_prefill_ns (docs/api.md:293-294) and have always recorded admission cost estimates rather than measured execution times.
  • Simplicity S1 (Delete RowRestoreLatency and reuse selene::levels::Rate) — Inaccurate: Rate (selene/src/levels.rs:36-87) is pub(crate) in flare-selene, tracks upward-recovering bytes/sec toward a finite seed, and its started() has the same unconditional last overwrite without per-key in_flight duration tracking. Deleting 3 lines at runtime.rs:301-303 is far simpler than exporting and generalizing Rate across crates.
  • Simplicity S3 (Remove plan_refreshed: bool and move refresh out of begin_pool_lookup) — Inaccurate: Verified at helios/src/server/runtime.rs:3183-3240, 3303-3315 that the retry path does not refresh twice (begin_pool_lookup returns true after :3222, so :3307 is skipped), and begin_pool_lookup needs the refreshed plan.resident_tokens() before awaits_pool() (:1625) to decide stale-ticket reissue (:3210) and lookup necessity (:3235).
  • Simplicity S4 (Drop free.clone() and Some((0, 0)) in Arena::coalescing_block) — False: Verified at selene-manager/src/arena.rs:163-200 and selene-manager/src/store.rs:2246-2269, 5346 that (1) free.clone() is required because buddy simulation mutates free in place (:183-198), and (2) Some((0, 0)) handles concurrent Arc<Extent> release from WindowHold on Tokio pool threads between allocate() and coalescing_block(), avoiding needless eviction of clean records.
  • Prior Round-1 items already resolved in 19ce4a7b (verified closed): TierStore::retired / retired_offered merge, filter_writeback_waiters deduplication (including close_operations), scalar Metrics::host_lookup_cost, Incoming::clear_pool_lookup, and helios/src/cache.rs + verification/helios-lifecycle/check.py:515-528 cleanup.

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
yatesdr force-pushed the perf/selene-prefix-cache-holistic branch from 19ce4a7 to 0ebee3d Compare December 2, 2026 18:07
@yatesdr

yatesdr commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased cleanly onto main (4cc6f2fd, resolving the end-of-file test conflict in helios/src/scheduler/checkpoints.rs) and addressed the Autobot findings in 0ebee3d4:

  • Fixed RowRestoreLatency::start decay-clock reset on failed fetches (helios/src/server/runtime.rs): stopped overwriting last_median in start() so failed row-only fetches preserve the aged decay clock, and added a regression test in helios/src/server/runtime/phase_tests.rs.
  • Deduplicated worth_restore (selene/src/store.rs, selene/src/lib.rs, helios/src/server/runtime.rs): exported flare_selene::worth_restore, expressed worth_transfer through it, and removed the Helios duplicate.
  • Grouped admit_with_host_store request arguments (helios/src/server/runtime.rs): extracted HostAdmissionProbe and conditioned_inputs_from_images, removing #[allow(clippy::too_many_arguments)].
  • Windows direct-I/O fallback & shared pool level ordering (selene/src/disk.rs, selene/src/levels.rs, helios/src/server/metrics.rs): matched ErrorKind::Unsupported | ErrorKind::InvalidInput in non-Unix is_direct_unsupported, and shared levels::POOL_LEVELS between Ranking::rates() and Prometheus label rendering.
  • Updated PR description with explicit disclosures for Kind::StoreInvalidated = 4, sub-page warm memory startup validation, public flare-selene API updates, narrowed fallback prefill_rate EMA, and the 5d53040e hardware A/B baseline.

Re-verified on Linux (0ebee3d4): RUSTFLAGS="-D warnings" cargo check --locked --all-targets clean across all 4 crates; selene (585/585), selene-manager (205 lib + 128 integration), helios (1,817/1,817 release lib), flare (254/254 release), and verification/helios-lifecycle/check.py --mutations (8/8 TLA+ models + all Rust mutations) all passed.

@flare-autobot

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Ready To Merge

Head 0ebee3d4 cleanly rebases onto main (4cc6f2fd, preserving #660 and #670) and resolves every blocker, disclosure item, subtraction, and platform/ordering nit from Round 2. Direct verification of all four subsystems confirms no remaining correctness, safety, concurrency, or CI blockers; only optional cleanups and merge-order coordination remain.

  • Blockers: 0 · Should fix: 0 · Subtract/Simplify: 1 · Nits: 3
Walkthrough
  • Resident-aware lookup, diskless intake sizing & telemetry (helios/src/server/runtime.rs:1635-1650, 3271-3367, helios/src/server/metrics.rs:1409-1428, selene/src/offload.rs:676-712, selene/src/levels.rs:109-132, selene/src/store.rs:244-256, 377, 451-479): Passes GPU-resident token offsets on pool lookups, allocates zero local intake slots when local disk is disabled (failing cleanly on sub-page memory-only budgets), separates ready disk inventory from uncommitted reservations, shares levels::POOL_LEVELS between Ranking::rates() and Prometheus labels, exports flare_selene::worth_restore, and groups admission probe parameters into HostAdmissionProbe.
  • L1 DRAM clean retention & non-blocking shutdown drain (selene/src/memory.rs:923-1085, selene/src/pool/store.rs:307-357, selene/src/store.rs:401-404, 433-440): Retains clean persisted_in_pool records in L1 DRAM with invariant-checked clean_slots and handover revalidation (handover_valid, refresh_ancestors, refresh_same_page_descendants, promote_role), and narrows shutdown drain to pending_pool_drain().
  • GPU snapshot-alias packing, pressure eviction & restore pricing (helios/src/runtime_core/cache_memory.rs:655-770, helios/src/scheduler/cache_memory.rs:593-649, helios/src/cache.rs:628-707, helios/src/scheduler/checkpoints.rs:445-494, helios/src/server/runtime.rs:250-333, verification/helios-lifecycle/check.py:515-528): Packs shared GPU snapshot aliases with symmetric exponential+binary handle budgeting, adds evict_for_pressure with matching mutation guard, prices restores via read-only estimate_prefill_delta_ns paired with RowRestoreLatency (preserving aged decay clocks on failed fetches, covered at helios/src/server/runtime/phase_tests.rs:8829-8851).
  • Direct compressed I/O, event-driven waiters, clean arena retention & offer coalescing (selene/src/disk.rs:848-875, 1271-1447, 1774-1786, selene/src/shard.rs:465-500, selene-manager/src/arena.rs:163-200, selene-manager/src/store.rs:1443-1666, 2237-2272, 5309-5365): Uses aligned whole-record O_DIRECT writes with exact set_len truncation and portable is_direct_unsupported fallback, propagates Kind::StoreInvalidated = 4 across sharded ranks, replaces tick-polled put waits with lossless WindowReleaseSignal + WindowHold drop-ordered wakeups and epoch-tracked rotating scans, retains clean manager RAM via Arena::coalescing_block, and coalesces covered waiting offers directly to Present.
Merge Risk: Medium · up to 0ebee3d
  • Broad cross-crate cache-core surface (+10,106 / -1,158 across 42 files): Touches GPU VMM snapshot-alias planning (helios/src/runtime_core/cache_memory.rs), scheduler pressure eviction and prefill-delta pricing (helios/src/scheduler/), local/pooled host offload and direct I/O (selene/), and manager arena retention and event-driven waiter wakeups (selene-manager/src/store.rs, arena.rs). Core state-machine invariants are guarded by debug assertions, unit/integration suites, and 8/8 TLA+ models with mutation checks.
  • Wire, startup, and public crate compatibility: Adds rank-relay wire event Kind::StoreInvalidated = 4 (selene/src/shard.rs:470, 484), fails startup cleanly on sub-page memory-only budgets (selene/src/offload.rs:706-712), splits committed vs reserved disk inventory gauges (docs/api.md:390-394), and updates public flare-selene APIs (selene/src/store.rs:248-256, 377, 401-404, 433-440, 451, selene/src/levels.rs:109-114) in lockstep with workspace callers; all are now explicitly disclosed in the PR description.
  • Concurrent PR overlap: Open PRs #655 (helios/src/scheduler/checkpoints.rs), #665 (helios/src/cache.rs, docs/prefix-cache-offload.md (not opened)), and #659 (helios/src/runtime_core/cache_memory.rs) modify overlapping regions and will need coordinated merge sequencing.
Pre-merge checks: ✅ 3 passed · ⚠️ 1 warning
  • ✅ Security / malicious screen: No credential handling, external exfiltration, or prompt-injection vectors found; unsafe slice construction in selene/src/disk.rs:1277, 1321, 1404 is bounded by caller-pinned buffer/slab lifetimes.
  • ✅ Charter & value fit: Directly advances the prefix-caching charter goal, stays model-agnostic, fixes open issue #451, and follows the four-part PR description with explicit disclosures (note: SM120 A/B tables remain measured on pre-refactor 7d7dcdcb vs 5d53040e and transparently noted as such).
  • ⚠️ Related / duplicate / conflict check: Directly addresses #451 (issue still open and un-updated with the midpoint half-width conclusion); overlaps open PRs #655, #665, and #659 with merge order to be coordinated.
  • ✅ Tests & verification evidence: Author reports clean -D warnings check across all 4 crates and passing Linux suites on 0ebee3d4 (selene 585, selene-manager 205 lib + 128 integration, helios 1,817 release lib, flare 254 release, and verification/helios-lifecycle/check.py --mutations 8/8 TLA+ models + Rust mutations), including the new RowRestoreLatency aged-decay regression test (phase_tests.rs:8829-8851); confirm green GitHub CI checks on 0ebee3d4 before merging.
Subtract / Simplify: 1 item
  1. Share greedy conditioned-window partitioning between conditioned_window_ends and set_conditioned_inputs (helios/src/scheduler.rs:2094-2123, :2162-2183): Both loops implement the same features + input.feature_range.len() > capacity boundary split (with conditioned_window_ends additionally filtering token_span.end > consumed). Extracting a small shared window-boundary helper keeps both paths aligned if conditioned-input windowing changes later.
Nits: 3 items
  • Post wrap-up on #451: Add a brief comment on open issue #451 recording the midpoint half-width conflict-span resolution implemented here.
  • Coordinate merge order: Sequence with open PRs #655 (helios/src/scheduler/checkpoints.rs), #665 (helios/src/cache.rs, docs/prefix-cache-offload.md (not opened)), and #659 (helios/src/runtime_core/cache_memory.rs).
  • PR-body wording & optional follow-up: In What §3, refer to flare_host_cache_pool_inbound_bytes_per_second{level} as "pool restore rate estimates" (matching helios/src/server/metrics.rs:1412 and docs/api.md:394-398, which already document it accurately). Optionally, if separating pooled HostNvme vs RemoteNvme (or NeighbourGpu vs HostDram) row-restore latencies becomes useful later, RowRestoreSource (helios/src/server/runtime.rs:250-260) can key on Level.
Dropped on verification
  • Upstream claims that 0ebee3d4 and all Round-2 fixes were absent (RowRestoreLatency::start, worth_restore, HostAdmissionProbe, POOL_LEVELS, Windows is_direct_unsupported, PR body disclosures) — Stale snapshot: Upstream flash lenses inspected the stale default ref (19ce4a7b) instead of pr/674 (0ebee3d4), where every one of those fixes is verified landed (helios/src/server/runtime.rs:284-293, 3271-3362, helios/src/server/runtime/phase_tests.rs:8829-8851, selene/src/store.rs:451-479, 516-519, selene/src/lib.rs:53, selene/src/disk.rs:1779-1785, selene/src/levels.rs:109-132, helios/src/server/metrics.rs:1418-1427).
  • Correctness F1b (RowRestoreLatency::in_flight has no reaper) — Duplicate / already dropped in Round 1: row_restore_latency.start/finish (helios/src/server/runtime.rs:2814, 3410-3415) is 1:1 paired with scheduler.finish_inbound (:2815, 3418), so a dropped StoreEvent::Fetched already leaks the scheduler's InboundTicket and GPU pages.
  • Correctness F2 (observe_prefill_rate requiring step.lanes.len() == 1 pins multi-lane servers at INITIAL_PREFILL_RATE forever) — False: ActionCosts::observe (helios/src/scheduler/cost.rs:830-864) updates PrefillPredictor on every GPU-timed prefill step regardless of lane count, so estimate_prefill_delta_ns (helios/src/scheduler/checkpoints.rs:445-494, called at helios/src/server/runtime.rs:3257-3266) prices warm restores without consulting fallback_prefill_rate.
  • Correctness F4 (Rate::get() permanently clamps faster-than-seed rates at self.seed) — False: Verified at selene/src/levels.rs:69-75 and test :169-172 that .min(self.seed) applies only in the Some(last) if self.median < self.seed recovery arm; measured rates >= seed return uncapped via _ => self.median, and metrics.rs:1412 / selene/src/store.rs:254-256 / docs/api.md:394-398 accurately document the gauge as source-ranking rate estimates.
  • Simplicity F1 (delete RowRestoreLatency and reuse selene::levels::Rate) — Already dropped in Round 2: Rate is pub(crate) in flare-selene, models upward-recovering throughput with a finite seed, and lacks per-key in_flight duration tracking; removing the 3-line timestamp overwrite in start() is strictly simpler.
  • Simplicity F5 (replace aligned-prefix branch in write_record_direct at selene/src/disk.rs:1278-1305 with write_direct_slices) — Misguided / throughput regression: write_record_direct writes the multi-hundred-MiB aligned prefix zero-copy from span.address and copies only the < 4 KiB tail into self.scratch in a single ring.transfer, whereas write_direct_slices (:1331-1376) copies the entire record through the small scratch buffer in sequential transfers.

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
yatesdr force-pushed the perf/selene-prefix-cache-holistic branch from 0ebee3d to 45fb380 Compare December 2, 2026 18:41
@lukealonso

Copy link
Copy Markdown
Collaborator

Review of helios/ changes (reviewed at head 0ebee3d4, base 4cc6f2fd): Changes Requested

The GPU snapshot-alias packing (helios/src/runtime_core/cache_memory.rs), read-only prefill-delta estimator (helios/src/scheduler/checkpoints.rs), and Prometheus metric updates (helios/src/server/metrics.rs) are solid, but there are three correctness bugs and one hot-path performance defect in helios/ that should be fixed before merge.


1. Bugs

1.1 observe_prefill_rate is unconditionally dead code (helios/src/server/runtime.rs:3052-3071)

let capacity = step.prefill_capacity() as u64;
if !step.kind.is_prefill()
    || step.lanes.len() != 1
    || capacity == 0
    || (step.lanes[0].tokens as u64).saturating_mul(2) < capacity
{
    return;
}
  • ScheduledStep::prefill_capacity() (helios/src/scheduler.rs:465-467) returns self.mixed.as_ref().map_or(0, |m| m.prefill_capacity).
  • Every pure prefill step (step.kind.is_prefill() == true: Prefill, TerminalPrefill, or ScoredPrefill) has step.mixed == None, so step.prefill_capacity() always returns 0.
  • Every Mixed step has step.kind.is_prefill() == false.

As a result, !step.kind.is_prefill() || capacity == 0 is always true. observe_prefill_rate never updates self.prefill_rate, leaving the cold fallback permanently frozen at INITIAL_PREFILL_RATE (8000.0). On pure prefill steps, the prefill capacity is step.token_capacity, not step.prefill_capacity().

Fix: Use step.token_capacity as u64 (since !step.kind.is_prefill() already filters to pure prefill steps) and add a unit test in helios/src/server/runtime/phase_tests.rs verifying that observe_prefill_rate updates worker.prefill_rate when tokens * 2 >= token_capacity and skips < 50% fills and multi-lane steps.


1.2 page_pressure_victim_priority breaks recency and role protection whenever unpinned checkpoints overlap (helios/src/scheduler/cache_memory.rs:204-224, :391-409, :593-649)

page_pressure_victim_priority orders candidates by:

(
    !releases_page,
    node.retention_rank().use_epoch,
    !role_preserving_compaction,
)

followed by (node.retention_rank(), node.id) in select_eviction_candidate.

Because !releases_page sorts ahead of use_epoch and role:

  1. Hot Anchor leaves evicted ahead of dead overlapping pairs: Whenever two unpinned cold checkpoints (for example, epoch 1 and epoch 2 Endpoint ancestors or same-page checkpoints with tail_pages.is_empty()) share a backing band (refs == 2 each), neither individually satisfies refs[page] == 1, so both get releases_page == false. Meanwhile, a brand-new hot Anchor leaf from epoch 10,000 with tail_pages gets releases_page == true. Under mandatory page pressure (evict_for_pressure, where below = None), evict_for_pressure destroys every hot Anchor/Message leaf in the cache before touching those dead epoch-1/2 overlapping checkpoints.

  2. Unrelated leaf eviction on pure snapshot backing conflict (need_pages == 0): In ensure_resources, when need_pages == 0 and backing_conflict == true (free pages already suffice, but the currently free snapshot conflicts with them), evict_for_pressure sets page_pressure = true. It evicts a recent hot leaf in an unrelated band rather than a cold epoch-1 overlapping ancestor whose snapshot itself could immediately satisfy available_snapshot(pages) at zero page cost.

  3. Documentation mismatch (docs/runtime-core-design.md:869-873):

    "Under page pressure, victim selection prioritizes checkpoints that release at least one usable KV page (leaf tail pages or uniquely referenced snapshot-backing pages) over overlapping rows that release none, preserves completion recency..."

    Completion recency is only preserved within each releases_page partition, not globally.

Fix: Distinguish checkpoints whose shared backing is held by a pinned or in-flight owner (genuinely unfreeable right now) from checkpoints whose shared backing is held only by other unpinned cold checkpoints (freeable together), or bound the !releases_page skip so it cannot sacrifice a strictly newer Anchor/Message leaf ahead of ancient unpinned overlapping entries. Also check whether need_pages == 0 && backing_conflict should prefer freeing an unblocked snapshot over evicting an unrelated hot leaf, and align docs/runtime-core-design.md:869-873 with the resulting policy.


1.3 RowRestoreLatency::observe sign inversion on count == 2 resurrects a decayed spike on a fast probe (helios/src/server/runtime.rs:307-329)

RowRestoreLatency::observe maintains a 3-sample ring buffer of latencies (seconds, where lower is faster) and computes:

ordered[..bucket.count].sort_by(f64::total_cmp);
bucket.last_median = Some((ordered[bucket.count / 2], std::time::Instant::now()));

This mirrors selene::levels::Rate::observe (selene/src/levels.rs:65-67), where Rate tracks bytes/sec (higher is faster) so values[2 / 2] = values[1] selects the faster sample and clears a single slow transfer on the first fast recovery probe.

Because RowRestoreLatency is inverted (lower is faster), ordered[2 / 2] = ordered[1] selects the slower sample when count == 2:

  • Suppose one 500 ms spike occurs (samples = [0.500], count = 1, last_median = (0.500, t0)).
  • After 30–40 s, the decayed estimate drops below threshold and admits a recovery probe that succeeds in 2 ms.
  • observe(0.002) produces ordered[..2] = [0.002, 0.500], selects ordered[1] = 0.500, and resets last_median's timestamp to now — jumping estimate_seconds() right back to 500 ms and locking out row-only restores for another full recovery window despite the 2 ms success.

Fix: Use ordered[(bucket.count - 1) / 2] (lower median, symmetric with Rate's upper median for throughput) so a single spike clears on the first fast probe instead of re-arming the decay clock, and add a regression test for a single aged spike followed by a fast probe.


2. Hot-Path Performance Defect in Pressure Eviction

Locations: helios/src/scheduler/cache_memory.rs:204-224, :391-409, :608-649, and helios/src/cache.rs:640-656.

On a large-KV-budget core such as DeepSeek-V4.1-Flash TP4 (156,956 KV pages, 4,864 snapshots, <= 172 pages per snapshot) or Qwen3.8 TP2 (span <= 384 pages), pressure eviction currently performs three avoidable O(N) / O(N * span) allocations and scans per single evicted victim on the single-threaded scheduler loop:

  1. Unconditional 628 KiB Vec<u32> clone per victim (scheduler/cache_memory.rs:608): evict_for_pressure clones self.page_snapshot_refs (156,956 * 4 B = 628 KiB) on every iteration of ensure_resources and refill_reservations, even when self.cache.pending_retirement().is_empty() && self.retired.is_empty() (the common case when no fenced retirements are in flight). Using Cow::Borrowed(&self.page_snapshot_refs) when no retirements are pending eliminates this allocation on the common path.
  2. Per-victim HashMap allocation over all checkpoints (cache.rs:640-656): select_eviction_candidate allocates and populates a fresh HashMap<CheckpointId, RetentionRole> over all self.nodes (up to 4,864 nodes) on every single call in evict_for_pressure and every loop iteration of simulate_snapshot_quote. Tracking only_child: Option<CheckpointId> directly on Checkpoint alongside child_count makes the role check O(1) with zero heap allocation.
  3. O(candidates * span) scan inside page_pressure_victim_priority (scheduler/cache_memory.rs:211-218): Scanning range.clone().any(|page| refs[page] == 1) per candidate costs up to 4,864 * 172 (~836k) checks per single victim inside both evict_for_pressure and simulate_snapshot_quote (where select_snapshots explicitly uses prefix sums to avoid O(candidates * span)). A prefix sum of u32::from(refs[p] == 1) built once per pass makes releases_page O(1) per candidate.

(Minor consistency note in evict_for_pressure: retiring_snapshots chains pending_retirement and retired without deduplicating via BTreeSet as projected_fits does at helios/src/scheduler/cache_memory.rs:526.)


3. Minor Edge Cases and Cleanups in helios/

  1. begin_pool_lookup misses full-GPU-hit eviction while queued (helios/src/server/runtime.rs:3171-3228): If a request arrives when the full prompt is GPU-resident (resident_tokens == prompt.len()), begin_pool_lookup stores pool_plan = Some(plan) and leaves pool_lookup = None. If the request is capacity-blocked and that GPU checkpoint is evicted before admission, incoming.pool_plan.is_some() && !retry returns false at let Some(ticket_resident) = ... else { return false; } without refreshing plan or issuing a pool lookup. (Pre-existing gap, directly adjacent to the new stale-ticket reissue logic.)
  2. plan_mapping_handles binary search monotonicity note (helios/src/runtime_core/cache_memory.rs:754-766): Layout::grouped followed by pack_rows is not strictly monotone in granules because a larger chunk can cross a row boundary and stop being eligible for pack_rows merging. Because winning is only updated when candidate_total < limit, the search never violates the handle limit and stays <= hi, so it is safe; add a short comment noting it finds a feasible granules <= hi rather than assuming strict monotonicity.
  3. Duplicated conditioned-window partitioning (helios/src/scheduler.rs:2094-2123, :2162-2183): conditioned_window_ends duplicates set_conditioned_inputs's features + input.feature_range.len() > capacity boundary loop; extracting a shared helper keeps both paths aligned.

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Changes Requested

The selene/ and selene-manager/ changes (direct O_DIRECT packed writes, StoreInvalidated propagation, clean L1 DRAM and buddy-coalesced manager RAM retention, lossless WindowReleaseSignal / epoch-tracked waiter wakeups, disk inventory/reservation metric split) and the helios/ GPU snapshot-alias packing and read-only prefill-delta estimator are well-engineered and sound. However, head 45fb380 (rebased onto main c513e46a, including #665) has three verified correctness blockers in helios/ — including a new rebase regression where page_pressure_victim_priority bypasses #665's scan-resistant is_protected(node) tier, an unconditionally dead observe_prefill_rate sampler, and an inverted upper-median index in RowRestoreLatency::observe — plus three per-victim O(N) / O(N * span) scheduler hot-path costs and stale pre-#665 A/B baselines.

  • Blockers: 3 · Should fix: 2 · Subtract/Simplify: 2 · Nits: 3
Walkthrough
  • Resident-aware lookup, diskless intake sizing & telemetry (helios/src/server/runtime.rs:1602-1656, 3171-3429, helios/src/server/metrics.rs:1409-1428, selene/src/offload.rs:676-712, selene/src/levels.rs:109-132, selene/src/disk_store.rs:2140-2142, 3566-3584, 3749-3751, selene/src/store.rs:451-479): Forwards GPU-resident token offsets on pool lookups with once-per-episode stale-ticket refresh, sizes local intake slots to 0 when local disk is disabled (failing cleanly when checkpoint_memory < page_record_bytes), splits ready disk inventory from uncommitted reservations, shares levels::POOL_LEVELS between Ranking::rates() and Prometheus rendering, and exports flare_selene::worth_restore.
  • L1 DRAM clean retention & non-blocking drain (selene/src/memory.rs:721-770, 914-1095): Retains persisted_in_pool records in local DRAM with invariant-checked clean_slots accounting and handover revalidation (handover_valid, refresh_ancestors, refresh_same_page_descendants, promote_role).
  • GPU snapshot-alias packing, pressure eviction & restore pricing (helios/src/runtime_core/cache_memory.rs:67-101, 235-330, 655-770, helios/src/scheduler/cache_memory.rs:204-223, 365-430, 593-649, helios/src/cache.rs:722-820, helios/src/scheduler/checkpoints.rs:445-494, helios/src/server/runtime.rs:249-333, 3052-3075, verification/helios-lifecycle/check.py:515-528): Admits exact half-width alias planes ordered by descending midpoint with symmetric exponential+binary handle budgeting, adds evict_for_pressure and page_pressure_victim_priority, and prices host restores via read-only estimate_prefill_delta_ns paired with RowRestoreLatency and a narrowed cold fallback EMA.
  • Direct packed NVMe writes, event-driven waiters, clean arena retention & offer coalescing (selene/src/disk.rs:837-881, 1272-1447, 1765-1786, selene/src/shard.rs:465-520, selene-manager/src/arena.rs:163-200, selene-manager/src/store.rs:1406-1475, 1588-1666, 2237-2272, 5044-5073, 5328-5365): Writes whole compressed v4 records via aligned O_DIRECT with exact set_len truncation and portable is_direct_unsupported fallback, propagates Kind::StoreInvalidated = 4 across sharded ranks, replaces timer-polled put waits with drop-ordered WindowHold / WindowReleaseSignal wakeups and rotating epoch-tracked scans, and retains clean manager RAM extents evicted only when Arena::coalescing_block can form the target buddy class.
Merge Risk: High · up to 45fb380
  • Active correctness regressions on the helios/ scheduler and restore-pricing paths: Under page_pressure, select_eviction_candidate now defeats #665's scan-resistant reuse protection (is_protected(node)) and sacrifices hot leaves ahead of cold overlapping checkpoints; observe_prefill_rate is permanently dead; and RowRestoreLatency::observe locks out row-only restores after a fast recovery probe.
  • Hot-path scheduler overhead under VRAM pressure: On large-KV-budget deployments (DeepSeek-V4.1-Flash TP4: 156,956 pages, 4,864 snapshots), pressure eviction clones ~628 KiB (page_snapshot_refs), allocates a full HashMap<CheckpointId, RetentionRole>, and performs up to ~836k page-ref scans per single victim on the single-threaded scheduler loop.
  • Cross-crate compatibility surface (+10,106 / -1,158 across 42 files): Introduces internal rank-relay wire event Kind::StoreInvalidated = 4 (selene/src/shard.rs:470, 484), fails startup cleanly on sub-page memory-only budgets (selene/src/offload.rs:706-712), splits committed vs reserved disk gauges (tests/server/test_conditioned_input_cache.py:144-149), and updates public flare-selene APIs in lockstep — all properly disclosed in the PR description.
Pre-merge checks: ✅ 1 passed · ⚠️ 3 warnings
  • ✅ Security / malicious screen: No credential leaks, exfiltration, or unsafe memory bypasses found (unsafe raw_slice in selene/src/disk.rs:1277, 1321, 1404, 1765-1772 is guarded for len == 0 and bounded by caller-pinned lifetimes; the autobot.eidonix.com link in prior review comments is standard review-template text, not PR code).
  • ⚠️ Charter & value fit: Strongly aligned with the prefix-caching charter goal, model-agnostic, and solves #451; however, A/B Tables A–C compare against 5d53040e (9 commits behind current main c513e46a, predating #665's cache-eviction change and #663/#660's scheduler pricing changes), and the PR body still cites base 4cc6f2fd / HEAD 0ebee3d4 rather than c513e46a / 45fb380 (charter #210, docs/design-review.md:106-115).
  • ⚠️ Related / duplicate / conflict check: #665 is now merged into main (07e666e6), and the rebase onto it caused the is_protected bypass in Blocker flare run fails at "Prepare execution": cuGraphAddKernelNode_v2 CUDA_ERROR_INVALID_VALUE (qwen3.8-flash TP2, RTX PRO 5000 Blackwell 48 GB) #2; open issue #451 still has not been updated with the midpoint half-width conflict-span conclusion; concurrent open PRs #655 and #659 touch overlapping helios/ files.
  • ⚠️ Tests & verification evidence: Unit/integration suites and TLA+ mutation checks (verification/helios-lifecycle/check.py:515-528) were reported passing on 0ebee3d4 (not yet re-reported for rebased 45fb380), and the new tests do not exercise observe_prefill_rate, RowRestoreLatency::observe with count == 2, or evict_for_pressure against #665's is_protected tier / overlapping unpinned pairs.

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
yatesdr force-pushed the perf/selene-prefix-cache-holistic branch from 45fb380 to 831c47c Compare December 2, 2026 20:26
@yatesdr

yatesdr commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

@lukealonso Thank you for the thorough review — every item was a real catch. Rebased onto c513e46a (main, including #665) and pushed 831c47c7 with all fixes and regression tests:

1. Correctness bugs

  • 1.1 Dead observe_prefill_rate (helios/src/server/runtime.rs): Switched the fill-ratio check from step.lanes.len() (always 1 for single-lane prefill) to step.token_capacity as u64, and added a unit test verifying both the >= 50% acceptance and < 50% rejection thresholds.
  • 1.2 evict_for_pressure / freeable_page_prefix (helios/src/scheduler/cache_memory.rs, helios/src/cache.rs, docs/runtime-core-design.md):
    • Tightened page_pressure to need_pages > 0 (regardless of free_snapshots), so snapshot-only pressure no longer trips page-pressure priority while free_snapshots == 0 && need_pages > 0 still prefers page-freeing victims.
    • Preserved #665's is_protected(node) tiering and recency ordering under page_pressure, and distinguished genuinely pinned/non-evictable blocked owners from unpinned overlapping checkpoint pairs (freeable_page_prefix only flags a page as blocked when at least one unpinned-pair-excluding blocked owner holds it, and tests cover protected vs probationary, pinned vs unpinned overlapping pairs, and free_snapshots == 0 && need_pages > 0).
    • Aligned docs/runtime-core-design.md with the pressure-aware eviction ordering.
  • 1.3 RowRestoreLatency::observe median (helios/src/server/runtime.rs): Switched count == 2 (and even counts) from upper median ordered[count / 2] to lower median ordered[(count - 1) / 2], so a fast recovery probe after an aged spike immediately drops the estimate; added a regression test.

2. Hot-path scheduler allocations & complexity

  • 2.1 Zero-clone page_snapshot_refs (helios/src/scheduler.rs, helios/src/scheduler/cache_memory.rs): Reused a RefCell<Vec<i32>> scratch buffer on RequestScheduler for freeable_page_prefix and switched retiring-snapshot dedup to BTreeSet.
  • 2.2 Eliminated per-victim HashMap in select_eviction_candidate (helios/src/cache.rs): Maintained an only_child: Option<CheckpointId> link on Checkpoint (O(1) lookup on single-child compaction, zero allocations per eviction step).
  • 2.3 Eliminated quadratic per-victim / simulation scans (helios/src/scheduler/cache_memory.rs): Replaced per-candidate blocked range loops with O(1) prefix-sum queries, tracked available_pages incrementally in simulate_snapshot_quote, and added a zero-allocation fast path in pending_page_count() when retirement queues are empty.

3. Edge cases & cleanup

  • 3.1 Full-GPU-hit queued eviction (helios/src/server/runtime.rs): Recomputed pool_plan in begin_pool_lookup when a previously full-GPU-hit queued request loses its GPU prefix before dispatch so it still issues a pool lookup; added a regression test.
  • 3.2 plan_mapping_handles (helios/src/runtime_core/cache_memory.rs): Documented the non-monotonicity of exact half-width handle consumption, tracked per-rank best_rank_layouts across the search with a non-power-of-two fallback and fixed >= limit early exit, and added the 13-page (granules = 7) counterexample regression test.
  • 3.3 Conditioned window helper (helios/src/scheduler.rs): Extracted shared RequestScheduler::partition_conditioned_windows used by both plan_conditioned_windows and conditioned_window_ends.

Additional helios/ edge cases fixed in this pass

  • Local fallback after rejected pooled row-only hit (helios/src/server/runtime.rs): When a pooled row-only hit fails worth_restore, admit_with_host_store now retries local store.lookup(...) at the same endpoint before shrinking before, with a regression test.
  • Intermediate conditioned-window terminal pricing (helios/src/scheduler/checkpoints.rs): Updated interval_prefill_ns_for so intermediate conditioned window ends price their final chunk as TerminalPrefill (matching dispatch), with a regression test.

Verification on 831c47c7 (Linux)

  • RUSTFLAGS="-D warnings" cargo check --locked --all-targets: clean across selene, selene-manager, helios (--features runtime-core,server), and flare
  • helios release lib tests (--features runtime-core,server): 1,838/1,838 passed
  • flare release tests: 254/254 passed
  • verification/helios-lifecycle/check.py --mutations: 8/8 TLA+ models + all Rust mutations passed

@flare-autobot

Copy link
Copy Markdown
Collaborator

Autobot Review

Full Review · Value Proposition · Case File

Recommendation: Ready To Merge

Head 831c47c7 (rebased onto main c513e46a, including #665) cleanly resolves all three helios/ correctness blockers and the hot-path scheduler eviction defect from Round 4 and @lukealonso's review, each with targeted regression tests. Direct verification of the newly changed code and core invariants across helios/, selene/, and selene-manager/ finds zero remaining correctness, safety, concurrency, or CI blockers; only two small subtractive cleanups and non-blocking housekeeping nits remain (confirm green GitHub CI and @lukealonso's re-approval before merging).

  • Blockers: 0 · Should fix: 0 · Subtract/Simplify: 2 · Nits: 4
Walkthrough
  • Resident-aware lookup, diskless intake sizing & telemetry (helios/src/server/runtime.rs:3161-3246, 3312-3459, helios/src/server/metrics.rs:538-564, 914-950, selene/src/offload.rs:175-254, 675-712, docs/api.md:387-398): Forwards GPU-resident token offsets on pool lookups, refreshes queued full-GPU-hit plans if evicted before dispatch (runtime.rs:3185-3208), falls back to local copies at the same endpoint when a pooled row-only candidate is rejected (runtime.rs:3383-3413), sizes local intake slots to 0 when local disk is disabled, splits ready disk inventory from uncommitted reservations, and exports per-level pool restore rates.
  • L1 DRAM clean retention & non-blocking drain (selene/src/memory.rs:3517-3527, selene/src/pool/store.rs:289-321, selene/src/pool/local.rs:83-90): Retains clean persisted_in_pool records in L1 DRAM with invariant-checked clean_slots accounting and narrows shutdown drain to pending_pool_drain().
  • GPU snapshot-alias packing, pressure eviction & restore pricing (helios/src/runtime_core/cache_memory.rs:655-830, 1633-1686, helios/src/scheduler/cache_memory.rs:205-269, 397-553, 662-668, 713-820, helios/src/scheduler.rs:744, 1282-1293, 1375-1386, 2136-2241, helios/src/cache.rs:80, 306-319, 554-560, 662-677, 699-720, 848-850, 1040-1054, helios/src/scheduler/checkpoints.rs:280-314, 403-409, 453-502, helios/src/server/runtime.rs:262-335, 3054-3077, docs/runtime-core-design.md:846-888): Packs exact half-width alias planes with midpoint ordering and non-power-of-two/per-rank handle-budget fallback; replaces per-victim eviction clones/maps/scans with freeable_prefix_scratch prefix sums and Checkpoint::only_child while preserving #665 reuse protection and recency; prices restores via read-only estimate_prefill_delta_ns (including intermediate conditioned-window terminal chunks), lower-median RowRestoreLatency, and a fixed step.token_capacity fallback observe_prefill_rate EMA.
  • Direct compressed I/O, event-driven waiters, clean arena retention & offer coalescing (selene/src/disk.rs:848-875, 1272-1425, selene/src/disk_store.rs:346-415, selene-manager/src/arena.rs:163-200, selene-manager/src/store.rs:1406-1738, 2237-2272, 5049-5072, 5758-5762): Writes whole compressed v4 records via aligned O_DIRECT I/O with exact set_len truncation and StoreInvalidated propagation, replaces timer-polled put waits with lossless WindowReleaseSignal wakeups and rotating epoch-tracked scans, retains clean manager RAM extents via buddy coalescing_block, and resolves covered waiting offers directly to Present.
Merge Risk: Medium · up to 831c47c
  • Large cross-crate cache-core surface (+11,418 / -1,237 across 42 files): Touches GPU VMM snapshot-alias planning (helios/src/runtime_core/cache_memory.rs), scheduler pressure eviction and prefill-delta pricing (helios/src/scheduler/), host offload/sharding/direct I/O (selene/), and manager arena retention and waiter scheduling (selene-manager/src/store.rs, arena.rs). Core invariants (only_child, clean_slots, prefix-sum cache invalidation, disk accounting, WindowReleaseSignal wakeups) are covered by debug assertions, unit/integration suites, and 8/8 TLA+ models with mutation checks (verification/helios-lifecycle/check.py:515-528).
  • Operator-visible wire, startup, and metric changes (all disclosed): Adds internal multi-host TP rank-relay event Kind::StoreInvalidated = 4 (requiring matching rank builds), fails startup cleanly on sub-page memory-only budgets (selene/src/offload.rs:706-712), separates committed vs reserved disk gauges (docs/api.md:390-394), drops flare_host_cache_intake_slots to 0 without local disk, and updates public flare-selene APIs in lockstep with workspace callers.
  • Downstream & concurrent PR coupling: PR #694 is already stacked directly on 831c47c7 consuming this PR's public surface, while open PRs #655 and #659 touch overlapping helios/ files (checkpoints.rs, runtime_core/cache_memory.rs) and will need coordinated merge sequencing.
Pre-merge checks: ✅ 2 passed · ⚠️ 2 warnings
  • ✅ Security / malicious screen: No credential leaks, external exfiltration, unsafe memory bypasses, or prompt-injection vectors in PR code (unsafe raw_slice uses in selene/src/disk.rs:1277, 1321, 1404 are bounded by caller-pinned buffer/slab lifetimes; the external "Full Review" links in earlier comments are standard Autobot review-template footers, not PR code).
  • ⚠️ Charter & value fit: Strongly aligned with the prefix-caching charter goal, model-agnostic, resolves #451, and discloses all wire/startup/API/baseline caveats; however, headline SM120 A/B Tables A–C remain measured on pre-refactor 7d7dcdcb vs 5d53040e (predating #665, #663, and #660), transparently noted in the PR description (charter #210).
  • ⚠️ Related / duplicate / conflict check: Open issue #451 still lacks a closing comment summarizing the midpoint half-width conflict-span design (docs/runtime-core-design.md:846-858); #694 is stacked on 831c47c7, and #655/#659 touch overlapping helios/ files.
  • ✅ Tests & verification evidence: Regression tests in helios/src/server/runtime/phase_tests.rs:9073-9350, helios/src/runtime_core/cache_memory.rs:1633-1686, helios/src/scheduler/cache_memory.rs, and helios/src/cache.rs:1040-1054 cover all Round 4 / @lukealonso fixes with clean isolation and production paths; author reports clean -D warnings check, 1,838 helios release lib, 585 selene, 205 + 128 selene-manager, 254 flare tests, and verification/helios-lifecycle/check.py --mutations (8/8 TLA+ models + Rust mutations) passing on 831c47c7 (confirm green GitHub CI on 831c47c7 before merge).

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.

…tion, NVMe throughput, and GPU snapshot packing

Prefix-cache serving across Selene, selene-manager, and Helios suffered from
four coupled bottlenecks under multi-turn and multi-instance workloads:
resident GPU prefixes bypassed pool lookups even when a deeper prefix existed
in the shared pool, local L1 DRAM records were dropped on pool handover while
unused intake buffers reserved pinned host RAM without local disk, CUDA
snapshot-alias packing over-excluded GPU KV pages under handle-count limits
while wall-clock EMA mispriced host restores, and selene-manager writeback
relied on buffered packed writes, timer-polled waiters, and immediate clean
arena eviction.

This change updates prefix-cache lookup, retention, GPU snapshot allocation,
restore pricing, and manager NVMe writeback across the shared runtime:

- Resident-aware lookup, intake sizing, and telemetry (`selene`, `helios`):
  Keep host and pool lookup active whenever a deeper prefix can extend a
  partially resident GPU prefix (recomputing `pool_plan` and issuing a pool
  lookup if a previously full-GPU-hit queued request loses its GPU prefix
  before dispatch, and retrying local host storage at the same endpoint when a
  pooled row-only hit fails restore pricing); allocate zero local intake slots
  when local disk is disabled and fail startup cleanly on sub-page memory-only
  budgets; preflight doomed L1 evictions before writeback; separate ready
  on-disk inventory (`flare_host_cache_disk_records` / `_bytes`) from
  uncommitted reservations (`flare_host_cache_disk_reserved_*`); and expose
  per-level pool restore rate gauges
  (`flare_host_cache_pool_inbound_bytes_per_second{level}`) using the shared
  `POOL_LEVELS` ordering.
- L1 DRAM retention and non-blocking drain (`selene`, `helios`): Retain clean
  `persisted_in_pool` records in L1 DRAM after pool handover with explicit
  `clean_slots` accounting, decouple capture headroom from intake sizing, and
  run shutdown drain without blocking request teardown.
- GPU snapshot packing, pressure eviction, and restore pricing (`helios`):
  Pack shared GPU snapshot aliases using midpoint-ordered half-width spans and
  per-rank handle budgeting (`plan_mapping_handles`, solving NVIDIA#451); make GPU
  cache eviction pressure-aware (`evict_for_pressure`) while preserving
  dual-turnover reuse protection (`is_protected`), distinguishing pinned from
  unpinned overlapping pairs, and avoiding per-victim allocations via cached
  `only_child` links, reusable page-ref scratch, and prefix-sum range checks;
  price host restores using read-only scheduler prefill-delta estimates
  (`estimate_prefill_delta_ns`, pricing every conditioned window end as
  terminal) shared through `flare_selene::worth_restore` (with a narrowed
  cold-start `prefill_rate` EMA sampled from `step.token_capacity` until
  prefill capacities are measured); track row-restore latency separately per
  source using the lower median without resetting the decay clock on failed
  fetches; derive prefill observation duration from GPU timing with `wall_ns`
  fallback when GPU duration is absent; and record prefill-saved seconds
  directly in `Metrics::host_lookup_cost`.
- Direct compressed I/O, event-driven waiters, and arena retention
  (`selene`, `selene-manager`): Use aligned whole-record `O_DIRECT` writes for
  compressed v4 records (`WriteRecord` / `WritePacked`) with cross-platform
  direct-I/O fallback handling, propagate `Kind::StoreInvalidated = 4` across
  sharded ranks, replace polled waiters with event-driven epoch-tracked wakeups
  (`writeback_waiters` / `inflight_waiters`), retain clean records in manager
  RAM with buddy coalescing on eviction, and resolve waiting put offers
  directly to `Present` when publication covers the offer while rechecking
  upgrades and forks.

Compatibility: On-disk v4 records remain readable across `kvc=off`, `cpu`,
and `gpu` modes without re-exporting model cores or changing Protobuf schemas.
Multi-host TP deployments require matching rank builds for the new internal
rank-relay event `Kind::StoreInvalidated = 4`. Sub-page warm memory budgets
without local disk now fail startup explicitly. Public `flare-selene` trait
and struct signatures (`HostStore::begin_lookup`, `TierStore::retired`,
`TierStore::pending_pool_drain`, `HostHit.pooled`, `StoreStats` reserved/rate
fields, `worth_restore`, `levels::POOL_LEVELS`) are updated in lockstep with
workspace callers. Multi-process TP>=2 packed pool puts remain unsupported by
the existing selene-manager protocol contract.

Measured results on SM120 (4x RTX PRO 6000, baseline `5d53040e` vs pre-refactor
revision `7d7dcdcb`; rebased onto `c513e46a`):
- `DeepSeek-V4.1-Flash` TP4 (24 prompts / 72 checkpoints): GPU shared
  snapshot capacity increased from 1,946 to 4,864 (+2.50x), snapshot-excluded
  KV pages dropped from 5,917 to 2,390 (-59.6%, freeing 3,527 KV pages /
  451K tokens), and pinned intake slots dropped from 1,600 to 0.
- `Qwen3.8-Flash-Next` TP1 (`selene-manager` 512M RAM / 1200M NVMe, 12
  prompts + restart + 6-prompt reread): post-restart cache-hit tokens rose
  from 66.56% to 83.23% (mean latency -28.3%, p50 -42.9%), manager RAM hits
  doubled (1 -> 2), writeback waiter churn dropped 93.1% (87 -> 6), NVMe
  writes dropped 11.5% (2.97 GB -> 2.63 GB), and evictions dropped 20%
  (10 -> 8) with 0 NVMe errors.
- `2x GLM-5.3-Flash` TP2 (`kvc=off` + `selene-manager`, 6x3 multi-turn
  A->B->A): retained 3.65 GiB (35 records) in L1 DRAM (vs 0 B), cut NVMe
  write volume 26.4% (4.10 GB -> 3.02 GB), increased manager NVMe throughput
  2.85x (370.5 MB/s -> 1,054.8 MB/s), cut writeback waiter churn 96.2%
  (293 -> 11), and cut Turn 3 p50 latency 12.2% (0.8614s -> 0.7566s).
- `GLM-5.3-Flash` TP2 local disk (`kvc=gpu`, 1500M limit): byte-identical
  compression ratios (`1.5150x` populate, `1.5166x` reread), 0 codec/verify
  failures, tight eviction enforced under 1500M.
- Cross-node TCP (`2x Qwen3.8` TP1 on SM120 <-> aarch64 `selene` manager):
  0 text mismatches, 88.95% partial-GPU resident-extension cache hits,
  2,388.8 MB/s remote NVMe writes, 0 errors.
- Live saturation, compression under load, and fault-injection recovery on
  SM120: 284/284 HTTP 200 across 16-way tight-manager storms, live manager
  `SIGKILL` + reconnect, `2x GLM-5.3` TP2 VRAM/eviction bursts, `kvc=gpu` /
  `cpu` / `off` 1000M local-disk saturation, live record truncation +
  read-only recovery, and `DeepSeek-V4.1` TP4 64x16w bursts (0 HTTP 500s,
  0 NVMe errors, 0 codec/verify failures, 0 deterministic text mismatches).

Verification: `RUSTFLAGS="-D warnings" cargo check --locked --all-targets`
clean across `selene`, `selene-manager`, `helios` (`--features
runtime-core,server`), and `flare`; Linux tests passed across `selene`
(585/585), `selene-manager` (205/205 lib + 128/128 client/pool integration),
`helios` (1,838/1,838 release lib tests excl. root-chmod and
`FLARE_TEST_TEMPLATE_DIR` tests), `flare` (254/254 release tests), and
`verification/helios-lifecycle/check.py --mutations` (8/8 TLA+ models + all
Rust mutations).

Signed-off-by: yatesdr <6937857+yatesdr@users.noreply.github.com>
Design-Signed-Off-By: yatesdr; design-review=2e5b
Discord: D-Rock
@yatesdr
yatesdr force-pushed the perf/selene-prefix-cache-holistic branch from ec2e3db to ffbf2dc Compare December 3, 2026 17:40
@lukealonso
lukealonso merged commit def9179 into NVIDIA:main Dec 3, 2026
3 checks passed
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:memory Memory budgets, allocation lifetimes, scratch sharing, and capacity. 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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants