Correctness, Contracts & System-Level Consequences — PR #674 @ 19ce4a7b
Key findings
- Major — a self-rearming pump makes the selene-manager owner thread spin at CPU speed whenever any put, get, or writeback wake is outstanding.
selene-manager/src/store.rs:5067-5072re-sendsStoreCommand::Tickat the end ofpump(), and the owner loop callspump()after every batch (selene-manager/src/control.rs:227). Since that one thread serializes all pool state, a single stuck put head-of-line blocks every client. Verified. - Major —
RowRestoreLatencybumps its decay clock onstart(), so a failed restore pins the estimate at the full median forever.helios/src/server/runtime.rs:299-303plus the early return infinishat:313-315. This makes the scheduler more likely to reject a cheap local DRAM row restore — the opposite of the PR's stated intent. The added test only covers the no-median case (phase_tests.rs:8799-8801). Verified. - Major — undisclosed rank-relay wire incompatibility. New
Kind::StoreInvalidated = 4(selene/src/shard.rs:470,484) with a hard decode rejection for unknown codes (:485). Mixed-version ranks cannot interoperate, and the PR body discloses nothing about it. Verified. - Major — three public
selenecrate signatures changed without disclosure (HostStore::begin_lookupgainsresident,TierStore::retiredgains_offered, newTierStore::pending_pool_drain, plusHostHit.pooledand threeStoreStatsfields). Every out-of-tree implementor stops compiling. Verified atselene/src/store.rs:377,401-404,433-440,100-103,244-256. - Major — charter #210 unmet. Tables A–F are an author-reported A/B against
5d53040e;mainis1fbcc3c9, and#663(latency pricing,8489d504) lands inside that gap and prices the same restore decision. The body states benchmarks ran on7d7dcdcb; head19ce4a7bhas no reported benchmark or CI evidence. - Minor ×5 — row-restore buckets ignore the source level (
runtime.rs:257-268vsselene/src/pool/store.rs:465,479); Windows loses the buffered packed-write fallback (disk.rs:1774-1780+eos/src/windows.rs:104-108); a stuck reclaim permanently blackholes its key (disk_store.rs:2516-2518,2643-2645,2697-2699); counter decrements can wrap in release (disk_store.rs:2789-2792); and the metric span semantics shifted (metrics.rs:538-560,runtime.rs:3344-3353). - Verified sound:
evict_for_pressurecannot spin (scheduler.rs:1261-1289); the writeback wake scan terminates; theO_DIRECTpacked path round-trips and recovers exact logical length; clean-L1 retention is guarded by a real invariant.
1. Unintended system-level consequences
F1 (Major) — Unbounded self-rearming pump on the store-owner thread
pump ends by re-signalling itself whenever any work remains:
// selene-manager/src/store.rs:5067-5072 (end of `pump`)
if !self.pending_puts.is_empty()
|| !self.pending_gets.is_empty()
|| self.writeback_wake_remaining > 0
{
self.notify_wakeup();
}
notify_wakeup is a non-blocking try_send of Tick:
// selene-manager/src/store.rs:874-878
fn notify_wakeup(&self) {
if let Some(tx) = self.wakeup.get() {
let _ = tx.try_send(StoreCommand::Tick);
}
}
And the owner loop calls pump() immediately after each batch:
// selene-manager/src/control.rs:216-227
store.handle(command);
batch -= 1;
if batch == 0 { break; }
match receiver.try_recv() {
Ok(next) => command = next,
Err(tokio::sync::mpsc::error::TryRecvError::Empty) => break,
Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => break 'outer,
}
}
store.pump();
Before this change the only driver was the 10 ms tick thread:
// selene-manager/src/control.rs:421-435
cleanup.tick = Some(thread::spawn(move || {
let mut notified = false;
loop {
if tick_stop.load(Ordering::Acquire) && !notified { tick_notice.notify_one(); notified = true; }
thread::sleep(Duration::from_millis(10));
if matches!(tick_commands.try_send(StoreCommand::Tick),
Err(mpsc::error::TrySendError::Closed(_))) { break; }
Impact. A put that stays queued in pending_puts — e.g. one the session or namespace cannot accept yet, which is exactly the steady state under the "tight manager" saturation runs the PR reports — produces Tick → pump → Tick at CPU speed instead of every 10 ms. run_store_owner is a single thread that owns all pool state; while it spins in pump, receiver.blocking_recv() is never reached, so every client's puts, gets, grants and outboxes are head-of-line blocked behind the loop. The same amplification applies on the client side: selene/src/disk.rs:533-535 invokes on_reply() after every disk job reply, i.e. a full pump() per disk completion rather than per tick.
Fix. Only self-notify when a state transition actually occurred since the previous pump — carry a dirty/progress flag set by the mutating paths and cleared at pump entry, then if self.dirty { self.notify_wakeup() }. Keep the 10 ms tick as the backstop for states that genuinely wait on time.
2. Correctness and safety
F2 (Major) — RowRestoreLatency decay clock is bumped by failed restores
// helios/src/server/runtime.rs:299-304 (`start`)
let bucket = self.buckets.entry(source).or_default();
bucket.in_flight += 1;
if let Some((_, last)) = &mut bucket.last_median {
*last = now;
}
// helios/src/server/runtime.rs:306-317 (`finish`)
fn finish(&mut self, key: &crate::cache::PrefixKey, ok: bool) {
let Some((source, started)) = self.in_flight.remove(key) else { return; };
if let Some(bucket) = self.buckets.get_mut(&source) {
bucket.in_flight = bucket.in_flight.saturating_sub(1);
}
if !ok {
return;
}
self.observe(source, started.elapsed().as_secs_f64());
}
estimate_seconds returns the undecayed median while in flight and a 10 s half-life decay otherwise:
// helios/src/server/runtime.rs:339-342
if bucket.in_flight > 0 {
return median;
}
median * 0.5f64.powf(last.elapsed().as_secs_f64() / Self::RECOVERY_SECONDS)
The failed-fetch path starts then finishes with ok = false:
// helios/src/server/runtime.rs:3401-3407
if row_only {
row_restore_latency.start(key, source);
}
if store.fetch(hit, ticket).is_err() {
if row_only {
row_restore_latency.finish(&key, false);
}
Impact. A source that is currently failing (record evicted, NVMe read error, manager refusal) resets last_median's timestamp on every attempt, so the estimate never decays and stays pinned at the full median. worth_restore(transfer_seconds, prefill_saved_seconds) (runtime.rs:3354) then keeps rejecting restores it should accept after the decay period — a pricing defect that biases against cheap local DRAM row restores from a stale slow measurement, exactly the failure mode the PR says it removes. It is not a correctness or concurrency bug.
Test gap. The added regression test only exercises the no-median case, so it passes with the bug present:
// helios/src/server/runtime/phase_tests.rs:8799-8801
worker.row_restore_latency.start(dummy_key, local_dram);
worker.row_restore_latency.finish(&dummy_key, false);
assert_eq!(worker.row_restore_latency.estimate_seconds(local_dram), 0.0);
Fix. Do not touch last_median in start(); the in-flight start instant is already recorded in self.in_flight. Add a test that observes a median, ages the bucket, then does start + finish(false) and asserts the decayed value is retained.
F7 (Minor) — A stuck reclaim permanently blackholes its key
// selene/src/disk_store.rs:2516-2518
pub(crate) fn has_pending_reclaim(&self, key: PrefixKey) -> bool {
self.maintenance.values().any(|job| job.key == key)
}
// selene/src/disk_store.rs:2643-2645 (`store`)
if self.has_pending_reclaim(checkpoint.key) {
return Ok(Some(StoreOutcome::Retry(StoreReason::Inflight)));
}
// selene/src/disk_store.rs:2697-2699 (`reserve_capture`)
if self.has_pending_reclaim(key) {
return Ok(None);
}
Impact. Previously only truncates carried a key (Reclaim.key was Option<PrefixKey>, None for unlinks), so a lost unlink reply could not block re-storing that key. Reclaim.key is now always populated (:2103-2108), so an unlink whose reply never arrives keeps maintenance populated and that prefix can never be re-captured for the lifetime of the process — a permanent silent cache-capacity leak on the fault path. Separately, has_pending_reclaim is a linear scan of maintenance executed on every store attempt, now unconditionally.
Fix. Key-block only for reclaims that will actually replace the key, or add an abandonment deadline that drops a maintenance job whose reply exceeds a bounded age; and index pending reclaim keys in a set instead of scanning.
F8 (Minor) — Counter decrements can wrap in release builds
// selene/src/disk_store.rs:2788-2797
let was_ready = self.index.node(&key).unwrap().ready;
if was_ready {
self.committed_records -= 1;
self.committed_bytes -= old.location.bytes;
}
self.replacements.insert(key, old);
Sibling helpers use saturating_sub (:3152-3158), but the accounting invariant is only asserted in debug/test builds (assert_disk_accounting, :3565-3589, called from stats() at :3731-3733).
Impact. In release, any accounting drift wraps committed_records/committed_bytes to a near-u64::MAX gauge instead of panicking, which the new flare_host_cache_disk_records/disk_bytes Prometheus series would surface as a catastrophic, misleading number. Use saturating_sub/checked_sub and always assert.
Verified sound (not issues)
evict_for_pressurecannot spin.backing_conflict = snapshot_unavailable && !free_snapshots.is_empty()(helios/src/scheduler.rs:1263), and when the eviction report is empty the loop returns an admission error rather than iterating:// helios/src/scheduler.rs:1284-1289 if evicted.retired.is_empty() { return Err(crate::Error::admission( crate::AdmissionError::Capacity, "live request resources are exhausted or awaiting GPU retirement", )); }- The writeback wake scan terminates despite re-entry without an epoch bump: already-stamped waiters are skipped and
writeback_wake_remainingreaches 0 whenadvanced == len(selene-manager/src/store.rs:1610-1666);filter_writeback_waiters(:1443-1475) is the single removal funnel, so no waiter is lost. - The
O_DIRECTpacked path is correct:write_packedpads the final block, then truncates to exact logical length (selene/src/disk.rs:1408-1421,file.set_len(total)), with round-trip and scan-recovery coverage for unaligned and multi-block payloads (:1327-1379, tests:4160+). - Clean-L1 retention is guarded by a real invariant (
assert_clean_slots_invariant, invoked fromrelease_removed/promote_role/mark_durable/pin_record/unpin_recordinselene/src/memory.rs). worth_restore(runtime.rs:225-229) is a faithful port ofworth_transfer(selene/src/store.rs:459-468), including the non-finite rejection.prefill_rateis retained, not removed, and is narrowed (single lane,tokens*2 >= capacity, prefers GPU duration withwall_nsfallback):
Excluding queue wait raises the rate, which shrinks// helios/src/server/runtime.rs:3071-3085 if !step.kind.is_prefill() || step.lanes.len() != 1 || capacity == 0 || (step.lanes[0].tokens as u64).saturating_mul(2) < capacity { return; } let Some(duration_ns) = crate::scheduler::observed_duration_ns(timing) .or((timing.wall_ns > 0).then_some(timing.wall_ns)) else { return; };gained / rateand so biases against marginal restores — the safe direction.
3. Architecture, contracts & platform parity
F3 (Major) — Undisclosed rank-relay wire incompatibility
// selene/src/shard.rs:465-471
enum Kind {
Stored,
Fetched,
Truncated,
Unlinked,
StoreInvalidated,
}
// selene/src/shard.rs:478-487
fn decode(code: u8) -> Result<Self> {
Ok(match code {
0 => Self::Stored,
...
4 => Self::StoreInvalidated,
_ => return Err(invalid("unknown prefix record event kind")),
})
}
Impact. A rank on an older build receiving code 4 fails the event decode outright, so a rolling upgrade or any mixed-version rank set cannot interoperate — this is the "supported matrix & compatibility" requirement in the charter ("verify that existing data, artifacts, and exported cores still load"). Nothing in the PR body's "Compatibility and Limitations" section mentions it. Note also that record_with_header remaps the new kind to a Stored reply (shard.rs:653-656) and only emits it when the store wrote nowhere (:729-732), so the wire code is an internal signal, not a new user-visible operation.
Fix. Declare the wire addition in "Compatibility and Limitations" as a version-skew constraint (all ranks must be upgraded together), or make the decoder tolerate unknown codes for forwards-compatibility.
F4 (Major) — Three public crate signatures changed without disclosure
// selene/src/store.rs:377
fn begin_lookup(&mut self, _history: &dyn History, _resident: u64) -> Option<LookupTicket> {
// selene/src/store.rs:401-404
/// Local DRAM records that still need pool handover before shutdown drain can finish.
fn pending_pool_drain(&self) -> usize {
self.stats().memory_records
}
// selene/src/store.rs:433-440
fn retired(
&mut self,
_key: PrefixKey,
_tier: PoolTier,
_how: Retirement,
_offered: &[Retiring],
) {
}
Plus HostHit.pooled: bool (selene/src/store.rs:100-103) and StoreStats.disk_reserved_records / disk_reserved_bytes / pool_inbound_rates: Option<[f64; 4]> (:244-256).
Impact. HostStore and TierStore are public traits. Any out-of-tree implementor — or test fixture, or downstream SDK integration — stops compiling. begin_lookup's new resident parameter is the load-bearing one: it is the resident-aware lookup this PR is built on, so it cannot be shimmed. Fix. Add a "Compatibility and Limitations" bullet naming the three signatures and the HostHit/StoreStats field additions.
F6 (Minor) — Windows loses the buffered fallback for packed writes
// selene/src/disk.rs:1774-1781
fn is_direct_unsupported(error: &io::Error) -> bool {
#[cfg(unix)]
{
error.raw_os_error() == Some(libc::EINVAL)
}
#[cfg(not(unix))]
{
false
}
}
But the Windows opener can reject the file with Unsupported:
// eos/src/windows.rs:104-109
if sector == 0 || 4096 % sector != 0 {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
format!("direct I/O sector size {sector} does not divide 4096"),
));
}
The buffered fallback arm is therefore unreachable on Windows:
// selene/src/disk.rs:1423-1429
Err(e) if is_direct_unsupported(&e) => {
let mut file = OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(&temporary)
.map_err(|e| io_failure("create packed record file", e))?;
Impact. Pre-PR every packed write went through the buffered path, so packed (kvc=cpu/kvc=gpu) storage worked on any Windows volume. Post-PR a volume reporting a non-divisor sector size hard-fails the write as create packed record file — a new platform regression on an untested target. Fix. In the non-unix arm match ErrorKind::Unsupported | ErrorKind::InvalidInput.
F5 (Minor) — Row-restore buckets ignore the source level, defeating half the stated separation
// helios/src/server/runtime.rs:255-268
/// Source class for row-only host restores so slow remote or NVMe claims cannot
/// raise the admission floor for fast local DRAM hits.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct RowRestoreSource {
pooled: bool,
tier: flare_selene::Tier,
}
The pool already knows the 4-valued level one line before it picks the coarser tier:
// selene/src/pool/store.rs:465
let estimated_seconds = self.rates.part_seconds(plan.part.level, bytes);
...
// selene/src/pool/store.rs:479-480
tier: candidate.tier,
pooled: true,
Impact. flare_selene::Tier is Dram/Nvme, while the pool has four levels (neighbour_gpu, host_dram, host_nvme, remote_nvme — the same four the PR adds gauges for). A slow remote-NVMe claim and a fast local-NVMe claim share one median, so the floor at runtime.rs:3344-3350 (hit.estimated_seconds.max(row_restore_latency.estimate_seconds(source))) can still let a slow remote claim raise the local floor. Only DRAM-vs-NVMe is isolated. Fix. Key the bucket on plan.part.level (carry it on HostHit) rather than Tier.
4. Tests & claim accuracy
F10 (Major) — Charter #210 unmet, and the baseline is stale
The charter states: "Performance PRs need benchmarks showing an actual speedup over main on a served workload (#210)." Tables A–F in the body are an A/B against 5d53040e, while the PR base is 1fbcc3c9; the four commits in the gap include 8489d504 #663 ("price first-output waiting age on incumbent decode rounds"), which prices the very restore decisions Tables B and C report on. The body itself says the numbers were run on 7d7dcdcb ("hardware benchmarks and live saturation runs executed on pre-refactor commit 7d7dcdcb"), so no benchmark and no CI run is reported for head 19ce4a7b — including the final RowRestoreLatency/pump code that this review finds defective. Fix. Re-run Tables A–C on 1fbcc3c9 → 19ce4a7b with attached logs; report CI on the head SHA.
F9 (Minor) — Metric span semantics shifted without a docs note
// helios/src/server/metrics.rs:538-543
pub(super) fn host_lookup_cost(
&self,
missing_tokens: u64,
transfer_seconds: f64,
prefill_saved_seconds: f64,
) {
For row-only hits the transfer_seconds argument is now a floor, not a measurement:
// helios/src/server/runtime.rs:3346-3353
let source = row_restore_source(&hit);
let transfer_seconds = if hit.pages == 0 {
hit.estimated_seconds
.max(row_restore_latency.estimate_seconds(source))
} else {
hit.estimated_seconds
};
metrics.host_lookup_cost(missing_tokens, transfer_seconds, prefill_saved_seconds);
and prefill_saved_seconds comes from the scheduler's graph-timing model, with a gained / fallback_prefill_rate fallback only while cold:
// helios/src/server/runtime.rs:3269-3280
if let Some(saved_ns) = scheduler.estimate_prefill_delta_ns(...) {
return saved_ns as f64 * 1e-9;
}
let gained = candidate_tokens.saturating_sub(resident_tokens);
gained as f64 / fallback_prefill_rate.max(1.0)
Impact. flare_host_cache_prefill_ns was previously missing / measured_rate; it is now largely a modelled quantity, and host_transfer_ns for row-only hits is a decision floor rather than an observed transfer. Dashboards and any tuning that compares these series across the upgrade will misread them. Fix. Note the change in docs/api.md (not opened) alongside the other new gauges.
Open questions
- Does the pump self-notify actually settle under the tight-manager workload the PR benchmarks?
pending_putsonly drains when the session/namespace accepts the put; if a namespace is saturated for seconds, F1 turns the owner thread into a spin loop for that whole window. No test in the diff exercisespending_putsnon-empty across consecutive pumps — I could not find one. - Is the baseline re-run possible at all? Tables B and C report latency deltas (
-28.3% mean,-12.2% p50) that#663directly targets; without a1fbcc3c9run, the attribution between #674 and #663 cannot be settled from the repo. - Nothing answers #451's own question ("do wider planes widen each snapshot's conflict range?"). The diff asserts midpoint pairing does not widen any row's span and adds
row_conflicts/verify_physical_invariants, but #451 has no update from the PR and no conflict-pressure workload is benchmarked. - Merge order with #665 (open,
FujitsuPolycom), which rewrites the same victim-selection function inhelios/src/cache.rsand the samedocs/prefix-cache-offload.md(not opened) sections, and with #659 (open) onhelios/src/runtime_core/cache_memory.rs(not opened). Neither PR references the other; this PR'sevict_for_pressure+eviction_candidate_with_priorityrestructure will conflict textually and semantically. - No SM121 / GB10 / SM103 evidence, although the charter names those targets.
- Zero human engagement: two bot comments, no reviews, no labels, on a 41-file cross-crate cache-core change.
What I could not verify
selene/src/memory.rs,selene/src/disk_store.rs's full state machine,selene/src/composite.rs(not opened),helios/src/runtime_core/cache_memory.rs(not opened),helios/src/scheduler/cache_memory.rs,helios/src/scheduler/checkpoints.rs, andhelios/src/server/runtime/phase_tests.rsbeyond the specific cited regions — the hunks are too large to audit exhaustively in one pass, so findings in those files are confirmed at the cited lines only.- No Windows or SM121 hardware was available; F6 is derived from the
#[cfg(not(unix))]arm plus theeosWindows opener's error kind, not from a run. - I did not run the test suite; all test-gap claims (F2, F9) come from reading the assertions.
Author action list
- Fix the
RowRestoreLatencyclock (helios/src/server/runtime.rs:301-303) and add the observe→age→fail test. - Gate the pump self-notify on real progress (
selene-manager/src/store.rs:5067-5072), and stop callingon_reply()per disk completion (selene/src/disk.rs:533-535). - Disclose: the
Kind::StoreInvalidated = 4wire code, the three public-API signature changes, and the sub-page memory-only startup error. - Re-baseline Tables A–C against
1fbcc3c9and post CI on19ce4a7b. - Windows: match
Unsupported | InvalidInputin the non-unixis_direct_unsupportedarm; make reclaim key-blocking bounded; use saturating decrements. - Key
RowRestoreSourceon pool level rather thanTier; document thehost_transfer_ns/host_prefill_nsspan change indocs/api.md(not opened). - Post the midpoint half-width conclusion on #451; agree merge order with #665 and #659.