From 5269e99cb9891800196e1335ed624e15cd1ed836 Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 24 Oct 2026 00:22:37 -0500 Subject: [PATCH 1/5] A resident page discarded by an engine relaunch is recorded and named on her next cold turn (card 6b28a445) Line 6, every fast-path miss is loud, on top of #5348. A replacement now saves residents first, but three paths cannot, and they lost the KV with no record: checkpoint_before_replacement returned Ok when the generation had exited or paging was quarantined, and retire_adopted skipped the checkpoint when paging was quarantined and returned Ok when the adopted engine was already dead. The cold turn that followed said no_page or page_on_disk_unconfirmed, blaming the page store for a relaunch. Each of those paths now calls EndpointSlots::record_relaunch_discard with its reason (engine_exited, paging_uncertain, adopted_engine_dead). That records the minds held in a slot without a confirmed save, and probes inference.kv_page.discarded_by_relaunch with the count. The record lives on the endpoint because the pool is replaced with the engine. Every admission takes its own page's record, so only the first turn after the relaunch is blamed on it. A cold turn then reports cause=discarded_by_relaunch with discard_reason. The record is one entry per mind, replaced and never grown; forks die with their core and are not recorded, as in the ledger. New file slots/relaunch_discard.rs; test slots::tests::a_relaunch_records_only_unsaved_residents_and_their_next_turn_takes_it_once. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../llama_server/adopted_retirement.rs | 12 +++- core/continuum-engine/src/inference/slots.rs | 2 + .../src/inference/slots/engine_generation.rs | 7 ++ .../src/inference/slots/kv_slot_pool.rs | 4 ++ .../src/inference/slots/relaunch_discard.rs | 67 +++++++++++++++++++ .../src/inference/slots/tests.rs | 26 +++++++ .../src/inference/turn_admission.rs | 14 ++-- 7 files changed, 125 insertions(+), 7 deletions(-) create mode 100644 core/continuum-engine/src/inference/slots/relaunch_discard.rs diff --git a/core/continuum-engine/src/inference/llama_server/adopted_retirement.rs b/core/continuum-engine/src/inference/llama_server/adopted_retirement.rs index 329cf37a7a..0ad4d1b75b 100644 --- a/core/continuum-engine/src/inference/llama_server/adopted_retirement.rs +++ b/core/continuum-engine/src/inference/llama_server/adopted_retirement.rs @@ -23,13 +23,19 @@ impl LlamaServerProcess { return Err(LlamaServerError::Spawn("recorded live lane belongs to another endpoint".into())); } let incarnation = lane.incarnation(); + let endpoint = crate::inference::slots::directory().endpoint(&self.root); match incarnation.liveness() { - Liveness::Dead => return Ok(()), + Liveness::Dead => { + // Its residents' KV died with it; their next turns name this (card 6b28a445). + endpoint.record_relaunch_discard(crate::inference::slots::DiscardReason::AdoptedEngineDead); + return Ok(()); + } Liveness::Unknown => return Err(LlamaServerError::Spawn("adopted engine identity is unverified; refusing retirement".into())), Liveness::Alive => {} } - let endpoint = crate::inference::slots::directory().endpoint(&self.root); - if !endpoint.paging_recovery_required() { + if endpoint.paging_recovery_required() { + endpoint.record_relaunch_discard(crate::inference::slots::DiscardReason::PagingUncertain); + } else { transition.checkpoint_adopted_before_replacement( &self.client, &self.root, incarnation, current, ).await.map_err(LlamaServerError::Spawn)?; diff --git a/core/continuum-engine/src/inference/slots.rs b/core/continuum-engine/src/inference/slots.rs index 10ea03cbea..11488cad7b 100644 --- a/core/continuum-engine/src/inference/slots.rs +++ b/core/continuum-engine/src/inference/slots.rs @@ -52,6 +52,8 @@ use saved_ledger::{LedgerSnapshot, LoadedLedger}; #[cfg(test)] use saved_ledger::{SavedLedgerFile, LEDGER_FORMAT, SAVED_LEDGER_FILE}; mod engine_generation; +mod relaunch_discard; +pub(crate) use relaunch_discard::DiscardReason; pub use engine_generation::*; mod placement; pub use placement::*; diff --git a/core/continuum-engine/src/inference/slots/engine_generation.rs b/core/continuum-engine/src/inference/slots/engine_generation.rs index a531b7fbfa..d38e634cce 100644 --- a/core/continuum-engine/src/inference/slots/engine_generation.rs +++ b/core/continuum-engine/src/inference/slots/engine_generation.rs @@ -284,6 +284,12 @@ impl EndpointTransition { ) -> Result<(), String> { let generation = self.previous_generation().ok_or("replacement requires a known generation")?; if generation.has_exited() || self.endpoint.paging_recovery_required() { + // Nothing can be saved: the engine is gone, or a save could not be trusted. + self.endpoint.record_relaunch_discard(if generation.has_exited() { + DiscardReason::EngineExited + } else { + DiscardReason::PagingUncertain + }); return Ok(()); } let original = self.capture_suspension(&generation)?; @@ -558,6 +564,7 @@ impl SlotDirectory { gate: Arc::new(tokio::sync::RwLock::new(())), paging_tasks: Mutex::new(tokio::task::JoinSet::new()), ready_rx, + discarded: Mutex::new(std::collections::HashMap::new()), state: Mutex::new(EndpointState { ready, paging_uncertain: false, diff --git a/core/continuum-engine/src/inference/slots/kv_slot_pool.rs b/core/continuum-engine/src/inference/slots/kv_slot_pool.rs index bf0aeb0a0e..8623d353d7 100644 --- a/core/continuum-engine/src/inference/slots/kv_slot_pool.rs +++ b/core/continuum-engine/src/inference/slots/kv_slot_pool.rs @@ -459,6 +459,10 @@ pub struct EndpointSlots { pub(super) paging_tasks: Mutex>, /// The read side of `EndpointState::ready`, for turns that hold through a transition. pub(super) ready_rx: tokio::sync::watch::Receiver, + /// Residents a relaunch discarded unsaved, until their next turn takes the record + /// (card 6b28a445). On the endpoint because the pool does not outlive the engine. + /// Bounded by the minds that were resident: one entry per mind, replaced, never grown. + pub(super) discarded: Mutex>, } pub struct EndpointAdmission { diff --git a/core/continuum-engine/src/inference/slots/relaunch_discard.rs b/core/continuum-engine/src/inference/slots/relaunch_discard.rs new file mode 100644 index 0000000000..dc8f544c0b --- /dev/null +++ b/core/continuum-engine/src/inference/slots/relaunch_discard.rs @@ -0,0 +1,67 @@ +//! Residents an engine relaunch discards, remembered until their next turn (card 6b28a445). +//! +//! A replacement saves residents first (#5348), but three paths cannot: the engine already +//! exited, paging is quarantined (a save could not be trusted), or an adopted engine is +//! already dead. Their slots' KV is gone with the engine. The pool is rebuilt for the next +//! generation, so the record lives on the endpoint, and the resident's next turn takes it: +//! a cold turn then names the relaunch, instead of reading as a lost page or a ledger defect. + +use super::*; + +/// Why a relaunch discarded residents' unsaved KV. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum DiscardReason { + /// The owned engine exited before its replacement could save anything. + EngineExited, + /// Paging completion was uncertain, so the endpoint was quarantined and no save ran. + PagingUncertain, + /// The adopted engine's process was already gone when retirement looked. + AdoptedEngineDead, +} + +impl DiscardReason { + pub(crate) fn as_str(self) -> &'static str { + match self { + Self::EngineExited => "engine_exited", + Self::PagingUncertain => "paging_uncertain", + Self::AdoptedEngineDead => "adopted_engine_dead", + } + } +} + +impl KvSlotPool { + /// The minds held in a slot without a confirmed save: what a relaunch now loses. A fork + /// dies with the core that ran it, so only minds, as in the ledger. + pub(super) fn unsaved_residents(&self) -> Vec { + // Lock order: `saved`, then `holders` (see `ledger_snapshot`). + let saved = self.saved.lock(); + let holders = self.holders.lock(); + holders.values().filter(|key| key.as_mind().is_some() && !saved.contains(key)).copied().collect() + } +} + +impl EndpointSlots { + /// Record that a relaunch is discarding this endpoint's unsaved residents, and say so. + pub(crate) fn record_relaunch_discard(&self, reason: DiscardReason) { + let pool = self.state.lock().pool.as_ref().and_then(Clone::clone); + let lost = pool.map_or_else(Vec::new, |pool| pool.unsaved_residents()); + continuum_base::probe!( + class = "inference.kv_page.discarded_by_relaunch", + reason = reason.as_str(), + residents = lost.len() as u64, + "an engine relaunch discarded residents' unsaved KV: their next turns prefill in full" + ); + let mut discarded = self.discarded.lock(); + for key in lost { + discarded.insert(key, reason); + } + } +} + +impl EndpointAdmission { + /// Why a relaunch discarded `key`'s KV, if one did since its last turn. Taken once, so a + /// later cold turn is never blamed on an old relaunch. + pub(crate) fn take_relaunch_discard(&self, key: &PageKey) -> Option { + self.endpoint.discarded.lock().remove(key) + } +} diff --git a/core/continuum-engine/src/inference/slots/tests.rs b/core/continuum-engine/src/inference/slots/tests.rs index c9888b2310..d7b89e6795 100644 --- a/core/continuum-engine/src/inference/slots/tests.rs +++ b/core/continuum-engine/src/inference/slots/tests.rs @@ -184,6 +184,32 @@ mod adopted_checkpoint; PageKey::mind(Uuid::from_u128(p)).expect("non-nil test id") } + // what this catches (card 6b28a445): a relaunch that cannot save (engine exited, paging + // quarantined, adopted engine dead) discarded residents' KV with no record, so their + // next cold turn read as a lost page. Only minds held WITHOUT a confirmed save are + // recorded, the record survives the pool being replaced, and it is taken exactly once. + #[tokio::test] + async fn a_relaunch_records_only_unsaved_residents_and_their_next_turn_takes_it_once() { + let dir = SlotDirectory { endpoints: dashmap::DashMap::new() }; + let endpoint = dir.endpoint("test://relaunch"); + let pool = Arc::new(KvSlotPool::new("test://relaunch", 4)); + pool.holders.lock().insert(0, mind(1)); + pool.holders.lock().insert(1, mind(2)); + pool.holders.lock().insert(2, key(3, 4)); + pool.note_saved(mind(2)); + endpoint.state.lock().pool = Some(Some(pool)); + + endpoint.record_relaunch_discard(DiscardReason::EngineExited); + // The next generation's pool replaces this one; the record is the endpoint's. + endpoint.state.lock().pool = Some(Some(Arc::new(KvSlotPool::new("test://relaunch", 4)))); + + let admission = endpoint.admit().await.expect("an open endpoint admits"); + assert_eq!(admission.take_relaunch_discard(&mind(1)), Some(DiscardReason::EngineExited)); + assert_eq!(admission.take_relaunch_discard(&mind(1)), None, "taken once"); + assert_eq!(admission.take_relaunch_discard(&mind(2)), None, "a saved page restores; nothing was lost"); + assert_eq!(admission.take_relaunch_discard(&key(3, 4)), None, "a fork dies with its core anyway"); + } + // regression for card 6102ac09 (BigMama, 2026-09-26 12:28Z): a turn that reached a // loading engine was refused instantly — 16 of Kimi's 26 requests in 90 min failed // inside a 90 s launch window, half of them on the cross-grid fallback. diff --git a/core/continuum-engine/src/inference/turn_admission.rs b/core/continuum-engine/src/inference/turn_admission.rs index c60a7ebe76..3cbb362774 100644 --- a/core/continuum-engine/src/inference/turn_admission.rs +++ b/core/continuum-engine/src/inference/turn_admission.rs @@ -390,22 +390,28 @@ async fn admit( admission.page_in = PageIn::Resident; } admission.uncommitted = Some((Arc::clone(pool), k, pg.slot)); + // Taken on every admission, so only the first turn after a relaunch is blamed on it. + let discarded = admission._endpoint.take_relaunch_discard(&k); if !pg.already_resident && !pg.restore { // Every fast-path miss is loud: this turn prefills from its first token. // With no page on disk that is a first visit; a page on disk the ledger does // not confirm (lost before a save finished, or a ledger that did not load) // is the defect class, never a quiet slower path. + // A relaunch that discarded this resident unsaved is the cause, whatever + // is on disk (card 6b28a445); otherwise the page store answers. let on_disk = pool.page_on_disk(&k); continuum_base::probe!( class = "inference.kv_page.cold_turn", page = %k, slot = pg.slot as u64, warm_only, - cause = match on_disk { - Some(true) => "page_on_disk_unconfirmed", - Some(false) => "no_page", - None => "no_page_dir", + cause = match (discarded, on_disk) { + (Some(_), _) => "discarded_by_relaunch", + (None, Some(true)) => "page_on_disk_unconfirmed", + (None, Some(false)) => "no_page", + (None, None) => "no_page_dir", }, + discard_reason = discarded.map_or("", crate::inference::slots::DiscardReason::as_str), "this page's slot holds none of its KV and no restorable page exists: it prefills in full" ); } From 4d94c369f8a2aa6e94caafb51b1e911eda453b17 Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 24 Oct 2026 00:28:17 -0500 Subject: [PATCH 2/5] A relaunch discard is captured early and recorded only once the engine is gone; retention is one pool of slots (card 6b28a445) Codex's review of #5357 at ab7788bbb: (1) The record was not bounded: minds discarded by one relaunch that never returned stayed forever, across generations. DiscardLog now keeps at most the latest discarding pool's slot count, oldest evicted first. One relaunch cannot discard more minds than it had slots, so the latest is kept whole, and an empty capture evicts nothing. (2) A loss was recorded before the retirement re-checked current(), re-verified the engine's identity or signalled it, so a superseded or refused retirement could report a loss that never happened. The residents are now captured as a PendingDiscard (must_use) while the old pool is installed, and committed only once the engine is actually gone. checkpoint_before_replacement returns the capture, and launch commits it after kill_child. retire_adopted commits after signal_if_same succeeds, or as adopted_engine_dead when the engine is seen dead. Every early return drops the capture unrecorded. Tests: the lifecycle path through checkpoint_before_replacement (a dropped capture records nothing, a committed one is taken once and survives the pool's replacement), and retention across three generations. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../llama_server/adopted_retirement.rs | 23 +++-- .../src/inference/llama_server/launch.rs | 7 +- core/continuum-engine/src/inference/slots.rs | 3 +- .../src/inference/slots/engine_generation.rs | 16 ++-- .../src/inference/slots/kv_slot_pool.rs | 6 +- .../src/inference/slots/relaunch_discard.rs | 84 +++++++++++++++---- .../src/inference/slots/tests.rs | 60 +++++++++++-- 7 files changed, 160 insertions(+), 39 deletions(-) diff --git a/core/continuum-engine/src/inference/llama_server/adopted_retirement.rs b/core/continuum-engine/src/inference/llama_server/adopted_retirement.rs index 0ad4d1b75b..d5ddc2daab 100644 --- a/core/continuum-engine/src/inference/llama_server/adopted_retirement.rs +++ b/core/continuum-engine/src/inference/llama_server/adopted_retirement.rs @@ -23,29 +23,39 @@ impl LlamaServerProcess { return Err(LlamaServerError::Spawn("recorded live lane belongs to another endpoint".into())); } let incarnation = lane.incarnation(); + use crate::inference::slots::DiscardReason; let endpoint = crate::inference::slots::directory().endpoint(&self.root); match incarnation.liveness() { Liveness::Dead => { // Its residents' KV died with it; their next turns name this (card 6b28a445). - endpoint.record_relaunch_discard(crate::inference::slots::DiscardReason::AdoptedEngineDead); + endpoint.pending_discard(DiscardReason::AdoptedEngineDead).commit(); return Ok(()); } Liveness::Unknown => return Err(LlamaServerError::Spawn("adopted engine identity is unverified; refusing retirement".into())), Liveness::Alive => {} } - if endpoint.paging_recovery_required() { - endpoint.record_relaunch_discard(crate::inference::slots::DiscardReason::PagingUncertain); + // Quarantined paging cannot save: its residents are captured now, recorded only once + // the engine is signalled or seen dead, so a superseded or refused retirement never + // reports a loss (card 6b28a445). + let unsaved = if endpoint.paging_recovery_required() { + Some(endpoint.pending_discard(DiscardReason::PagingUncertain)) } else { transition.checkpoint_adopted_before_replacement( &self.client, &self.root, incarnation, current, ).await.map_err(LlamaServerError::Spawn)?; - } + None + }; if !current() { return Err(LlamaServerError::Superseded); } // A completed checkpoint is not authority to signal a reused PID. match incarnation.liveness() { - Liveness::Dead => return Ok(()), + Liveness::Dead => { + if let Some(unsaved) = unsaved { + unsaved.because(DiscardReason::AdoptedEngineDead).commit(); + } + return Ok(()); + } Liveness::Unknown => return Err(LlamaServerError::Spawn("adopted engine identity became unverified after checkpoint".into())), Liveness::Alive => {} } @@ -58,6 +68,9 @@ impl LlamaServerProcess { // No await between signalling and retaining custody. Cancellation of the // wait cannot turn this predecessor back into a serving candidate. *self.retiring_adopted.lock() = Some(incarnation); + if let Some(unsaved) = unsaved { + unsaved.commit(); + } self.await_adopted_exit(incarnation, Duration::from_secs(10)).await } diff --git a/core/continuum-engine/src/inference/llama_server/launch.rs b/core/continuum-engine/src/inference/llama_server/launch.rs index aea830ad22..760ade3b62 100644 --- a/core/continuum-engine/src/inference/llama_server/launch.rs +++ b/core/continuum-engine/src/inference/llama_server/launch.rs @@ -62,6 +62,8 @@ impl LlamaServerProcess { // residents' slots unsaved and their next acts re-prefilled 70k-115k tokens. The // transition has drained every reader, so no turn is decoding. A failed save // defers replacement rather than destroying the only fresh resident state. + // Residents an exited or quarantined engine loses unsaved: recorded once it is killed. + let mut discarded = None; if had_own_child && !restoring { let started = std::time::Instant::now(); let outcome = transition.checkpoint_before_replacement(&self.client, &self.root, current).await; @@ -71,12 +73,15 @@ impl LlamaServerProcess { ms = started.elapsed().as_millis() as u64, "resident checkpoint decision before engine replacement" ); - outcome.map_err(LlamaServerError::Spawn)?; + discarded = outcome.map_err(LlamaServerError::Spawn)?; } if self.is_live_lane && !had_own_child && !restoring { self.retire_adopted(&mut transition, current).await?; } self.kill_child(); + if let Some(discarded) = discarded { + discarded.commit(); + } // A freed listener is not proof that the predecessor stopped decoding. // Poll ONLY its retained owned Child; cancelled/failed transitions remain diff --git a/core/continuum-engine/src/inference/slots.rs b/core/continuum-engine/src/inference/slots.rs index 11488cad7b..8ff85da0a9 100644 --- a/core/continuum-engine/src/inference/slots.rs +++ b/core/continuum-engine/src/inference/slots.rs @@ -53,7 +53,8 @@ use saved_ledger::{LedgerSnapshot, LoadedLedger}; use saved_ledger::{SavedLedgerFile, LEDGER_FORMAT, SAVED_LEDGER_FILE}; mod engine_generation; mod relaunch_discard; -pub(crate) use relaunch_discard::DiscardReason; +pub(crate) use relaunch_discard::{DiscardReason, PendingDiscard}; +use relaunch_discard::DiscardLog; pub use engine_generation::*; mod placement; pub use placement::*; diff --git a/core/continuum-engine/src/inference/slots/engine_generation.rs b/core/continuum-engine/src/inference/slots/engine_generation.rs index d38e634cce..603190a290 100644 --- a/core/continuum-engine/src/inference/slots/engine_generation.rs +++ b/core/continuum-engine/src/inference/slots/engine_generation.rs @@ -275,22 +275,22 @@ impl EndpointTransition { /// Planned replacement cannot discard a healthy engine's unsaved residents. /// A terminal refusal resumes the exact original ledger; an uncertain write - /// stays quarantined. Dead engines and quarantined paging use recovery instead. + /// stays quarantined. Dead engines and quarantined paging use recovery instead: + /// nothing can be saved, so their unsaved residents come back as a + /// [`PendingDiscard`] the caller commits once the engine is killed (card 6b28a445). pub(crate) async fn checkpoint_before_replacement( &mut self, client: &reqwest::Client, root: &str, current: &(dyn Fn() -> bool + Send + Sync), - ) -> Result<(), String> { + ) -> Result, String> { let generation = self.previous_generation().ok_or("replacement requires a known generation")?; if generation.has_exited() || self.endpoint.paging_recovery_required() { - // Nothing can be saved: the engine is gone, or a save could not be trusted. - self.endpoint.record_relaunch_discard(if generation.has_exited() { + return Ok(Some(self.endpoint.pending_discard(if generation.has_exited() { DiscardReason::EngineExited } else { DiscardReason::PagingUncertain - }); - return Ok(()); + }))); } let original = self.capture_suspension(&generation)?; let result = self.checkpoint_residents(client, root).await.map(|_| ()); @@ -303,7 +303,7 @@ impl EndpointTransition { if !current() { return Err("replacement intent changed after checkpoint".into()); } - Ok(()) + Ok(None) } pub(crate) fn capture_suspension( @@ -564,7 +564,7 @@ impl SlotDirectory { gate: Arc::new(tokio::sync::RwLock::new(())), paging_tasks: Mutex::new(tokio::task::JoinSet::new()), ready_rx, - discarded: Mutex::new(std::collections::HashMap::new()), + discarded: Mutex::new(DiscardLog::default()), state: Mutex::new(EndpointState { ready, paging_uncertain: false, diff --git a/core/continuum-engine/src/inference/slots/kv_slot_pool.rs b/core/continuum-engine/src/inference/slots/kv_slot_pool.rs index 8623d353d7..98826d24c0 100644 --- a/core/continuum-engine/src/inference/slots/kv_slot_pool.rs +++ b/core/continuum-engine/src/inference/slots/kv_slot_pool.rs @@ -460,9 +460,9 @@ pub struct EndpointSlots { /// The read side of `EndpointState::ready`, for turns that hold through a transition. pub(super) ready_rx: tokio::sync::watch::Receiver, /// Residents a relaunch discarded unsaved, until their next turn takes the record - /// (card 6b28a445). On the endpoint because the pool does not outlive the engine. - /// Bounded by the minds that were resident: one entry per mind, replaced, never grown. - pub(super) discarded: Mutex>, + /// (card 6b28a445). On the endpoint because the pool does not outlive the engine; + /// retention is bounded by [`DiscardLog`]. + pub(super) discarded: Mutex, } pub struct EndpointAdmission { diff --git a/core/continuum-engine/src/inference/slots/relaunch_discard.rs b/core/continuum-engine/src/inference/slots/relaunch_discard.rs index dc8f544c0b..f23cfb2706 100644 --- a/core/continuum-engine/src/inference/slots/relaunch_discard.rs +++ b/core/continuum-engine/src/inference/slots/relaunch_discard.rs @@ -2,9 +2,13 @@ //! //! A replacement saves residents first (#5348), but three paths cannot: the engine already //! exited, paging is quarantined (a save could not be trusted), or an adopted engine is -//! already dead. Their slots' KV is gone with the engine. The pool is rebuilt for the next +//! already dead. Their slots' KV goes with the engine. The pool is rebuilt for the next //! generation, so the record lives on the endpoint, and the resident's next turn takes it: //! a cold turn then names the relaunch, instead of reading as a lost page or a ledger defect. +//! +//! Two steps, so a retirement that is superseded or refused never reports a loss: the +//! candidates are captured while the old pool is still installed ([`PendingDiscard`]), and +//! committed only once the engine is actually killed, signalled, or observed dead. use super::*; @@ -29,6 +33,64 @@ impl DiscardReason { } } +/// The endpoint's discard records, oldest first. Retention is at most one pool's worth of +/// slots (the most recent discarding pool's count): one relaunch can discard no more minds +/// than it had slots, so the latest relaunch is always kept whole, and an older record is +/// evicted, oldest first, only by newer ones. An evicted mind's cold turn then reads as the +/// page store's answer, never as a relaunch it cannot be tied to. +#[derive(Debug, Default)] +pub(super) struct DiscardLog { + entries: std::collections::VecDeque<(PageKey, DiscardReason)>, +} + +impl DiscardLog { + fn record(&mut self, keys: &[PageKey], reason: DiscardReason, retain: usize) { + for key in keys { + self.entries.retain(|(held, _)| held != key); + self.entries.push_back((*key, reason)); + } + while self.entries.len() > retain { + self.entries.pop_front(); + } + } + + pub(super) fn take(&mut self, key: &PageKey) -> Option { + let at = self.entries.iter().position(|(held, _)| held == key)?; + self.entries.remove(at).map(|(_, reason)| reason) + } +} + +/// Residents a relaunch is about to discard, captured from the pool being replaced. Dropped +/// without [`Self::commit`] (a superseded or refused retirement), it records nothing. +#[must_use = "a discard is recorded only when the engine is actually gone: commit it there"] +pub(crate) struct PendingDiscard { + endpoint: Arc, + keys: Vec, + retain: usize, + reason: DiscardReason, +} + +impl PendingDiscard { + /// The same residents, lost for a different reason (the engine died before the signal). + pub(crate) fn because(self, reason: DiscardReason) -> Self { + Self { reason, ..self } + } + + /// The engine is gone: record the loss and say so. + pub(crate) fn commit(self) { + continuum_base::probe!( + class = "inference.kv_page.discarded_by_relaunch", + reason = self.reason.as_str(), + residents = self.keys.len() as u64, + "an engine relaunch discarded residents' unsaved KV: their next turns prefill in full" + ); + // Nothing lost records nothing: an empty capture never evicts older records. + if !self.keys.is_empty() { + self.endpoint.discarded.lock().record(&self.keys, self.reason, self.retain.max(self.keys.len())); + } + } +} + impl KvSlotPool { /// The minds held in a slot without a confirmed save: what a relaunch now loses. A fork /// dies with the core that ran it, so only minds, as in the ledger. @@ -41,20 +103,12 @@ impl KvSlotPool { } impl EndpointSlots { - /// Record that a relaunch is discarding this endpoint's unsaved residents, and say so. - pub(crate) fn record_relaunch_discard(&self, reason: DiscardReason) { + /// Capture the residents the installed pool would lose if its engine went now. Nothing is + /// recorded until the caller commits, once the engine is actually gone. + pub(crate) fn pending_discard(self: &Arc, reason: DiscardReason) -> PendingDiscard { let pool = self.state.lock().pool.as_ref().and_then(Clone::clone); - let lost = pool.map_or_else(Vec::new, |pool| pool.unsaved_residents()); - continuum_base::probe!( - class = "inference.kv_page.discarded_by_relaunch", - reason = reason.as_str(), - residents = lost.len() as u64, - "an engine relaunch discarded residents' unsaved KV: their next turns prefill in full" - ); - let mut discarded = self.discarded.lock(); - for key in lost { - discarded.insert(key, reason); - } + let (keys, retain) = pool.map_or((Vec::new(), 0), |pool| (pool.unsaved_residents(), pool.n_slots() as usize)); + PendingDiscard { endpoint: Arc::clone(self), keys, retain, reason } } } @@ -62,6 +116,6 @@ impl EndpointAdmission { /// Why a relaunch discarded `key`'s KV, if one did since its last turn. Taken once, so a /// later cold turn is never blamed on an old relaunch. pub(crate) fn take_relaunch_discard(&self, key: &PageKey) -> Option { - self.endpoint.discarded.lock().remove(key) + self.endpoint.discarded.lock().take(key) } } diff --git a/core/continuum-engine/src/inference/slots/tests.rs b/core/continuum-engine/src/inference/slots/tests.rs index d7b89e6795..e20d9e5986 100644 --- a/core/continuum-engine/src/inference/slots/tests.rs +++ b/core/continuum-engine/src/inference/slots/tests.rs @@ -184,24 +184,45 @@ mod adopted_checkpoint; PageKey::mind(Uuid::from_u128(p)).expect("non-nil test id") } - // what this catches (card 6b28a445): a relaunch that cannot save (engine exited, paging - // quarantined, adopted engine dead) discarded residents' KV with no record, so their - // next cold turn read as a lost page. Only minds held WITHOUT a confirmed save are - // recorded, the record survives the pool being replaced, and it is taken exactly once. + // what this catches (card 6b28a445): a relaunch that cannot save (here, an engine that + // already exited) lost residents' KV with no record, so their next cold turn read as a + // lost page. Through the real replacement path: the loss is only CAPTURED by the + // checkpoint decision, and a capture dropped without commit (a superseded or refused + // retirement) records nothing. Committed, only minds held without a confirmed save are + // recorded, the record survives the pool's replacement, and it is taken exactly once. #[tokio::test] - async fn a_relaunch_records_only_unsaved_residents_and_their_next_turn_takes_it_once() { + async fn a_relaunch_records_unsaved_residents_only_when_committed_and_their_next_turn_takes_it_once() { let dir = SlotDirectory { endpoints: dashmap::DashMap::new() }; let endpoint = dir.endpoint("test://relaunch"); + let mut transition = endpoint.transition().await; + let generation = transition.start_generation().expect("first generation"); let pool = Arc::new(KvSlotPool::new("test://relaunch", 4)); pool.holders.lock().insert(0, mind(1)); pool.holders.lock().insert(1, mind(2)); pool.holders.lock().insert(2, key(3, 4)); pool.note_saved(mind(2)); endpoint.state.lock().pool = Some(Some(pool)); + generation.observed_exit(); + let client = reqwest::Client::new(); - endpoint.record_relaunch_discard(DiscardReason::EngineExited); + let superseded = transition + .checkpoint_before_replacement(&client, "test://relaunch", &|| true) + .await + .expect("an exited engine has nothing to save") + .expect("its unsaved residents are captured"); + drop(superseded); + assert_eq!(endpoint.discarded.lock().take(&mind(1)), None, "a capture never committed records nothing"); + + transition + .checkpoint_before_replacement(&client, "test://relaunch", &|| true) + .await + .expect("an exited engine has nothing to save") + .expect("its unsaved residents are captured") + .commit(); + drop(transition); // The next generation's pool replaces this one; the record is the endpoint's. endpoint.state.lock().pool = Some(Some(Arc::new(KvSlotPool::new("test://relaunch", 4)))); + endpoint.state.lock().ready.send_replace(true); // the replacement verified ready let admission = endpoint.admit().await.expect("an open endpoint admits"); assert_eq!(admission.take_relaunch_discard(&mind(1)), Some(DiscardReason::EngineExited)); @@ -210,6 +231,33 @@ mod adopted_checkpoint; assert_eq!(admission.take_relaunch_discard(&key(3, 4)), None, "a fork dies with its core anyway"); } + // what this catches (card 6b28a445, Codex's review): minds discarded by one relaunch that + // never return stayed recorded forever, across every later generation. Retention is one + // pool's worth of slots: the latest relaunch is kept whole, older records are evicted + // oldest first, and an empty capture evicts nothing. + #[tokio::test] + async fn discard_records_keep_one_pool_of_slots_across_generations() { + let dir = SlotDirectory { endpoints: dashmap::DashMap::new() }; + let endpoint = dir.endpoint("test://retention"); + let relaunch = |minds: &[u128]| { + let pool = Arc::new(KvSlotPool::new("test://retention", 3)); + for (slot, m) in minds.iter().enumerate() { + pool.holders.lock().insert(slot as u32, mind(*m)); + } + endpoint.state.lock().pool = Some(Some(pool)); + endpoint.pending_discard(DiscardReason::PagingUncertain).commit(); + }; + relaunch(&[1, 2, 3]); + relaunch(&[4, 5]); + relaunch(&[]); + let mut log = endpoint.discarded.lock(); + assert_eq!(log.take(&mind(1)), None, "oldest evicted first"); + assert_eq!(log.take(&mind(2)), None, "oldest evicted first"); + for kept in [3, 4, 5] { + assert_eq!(log.take(&mind(kept)), Some(DiscardReason::PagingUncertain), "mind {kept} kept"); + } + } + // regression for card 6102ac09 (BigMama, 2026-09-26 12:28Z): a turn that reached a // loading engine was refused instantly — 16 of Kimi's 26 requests in 90 min failed // inside a 90 s launch window, half of them on the cross-grid fallback. From df60aaa74ba89a6c7f553ab55ddc79faf5938d5f Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 24 Oct 2026 01:54:17 -0500 Subject: [PATCH 3/5] The retention test defines 'oldest' with one mind per relaunch (card 6b28a445) CI job 120805073062 at 769d5d7af: discard_records_keep_one_pool_of_slots_across_generations asserted minds 1 and 2 were evicted after relaunches [1,2,3] then [4,5]. But the residents of one relaunch come from a HashMap, so their order within that relaunch is arbitrary, and which two were oldest was not defined. The test now evicts with one mind per relaunch ([1],[2],[3],[4] at three slots: 1 evicted), then checks that a whole pool's relaunch ([7,8,9]) is kept whole over an older one ([5,6]) and that an empty relaunch evicts nothing. The code is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../src/inference/slots/tests.rs | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/core/continuum-engine/src/inference/slots/tests.rs b/core/continuum-engine/src/inference/slots/tests.rs index e20d9e5986..c49e407c3d 100644 --- a/core/continuum-engine/src/inference/slots/tests.rs +++ b/core/continuum-engine/src/inference/slots/tests.rs @@ -247,13 +247,25 @@ mod adopted_checkpoint; endpoint.state.lock().pool = Some(Some(pool)); endpoint.pending_discard(DiscardReason::PagingUncertain).commit(); }; - relaunch(&[1, 2, 3]); - relaunch(&[4, 5]); - relaunch(&[]); + // One mind per relaunch, so "oldest" is defined: the first is evicted by the fourth. + for m in [1, 2, 3, 4] { + relaunch(&[m]); + } + { + let mut log = endpoint.discarded.lock(); + assert_eq!(log.take(&mind(1)), None, "oldest evicted first"); + for kept in [2, 3, 4] { + assert_eq!(log.take(&mind(kept)), Some(DiscardReason::PagingUncertain), "mind {kept} kept"); + } + } + relaunch(&[5, 6]); + relaunch(&[7, 8, 9]); // a whole pool of slots: the latest relaunch is kept whole + relaunch(&[]); // nothing lost evicts nothing let mut log = endpoint.discarded.lock(); - assert_eq!(log.take(&mind(1)), None, "oldest evicted first"); - assert_eq!(log.take(&mind(2)), None, "oldest evicted first"); - for kept in [3, 4, 5] { + for evicted in [5, 6] { + assert_eq!(log.take(&mind(evicted)), None, "mind {evicted} evicted by a newer relaunch"); + } + for kept in [7, 8, 9] { assert_eq!(log.take(&mind(kept)), Some(DiscardReason::PagingUncertain), "mind {kept} kept"); } } From a2b30500d112c1256d5b2fe5d2c61499b9f7d2b5 Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 24 Oct 2026 02:28:56 -0500 Subject: [PATCH 4/5] A relaunch's loss is recorded at the engine's observed death, never when the kill is sent (card 6b28a445) Codex's re-review of #5357 at 5d8e4c2ed: launch committed the discard right after kill_child (a void call that may only log a failed signal), and retire_adopted committed it right after signal_if_same, both before any exit was observed. A sent signal is not a death. - Owned engine: checkpoint_before_replacement hands its capture to the endpoint (PendingDiscard::on_exit_of), held for that generation (DiscardLog's watch) and recorded by EngineGeneration::observed_exit, or at once if the exit was already observed. A generation already watched keeps its first capture, so re-entry never records twice. launch.rs is back to canary's. - Adopted engine: the capture rides the retirement custody beside retiring_adopted (LlamaServerProcess::retiring_discard). await_adopted_exit records it only when the exact process is seen gone, so a timed-out, cancelled or re-entered wait records nothing until then. A failed signal returns before custody, so its capture drops unrecorded. An engine already seen dead is recorded at once. Tests: through checkpoint_before_replacement, nothing is recorded while quarantined (two attempts), the observed exit records it once, and a re-entry after exit adds nothing. adopted_exit_wait_retains_custody_until_observed_exit now checks that no loss is recorded after a cancelled poll or a zero-budget timeout, and that the real child's exit records it. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- .../llama_server/adopted_retirement.rs | 34 +++-- .../src/inference/llama_server/launch.rs | 7 +- .../src/inference/llama_server/process.rs | 5 + .../src/inference/slots/engine_generation.rs | 17 ++- .../src/inference/slots/relaunch_discard.rs | 125 ++++++++++++++---- .../src/inference/slots/tests.rs | 41 +++--- 6 files changed, 162 insertions(+), 67 deletions(-) diff --git a/core/continuum-engine/src/inference/llama_server/adopted_retirement.rs b/core/continuum-engine/src/inference/llama_server/adopted_retirement.rs index d5ddc2daab..f80d84efdf 100644 --- a/core/continuum-engine/src/inference/llama_server/adopted_retirement.rs +++ b/core/continuum-engine/src/inference/llama_server/adopted_retirement.rs @@ -34,9 +34,9 @@ impl LlamaServerProcess { Liveness::Unknown => return Err(LlamaServerError::Spawn("adopted engine identity is unverified; refusing retirement".into())), Liveness::Alive => {} } - // Quarantined paging cannot save: its residents are captured now, recorded only once - // the engine is signalled or seen dead, so a superseded or refused retirement never - // reports a loss (card 6b28a445). + // Quarantined paging cannot save: its residents are captured now and recorded only + // when the engine is seen dead, so a superseded, refused or still-waiting retirement + // never reports a loss (card 6b28a445). let unsaved = if endpoint.paging_recovery_required() { Some(endpoint.pending_discard(DiscardReason::PagingUncertain)) } else { @@ -66,11 +66,10 @@ impl LlamaServerProcess { }, ).map_err(LlamaServerError::Spawn)?; // No await between signalling and retaining custody. Cancellation of the - // wait cannot turn this predecessor back into a serving candidate. + // wait cannot turn this predecessor back into a serving candidate. A signal is + // not a death: the residents' loss is recorded when the exit is observed. *self.retiring_adopted.lock() = Some(incarnation); - if let Some(unsaved) = unsaved { - unsaved.commit(); - } + *self.retiring_discard.lock() = unsaved; self.await_adopted_exit(incarnation, Duration::from_secs(10)).await } @@ -97,6 +96,11 @@ impl LlamaServerProcess { and verifies readiness before reopening admission", incarnation.pid, incarnation.started_s )))??; *self.retiring_adopted.lock() = None; + // Its death is observed: the residents it held unsaved are now lost. + let discarded = self.retiring_discard.lock().take(); + if let Some(discarded) = discarded { + discarded.commit(); + } Ok(()) } } @@ -107,7 +111,9 @@ mod tests { use crate::inference::engine_residency::{EngineIncarnation, ProcessProbe, probe_process}; // Exercise the wait against a real isolated process. Cancellation and timeout - // retain custody; only its observed exit permits the next launch to proceed. + // retain custody; only its observed exit permits the next launch to proceed. The + // residents it held unsaved are recorded as lost at that observed exit, never while a + // cancelled or timed-out wait still holds custody (card 6b28a445). #[tokio::test] async fn adopted_exit_wait_retains_custody_until_observed_exit() -> Result<(), Box> { const CHILD: &str = "CONTINUUM_ADOPTED_EXIT_FIXTURE"; @@ -128,8 +134,14 @@ mod tests { return Err("fixture process identity unavailable".into()); }; let incarnation = EngineIncarnation { pid: child.id(), started_s, port: 0 }; - let process = LlamaServerProcess::with_root(format!("http://exit-fixture-{}", uuid::Uuid::new_v4())); + let root = format!("http://exit-fixture-{}", uuid::Uuid::new_v4()); + let process = LlamaServerProcess::with_root(root.clone()); *process.retiring_adopted.lock() = Some(incarnation); + let endpoint = crate::inference::slots::directory().endpoint(&root); + let resident = crate::inference::slots::PageKey::mind(uuid::Uuid::new_v4()).ok_or("non-nil id")?; + let lost = crate::inference::slots::DiscardReason::PagingUncertain; + *process.retiring_discard.lock() = + Some(crate::inference::slots::PendingDiscard::for_test(endpoint.clone(), vec![resident], lost)); { use std::future::Future; let wait = process.await_adopted_exit(incarnation, Duration::from_secs(10)); @@ -142,10 +154,14 @@ mod tests { assert_eq!(*process.retiring_adopted.lock(), Some(incarnation)); assert!(process.await_adopted_exit(incarnation, Duration::ZERO).await.is_err()); assert_eq!(*process.retiring_adopted.lock(), Some(incarnation)); + assert_eq!(endpoint.admit().await?.take_relaunch_discard(&resident), None, + "no loss is recorded while the wait still holds custody"); drop(child.stdin.take()); child.wait()?; process.await_adopted_exit(incarnation, Duration::from_secs(1)).await?; assert_eq!(*process.retiring_adopted.lock(), None); + assert_eq!(endpoint.admit().await?.take_relaunch_discard(&resident), Some(lost), + "the observed exit records the loss"); Ok(()) } } diff --git a/core/continuum-engine/src/inference/llama_server/launch.rs b/core/continuum-engine/src/inference/llama_server/launch.rs index 760ade3b62..aea830ad22 100644 --- a/core/continuum-engine/src/inference/llama_server/launch.rs +++ b/core/continuum-engine/src/inference/llama_server/launch.rs @@ -62,8 +62,6 @@ impl LlamaServerProcess { // residents' slots unsaved and their next acts re-prefilled 70k-115k tokens. The // transition has drained every reader, so no turn is decoding. A failed save // defers replacement rather than destroying the only fresh resident state. - // Residents an exited or quarantined engine loses unsaved: recorded once it is killed. - let mut discarded = None; if had_own_child && !restoring { let started = std::time::Instant::now(); let outcome = transition.checkpoint_before_replacement(&self.client, &self.root, current).await; @@ -73,15 +71,12 @@ impl LlamaServerProcess { ms = started.elapsed().as_millis() as u64, "resident checkpoint decision before engine replacement" ); - discarded = outcome.map_err(LlamaServerError::Spawn)?; + outcome.map_err(LlamaServerError::Spawn)?; } if self.is_live_lane && !had_own_child && !restoring { self.retire_adopted(&mut transition, current).await?; } self.kill_child(); - if let Some(discarded) = discarded { - discarded.commit(); - } // A freed listener is not proof that the predecessor stopped decoding. // Poll ONLY its retained owned Child; cancelled/failed transitions remain diff --git a/core/continuum-engine/src/inference/llama_server/process.rs b/core/continuum-engine/src/inference/llama_server/process.rs index 11eee9eff1..07064e04ca 100644 --- a/core/continuum-engine/src/inference/llama_server/process.rs +++ b/core/continuum-engine/src/inference/llama_server/process.rs @@ -30,6 +30,9 @@ pub struct LlamaServerProcess { pub(super) last_started: parking_lot::Mutex>, /// A signalled adopted predecessor stays fenced across timeout/cancellation. pub(super) retiring_adopted: parking_lot::Mutex>, + /// The residents that predecessor loses unsaved, recorded only once its exit is observed + /// (card 6b28a445). Held with `retiring_adopted`, so a re-entered wait still records it. + pub(super) retiring_discard: parking_lot::Mutex>, /// The LoRA genome set (sorted paths) the CURRENT child was launched with — /// the truthful record of what `/lora-adapters` holds, since llama.cpp has no /// API to query it. `ensure_model_serving` compares this against the desired @@ -133,6 +136,7 @@ impl LlamaServerProcess { pending_resource_reservation: parking_lot::Mutex::new(None), last_started: parking_lot::Mutex::new(None), retiring_adopted: parking_lot::Mutex::new(None), + retiring_discard: parking_lot::Mutex::new(None), served_adapters: Arc::new(StdMutex::new(Vec::new())), retained_page_dir: Arc::new(parking_lot::Mutex::new(None)), // THE host's live lane — pins the canonical port, owns the reclaim @@ -166,6 +170,7 @@ impl LlamaServerProcess { pending_resource_reservation: parking_lot::Mutex::new(None), last_started: parking_lot::Mutex::new(None), retiring_adopted: parking_lot::Mutex::new(None), + retiring_discard: parking_lot::Mutex::new(None), served_adapters: Arc::new(StdMutex::new(Vec::new())), retained_page_dir: Arc::new(parking_lot::Mutex::new(None)), // Ephemeral lane on its OWN scanned port: NOT the canonical live lane. diff --git a/core/continuum-engine/src/inference/slots/engine_generation.rs b/core/continuum-engine/src/inference/slots/engine_generation.rs index 603190a290..84cb8bce49 100644 --- a/core/continuum-engine/src/inference/slots/engine_generation.rs +++ b/core/continuum-engine/src/inference/slots/engine_generation.rs @@ -31,6 +31,9 @@ impl EngineGeneration { // Do not mutate a ledger while an old HTTP future can still write // it. Replacement readiness drains admissions and replaces it. } + drop(state); + // A relaunch that could not save waited for this death to record its loss. + endpoint.relaunch_exit_observed(self.id); } } } @@ -276,21 +279,23 @@ impl EndpointTransition { /// Planned replacement cannot discard a healthy engine's unsaved residents. /// A terminal refusal resumes the exact original ledger; an uncertain write /// stays quarantined. Dead engines and quarantined paging use recovery instead: - /// nothing can be saved, so their unsaved residents come back as a - /// [`PendingDiscard`] the caller commits once the engine is killed (card 6b28a445). + /// nothing can be saved, so their unsaved residents are recorded as lost when this + /// generation's exit is observed, at once if it already was (card 6b28a445). pub(crate) async fn checkpoint_before_replacement( &mut self, client: &reqwest::Client, root: &str, current: &(dyn Fn() -> bool + Send + Sync), - ) -> Result, String> { + ) -> Result<(), String> { let generation = self.previous_generation().ok_or("replacement requires a known generation")?; if generation.has_exited() || self.endpoint.paging_recovery_required() { - return Ok(Some(self.endpoint.pending_discard(if generation.has_exited() { + let reason = if generation.has_exited() { DiscardReason::EngineExited } else { DiscardReason::PagingUncertain - }))); + }; + self.endpoint.pending_discard(reason).on_exit_of(&generation); + return Ok(()); } let original = self.capture_suspension(&generation)?; let result = self.checkpoint_residents(client, root).await.map(|_| ()); @@ -303,7 +308,7 @@ impl EndpointTransition { if !current() { return Err("replacement intent changed after checkpoint".into()); } - Ok(None) + Ok(()) } pub(crate) fn capture_suspension( diff --git a/core/continuum-engine/src/inference/slots/relaunch_discard.rs b/core/continuum-engine/src/inference/slots/relaunch_discard.rs index f23cfb2706..f29e0f6253 100644 --- a/core/continuum-engine/src/inference/slots/relaunch_discard.rs +++ b/core/continuum-engine/src/inference/slots/relaunch_discard.rs @@ -6,9 +6,12 @@ //! generation, so the record lives on the endpoint, and the resident's next turn takes it: //! a cold turn then names the relaunch, instead of reading as a lost page or a ledger defect. //! -//! Two steps, so a retirement that is superseded or refused never reports a loss: the -//! candidates are captured while the old pool is still installed ([`PendingDiscard`]), and -//! committed only once the engine is actually killed, signalled, or observed dead. +//! Two steps, so a retirement that is superseded, refused, or still waiting never reports a +//! loss: the candidates are captured while the old pool is still installed +//! ([`PendingDiscard`]), and recorded only when the engine's death is OBSERVED. A sent +//! signal is not a death. An owned engine's capture waits on the endpoint for that +//! generation's [`EngineGeneration::observed_exit`]; an adopted engine's waits in the +//! process owner's retirement custody until its exact process is seen gone. use super::*; @@ -33,6 +36,32 @@ impl DiscardReason { } } +/// The residents one relaunch loses, and why. +#[derive(Debug)] +struct Capture { + keys: Vec, + retain: usize, + reason: DiscardReason, +} + +impl Capture { + fn report(&self) { + continuum_base::probe!( + class = "inference.kv_page.discarded_by_relaunch", + reason = self.reason.as_str(), + residents = self.keys.len() as u64, + "an engine relaunch discarded residents' unsaved KV: their next turns prefill in full" + ); + } +} + +/// An owned generation's capture: waiting for its exit, or already recorded. +#[derive(Debug)] +enum Watch { + Awaiting(Capture), + Settled, +} + /// The endpoint's discard records, oldest first. Retention is at most one pool's worth of /// slots (the most recent discarding pool's count): one relaunch can discard no more minds /// than it had slots, so the latest relaunch is always kept whole, and an older record is @@ -41,15 +70,22 @@ impl DiscardReason { #[derive(Debug, Default)] pub(super) struct DiscardLog { entries: std::collections::VecDeque<(PageKey, DiscardReason)>, + /// The owned generation whose relaunch captured residents, until its exit is observed. + /// One per endpoint: the next generation cannot start before this one's exit is verified. + watch: Option<(Uuid, Watch)>, } impl DiscardLog { - fn record(&mut self, keys: &[PageKey], reason: DiscardReason, retain: usize) { - for key in keys { + fn record(&mut self, capture: &Capture) { + // Nothing lost records nothing: an empty capture never evicts older records. + if capture.keys.is_empty() { + return; + } + for key in &capture.keys { self.entries.retain(|(held, _)| held != key); - self.entries.push_back((*key, reason)); + self.entries.push_back((*key, capture.reason)); } - while self.entries.len() > retain { + while self.entries.len() > capture.retain.max(capture.keys.len()) { self.entries.pop_front(); } } @@ -58,37 +94,68 @@ impl DiscardLog { let at = self.entries.iter().position(|(held, _)| held == key)?; self.entries.remove(at).map(|(_, reason)| reason) } + + /// Hold `capture` until `generation`'s exit is observed. A generation already watched + /// (awaiting or settled) keeps its first capture, so a re-entered retirement never + /// records twice. + fn await_exit(&mut self, generation: Uuid, capture: Capture) { + if self.watch.as_ref().is_some_and(|(watched, _)| *watched == generation) { + return; + } + self.watch = Some((generation, Watch::Awaiting(capture))); + } + + /// `generation` was seen gone: record what its relaunch captured, once. + fn exit_observed(&mut self, generation: Uuid) -> Option { + match self.watch.take() { + Some((watched, Watch::Awaiting(capture))) if watched == generation => { + self.record(&capture); + self.watch = Some((generation, Watch::Settled)); + Some(capture) + } + other => { + self.watch = other; + None + } + } + } } /// Residents a relaunch is about to discard, captured from the pool being replaced. Dropped -/// without [`Self::commit`] (a superseded or refused retirement), it records nothing. -#[must_use = "a discard is recorded only when the engine is actually gone: commit it there"] +/// without being recorded (a superseded or refused retirement), it records nothing. +#[must_use = "a discard is recorded only when the engine's death is observed"] pub(crate) struct PendingDiscard { endpoint: Arc, - keys: Vec, - retain: usize, - reason: DiscardReason, + capture: Capture, } impl PendingDiscard { /// The same residents, lost for a different reason (the engine died before the signal). - pub(crate) fn because(self, reason: DiscardReason) -> Self { - Self { reason, ..self } + pub(crate) fn because(mut self, reason: DiscardReason) -> Self { + self.capture.reason = reason; + self } - /// The engine is gone: record the loss and say so. + /// The engine's death was observed: record the loss and say so. pub(crate) fn commit(self) { - continuum_base::probe!( - class = "inference.kv_page.discarded_by_relaunch", - reason = self.reason.as_str(), - residents = self.keys.len() as u64, - "an engine relaunch discarded residents' unsaved KV: their next turns prefill in full" - ); - // Nothing lost records nothing: an empty capture never evicts older records. - if !self.keys.is_empty() { - self.endpoint.discarded.lock().record(&self.keys, self.reason, self.retain.max(self.keys.len())); + self.capture.report(); + self.endpoint.discarded.lock().record(&self.capture); + } + + /// An owned engine: record once `generation`'s exit is observed, now if it already was. + pub(crate) fn on_exit_of(self, generation: &EngineGeneration) { + self.endpoint.discarded.lock().await_exit(generation.id, self.capture); + if generation.has_exited() { + self.endpoint.relaunch_exit_observed(generation.id); } } + + /// A test's capture of `keys` without a pool. + #[cfg(test)] + pub(crate) fn for_test(endpoint: Arc, keys: Vec, reason: DiscardReason) -> Self { + let retain = keys.len(); + Self { endpoint, capture: Capture { keys, retain, reason } } + } } impl KvSlotPool { @@ -108,7 +175,15 @@ impl EndpointSlots { pub(crate) fn pending_discard(self: &Arc, reason: DiscardReason) -> PendingDiscard { let pool = self.state.lock().pool.as_ref().and_then(Clone::clone); let (keys, retain) = pool.map_or((Vec::new(), 0), |pool| (pool.unsaved_residents(), pool.n_slots() as usize)); - PendingDiscard { endpoint: Arc::clone(self), keys, retain, reason } + PendingDiscard { endpoint: Arc::clone(self), capture: Capture { keys, retain, reason } } + } + + /// An owned generation's exit was observed: record what its relaunch captured, if any. + pub(super) fn relaunch_exit_observed(&self, generation: Uuid) { + let recorded = self.discarded.lock().exit_observed(generation); + if let Some(capture) = recorded { + capture.report(); + } } } diff --git a/core/continuum-engine/src/inference/slots/tests.rs b/core/continuum-engine/src/inference/slots/tests.rs index c49e407c3d..728247bfea 100644 --- a/core/continuum-engine/src/inference/slots/tests.rs +++ b/core/continuum-engine/src/inference/slots/tests.rs @@ -184,14 +184,15 @@ mod adopted_checkpoint; PageKey::mind(Uuid::from_u128(p)).expect("non-nil test id") } - // what this catches (card 6b28a445): a relaunch that cannot save (here, an engine that - // already exited) lost residents' KV with no record, so their next cold turn read as a - // lost page. Through the real replacement path: the loss is only CAPTURED by the - // checkpoint decision, and a capture dropped without commit (a superseded or refused - // retirement) records nothing. Committed, only minds held without a confirmed save are - // recorded, the record survives the pool's replacement, and it is taken exactly once. + // what this catches (card 6b28a445): a relaunch that cannot save (here, quarantined + // paging) lost residents' KV with no record, so their next cold turn read as a lost page; + // and, per Codex's review, a record made when the kill was SENT reports a loss that may + // not have happened. Through the real replacement path: nothing is recorded while the + // engine is only quarantined, even on re-entry; its observed exit records only the + // minds held without a confirmed save, once; a re-entry after the exit records nothing + // more; the record survives the pool's replacement and is taken exactly once. #[tokio::test] - async fn a_relaunch_records_unsaved_residents_only_when_committed_and_their_next_turn_takes_it_once() { + async fn a_relaunch_records_unsaved_residents_only_at_the_observed_exit_and_once() { let dir = SlotDirectory { endpoints: dashmap::DashMap::new() }; let endpoint = dir.endpoint("test://relaunch"); let mut transition = endpoint.transition().await; @@ -202,31 +203,29 @@ mod adopted_checkpoint; pool.holders.lock().insert(2, key(3, 4)); pool.note_saved(mind(2)); endpoint.state.lock().pool = Some(Some(pool)); - generation.observed_exit(); + endpoint.quarantine_paging(); let client = reqwest::Client::new(); - let superseded = transition - .checkpoint_before_replacement(&client, "test://relaunch", &|| true) - .await - .expect("an exited engine has nothing to save") - .expect("its unsaved residents are captured"); - drop(superseded); - assert_eq!(endpoint.discarded.lock().take(&mind(1)), None, "a capture never committed records nothing"); - + for _attempt in 0..2 { + transition + .checkpoint_before_replacement(&client, "test://relaunch", &|| true) + .await + .expect("quarantined paging has nothing to save"); + assert_eq!(endpoint.discarded.lock().take(&mind(1)), None, "the kill is not the death"); + } + generation.observed_exit(); transition .checkpoint_before_replacement(&client, "test://relaunch", &|| true) .await - .expect("an exited engine has nothing to save") - .expect("its unsaved residents are captured") - .commit(); + .expect("an exited engine has nothing to save"); drop(transition); // The next generation's pool replaces this one; the record is the endpoint's. endpoint.state.lock().pool = Some(Some(Arc::new(KvSlotPool::new("test://relaunch", 4)))); endpoint.state.lock().ready.send_replace(true); // the replacement verified ready let admission = endpoint.admit().await.expect("an open endpoint admits"); - assert_eq!(admission.take_relaunch_discard(&mind(1)), Some(DiscardReason::EngineExited)); - assert_eq!(admission.take_relaunch_discard(&mind(1)), None, "taken once"); + assert_eq!(admission.take_relaunch_discard(&mind(1)), Some(DiscardReason::PagingUncertain)); + assert_eq!(admission.take_relaunch_discard(&mind(1)), None, "recorded once, taken once"); assert_eq!(admission.take_relaunch_discard(&mind(2)), None, "a saved page restores; nothing was lost"); assert_eq!(admission.take_relaunch_discard(&key(3, 4)), None, "a fork dies with its core anyway"); } From 84505ee265ce154748cb5c996a8a5c6fbac47a11 Mon Sep 17 00:00:00 2001 From: joelteply Date: Sat, 24 Oct 2026 02:38:15 -0500 Subject: [PATCH 5/5] Two unwired-fixture entries named modules #5367 deleted (card 6b28a445) #5357's core job 120814431211 at bd3a1c1ed: module_wiring_guard listed PageFaultOnly (genome bus) and RecorderModule (genome local_manager), and #5367 (4ac5e6448) deleted both with the old paging stacks. The two entries are deleted. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE --- core/continuum-core/src/test_env/module_wiring_guard.rs | 8 -------- 1 file changed, 8 deletions(-) diff --git a/core/continuum-core/src/test_env/module_wiring_guard.rs b/core/continuum-core/src/test_env/module_wiring_guard.rs index 5c54a0438f..11f4a9e8cf 100644 --- a/core/continuum-core/src/test_env/module_wiring_guard.rs +++ b/core/continuum-core/src/test_env/module_wiring_guard.rs @@ -64,18 +64,10 @@ const UNWIRED: &[Unwired] = &[ module: "OptedInModule", why: "fixture: sibling of DefaultsModule, opts into every hook", }, - Unwired { - module: "PageFaultOnly", - why: "fixture: genome bus subscriber asserting fault-only delivery", - }, Unwired { module: "ReadyModule", why: "fixture: runtime readiness-gate test", }, - Unwired { - module: "RecorderModule", - why: "fixture: genome local_manager call recorder", - }, Unwired { module: "SlowJoiner", why: "fixture: a module that saves and then cannot be joined inside the phase bound — drives ModuleStopOutcome::JoinTimedOut, which before it existed only as a literal in assertions",