Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion core/continuum-engine/src/inference/llama_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
51 changes: 48 additions & 3 deletions core/continuum-engine/src/inference/llama_server/pool_growth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,56 @@
/// is stale and never acts.
static REQUESTED: parking_lot::Mutex<Option<u32>> = 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<Option<(u32, crate::inference::resource_admission::Quiesced)>> = 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.
Expand Down Expand Up @@ -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");
Expand Down
2 changes: 2 additions & 0 deletions core/continuum-engine/src/inference/resource_admission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ mod gate;
mod lanes;
mod metrics;
mod progress;
mod quiesce;
mod serving_lane_permit;
#[cfg(test)]
mod tests;
Expand All @@ -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;
13 changes: 13 additions & 0 deletions core/continuum-engine/src/inference/resource_admission/lanes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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<super::quiesce::Quiesced> {
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.
Expand Down Expand Up @@ -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(),
}
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -434,6 +446,7 @@ impl LaneAdmission {
directed,
priority,
released: &self.released,
_entry: entry,
}
};
(observer, acquire)
Expand Down
198 changes: 198 additions & 0 deletions core/continuum-engine/src/inference/resource_admission/quiesce.rs
Original file line number Diff line number Diff line change
@@ -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<Quiesced> {
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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ pub struct ServingLanePermit {
pub(super) persona: Option<uuid::Uuid>,
/// 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 {
Expand Down
4 changes: 0 additions & 4 deletions core/continuum-serving/src/modules/serving_daemon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::sync::atomic::AtomicU64>,
/// 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<parking_lot::Mutex<Option<(u32, bool)>>>,
/// 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<Option<crate::capacity::window_grant::PoolGrants>>,
Expand Down Expand Up @@ -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)),
Expand Down
4 changes: 0 additions & 4 deletions core/continuum-serving/src/modules/serving_daemon/health.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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(),
Expand Down
3 changes: 3 additions & 0 deletions core/continuum-serving/src/modules/serving_daemon/launch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
{
Expand Down
Loading
Loading