diff --git a/core/continuum-engine/src/inference/llama_server.rs b/core/continuum-engine/src/inference/llama_server.rs index 02f32e2ce4..4e35f5aa03 100644 --- a/core/continuum-engine/src/inference/llama_server.rs +++ b/core/continuum-engine/src/inference/llama_server.rs @@ -57,7 +57,7 @@ mod convergence_attempt; mod reconcile; mod shared_pool; mod pool_growth; -pub use pool_growth::request_pool_growth; +pub use pool_growth::{end_hold_if_decided, end_stale_hold, growth_requested, request_pool_growth}; pub use reconcile::{ensure_model_serving, ensure_model_serving_if_current}; mod smoke; diff --git a/core/continuum-engine/src/inference/llama_server/pool_growth.rs b/core/continuum-engine/src/inference/llama_server/pool_growth.rs index 3d6a2b402a..b14af51058 100644 --- a/core/continuum-engine/src/inference/llama_server/pool_growth.rs +++ b/core/continuum-engine/src/inference/llama_server/pool_growth.rs @@ -17,11 +17,56 @@ /// is stale and never acts. static REQUESTED: parking_lot::Mutex> = parking_lot::Mutex::new(None); -/// Ask the engine owner to relaunch engine `pid` once into the larger pool its next target carries. -pub fn request_pool_growth(pid: u32) { +/// Admission held for the relaunch, with the engine process it was taken for (card 2540194e): +/// the engine is idle by construction rather than by a sample. It is held across the relaunch +/// until the new engine answers, because a request released into a relaunching engine just fails. +static HELD: parking_lot::Mutex> = parking_lot::Mutex::new(None); + +/// Ask the engine owner to relaunch engine `pid` once into the larger pool its next target carries, +/// with admission already quiesced (`held`) so nothing is generating when it does. +pub fn request_pool_growth(pid: u32, held: crate::inference::resource_admission::Quiesced) { + *HELD.lock() = Some((pid, held)); + request(pid); +} + +fn request(pid: u32) { *REQUESTED.lock() = Some(pid); } +/// Whether engine `pid` has a growth relaunch requested and not yet decided. +pub fn growth_requested(pid: u32) -> bool { + *REQUESTED.lock() == Some(pid) +} + +/// After an ensure: end the hold once its relaunch was decided (the request is spent, so the +/// relaunch ran to a serving engine or failed). A hold whose request is still pending stays. +pub fn end_hold_if_decided() { + let mut held = HELD.lock(); + if held.as_ref().is_some_and(|(pid, _)| !growth_requested(*pid)) { + end(held.take(), "relaunch_ended"); + } +} + +/// End a hold taken for an engine process other than `running`, the one now serving: a new engine +/// answers, whatever replaced the old one. Never while no engine serves (mid-relaunch). +pub fn end_stale_hold(running: u32) { + let mut held = HELD.lock(); + if held.as_ref().is_some_and(|(pid, _)| *pid != running) { + end(held.take(), "engine_replaced"); + } +} + +fn end(held: Option<(u32, crate::inference::resource_admission::Quiesced)>, reason: &'static str) { + if let Some((pid, quiesced)) = held { + continuum_base::probe!(target: "continuum_core::inference::llama_server", class = "serving.pool.grow_held", + pid = u64::from(pid), + held_ms = quiesced.held_ms(), + reason = reason, + "admission reopens: the pool's one relaunch held it this long (drain + relaunch to ready)" + ); + } +} + /// Whether the running engine is due its one growth relaunch: the daemon asked for this process, /// and the target's pool is strictly larger than what the process reports holding. Unknown (no /// process, no reported pool) is never a growth. @@ -51,7 +96,7 @@ mod tests { // A pid no other test in this binary uses. let pid = 4_000_000_001; assert!(!growth_due(Some(pid), Some(16_640), 257_536), "never asked: no growth"); - request_pool_growth(pid); + request(pid); assert!(!growth_due(Some(pid + 1), Some(16_640), 257_536), "asked for another process: stale"); assert!(!growth_due(Some(pid), Some(257_536), 257_536), "not strictly larger: no relaunch"); assert!(!growth_due(Some(pid), Some(300_000), 257_536), "downward never relaunches"); diff --git a/core/continuum-engine/src/inference/resource_admission.rs b/core/continuum-engine/src/inference/resource_admission.rs index 888f737714..404197c784 100644 --- a/core/continuum-engine/src/inference/resource_admission.rs +++ b/core/continuum-engine/src/inference/resource_admission.rs @@ -16,6 +16,7 @@ mod gate; mod lanes; mod metrics; mod progress; +mod quiesce; mod serving_lane_permit; #[cfg(test)] mod tests; @@ -24,4 +25,5 @@ pub use gate::*; pub use lanes::*; pub use metrics::*; pub use progress::{LaneWait, LaneProgress}; +pub use quiesce::{AdmissionEntry, Quiesced}; pub use serving_lane_permit::ServingLanePermit; diff --git a/core/continuum-engine/src/inference/resource_admission/lanes.rs b/core/continuum-engine/src/inference/resource_admission/lanes.rs index b2c3d3939c..625761120c 100644 --- a/core/continuum-engine/src/inference/resource_admission/lanes.rs +++ b/core/continuum-engine/src/inference/resource_admission/lanes.rs @@ -92,6 +92,8 @@ pub struct LaneAdmission { pub(super) work_waiting: AtomicUsize, /// Fires on every permit release so a parked ambient caller re-checks. pub(super) released: tokio::sync::Notify, + /// Held while the engine relaunches: every request enters it before either semaphore. + pub(super) quiesce: super::quiesce::Quiescer, } #[derive(Clone, Copy, Debug)] @@ -157,6 +159,13 @@ pub fn set_served_lane_count(lanes: usize) { LANES.set_served_lane_count(lanes); } +/// Hold every new inference request and wait until every request in admission has ended: the +/// engine is then idle by construction, for its one upward relaunch (card 2540194e). `None` when a +/// quiesce already runs. Dropping the result reopens admission. +pub async fn quiesce_admission() -> Option { + LANES.quiesce.quiesce().await +} + /// Reconcile installed permits without waiting for running calls. The difference /// between installed and a smaller target is debt retried on the next serving tick. /// Caller holds the owner resize lock, the installed-permit accounting. @@ -260,6 +269,7 @@ impl LaneAdmission { resize_lock: Mutex::new(()), work_waiting: AtomicUsize::new(0), released: tokio::sync::Notify::const_new(), + quiesce: super::quiesce::Quiescer::new(), } } @@ -357,6 +367,8 @@ impl LaneAdmission { let (observer, progress) = self.observe(persona, priority); let aging = observer.clone(); let acquire = async move { + // Entered before either semaphore, so a quiesce for a relaunch holds every request. + let entry = self.quiesce.enter().await; let queued_at = std::time::Instant::now(); let directed = priority.is_directed(); // Non-directed reserves within the (lanes-1) budget FIRST, so the physical-lane @@ -434,6 +446,7 @@ impl LaneAdmission { directed, priority, released: &self.released, + _entry: entry, } }; (observer, acquire) diff --git a/core/continuum-engine/src/inference/resource_admission/quiesce.rs b/core/continuum-engine/src/inference/resource_admission/quiesce.rs new file mode 100644 index 0000000000..6114bb891e --- /dev/null +++ b/core/continuum-engine/src/inference/resource_admission/quiesce.rs @@ -0,0 +1,198 @@ +//! Quiescing admission: the one place a relaunch makes the engine idle instead of waiting to +//! sample it idle (card 2540194e). The pool's one upward relaunch (S2 debt, `pool_growth`) needs +//! an engine with nothing generating; #5742 waited for a `/slots` read showing that, and on the M5 +//! on 2026-11-03 five residents on 409-token windows acted without pause, so the read never came +//! and the 2,048-token launch pool was kept for good. +//! +//! The shape: every lane request ENTERS first (one count, before either semaphore), then checks +//! the flag; a quiesce SETS the flag first, then waits for the count to reach zero. Both orders are +//! SeqCst, so no request slips between them. A request that finds admission quiescing leaves and +//! waits for the quiesce to end; one already entered runs to its end. Both waits are events (a +//! `Notify` the last leaver and the ending quiesce fire), never a poll. The entry is held by the +//! request's permit, so it ends with the call or its cancellation. + +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst}; + +/// Admission's quiesce state, one per gate. +pub(super) struct Quiescer { + quiescing: AtomicBool, + /// Requests that entered admission and have not ended: queued for a lane or holding one. + entered: AtomicUsize, + /// Fires when a quiesce ends: a request held at entry re-enters. + resumed: tokio::sync::Notify, + /// Fires when the last entered request leaves while a quiesce waits. + drained: tokio::sync::Notify, +} + +impl Quiescer { + pub(super) const fn new() -> Self { + Self { + quiescing: AtomicBool::new(false), + entered: AtomicUsize::new(0), + resumed: tokio::sync::Notify::const_new(), + drained: tokio::sync::Notify::const_new(), + } + } + + /// Enter admission, held while a quiesce runs. The entry counts until it drops. + pub(super) async fn enter(&'static self) -> AdmissionEntry { + loop { + // Registered before the check, so an end of the quiesce between them still wakes us. + let resumed = self.resumed.notified(); + tokio::pin!(resumed); + resumed.as_mut().enable(); + self.entered.fetch_add(1, SeqCst); + if !self.quiescing.load(SeqCst) { + return AdmissionEntry(self); + } + self.leave(); + resumed.await; + } + } + + fn leave(&self) { + if self.entered.fetch_sub(1, SeqCst) == 1 && self.quiescing.load(SeqCst) { + self.drained.notify_waiters(); + } + } + + /// Hold every new admission and wait until every entered request has ended. `None` when a + /// quiesce already runs. Dropping the result (or this future before it resolves) reopens + /// admission. + pub(super) async fn quiesce(&'static self) -> Option { + if self + .quiescing + .compare_exchange(false, true, SeqCst, SeqCst) + .is_err() + { + return None; + } + let quiesced = Quiesced { + owner: self, + started: std::time::Instant::now(), + }; + loop { + let drained = self.drained.notified(); + tokio::pin!(drained); + drained.as_mut().enable(); + if self.entered.load(SeqCst) == 0 { + return Some(quiesced); + } + drained.await; + } + } + + #[cfg(test)] + pub(super) fn entered(&self) -> usize { + self.entered.load(SeqCst) + } +} + +/// One request's place in admission, from entry until its permit (or its cancelled wait) drops. +#[derive(Debug)] +pub struct AdmissionEntry(&'static Quiescer); + +impl Drop for AdmissionEntry { + fn drop(&mut self) { + self.0.leave(); + } +} + +impl std::fmt::Debug for Quiescer { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Quiescer") + .field("quiescing", &self.quiescing.load(SeqCst)) + .field("entered", &self.entered.load(SeqCst)) + .finish() + } +} + +/// Admission held, with nothing entered: the engine generates nothing until this drops. Its +/// owner holds it across the engine's relaunch until the new engine answers, because a request +/// released into a relaunching engine just fails (Fable on card 2540194e). +#[derive(Debug)] +pub struct Quiesced { + owner: &'static Quiescer, + started: std::time::Instant, +} + +impl Quiesced { + /// How long admission has been held: the measured cost of the relaunch it bought. + pub fn held_ms(&self) -> u64 { + self.started.elapsed().as_millis() as u64 + } +} + +impl Drop for Quiesced { + fn drop(&mut self) { + self.owner.quiescing.store(false, SeqCst); + self.owner.resumed.notify_waiters(); + continuum_base::probe!( + class = "admission.quiesce.ended", + held_ms = self.held_ms(), + "admission reopened after a quiesce" + ); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn leaked() -> &'static Quiescer { + Box::leak(Box::new(Quiescer::new())) + } + + // what this catches (the M5, 2026-11-03: the pool's one relaunch waited for an idle sample + // that continuous acts never gave): a quiesce that never completes under load, or one that + // lets a request in beside it. It completes when the entered requests end, holds every new + // one meanwhile, and reopens on drop. + #[tokio::test] + async fn a_quiesce_waits_out_entered_requests_and_holds_new_ones_until_it_ends() { + let gate = leaked(); + let running = gate.enter().await; + let mut quiesce = Box::pin(gate.quiesce()); + assert!( + futures::poll!(quiesce.as_mut()).is_pending(), + "a request is running: not idle yet" + ); + let mut late = Box::pin(gate.enter()); + assert!( + futures::poll!(late.as_mut()).is_pending(), + "a new request is held" + ); + assert_eq!(gate.entered(), 1, "the held request does not count"); + drop(running); + let quiesced = quiesce.await.expect("the only quiesce"); + assert!(gate.quiesce().await.is_none(), "one quiesce at a time"); + assert!( + futures::poll!(late.as_mut()).is_pending(), + "still held while quiesced" + ); + drop(quiesced); + let entry = late.await; + assert_eq!(gate.entered(), 1, "reopened: the held request entered"); + drop(entry); + assert_eq!(gate.entered(), 0); + } + + // what this catches: a cancelled wait that leaves its count behind, so a quiesce never + // completes. A request cancelled while held, or after entering, leaves nothing counted. + #[tokio::test] + async fn a_cancelled_request_leaves_nothing_counted() { + let gate = leaked(); + let entered = gate.enter().await; + let quiesce = gate.quiesce(); + tokio::pin!(quiesce); + assert!(futures::poll!(quiesce.as_mut()).is_pending()); + let mut held = Box::pin(gate.enter()); + assert!(futures::poll!(held.as_mut()).is_pending()); + drop(held); + drop(entered); + assert!( + quiesce.await.is_some(), + "the quiesce completes once the entered request is gone" + ); + assert_eq!(gate.entered(), 0); + } +} diff --git a/core/continuum-engine/src/inference/resource_admission/serving_lane_permit.rs b/core/continuum-engine/src/inference/resource_admission/serving_lane_permit.rs index d6e004e77c..72e5869f7f 100644 --- a/core/continuum-engine/src/inference/resource_admission/serving_lane_permit.rs +++ b/core/continuum-engine/src/inference/resource_admission/serving_lane_permit.rs @@ -21,6 +21,9 @@ pub struct ServingLanePermit { pub(super) persona: Option, /// The gate this permit came from — its release wakes parked ambient callers. pub(super) released: &'static tokio::sync::Notify, + /// Its place in admission. LAST: fields drop in order, so the lane and the in-flight marker + /// are released before a quiesce can see this request gone (`quiesce`). + pub(super) _entry: super::quiesce::AdmissionEntry, } impl Drop for ServingLanePermit { diff --git a/core/continuum-serving/src/modules/serving_daemon.rs b/core/continuum-serving/src/modules/serving_daemon.rs index 9bd7858de8..1dd9ef0fd9 100644 --- a/core/continuum-serving/src/modules/serving_daemon.rs +++ b/core/continuum-serving/src/modules/serving_daemon.rs @@ -354,9 +354,6 @@ pub struct ServingDaemonModule { /// The engine process the one upward pool relaunch was asked for (`pool_growth`): once per /// engine, S2 debt. pool_growth_tried: Arc, - /// The latest `/slots` read as `(engine pid, no slot processing)`: the moment the one upward - /// pool relaunch may cost no generation in flight (`pool_growth`). - engine_idle: Arc>>, /// Each local mind's grant on the engine's pool (`grants.rs`): what her binding follows. /// `None` until a ready engine has been granted from. grants_tx: watch::Sender>, @@ -557,7 +554,6 @@ impl ServingDaemonModule { plan_budget_bytes: Arc::new(std::sync::atomic::AtomicU64::new(0)), shared_pool_move_tried: Arc::new(std::sync::atomic::AtomicU64::new(0)), pool_growth_tried: Arc::new(std::sync::atomic::AtomicU64::new(0)), - engine_idle: Arc::new(parking_lot::Mutex::new(None)), grants_tx: watch::channel(None).0, shared_pool_of: Arc::new(parking_lot::Mutex::new(None)), served_pool: Arc::new(std::sync::atomic::AtomicU32::new(0)), diff --git a/core/continuum-serving/src/modules/serving_daemon/health.rs b/core/continuum-serving/src/modules/serving_daemon/health.rs index df0638e77f..2b0f18e026 100644 --- a/core/continuum-serving/src/modules/serving_daemon/health.rs +++ b/core/continuum-serving/src/modules/serving_daemon/health.rs @@ -137,7 +137,6 @@ impl ServingDaemonModule { } let server = self.server.clone(); let reading = self.prefill_knee_reading.clone(); - let engine_idle = self.engine_idle.clone(); // the model the rates are measured FOR; with the engine's pid (read on the task), two // reads pair only on the same engine process let model = self.serving_tx.borrow().active_model.clone(); @@ -154,9 +153,6 @@ impl ServingDaemonModule { .zip(crate::inference::lane_pidfile::read()) .map(|(model, pid)| crate::inference::prefill_knee::EngineRead { model, pid }); if let Some(slots) = server.slots_body().await { - if let Some(pid) = engine.as_ref().map(|e| e.pid) { - *engine_idle.lock() = Some((pid, super::pool_growth::no_slot_processing(&slots))); - } crate::inference::prefill_knee::observe_slots( &slots, EpochMs::now().millis(), diff --git a/core/continuum-serving/src/modules/serving_daemon/launch.rs b/core/continuum-serving/src/modules/serving_daemon/launch.rs index 65a75071d7..6456539bb8 100644 --- a/core/continuum-serving/src/modules/serving_daemon/launch.rs +++ b/core/continuum-serving/src/modules/serving_daemon/launch.rs @@ -263,6 +263,9 @@ impl ServingDaemonModule { &admit, ) .await; + // The pool's one relaunch has run once its request is spent (to a serving engine, or + // failed): admission, quiesced for it, reopens here (card 2540194e). + crate::inference::llama_server::end_hold_if_decided(); if matches!(outcome, EnsureOutcome::Superseded) || (matches!(outcome, EnsureOutcome::AlreadyServing) && !current()) { diff --git a/core/continuum-serving/src/modules/serving_daemon/pool_growth.rs b/core/continuum-serving/src/modules/serving_daemon/pool_growth.rs index 171cee079e..e8483d48de 100644 --- a/core/continuum-serving/src/modules/serving_daemon/pool_growth.rs +++ b/core/continuum-serving/src/modules/serving_daemon/pool_growth.rs @@ -19,10 +19,22 @@ impl ServingDaemonModule { .any(|a| a.consumer_id == SERVING_CONSUMER_ID && a.kind == serving_pool_kind() && a.bytes > 0) } - /// Whether the running engine is due its one upward pool relaunch, asking the engine's owner - /// for it when it is. Read on the ready tick, beside the shared-pool move. + /// Whether the running engine is due its one upward pool relaunch now. Read on the ready tick, + /// beside the shared-pool move. + /// + /// The relaunch makes its own idle edge (card 2540194e): when the first steady plan proves a + /// larger pool, a task quiesces admission (every new inference request held, every entered one + /// run to its end) and only then asks the engine's owner for the relaunch, holding admission + /// until the new engine answers. #5742 instead waited for a `/slots` read with nothing + /// processing; on the M5 on 2026-11-03 five residents on 409-token windows acted without pause, + /// the read never came, and the 2,048-token launch pool was kept on two builds in a row. pub(super) fn pool_growth_due(&self, desired: &str, served_ctx: u32, lanes: u32) -> bool { let Some(engine) = self.server.served_incarnation() else { return false }; + // A hold taken for an engine that is no longer the one serving ends here. + crate::inference::llama_server::end_stale_hold(engine.pid); + if crate::inference::llama_server::growth_requested(engine.pid) { + return true; + } if self.pool_growth_tried.load(Ordering::Relaxed) == u64::from(engine.pid) { return false; } @@ -34,34 +46,37 @@ impl ServingDaemonModule { if !grows(self.serving_footprint_reported(), budget, running, wanted) { return false; } - // A relaunch loses what the engine is generating, and nothing else: a turn between - // generations (in a tool call) just waits for the engine. So it waits for a `/slots` read - // of THIS engine with no slot processing, and is retried on the next tick until one comes - // (Fable on #5741, card 5c9042f1). A turn's own durability is not the measure: the core - // stays up, so nothing would hand a cut generation back. - if *self.engine_idle.lock() != Some((engine.pid, true)) { - return false; - } self.pool_growth_tried.store(u64::from(engine.pid), Ordering::Relaxed); - crate::inference::llama_server::request_pool_growth(engine.pid); + let pid = engine.pid; continuum_base::probe!( target: "continuum_core::modules::serving_daemon", class = "serving.pool.grow_due", - pid = u64::from(engine.pid), + pid = u64::from(pid), running_tokens = u64::from(running), wanted_tokens = wanted, budget_gb = budget / 1_000_000_000, - "the first steady plan proves a larger pool than the engine launched with: one relaunch into it (S2 debt)" + "the first steady plan proves a larger pool than the engine launched with: quiescing admission for one relaunch into it (S2 debt)" ); - true + tokio::spawn(async move { + let Some(held) = crate::inference::resource_admission::quiesce_admission().await else { + continuum_base::probe!( + target: "continuum_core::modules::serving_daemon", class = "serving.pool.grow_quiesce_busy", + pid = u64::from(pid), + "admission is already quiescing: this engine's growth is not requested" + ); + return; + }; + continuum_base::probe!( + target: "continuum_core::modules::serving_daemon", class = "serving.pool.grow_quiesced", + pid = u64::from(pid), + drained_ms = held.held_ms(), + "admission quiesced: nothing is generating; the next ensure relaunches into the larger pool" + ); + crate::inference::llama_server::request_pool_growth(pid, held); + }); + false } } -/// PURE: whether a `/slots` body shows no slot processing a request. Anything but an array of -/// slots is unknown, and unknown is never idle. -pub(super) fn no_slot_processing(slots: &serde_json::Value) -> bool { - slots.as_array().is_some_and(|all| all.iter().all(|slot| slot["is_processing"].as_bool() == Some(false))) -} - /// PURE: whether a steady plan proves the pool should grow. Steady (serving's footprint reported, /// so the budget was sampled with the engine up), a sampled budget, a known running pool, and a /// wanted pool strictly larger. Equal or smaller never relaunches. @@ -71,7 +86,7 @@ pub(super) fn grows(steady: bool, budget_bytes: u64, running_tokens: u32, wanted #[cfg(test)] mod tests { - use super::{grows, no_slot_processing}; + use super::grows; // what this catches (the M5 2026-11-03, 81aef1844: a 16,640 pool launched from a boot-time // transient and kept): a pool that never grows from a bad launch, or a bridge that relaunches @@ -86,15 +101,4 @@ mod tests { assert!(!grows(true, 23_000_000_000, 1_310_720, 257_536), "downward never relaunches (590df4bc3's pool stays)"); } - // what this catches (Fable on #5741): the growth relaunch cutting a generation mid-decode. - // It waits for a read with no slot processing; a slot whose state cannot be read is never - // taken as idle. - #[test] - fn the_growth_waits_for_no_slot_processing() { - let slots = |busy: &[bool]| serde_json::Value::Array(busy.iter().map(|b| serde_json::json!({ "is_processing": b })).collect()); - assert!(no_slot_processing(&slots(&[false, false])), "every slot idle"); - assert!(!no_slot_processing(&slots(&[false, true])), "one generation in flight"); - assert!(!no_slot_processing(&serde_json::json!([{ "id": 0 }])), "a slot with no is_processing is unknown, not idle"); - assert!(!no_slot_processing(&serde_json::json!({ "error": "unavailable" })), "not a slots array: unknown"); - } }