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 (regression vs main), 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.
Merge Risk
Level: High
- Active correctness regressions on the
helios/scheduler and restore-pricing paths: Underpage_pressure,select_eviction_candidatenow defeats#665's scan-resistant reuse protection (is_protected(node)) and sacrifices hot leaves ahead of cold overlapping checkpoints;observe_prefill_rateis permanently dead; andRowRestoreLatency::observelocks out row-only restores after a fast recovery probe. - Hot-path scheduler overhead under VRAM pressure: On large-KV-budget deployments (
DeepSeek-V4.1-FlashTP4: 156,956 pages, 4,864 snapshots), pressure eviction clones ~628 KiB (page_snapshot_refs), allocates a fullHashMap<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,158across 42 files): Introduces internal rank-relay wire eventKind::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 publicflare-seleneAPIs in lockstep — all properly disclosed in the PR description.
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 to0when local disk is disabled (failing cleanly whencheckpoint_memory < page_record_bytes), splits ready disk inventory from uncommitted reservations, shareslevels::POOL_LEVELSbetweenRanking::rates()and Prometheus rendering, and exportsflare_selene::worth_restore. - L1 DRAM clean retention & non-blocking drain (
selene/src/memory.rs:721-770, 914-1095): Retainspersisted_in_poolrecords in local DRAM with invariant-checkedclean_slotsaccounting 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, addsevict_for_pressureandpage_pressure_victim_priority, and prices host restores via read-onlyestimate_prefill_delta_nspaired withRowRestoreLatencyand 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 alignedO_DIRECTwith exactset_lentruncation and portableis_direct_unsupportedfallback, propagatesKind::StoreInvalidated = 4across sharded ranks, replaces timer-polled put waits with drop-orderedWindowHold/WindowReleaseSignalwakeups and rotating epoch-tracked scans, and retains clean manager RAM extents evicted only whenArena::coalescing_blockcan form the target buddy class.
Pre-merge Checks
- [PASS] Security / malicious screen: No credential leaks, exfiltration, or unsafe memory bypasses found (
unsaferaw_sliceinselene/src/disk.rs:1277, 1321, 1404, 1765-1772is guarded forlen == 0and bounded by caller-pinned lifetimes; theautobot.eidonix.comlink in prior review comments is standard review-template text, not PR code). - [WARN] Charter & value fit: Strongly aligned with the prefix-caching charter goal, model-agnostic, and solves
#451; however, A/B Tables A–C compare against5d53040e(9 commits behind currentmainc513e46a, predating#665's cache-eviction change and#663/#660's scheduler pricing changes), and the PR body still cites base4cc6f2fd/ HEAD0ebee3d4rather thanc513e46a/45fb380(charter#210,docs/design-review.md:106-115). - [WARN] Related / duplicate / conflict check:
#665is now merged intomain(07e666e6), and the rebase onto it caused theis_protectedbypass in Blocker #2; open issue#451still has not been updated with the midpoint half-width conflict-span conclusion; concurrent open PRs#655and#659touch overlappinghelios/files. - [WARN] Tests & verification evidence: Unit/integration suites and TLA+ mutation checks (
verification/helios-lifecycle/check.py:515-528) were reported passing on0ebee3d4(not yet re-reported for rebased45fb380), and the new tests do not exerciseobserve_prefill_rate,RowRestoreLatency::observewithcount == 2, orevict_for_pressureagainst#665'sis_protectedtier / overlapping unpinned pairs.
Blockers
-
observe_prefill_rateis unconditionally dead code, freezing the cold-start restore fallback EMA (regression vsmain) (helios/src/server/runtime.rs:3052-3075,helios/src/scheduler.rs:437-467,helios/src/execution/manifest.rs:85-87):observe_prefill_ratecomputeslet capacity = step.prefill_capacity() as u64;(runtime.rs:3058) and returns early if!step.kind.is_prefill() || step.lanes.len() != 1 || capacity == 0 || ...(runtime.rs:3059-3065).ScheduledStep::prefill_capacity()(scheduler.rs:465-467) returnsself.mixed.as_ref().map_or(0, |m| m.prefill_capacity).validate_mixed(scheduler.rs:437-462) forbidsmixed.is_some()on any step withkind != GraphKind::Mixed, whileGraphKind::is_prefill()(manifest.rs:85-87) matches onlyPrefill | TerminalPrefill | ScoredPrefill.- Consequently,
!step.kind.is_prefill() || capacity == 0is always true.self.prefill_ratenever moves fromflare_selene::INITIAL_PREFILL_RATE(8000.0,runtime.rs:1288), even thoughestimated_prefill_saved_seconds(runtime.rs:3248-3269) relies on it wheneverestimate_prefill_delta_nsreturnsNoneon unmeasured/cold capacities (e.g., post-restart restores). Onmain, the sampler updated on every prefill with no capacity gate. No existing test callsobserve_prefill_rate(pricing tests athelios/src/server/runtime/phase_tests.rs:8665, 8707, 8780mutateworker.prefill_ratedirectly). - Fix: Replace
step.prefill_capacity() as u64withstep.token_capacity as u64(valid because!step.kind.is_prefill()already restricts to pure prefill steps), and add unit tests inhelios/src/server/runtime/phase_tests.rsverifying thatobserve_prefill_rateupdatesworker.prefill_ratefor single-lane pure prefills withtokens * 2 >= token_capacityand skips< 50%fills and multi-lane steps.
-
page_pressure_victim_prioritydisables#665's scan-resistant reuse protection, inverts recency/role protection for overlapping unpinned checkpoints, and evicts unrelated hot leaves on pure backing conflict (helios/src/scheduler/cache_memory.rs:204-223, 391-409, 593-649,helios/src/cache.rs:353-380, 788-790,helios/src/scheduler.rs:1263, 1276-1280,docs/runtime-core-design.md:869-873):- New regression from
45fb380rebase onto#665(07e666e6):select_eviction_candidate(helios/src/cache.rs:788-790) minimizes(priority(node, *role_preserving), self.eviction_key(node)), whereeviction_key(cache.rs:378-380) puts#665'sself.is_protected(node)(node.reused) first. Becausepage_pressure_victim_priority(scheduler/cache_memory.rs:218-222) returns(!releases_page, node.retention_rank().use_epoch, !role_preserving_compaction),use_epochsorts ahead ofis_protected(node). Underpage_pressure(bothevict_for_pressureon decode/admission andsimulate_snapshot_quoteon capture), even when zero snapshots overlap (releases_page == truefor every candidate), a reused protected checkpoint from epoch 100 is always evicted before an un-reused scan-pollution checkpoint from epoch 101 — completely defeating#665on shared-alias deployments. - Recency and role inversion under overlapping unpinned checkpoints: When two cold unpinned checkpoints share a backing band (
refs == 2), neither satisfiesrefs[page] == 1, so both getreleases_page == false. Under mandatory page pressure (evict_for_pressure, wherebelow = None,protected_token_budget = None), every hotAnchor/Messageleaf withtail_pages(releases_page == true) is evicted ahead of those dead cold overlapping checkpoints. This also contradicts the policy sentence this PR added atdocs/runtime-core-design.md:869-873("preserves completion recency"). - Unrelated hot-leaf eviction on pure snapshot backing conflict (
need_pages == 0): Inensure_resources(scheduler.rs:1263, 1276-1280),need_pages == 0 && backing_conflict == truesetspage_pressure = true(scheduler/cache_memory.rs:599-601), causingevict_for_pressureto destroy a recent hot leaf in an unrelated band for pages that are not needed rather than evicting a cold overlapping checkpoint whose snapshot can directly satisfyavailable_snapshot(pages). - Fix:
- Preserve
#665'sis_protected(node)tier ahead ofuse_epoch(e.g., includeis_protectedahead of recency in the page-pressure ordering, or apply thereleases_pagepreference within the protection tier rather than ahead ofeviction_key). - Distinguish backing held by a pinned/in-flight owner (genuinely unfreeable right now) from backing shared only by other unpinned cold checkpoints (freeable together), or bound the
!releases_pageskip so it cannot sacrifice strictly newer protected /Anchor/Messageleaves ahead of ancient unpinned overlapping entries. - When
need_pages == 0 && backing_conflict, prefer freeing an unblocked snapshot over evicting an unrelated hot leaf, aligndocs/runtime-core-design.md:869-873with the resulting invariant, and add tests for#665reuse protection under page pressure and overlapping unpinned pairs vs hot leaves.
- Preserve
- New regression from
-
RowRestoreLatency::observeselects the upper median oncount == 2, resurrecting a decayed latency spike on the first fast recovery probe (helios/src/server/runtime.rs:308-332, cf.selene/src/levels.rs:57-67):RowRestoreLatency::observesorts latencies ascending (lower is faster) and storesordered[bucket.count / 2]withInstant::now()(runtime.rs:316-318). This mirrorsselene::levels::Rate::observe(selene/src/levels.rs:65-67), whereRatetracks bytes/sec (higher is faster), sovalues[2 / 2] = values[1]selects the faster sample and clears a single slow spike on the first fast probe.- Because latency is inverted,
ordered[2 / 2] = ordered[1]selects the slower sample oncount == 2: after an aged500 msspike decays and admits a recovery probe that succeeds in2 ms,observe(0.002)picksordered[1] = 0.500and resets the timestamp tonow, locking out row-only restores for another full 10 s recovery window despite the fast probe succeeding. The new test (helios/src/server/runtime/phase_tests.rs:8829-8851) only coversstart/finish(false)decay preservation, not an aged spike followed by a fast probe. - Fix: Use the lower median
ordered[(bucket.count - 1) / 2]inRowRestoreLatency::observeand add a regression test inphase_tests.rsasserting that a single aged slow sample clears immediately on the first fast probe.
Should Fix
-
Remove three per-victim
O(N)/O(N * span)allocations and scans from the single-threaded scheduler loop during pressure eviction (helios/src/scheduler/cache_memory.rs:204-223, 391-409, 608-649,helios/src/cache.rs:740-753):- Unconditional
Vec<u32>clone per victim (scheduler/cache_memory.rs:608-626):evict_for_pressureclonesself.page_snapshot_refs(~628 KiB on DeepSeek-V4.1-Flash TP4's 156,956 pages) on every single call inensure_resourcesandrefill_reservations, even whenself.cache.pending_retirement().is_empty() && self.retired.is_empty(). UseCow::Borrowed(&self.page_snapshot_refs)when nothing is retiring; when retirements are pending, deduplicate retiring snapshot IDs viaBTreeSetmatchingprojected_fits(scheduler/cache_memory.rs:570). - Per-victim
HashMap<CheckpointId, RetentionRole>over all checkpoints (cache.rs:744-753): Rebuilt on every call inevict_for_pressureand every loop iteration ofsimulate_snapshot_quote(up to 4,864 checkpoints). Trackonly_child: Option<CheckpointId>directly onCheckpoint(cache.rs:69-87) alongsidechild_countso role-preserving compaction checks becomeO(1)with zero heap allocation. O(candidates * span)scan insidepage_pressure_victim_priority(scheduler/cache_memory.rs:211-217):range.clone().any(|page| refs[page] == 1)runs up to4,864 * 172(~836k) checks per victim, whereasselect_snapshotsin the same file uses prefix sums. Build a prefix sum ofu32::from(refs[p] == 1)once per pass soreleases_pageisO(1)per candidate.
- Unconditional
-
Re-baseline headline A/B measurements against current
main(>= c513e46a) and sync PR metadata /#451(charter#210,docs/design-review.md:106-115):- Tables A–C compare against
5d53040e(9 commits behind currentmainc513e46a, predating#665's cache-eviction policy change,#663/#660's scheduler pricing changes, and#667), and the PR description still reports base4cc6f2fdand HEAD0ebee3d4. After fixing Blockers #1–#3, re-verify the headline A/B against currentmain, update the PR body's base/HEAD and re-run test/TLA+ verification on the new head, and post the midpoint half-width conflict-span conclusion on open issue#451.
- Tables A–C compare against
Subtract / Simplify
- Share greedy conditioned-window partitioning between
conditioned_window_endsandset_conditioned_inputs(helios/src/scheduler.rs:2113-2142, 2181-2202):- Both methods implement the same
features + input.feature_range.len() > capacityboundary split in the sameimpl RequestScheduler(conditioned_window_endsadditionally filtersinput.token_span.end > consumed). Extract a single small window-partition helper so restore-pricing (helios/src/scheduler/checkpoints.rs:466, 482) and execution windowing cannot silently drift.
- Both methods implement the same
- Delete
priority_uses_role_preserving/track_role_preservingafter addingCheckpoint::only_child, and deduplicate the production priority closure (helios/src/cache.rs:732-811,helios/src/scheduler/cache_memory.rs:394-406, 627-638):- Once
only_child: Option<CheckpointId>makesrole_preservingO(1)with zero allocation (Should Fix #1), thepriority_uses_role_preservingparameter andtrack_role_preservingguard disappear cleanly with no allocation penalty oneviction_candidate. Also hoist the duplicatedpage_pressure_victim_priorityclosure atscheduler/cache_memory.rs:394-406and:627-638into one helper method.
- Once
Nits
begin_pool_lookupmisses full-GPU-hit eviction while capacity-blocked (helios/src/server/runtime.rs:3171-3228): If a request arrives with 100% GPU residency (resident_tokens == prompt.len()),pool_planis stored withpool_lookup = None. If that GPU checkpoint is evicted while the request waits on capacity,incoming.pool_plan.is_some() && !retryreturnsfalseat:3188-3190without refreshingpool_planor issuing a pool lookup (re-planning occurs only synchronously insideadmit_with_host_store). Refreshingpool_planand issuing a lookup whenpool_lookup.is_none()andresident_tokens < prompt.len()closes this edge case alongside the new stale-ticket reissue path.- Document non-monotonicity of
plan_mapping_handlesbinary search (helios/src/runtime_core/cache_memory.rs:754-766):Layout::grouped+pack_rowsis not strictly monotone ingranules(a wider group can cross a row boundary and stop merging), though the search is safe becausewinningis only updated whencandidate_total < limit. Add a brief comment stating it searches for a feasiblegranules <= hirather than assuming strict monotonicity. - Move
#[cfg(any(debug_assertions, test))]insideassert_clean_slots_invariant(selene/src/memory.rs:716-717, 781-782, 968-969, 1026-1027, 1054-1080): Keeping a no-op release body removes ~15 repeated#[cfg(...)]attributes at call sites.
Dropped on verification
- Correctness F7 (
wait_for_writebackseedinglast_wake_epoch: self.writeback_wake_epochdelays newly queued waiters up to 5 s) — False / misread invariant: Verified inselene-manager/src/store.rs:1406-1424, 1588-1666, 2018-2078, 5044-5073.wait_for_writebackis only entered immediately afterbegin_putattempted allocation under the current resource state (writeback_wake_epoch) and failed; tagging it with the current epoch is required to prevent immediate re-scanning/spinning within the same epoch when no new resource has been released. The next release event incrementswriteback_wake_epochand scans it. - Subtraction S1 (Delete
observe_prefill_rate,prefill_rate,INITIAL_PREFILL_RATE,worth_fetching,worth_transferinstead of fixingobserve_prefill_rate) — Unsafe regression on cold-start restores: Verified inhelios/src/scheduler/checkpoints.rs:189, 412-417andhelios/src/server/runtime/phase_tests.rs:8727-8766thatestimate_prefill_delta_nsreturnsNoneon a freshly restarted server before prefill capacities are measured (Table B's post-restart restore path); returning0.0would makeworth_restorereject every warm-pool restore after restart until cold prefills execute. Repairingobserve_prefill_rate(Blocker #1) is the correct fix. - Subtraction S2 (Collapse
RowRestoreLatencyontoselene::levels::Rateand key onselene::levels::Level) — Over-coupled / inaccurate: Verified inselene/src/levels.rs:36-87andhelios/src/server/runtime.rs:249-333.Rateispub(crate), tracks upward-recovering bytes/sec toward a finiteseed, and itsstarted()lacks per-keyin_flightduration tracking (and overwriteslast = Some(Instant::now()));HostHitdoes not carryLevel. Fixing the one-line median index inRowRestoreLatency::observe(Blocker #3) is much simpler and cleaner. - Subtraction S4 (Remove
plan_refreshed: booland alwaysplan.clone()without refreshing inadmit_with_host_store) — Buggy: Verified inhelios/src/server/runtime.rs:3183-3228, 3314-3326.begin_pool_lookupreturnsfalsewithout callingrefresh_admission_plan_in_placewheneverticket_resident == 0(:3191-3193),pool_lookupisNone(:3188-3190), or refresh erred (:3195-3196, 3210-3211). Removing thefalserefresh arm would pass staleAdmissionPlans into admission whenever GPU residency changes while queued. - Subtraction S3's unconditional
HashMapvariant (helios/src/cache.rs:740-753) — Performance regression: Droppingtrack_role_preservingwhile keeping the per-passHashMapwould add an unnecessaryO(N)heap allocation toeviction_candidatewhenprotected_token_budgetisNone. Replaced byCheckpoint::only_child(Should Fix #1 / Subtract #2). - Subtraction S5b (Delete 5-line
conditioned_inputs_from_imagesathelios/src/server/runtime.rs:3271-3278) — Low-signal churn: Small helper already shared across two call sites (runtime.rs:1713, 3335). - Discovery Dossier open question #3 (
in_flighthold prevents lower-median recovery inRowRestoreLatency) — False: Verified athelios/src/server/runtime.rs:295-306, 328-331thatfinish()decrementsbucket.in_flightto0(:300) before callingobserve()(:305), so fixingobserve()to(bucket.count - 1) / 2clears a decayed spike immediately upon probe completion while retaining intentional single-probe throttling while in flight.