From 89e3bc8a64c02b5e286dd2d05049186c86cd0b5d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 2 Nov 2026 20:55:59 -0600 Subject: [PATCH 1/3] One launch: the engine starts once on a shared KV pool; a window or slot change never relaunches it Joel, 2026-11-03: "Slot counts should never require shutdown." The M5's engine loaded its model 40 times (llama-server-58057.log) as the plan's slot count moved 1 -> 2 -> 1; each reload wiped every mind's cache, and slots holding 62-71k tokens re-prefilled in full. - The launch: `--kv-unified`. `-c` is the pool and `--parallel` the sequence ceiling (the seated minds + scratch). The pool is sized from the budget (`ModelFootprint::pool_within`), not from the cold plan's window x lanes, which gave 1 x 80k on a boot that counted two residents. - The engine reconcile relaunches only for a different model, genome, sight, KV decision, engine binary, or an engine not yet on the shared pool (once). The window, lane and cache grow ladders are deleted (WINDOW_RELAUNCH_TOLERANCE, the narrowing-trade guard, the memory-gate refusal, convergence geometry). - The daemon: the re-home ladder (streaks, cooldowns, plan highs, holds, the cache-size re-home) is deleted. A ready lane on the right model and genome is left alone. When the seated population moves, the launch path republishes (an AlreadyServing ensure, no relaunch). - Each seated mind is published her share, `seated_share(pool, seated, trained)`, so the ~30 readers of served_context_window and lanes are unchanged. - Dead with the ladder: the exam's steady hold (ServingSteadyHold). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/exam_serving.rs | 60 +- .../src/inference/lane_args.rs | 15 +- .../src/inference/llama_server.rs | 2 - .../src/inference/llama_server/control.rs | 8 + .../inference/llama_server/control_impl.rs | 7 + .../src/inference/llama_server/reconcile.rs | 279 +------- .../src/inference/llama_server/tests.rs | 11 + .../llama_server/tests/engine_install.rs | 34 +- .../inference/llama_server/tests/reconcile.rs | 236 +------ .../src/inference/planning/serving_plan.rs | 1 + .../inference/planning/serving_plan/pool.rs | 22 + .../src/inference/serving_holds.rs | 64 +- .../src/modules/serving_daemon.rs | 76 +-- .../src/modules/serving_daemon/demand.rs | 11 + .../src/modules/serving_daemon/launch.rs | 50 +- .../src/modules/serving_daemon/policy.rs | 189 +----- .../src/modules/serving_daemon/publication.rs | 18 +- .../src/modules/serving_daemon/reconcile.rs | 420 +----------- .../src/modules/serving_daemon/tests.rs | 60 +- .../modules/serving_daemon/tests/budget.rs | 121 ++-- .../serving_daemon/tests/one_launch.rs | 123 ++++ .../serving_daemon/tests/publication.rs | 48 +- .../serving_daemon/tests/reconciliation.rs | 54 +- .../modules/serving_daemon/tests/rehome.rs | 633 ------------------ 24 files changed, 426 insertions(+), 2116 deletions(-) create mode 100644 core/continuum-engine/src/inference/planning/serving_plan/pool.rs create mode 100644 core/continuum-serving/src/modules/serving_daemon/tests/one_launch.rs delete mode 100644 core/continuum-serving/src/modules/serving_daemon/tests/rehome.rs diff --git a/core/continuum-academy/src/cognition/exam_serving.rs b/core/continuum-academy/src/cognition/exam_serving.rs index 12305b8f30..81e701b59e 100644 --- a/core/continuum-academy/src/cognition/exam_serving.rs +++ b/core/continuum-academy/src/cognition/exam_serving.rs @@ -2,10 +2,10 @@ //! explicit at the exam seam, and the LUDICROUS window-grow that gives a benchmark the //! biggest window the model+machine allow. //! -//! The living-persona benchmark used to grab a bare steady-hold and *assume* it was a +//! The living-persona benchmark used to grab a bare hold and *assume* it was a //! co-tenant slot; the comment said "= `Placement::ShareLane`" but nothing computed it. This //! module makes it real: it runs the model-aware admission kernel ([`plan_placement`]), and -//! for a share it drives the correct GROW → SETTLE → PIN sequence: +//! for a share it drives the GROW → SETTLE sequence: //! 1. **GROW** — declare LUDICROUS ([`ServingLudicrousHold`] → `PowerMode::Performance`), so //! the daemon re-plans the shared lane to the biggest window the machine fits. Never a //! starved boot-window (the 2048-eco incident). @@ -14,7 +14,8 @@ //! A naive "force Performance then run" thrashes: acquiring Ludicrous is itself a re-plan //! → relaunch, and a relaunch mid-exam connection-refuses every generation (the reverted //! `95dcec669`). Settling BEFORE the tasks run absorbs that relaunch once, up front. -//! 3. **PIN** — take the steady-hold so no FURTHER relaunch bounces the running exam. +//! Nothing relaunches the engine for size since 2026-11-03 (one launch, a shared pool), so no +//! pin is needed once the exam runs. //! The verdict is CARRIED for observability + the curriculum ledger. //! //! The `SpawnLane`/`CpuSpill` arms are the rails a DIFFERENT-base exam or a grid placement @@ -25,7 +26,7 @@ use std::time::Duration; -use crate::inference::serving_holds::{ServingLudicrousHold, ServingSteadyHold}; +use crate::inference::serving_holds::ServingLudicrousHold; use crate::resources::placement::{plan_placement, LaneDemand, Placement, ResidentLane}; /// How long to watch for a grow-relaunch to START (lane goes not-ready) after declaring @@ -43,7 +44,7 @@ const LUDICROUS_SETTLE_TIMEOUT: Duration = Duration::from_secs(180); pub enum ExamAcquire { /// The exam base is already resident → she is measured as a co-tenant decode slot on the /// live lane (`lane_id`), NO second weight copy. The lane is grown to LUDICROUS - /// (Performance → biggest window), settled, then held steady for the exam. The validated + /// (Performance → biggest window) and settled for the exam. The validated /// single-GPU path. `reclaim` names any lower-tier lanes the daemon should tier down first /// (empty in the common case). SharedLane { @@ -71,12 +72,10 @@ impl ExamAcquire { } } -/// The RAII holds a shared-lane exam binds for its whole run: LUDICROUS (serve at Performance) -/// + STEADY (no further relaunch). Both release together when the context drops, reverting -/// serving to the live pressure-adaptive mode. +/// The RAII hold a shared-lane exam binds for its whole run: LUDICROUS (serve at Performance). +/// It releases when the context drops, reverting serving to the live pressure-adaptive mode. struct ExamHold { _ludicrous: ServingLudicrousHold, - _steady: ServingSteadyHold, } /// A held exam serving context. While alive, a shared-lane exam serves at the biggest window @@ -109,7 +108,7 @@ impl ExamServingContext { pub async fn acquire(capacity: u64, resident: &[ResidentLane], demand: &LaneDemand) -> Self { let acquire = Self::decide(capacity, resident, demand); let hold = if matches!(acquire, ExamAcquire::SharedLane { .. }) { - Some(Self::grow_settle_pin().await) + Some(Self::grow_settle().await) } else { None }; @@ -126,7 +125,7 @@ impl ExamServingContext { } /// The live serving inputs weren't resolvable (ungoverned host, model row missing, or the - /// lane isn't ready yet) — fall back to the share posture (grow → settle → pin) but MARK the + /// lane isn't ready yet) — fall back to the share posture (grow → settle) but MARK the /// verdict `unresolved` so the gap is visible rather than silently assumed. The exam still /// gets the biggest window; only the placement decision is recorded as "couldn't compute". pub async fn ludicrous_fallback() -> Self { @@ -139,15 +138,14 @@ impl ExamServingContext { lane_id: "live(unresolved)".to_string(), reclaim: Vec::new(), }, - _hold: Some(Self::grow_settle_pin().await), + _hold: Some(Self::grow_settle().await), } } - /// GROW (declare Ludicrous) → SETTLE (absorb any grow-relaunch) → PIN (steady-hold). The - /// Ludicrous hold is taken FIRST and kept, so `host_budget` plans at Performance for the - /// whole exam; the settle happens BEFORE the steady-hold so the pin lands on the grown, - /// stable lane — never on a lane about to relaunch. - async fn grow_settle_pin() -> ExamHold { + /// GROW (declare Ludicrous) → SETTLE. The Ludicrous hold is taken FIRST and kept, so + /// `host_budget` plans at Performance for the whole exam, and the exam starts on a settled + /// window. + async fn grow_settle() -> ExamHold { let ludicrous = ServingLudicrousHold::acquire(); let settled = crate::inference::llama_server::wait_for_serving_window_settle( LUDICROUS_SETTLE_GRACE, @@ -160,10 +158,8 @@ impl ExamServingContext { settled = settled.is_some(), "exam lane grown to Ludicrous (Performance) and settled before pinning" ); - let steady = ServingSteadyHold::acquire("eval"); ExamHold { _ludicrous: ludicrous, - _steady: steady, } } @@ -181,7 +177,7 @@ impl ExamServingContext { #[cfg(test)] mod tests { use super::*; - use crate::inference::serving_holds::{serving_held_steady, serving_ludicrous_active}; + use crate::inference::serving_holds::serving_ludicrous_active; use crate::resources::placement::DemandTier; const GIB: u64 = 1 << 30; @@ -267,43 +263,33 @@ mod tests { assert!(matches!(v, ExamAcquire::CpuSpill { .. })); } - // what this catches: the async ACQUIRE for a share holds BOTH Ludicrous and steady for the - // exam's lifetime and releases both on drop (RAII). With no live serving state the settle is - // a fast no-op, so this exercises the grow→settle→pin holds without a daemon. A spawn verdict - // holds nothing local. Guards the reverted-thrash regression: the exam pins the lane (steady) - // AND declares Ludicrous (Performance) — both, together. + // what this catches: the async ACQUIRE for a share holds Ludicrous for the exam's lifetime + // and releases it on drop (RAII). With no live serving state the settle is a fast no-op, so + // this exercises the grow→settle hold without a daemon. A spawn verdict holds nothing local. #[tokio::test] - async fn share_acquire_holds_ludicrous_and_steady_then_releases_on_drop() { + async fn share_acquire_holds_ludicrous_then_releases_on_drop() { // Spawn verdict first: holds nothing local, no global gauge touched. let resident = [live_lane("devstral-24b")]; let spawn = ExamServingContext::acquire(64 * GIB, &resident, &exam_demand("qwen-coder-32b")).await; - assert!(!spawn.holds(), "a spawn verdict holds no local grow/pin"); + assert!(!spawn.holds(), "a spawn verdict holds no local grow"); // Share verdict (under memory pressure — a dedicated copy won't fit at 28 GiB, so the - // isolate demand falls back to a co-tenant share): grows Ludicrous + pins steady. + // isolate demand falls back to a co-tenant share): grows Ludicrous. let ctx = ExamServingContext::acquire(28 * GIB, &resident, &exam_demand("devstral-24b")).await; assert!( ctx.holds(), - "a shared-lane exam holds the grown, pinned lane" + "a shared-lane exam holds the grown lane" ); assert!( serving_ludicrous_active(), "Ludicrous (Performance) is declared for the exam" ); - assert!( - serving_held_steady(), - "and the lane is pinned steady against further relaunch" - ); drop(ctx); assert!( !serving_ludicrous_active(), "drop reverts to the pressure-adaptive mode (RAII)" ); - assert!( - !serving_held_steady(), - "drop releases the steady pin (RAII)" - ); } } diff --git a/core/continuum-engine/src/inference/lane_args.rs b/core/continuum-engine/src/inference/lane_args.rs index 022bfb66c0..c8e4790c90 100644 --- a/core/continuum-engine/src/inference/lane_args.rs +++ b/core/continuum-engine/src/inference/lane_args.rs @@ -312,17 +312,18 @@ pub fn base_invocation( host.to_string(), arg("--port"), port.to_string(), - // llama-server's `-c` is the TOTAL KV cache, split evenly across the - // `--parallel` slots; each request only sees `-c / n_parallel` tokens. - // The plan's `context_window` is PER-LANE, so the total we must request - // is `context_window * lanes` — then each of `lanes` slots holds exactly - // one planned window. We pass `--parallel` EXPLICITLY (never inherit - // llama.cpp's default, which is 4 and silently quartered the window in - // the prior bug). See `served_total_ctx` / `parallel_lanes`. + // ONE SHARED POOL (2026-11-03): `-c` is the whole KV pool and `--parallel` the + // most sequences that may draw on it; under `--kv-unified` each sequence can use + // the whole pool and an idle one holds none. Both are fixed for the process's + // life: which minds hold how much is decided at runtime, never by a relaunch (the + // M5 loaded its model 40 times as the slot count moved 1 -> 2 -> 1, every + // reload wiping every mind's cache). `--parallel` stays explicit: llama.cpp's + // default is 4. See `served_total_ctx` / `parallel_lanes`. arg("-c"), total_ctx.to_string(), arg("--parallel"), lanes.to_string(), + arg("--kv-unified"), // KV PREFIX REUSE across a persona's turns. `cache_prompt:true` (sent // per-request) only reuses a slot's prior content when the *exact* // prefix still sits in that slot; with the volatile grounding tail diff --git a/core/continuum-engine/src/inference/llama_server.rs b/core/continuum-engine/src/inference/llama_server.rs index 1ae59f2767..c852efca6e 100644 --- a/core/continuum-engine/src/inference/llama_server.rs +++ b/core/continuum-engine/src/inference/llama_server.rs @@ -56,8 +56,6 @@ pub use liveness::{ mod convergence_attempt; mod reconcile; pub use reconcile::{ensure_model_serving, ensure_model_serving_if_current}; -#[cfg(test)] -pub(crate) use reconcile::{grow_refused_by_memory_gate, lane_grow_would_narrow_the_window}; mod smoke; use smoke::{ diff --git a/core/continuum-engine/src/inference/llama_server/control.rs b/core/continuum-engine/src/inference/llama_server/control.rs index 83e34d46f5..09305b7876 100644 --- a/core/continuum-engine/src/inference/llama_server/control.rs +++ b/core/continuum-engine/src/inference/llama_server/control.rs @@ -435,6 +435,14 @@ pub trait LlamaServerControl: Send + Sync { None } + /// Was the RUNNING engine launched on one shared KV pool (`--kv-unified`), read off its + /// own argv? An engine on fixed slots can change its slot count only by a relaunch, so + /// the reconcile moves it to the shared pool once. `None` = unknown (no live lane, argv + /// unreadable, a fake): an absence is not a mismatch. + fn launched_on_shared_pool(&self) -> Option { + None + } + /// Fingerprint of the server's `/slots` activity state (see /// [`slots_activity_fingerprint_of`]). The health heartbeat compares the value /// across two consecutive smoke-probe MISSES: changed → the serve loop is diff --git a/core/continuum-engine/src/inference/llama_server/control_impl.rs b/core/continuum-engine/src/inference/llama_server/control_impl.rs index c21abadd79..851de27274 100644 --- a/core/continuum-engine/src/inference/llama_server/control_impl.rs +++ b/core/continuum-engine/src/inference/llama_server/control_impl.rs @@ -333,6 +333,13 @@ impl LlamaServerControl for LlamaServerProcess { Some(crate::inference::lane_process::launch_kv_in(&argv)) } + fn launched_on_shared_pool(&self) -> Option { + let (_host, port) = split_host_port(&self.root); + let record = crate::inference::lane_registry::live_lane().filter(|r| r.port == port)?; + let argv = crate::inference::lane_process::command_args(record.pid)?; + Some(argv.iter().any(|a| a == "--kv-unified" || a == "-kvu")) + } + fn wedge_flag(&self) -> Option { self.wedge.clone() } diff --git a/core/continuum-engine/src/inference/llama_server/reconcile.rs b/core/continuum-engine/src/inference/llama_server/reconcile.rs index b1df6686a0..41170383f1 100644 --- a/core/continuum-engine/src/inference/llama_server/reconcile.rs +++ b/core/continuum-engine/src/inference/llama_server/reconcile.rs @@ -1,56 +1,12 @@ //! Reconcile responsibility of the llama-server process owner. use super::*; -/// A same-model/same-genome relaunch is required when the target per-slot window -/// exceeds the running server's served window by MORE than this. llama.cpp has no -/// hot-resize API, so a genuine window GROW can only be honored by a relaunch — -/// exactly like an adapter-set change. The margin absorbs llama.cpp's internal -/// 256-multiple padding of the launch `-c/--parallel` window (served ≈ round-up-256 -/// of the launched per-slot value), so a padded steady-state window never reads as -/// a spurious grow and re-triggers a relaunch every tick. Comfortably above one -/// 256-pad; the daemon only sends a grow target when it is ≥ 2× the served window -/// (its `starved` gate), so this margin never masks a real grow. -// context-budget-exempt: a HYSTERESIS band: how far the served window may drift before a relaunch is worth it. Tolerance, never a cap — it doesn't limit the window, it stops us thrashing it -pub(super) const WINDOW_RELAUNCH_TOLERANCE: u32 = 512; - - -/// Would relaunching toward `(target_lanes, target_window)` leave every citizen a -/// NARROWER lane than `(served_lanes, served_window)` serves, in exchange for more -/// lanes? The grow ladder's one geometry question (card d9d747b2): a lane grow that -/// costs window is a trade the ladder refuses; a pure lane grow, a window grow (at -/// any lane count), and an unreadable served side (0) are not. "Narrower" uses the -/// same tolerance the window check does — a 256-pad or the boot plan's drift under a -/// served window is not a trade. -pub(crate) fn lane_grow_would_narrow_the_window( - target_lanes: u32, - target_window: u32, - served_lanes: u32, - served_window: u32, -) -> bool { - if served_lanes == 0 || served_window == 0 || target_lanes <= served_lanes { - return false; - } - let tolerance = WINDOW_RELAUNCH_TOLERANCE.max(served_window / 8); - target_window.saturating_add(tolerance) < served_window -} - - -/// Is this relaunch a GROW that the closed memory gate forbids? The gate closes at -/// sustained Critical pressure and its contract is that subsystems refuse new -/// allocations (`is_memory_gate_closed`) — and a relaunch toward more lanes or a wider -/// window is the largest elective allocation this node makes. Eval and Whisper read the -/// gate; the grow ladder did not. Measured on the M5 2026-09-23: the engine settled at -/// 8 lanes × 35,328 while `memory.pressure` read Critical for 39 consecutive samples, -/// 36.8 GB resident on a 69 GB box. And fseventsd has twice taken over a quarter of the -/// machine (26.6 GB 2026-09-08, 14 GB 2026-09-24) — growing into THAT is how an -/// unattended node goes down. -/// -/// Only the lane and window axes are refused. A KV-type or sight relaunch is a -/// DECISION change, not necessarily a larger footprint, and stays allowed. Pure, so the -/// test does not touch the process-global gate. -pub(crate) fn grow_refused_by_memory_gate(gate_closed: bool, window_ok: bool, lanes_ok: bool, cache_ok: bool) -> bool { - gate_closed && (!window_ok || !lanes_ok || !cache_ok) -} - +// ONE LAUNCH (2026-11-03, Joel: "Slot counts should never require shutdown"). The engine +// starts once on a shared KV pool (`--kv-unified`); which minds hold how much of it is +// decided at runtime. A different window, lane count or cache grant is never a relaunch +// here: only a different model, genome the engine cannot take in place, sight, KV type, +// engine binary, an engine not yet on the shared pool, or a dead engine. The window, +// lane and cache grow ladders that lived here (WINDOW_RELAUNCH_TOLERANCE, the +// narrowing-trade guard, the memory-gate refusal) relaunched the M5's engine 40 times. /// Pure reconcile decision: bring the running server in line with `desired`. /// Split from the process impl so the branch logic is unit-tested against a @@ -88,24 +44,6 @@ pub async fn ensure_model_serving_if_current( outcome } -/// Engine replacement alone is not permission to apply a different geometry. -/// Geometry changes are reconsidered separately after convergence, under the trade guards. -pub(super) fn engine_convergence_target( - planned: &ServingTarget, - served_window: u32, - served_lanes: u32, -) -> Result { - let mut selected = planned.clone(); - { - if served_window == 0 || served_lanes == 0 { - return Err("engine convergence requires the incumbent's observed window and lane count; geometry is unknown".to_string()); - } - selected.context_window = served_window; - selected.lanes = served_lanes; - } - Ok(selected) -} - async fn serve_or_adopt( ctrl: &C, target: &ServingTarget, @@ -119,7 +57,6 @@ async fn serve_or_adopt( current: &ServingLifecycleCheck<'_>, ) -> EnsureOutcome { let mut convergence_pair = None; - let mut convergence_target = None; let active = match ctrl.active_model().await { Ok(active) => active, Err(LlamaServerError::Unreachable(_)) => None, @@ -198,97 +135,12 @@ async fn serve_or_adopt( } }; if genome_matches { - // Right model, right genome — but does the running server's per-slot - // WINDOW match the target? llama.cpp cannot hot-resize, so a target - // window that meaningfully EXCEEDS the served window is a real mismatch - // only a relaunch can honor — exactly like the adapter-set change below. - // Without this, a daemon-decided starved grow-back (2048→31k, same model - // + same genome) short-circuits to AlreadyServing and the lane stays - // frozen at the boot floor FOREVER, while the daemon re-decides "starved" - // and logs "re-homing" every tick — a relaunch that never happens - // (glass-boxed 2026-07-20: window pinned 2048 vs a 31k plan, benchmarks - // blocked). Grow-only: a down-plan is kept by the daemon's sticky window - // and never reaches here; a `/props` read failure (served 0/Err) is - // treated as "window OK" so a probe error never spuriously relaunches. - let served_window_probe = ctrl.served_context_window().await; - let window_ok = match &served_window_probe { - Ok(served) => { - let served = *served; - // Tolerance is a PERCENTAGE of the served window, floored at the - // flat minimum — never a bare flat count. A flat 512 is 0.35% of a - // 147k lane, so the boot plan's normal drift (it re-computes against - // live memory, which climbs ~7% once the old core frees its share: - // measured 2026-09-03, 147712 → 158107) tripped a RELAUNCH — a full - // ~7-10 min 35B reload on EVERY reboot, the dominant "resume is slow" - // cost. A warm lane at 88% of the ideal window NOW beats a cold ideal - // one in 10 minutes; the runtime re-home (streak-debounced) still - // grows it later if a bigger window's gain actually persists. A - // genuinely starved lane (2048 vs a 31k plan) still relaunches: - // 31k ≫ 2048 × 1.125. served 0 / probe-err stays "OK" (no spurious - // relaunch), unchanged. - let tolerance = WINDOW_RELAUNCH_TOLERANCE.max(served / 8); - served == 0 || target.context_window <= served.saturating_add(tolerance) - } - Err(e) => { - // Deliberate: a probe error must not spuriously relaunch a healthy - // lane (stated above). But the error is still evidence — if windows - // stop growing, this line is the reason, and it must be findable. - tracing::warn!(target: "continuum_core::inference::llama_server", error = %e, - "could not read the served window — treating the window as OK \ - (no spurious relaunch); a starved lane will not grow while this \ - probe keeps failing" - ); - true - } - }; - // LANE grow-back — the exact sibling of the window grow-back above. After a - // transient RAM/VRAM squeeze relaunched the lane at fewer parallel slots - // (n_seq_max 4→1), a later plan that wants more lanes would otherwise - // short-circuit to AlreadyServing on `genome_matches && window_ok` and stay - // FROZEN AT ONE LANE FOREVER — starving every citizen to one-at-a-time while - // the daemon re-decides the same plan each tick (glass-boxed 2026-08-11: - // ~11GB free, lanes stuck at 1, a benchmark solve infra-failed). llama.cpp - // cannot hot-resize n_seq_max any more than the window, so a lane increase - // needs a relaunch. Grow-only + discrete: served 0 = nothing to compare; - // target ≤ served is fine (a down-plan is the daemon's sticky choice); only - // target > served relaunches. - // - // ASK THE LANE, NOT OUR MEMORY OF IT (fixed 2026-08-19). This read used to - // be `current_serving().lanes` — the process-local snapshot — while the - // window operand three lines up probed the running server. That asymmetry - // is invisible for a lane we spawned (snapshot == process) and wrong for a - // PAST FORM OF OURSELF: a lane that survived a crash on the canonical port, - // named in our own custody record, has no entry in a fresh core's snapshot. - // Measured cost of the old read: a healthy 4-lane 27B declined, reaped and - // rebuilt over ~110s, returning at 3 lanes and a SMALLER window than the - // lane that was already running. Both operands now ask the process. - let served_lanes_probe = ctrl.served_lanes().await; - let lanes_ok = match &served_lanes_probe { - Ok(served) => *served == 0 || target.lanes <= *served, - Err(e) => { - // Deliberate, and identical to the window's policy above: a probe - // error must not spuriously relaunch a healthy lane. The error is - // still evidence — if lanes stop growing, this line is the reason. - tracing::warn!(target: "continuum_core::inference::llama_server", error = %e, - "could not read the served lane count — treating lanes as OK (no \ - spurious relaunch); a starved lane will not grow while this probe \ - keeps failing" - ); - true - } - }; - // Report what the LANE said, and say so when it could not be asked — a - // probe that silently substitutes a number is how the old bug hid. - let served_lanes = match &served_lanes_probe { - Ok(n) => n.to_string(), - Err(e) => format!("unreadable ({e})"), - }; - // SIGHT grow-back — the third sibling (2026-09-18). Today's decision may put + // SIGHT (2026-09-18). Today's decision may put // the projector on this lane (the only eyes on the node) while the running // server was spawned by an earlier core or policy without one: /props says // vision=false, and adopting it would keep the node blind until an // unrelated relaunch. A lane whose sight is below target relaunches for - // that alone, exactly like a window or lane count below target. A build + // that alone. A build // that publishes no modalities block is unverifiable and is NOT relaunched // in a loop for it (the daemon reports that case as unverified sight). let wants_sight = @@ -324,74 +176,11 @@ async fn serve_or_adopt( r.cache_type_or_default().eq_ignore_ascii_case(&planned_kv.cache_type) && r.flash_attn == planned_kv.flash_attn }); - // A LANE GROW MUST NOT NARROW THE WINDOW (card d9d747b2, the M5 2026-09-21 - // 09:29-09:36Z). The four checks are per-axis and grow-only, but a relaunch is - // a GEOMETRY change: the plan asked for 5 lanes and, to fit them, sized each at - // 36,810 over a lane serving 3 × 78,592. `lanes_ok` fired, the engine relaunched - // at 5 × 36,810, the next plan found the window starved and relaunched back to - // 3 × 78,592 — every ~3 min, 35 generations reaped in 20, a prompt cache that - // could never warm. The window is the requirement and lanes are throughput - // (card 18ba6a1b: the window first, then lanes), so a lane-driven relaunch that - // would leave every citizen a NARROWER lane than she has is a trade, not a - // grow-back, and the ladder refuses it. The opposite trade — a wider window at - // fewer lanes — stays allowed: that is the starved-window grow-back this ladder - // exists for. A plan that keeps asking is now a probe line, not a relaunch. - let served_window_n = served_window_probe.as_ref().ok().copied().unwrap_or(0); // unwrap_or: unreadable = 0 = no served window to compare against, same as window_ok's policy - let served_lanes_n = served_lanes_probe.as_ref().ok().copied().unwrap_or(0); // unwrap_or: unreadable = 0 = no served lanes to compare against, same as lanes_ok's policy - // THE CACHE GRANT IS LAUNCH GEOMETRY TOO (card d7294f0b). `--cache-ram` is fixed - // at spawn. Kimi's node, 2026-10-15 07:37-07:39Z: the daemon found her adopted - // lane's 3,248 MiB grant held no measured state and decided "re-homing" twice, - // but this rail compared only model, genes, window, lanes, sight and the KV type, - // answered AlreadyServing, and every switch between minds stayed a full re-prefill. - // The daemon's own rule decides here too: relaunch only when the running grant - // holds no state and the target's would. Unknown (no argv) or drift is never one. - let page_dir = kv_page_dir(target.model_id()); - crate::inference::slots::seed_state_samples(&page_dir).await; - let cache_ok = !crate::inference::lane_args::cache_relaunch_owed( - running_kv.as_ref().and_then(|r| r.cache_ram_mib), - target.host_prompt_cache_mib, - crate::inference::slots::measured_state_bytes(&page_dir), - ); - let refused_trade = !lanes_ok - && window_ok - && sight_ok - && kv_ok - && lane_grow_would_narrow_the_window( - target.lanes, - target.context_window, - served_lanes_n, - served_window_n, - ); - if refused_trade { - continuum_base::probe!(target: "continuum_core::inference::llama_server", class = "serving.grow_refused_trade", - model = target.model_id(), - target_lanes = target.lanes, - target_window = target.context_window, - served_lanes = served_lanes_n, - served_window = served_window_n, - "the plan wants more lanes at a NARROWER window than the lane serves — a \ - trade, not a grow-back; refused (card d9d747b2: following it relaunched the \ - engine every ~3 min between 5 × 36k and 3 × 78k). The lane keeps its window; \ - more lanes come when they fit at it", - ); - } - let gate_closed = crate::system_resources::is_memory_gate_closed(); - let refused_pressure = !refused_trade && grow_refused_by_memory_gate(gate_closed, window_ok, lanes_ok, cache_ok); - if refused_pressure { - continuum_base::probe!(target: "continuum_core::inference::llama_server", class = "serving.grow_refused_memory_gate", - model = target.model_id(), - target_lanes = target.lanes, - target_window = target.context_window, - served_lanes = served_lanes_n, - served_window = served_window_n, - window_ok, - lanes_ok, - "the plan wants a larger engine but the memory gate is CLOSED (sustained \ - Critical) — refused; the lane keeps its geometry. Growing into a machine \ - that is already short is how an unattended node goes down. The grow is \ - re-asked every tick and proceeds once the gate reopens", - ); - } + // THE SHARED POOL, once: an engine launched with fixed slots (every node before + // 2026-11-03) is moved to the shared pool by one relaunch; after that no window, + // lane or cache change ever relaunches it. Unknown (no argv, a fake) is not a + // mismatch. + let pool_ok = ctrl.launched_on_shared_pool().unwrap_or(true); // unwrap_or: unknown (no argv, a fake) is not a mismatch // THE ENGINE ITSELF — the fourth operand (card 7c5f139d). A deploy installs the // engine the pin names (install-llama-server.sh, stamp-gated, atomic), but every // deploy leaves the lane up for the next core, so an adopted lane keeps running @@ -443,50 +232,33 @@ async fn serve_or_adopt( }; *ENGINE_STALE.lock() = (!engine_current).then(|| pair.clone()); if !engine_ok { - let resize_admitted = false; // Engine convergence and geometry resize are separate lifecycle decisions. - match engine_convergence_target(target, served_window_n, served_lanes_n) { - Ok(selected) => convergence_target = Some(selected), - Err(reason) => return EnsureOutcome::Degraded { reason }, - } continuum_base::probe!(target: "continuum_core::inference::llama_server", class = "serving.engine.converged", model = target.model_id(), from = served_engine.as_deref().unwrap_or(""), // probe field: engine_ok=false implies both are known to = installed_engine.as_deref().unwrap_or(""), // probe field: as above - resize_admitted, - incumbent_lanes = served_lanes_n, - incumbent_window = served_window_n, - plan_lanes = target.lanes, - plan_window = target.context_window, "the running lane is on an engine older than the installed one: relaunching \ - onto the installed binary; preserve incumbent geometry unless a separate resize was admitted" + onto the installed binary" ); } - if !engine_ok - || ((!window_ok || !lanes_ok || !sight_ok || !kv_ok || !cache_ok) && !refused_trade && !refused_pressure) - { - continuum_base::probe!(target: "continuum_core::inference::llama_server", class = "serving.grow", + if !engine_ok || !sight_ok || !kv_ok || !pool_ok { + continuum_base::probe!(target: "continuum_core::inference::llama_server", class = "serving.relaunch", model = target.model_id(), - target_window = target.context_window, - target_lanes = target.lanes, - served_lanes = served_lanes.as_str(), - window_ok, - lanes_ok, + engine_ok, sight_ok, kv_ok, - cache_ok, + pool_ok, planned_kv = %planned_kv.cache_type, planned_flash_attn = planned_kv.flash_attn, running_kv = running_kv.as_ref().map(|r| r.cache_type_or_default().to_string()).unwrap_or_default(), // unwrap_or_default: "" = the running decision is unknown (no live argv); kv_ok is then true running_flash_attn = running_kv.as_ref().map(|r| r.flash_attn).unwrap_or(false), // unwrap_or: unknown reads false alongside the empty type above - "served geometry differs from the target (window, lanes, sight and/or the KV \ - decision) — relaunching (llama.cpp has no hot-resize; a genome-set match \ - alone must not strand a starved lane at the boot floor, a blind one without \ - its eyes, or an adopted lane on last deploy's cache type)", + "the running engine is not the one a launch would start now (its binary, its \ + sight, its KV decision, or a cache not yet on the shared pool) — relaunching \ + once; a window or lane change never relaunches", ); - // fall through to relaunch at the larger window / more lanes / with eyes / - // on the decided cache type. + // fall through to relaunch on the installed binary, with eyes, on the decided + // cache type, on the shared pool. } else { - // Window matches. Is the COMPUTE path alive? A child we spawned + // The launch matches. Is the COMPUTE path alive? A child we spawned // ourselves was decode-verified at `wait_ready` and is trusted // thereafter (no per-tick decode load). A server we did NOT spawn (an // orphan reclaimed from a dead core) can answer `/v1/models` while @@ -541,7 +313,6 @@ async fn serve_or_adopt( // Drop also runs on cancellation: only an actual launch-stage advance consumes // this pair. A refused checkpoint must remain eligible on the next tick. - let target = convergence_target.as_ref().unwrap_or(target); // unwrap_or: absent convergence retains the ordinary planned launch let _attempt = super::convergence_attempt::ConvergenceAttempt::new(ctrl, convergence_pair); match ctrl.serve_if_current(target, current).await { Ok(()) => { diff --git a/core/continuum-engine/src/inference/llama_server/tests.rs b/core/continuum-engine/src/inference/llama_server/tests.rs index 0f9021f1d6..697b261206 100644 --- a/core/continuum-engine/src/inference/llama_server/tests.rs +++ b/core/continuum-engine/src/inference/llama_server/tests.rs @@ -22,6 +22,8 @@ struct FakeControl { /// The KV decision the fake's running engine was launched with; `None` = unknown /// (the default, so every pre-existing case adopts on the other axes alone). launched_kv: Option, + /// Launched with fixed slots (no `--kv-unified`). + partitioned: bool, /// Whether the fake "owns" the running child (we spawned it). `false` = /// an adopted orphan (the conservative default that exercises the /// smoke-probe gate). @@ -58,6 +60,7 @@ impl FakeControl { decode_ok: true, slots_busy: None, launched_kv: None, + partitioned: false, owns: false, served_lanes: 0, served_window: 32768, @@ -121,6 +124,11 @@ impl FakeControl { self.launched_kv = Some(crate::inference::lane_process::LaunchKv { cache_type: cache_type.map(str::to_string), flash_attn, cache_ram_mib: None }); self } + /// Model an engine launched with fixed slots, no shared pool. + fn launched_partitioned(mut self) -> Self { + self.partitioned = true; + self + } /// Model an engine launched on THIS KV decision with a `--cache-ram` grant of `mib`. fn launched_with_cache(mut self, mib: u32) -> Self { let planned = crate::inference::kv_cache_plan::resolve(); @@ -201,6 +209,9 @@ impl LlamaServerControl for FakeControl { fn launch_kv(&self) -> Option { self.launched_kv.clone() } + fn launched_on_shared_pool(&self) -> Option { + self.partitioned.then_some(false) + } fn owns_child(&self) -> bool { self.owns } diff --git a/core/continuum-engine/src/inference/llama_server/tests/engine_install.rs b/core/continuum-engine/src/inference/llama_server/tests/engine_install.rs index 58a017e5c1..f3f3efb667 100644 --- a/core/continuum-engine/src/inference/llama_server/tests/engine_install.rs +++ b/core/continuum-engine/src/inference/llama_server/tests/engine_install.rs @@ -107,23 +107,21 @@ fn a_debug_build_is_refused_at_the_door_and_a_release_build_passes() { assert!(!super::is_debug_build("version: 0.3.0-dev (build 10751, commit 0a637ba22)\nbuilt with AppleClang 21.0.0.21000101 for Darwin arm64")); } -// The engine-only M5 convergence must preserve the incumbent's actual launch geometry. +// what this catches: the engine launched as fixed slots again (no `--kv-unified`), the shape +// whose slot count could change only by a relaunch (the M5 loaded its model 40 times on +// 2026-11-02/03). `-c` is the pool laid out as `--parallel` sequences, and every sequence may +// draw on all of it. #[test] -fn engine_only_convergence_preserves_incumbent_launch_arguments() { - for (lanes, window, planned_window) in [(2, 187136, 187136), (3, 76032, 76800)] { - let mut planned = target("convergence-fixture"); - planned.lanes = 1; - planned.context_window = planned_window; - let selected = super::super::reconcile::engine_convergence_target(&planned, window, lanes).unwrap(); - let invocation = crate::inference::lane_args::base_invocation( - Path::new("fixture.gguf"), selected.model_id(), "127.0.0.1", 1, - selected.parallel_lanes(), selected.served_total_ctx(), - selected.host_prompt_cache_mib, Path::new("pages"), - ); - assert_eq!(invocation.value_of("--parallel"), Some(lanes.to_string().as_str())); - assert_eq!(invocation.value_of("-c"), Some((lanes * window).to_string().as_str())); - } - let planned = target("convergence-fixture"); - assert!(super::super::reconcile::engine_convergence_target(&planned, 0, 2).is_err()); - assert!(super::super::reconcile::engine_convergence_target(&planned, 76032, 0).is_err()); +fn the_engine_launches_on_one_shared_pool() { + let mut planned = target("pool-fixture"); + planned.context_window = 58_112; + planned.lanes = 5; + let invocation = crate::inference::lane_args::base_invocation( + Path::new("fixture.gguf"), planned.model_id(), "127.0.0.1", 1, + planned.parallel_lanes(), planned.served_total_ctx(), + planned.host_prompt_cache_mib, Path::new("pages"), + ); + assert_eq!(invocation.value_of("-c"), Some("290560")); + assert_eq!(invocation.value_of("--parallel"), Some("5")); + assert!(invocation.has("--kv-unified")); } diff --git a/core/continuum-engine/src/inference/llama_server/tests/reconcile.rs b/core/continuum-engine/src/inference/llama_server/tests/reconcile.rs index de23d7c10b..27ac24ee73 100644 --- a/core/continuum-engine/src/inference/llama_server/tests/reconcile.rs +++ b/core/continuum-engine/src/inference/llama_server/tests/reconcile.rs @@ -1,35 +1,6 @@ //! Reconcile regression fixtures. #![cfg(test)] use super::*; -// what this catches: the per-lane → total `-c` arithmetic. llama-server's -// `-c` is the WHOLE KV cache split across `--parallel` slots, so to give each -// of `lanes` slots a full per-lane `context_window` the spawn must request -// `context_window * lanes` and pass `--parallel lanes`. Launching `-c -// context_window` alone let llama.cpp default to 4 slots and quarter the -// per-request window, 500-ing live deliberations ("Context size exceeded"). -// Regression here silently shrinks every persona's real prompt budget. -#[test] -fn served_total_ctx_is_per_lane_window_times_lanes() { - let mut t = target("coder-4b"); - t.context_window = 16_384; - t.lanes = 4; - assert_eq!(t.parallel_lanes(), 4); - assert_eq!( - t.served_total_ctx(), - 65_536, - "-c must be per-lane window × lanes so each slot holds one full window" - ); - - // lanes floored at 1: a single-lane plan serves the full window to one slot. - t.lanes = 1; - assert_eq!(t.served_total_ctx(), 16_384); - - // defensive floor: a zero lane count never collapses the cache to nothing. - t.lanes = 0; - assert_eq!(t.parallel_lanes(), 1); - assert_eq!(t.served_total_ctx(), 16_384); -} - // what this catches: the desired model already being served is a NO-OP — we // must not relaunch (which would kill the GPU-warm server). Regression here // would thrash the served model every tick. @@ -47,62 +18,6 @@ async fn already_serving_does_not_relaunch() { assert_eq!(ctrl.placements_recorded.load(Ordering::SeqCst), 1, "adoption records the placement"); } -// what this catches: a same-model / same-genome lane whose live per-slot window -// is STARVED far below the plan target (the 2048 boot-floor vs a 31k plan) must -// RELAUNCH to grow — llama.cpp has no hot-resize. Regression here (returning -// AlreadyServing on a genome-set match alone) strands the lane at the boot floor -// forever while the daemon logs "re-homing starved" every tick and never grows -// it — glass-boxed 2026-07-20, blocked all benchmark runs (prompts overflowed -// 2048). The daemon's `starved` gate only sends a target ≥ 2× the served window, -// so the grow is unambiguous. -#[tokio::test] -async fn starved_window_relaunches_to_grow() { - // Owned + decode-healthy: the ONLY thing wrong is the window (2048 ≪ 32768). - let ctrl = FakeControl::probe(Ok(Some("coder-14b".into()))) - .owned() - .with_served_window(2048); - let outcome = ensure_model_serving(&ctrl, &target("coder-14b"), false).await; - assert!( - matches!(outcome, EnsureOutcome::Spawned { .. }), - "a starved window must relaunch to grow, got {outcome:?}" - ); - assert_eq!( - ctrl.serves.load(Ordering::SeqCst), - 1, - "exactly one relaunch to the larger window" - ); -} - -// what this catches: THE 2026-09-03 SLOW-RESUME defect — a warm lane REAPED for a -// trivial window drift. On reboot the boot plan re-computes the window against live -// memory, which climbs ~7% once the old core frees its share (measured 147712 → -// 158107). A flat 512-token tolerance (0.35% of a 147k lane) tripped a full ~7-10 -// min 35B RELAUNCH on EVERY restart — the dominant "resume is slow" cost. Tolerance -// is now a percentage (max(512, served/8) ≈ 12.5%), so a warm lane within ~12.5% of -// the target is ADOPTED (warm-now beats cold-in-10-min); a genuinely starved lane -// (the 2× case above) still relaunches, and the runtime re-home grows a persistent -// gain later. -#[tokio::test] -async fn a_small_window_drift_adopts_the_warm_lane_not_a_slow_reload() { - // Owned + decode-healthy, serving 147712; the boot plan drifted to 158107 (~7%). - let ctrl = FakeControl::probe(Ok(Some("coder-14b".into()))) - .owned() - .with_served_window(147_712); - let mut t = target("coder-14b"); - t.context_window = 158_107; - let outcome = ensure_model_serving(&ctrl, &t, false).await; - assert_eq!( - outcome, - EnsureOutcome::AlreadyServing, - "a ~7% window drift must ADOPT the warm lane, not reload it; got {outcome:?}" - ); - assert_eq!( - ctrl.serves.load(Ordering::SeqCst), - 0, - "zero relaunches — the warm 35B lane is reused, not reloaded" - ); -} - // what this catches: THE 2026-08-19 DEFECT — a PAST FORM OF OURSELF being reaped // instead of adopted. A lane this core did not spawn (crash survivor on the // canonical port, named in our own custody record) already serves 4 slots at the @@ -133,105 +48,40 @@ async fn a_past_form_of_ourself_serving_enough_lanes_is_adopted_not_reaped() { ); } -// what this catches: the fix above must not disable lane grow-back (#214's sibling). -// A lane genuinely serving FEWER slots than the plan wants still has to relaunch — -// llama.cpp cannot hot-resize n_seq_max. Without this, "adopt more eagerly" would -// silently freeze every citizen at the squeezed slot count forever. +// what this catches: a window, lane count or cache grant that differs from the plan +// relaunching an engine on the shared pool. The M5 loaded its model 40 times as the plan's +// slot count moved 1 -> 2 -> 1 (2026-11-02/03), every reload wiping every mind's cache; a +// starved 2,048 window, one slot under a four-lane plan, and a grant that holds no state are +// all runtime matters now (Joel: "Slot counts should never require shutdown"). #[tokio::test] -async fn a_lane_serving_fewer_slots_than_planned_still_relaunches_to_grow() { - let ctrl = FakeControl::probe(Ok(Some("coder-14b".into()))) - .owned() - .with_served_lanes(1) - .with_served_window(32768); // window is FINE — only the lane count is short - let mut t = target("coder-14b"); - t.lanes = 4; - let outcome = ensure_model_serving(&ctrl, &t, false).await; - assert!( - matches!(outcome, EnsureOutcome::Spawned { .. }), - "1 served slot against a 4-lane plan must relaunch to grow, got {outcome:?}" - ); -} - -// what this catches (card d9d747b2, the M5 2026-09-21 09:29-09:36Z): a plan wanting -// MORE lanes at a NARROWER window than the lane serves (5 × 36,810 over 3 × 78,592) -// must not relaunch — following it thrashed the engine every ~3 min against the -// window grow-back and reaped 35 generations in 20 min. Both directions: the trade is -// refused and the lane stays; a pure lane grow at the served window still relaunches -// (the test above), and a WIDER window at fewer lanes still relaunches (the window is -// the requirement, lanes are throughput). -// what this catches: the grow ladder allocating through a CLOSED memory gate. The M5 -// settled at 8 lanes × 35,328 during 39 consecutive Critical samples (2026-09-23), and -// fseventsd has twice held over a quarter of the machine. A grow on either axis is -// refused while the gate is closed; a decision-only relaunch (KV type, sight) is not, -// and nothing is refused while the gate is open. -#[test] -fn a_closed_memory_gate_refuses_a_lane_or_window_grow() { - assert!(grow_refused_by_memory_gate(true, true, false, true), "more lanes through a closed gate"); - assert!(grow_refused_by_memory_gate(true, false, true, true), "a wider window through a closed gate"); - assert!(grow_refused_by_memory_gate(true, false, false, true), "both"); - assert!(grow_refused_by_memory_gate(true, true, true, false), "a bigger host cache through a closed gate (card d7294f0b)"); - assert!(!grow_refused_by_memory_gate(true, true, true, true), "geometry matches: a KV/sight relaunch is not a grow"); - assert!(!grow_refused_by_memory_gate(false, false, false, false), "an open gate refuses nothing"); -} - -#[tokio::test] -async fn a_lane_grow_that_would_narrow_the_window_is_refused_as_a_trade() { - // The predicate, at the measured numbers and at the edges. - assert!(lane_grow_would_narrow_the_window(5, 36_810, 3, 78_592), "the M5 loop's first step"); - assert!(lane_grow_would_narrow_the_window(4, 34_176, 3, 78_592), "and its second"); - assert!(!lane_grow_would_narrow_the_window(3, 78_592, 5, 36_810), "wider at fewer lanes is a grow-back"); - assert!(!lane_grow_would_narrow_the_window(5, 78_592, 3, 78_592), "a pure lane grow"); - assert!(!lane_grow_would_narrow_the_window(5, 70_000, 3, 78_592), "within the window tolerance (78,592 / 8)"); - assert!(!lane_grow_would_narrow_the_window(3, 31_000, 1, 2_048), "the 2k → 31k starved case grows both axes"); - assert!(!lane_grow_would_narrow_the_window(5, 36_810, 0, 0), "an unreadable served side is not a trade"); - // Fable's 45 s time series on the M5 (09:28-09:42Z): the DOWN steps are crash - // respawns under a trough budget, not this ladder (grow-only), and from any of - // them a wider plan must still climb out — lanes up or down. - assert!(!lane_grow_would_narrow_the_window(4, 34_176, 5, 36_810), "fewer lanes is never a refused trade"); - assert!(!lane_grow_would_narrow_the_window(1, 19_173, 4, 34_176)); - assert!(!lane_grow_would_narrow_the_window(3, 78_592, 1, 19_173), "out of the bottom: wider at more lanes"); - assert!(!lane_grow_would_narrow_the_window(2, 31_141, 1, 19_173), "out of the bottom: wider at more lanes"); - - // The ladder on the fake control: served 3 × 78,592, plan 5 × 36,810 → no relaunch. - let ctrl = FakeControl::probe(Ok(Some("coder-14b".into()))) - .owned() - .with_served_lanes(3) - .with_served_window(78_592); - let mut t = target("coder-14b"); - t.lanes = 5; - t.context_window = 36_810; - let outcome = ensure_model_serving(&ctrl, &t, false).await; - assert_eq!(outcome, EnsureOutcome::AlreadyServing, "a trade is refused, the lane keeps its window"); - assert_eq!(ctrl.serves.load(Ordering::SeqCst), 0, "no relaunch toward the narrower geometry"); - - // The other direction: served 5 × 36,810, plan 3 × 78,592 → relaunches (window grow-back). - let ctrl = FakeControl::probe(Ok(Some("coder-14b".into()))) - .owned() - .with_served_lanes(5) - .with_served_window(36_810); - let mut t = target("coder-14b"); - t.lanes = 3; - t.context_window = 78_592; - let outcome = ensure_model_serving(&ctrl, &t, false).await; - assert!(matches!(outcome, EnsureOutcome::Spawned { .. }), "a wider window at fewer lanes still grows, got {outcome:?}"); +async fn a_window_or_lane_change_never_relaunches_an_engine_on_the_shared_pool() { + for (served_lanes, served_window, plan_lanes, plan_window) in + [(1, 32_768, 4, 32_768), (2, 2_048, 2, 32_768), (5, 58_112, 1, 87_410), (2, 81_920, 1, 87_410)] + { + let ctrl = FakeControl::probe(Ok(Some("coder-14b".into()))) + .owned() + .launched_with_cache(1) + .with_served_lanes(served_lanes) + .with_served_window(served_window); + let mut t = target("coder-14b"); + t.lanes = plan_lanes; + t.context_window = plan_window; + let outcome = ensure_model_serving(&ctrl, &t, false).await; + assert_eq!(outcome, EnsureOutcome::AlreadyServing, "served {served_lanes} x {served_window}, plan {plan_lanes} x {plan_window}"); + assert_eq!(ctrl.serves.load(Ordering::SeqCst), 0, "served {served_lanes} x {served_window}, plan {plan_lanes} x {plan_window}"); + } } -// what this catches: the window-grow check must NOT fire on llama.cpp's 256-pad -// (served slightly BELOW target after internal rounding is normal) — only a real -// step-change grow relaunches. A served window one pad under target stays -// AlreadyServing; regression would relaunch every tick on padding noise. +// what this catches: an engine launched with fixed slots (every node before 2026-11-03) left +// on them, so its slot count still needs a relaunch to change. It moves to the shared pool by +// one relaunch; the test above proves no further one follows. #[tokio::test] -async fn padded_window_within_tolerance_does_not_relaunch() { +async fn an_engine_on_fixed_slots_moves_to_the_shared_pool_once() { let ctrl = FakeControl::probe(Ok(Some("coder-14b".into()))) .owned() - .with_served_window(32768 - 256); // one 256-pad under the 32768 target + .launched_partitioned(); let outcome = ensure_model_serving(&ctrl, &target("coder-14b"), false).await; - assert_eq!(outcome, EnsureOutcome::AlreadyServing); - assert_eq!( - ctrl.serves.load(Ordering::SeqCst), - 0, - "padding noise must not relaunch" - ); + assert!(matches!(outcome, EnsureOutcome::Spawned { .. }), "got {outcome:?}"); } // what this catches: an orphan that answers /v1/models with the RIGHT model @@ -309,36 +159,6 @@ async fn an_adopted_lane_on_last_deploys_kv_decision_relaunches_onto_this_ones() assert_eq!(ensure_model_serving(&unknown, &target("coder-14b"), false).await, EnsureOutcome::AlreadyServing); } -// what this catches (card d7294f0b, Kimi's node 2026-10-15 07:37-07:39Z): the daemon decided a -// cache re-home for an adopted lane whose --cache-ram held no measured state, and this rail -// answered AlreadyServing because it never compared the grant. With a measured state between -// the running grant and the target's, the lane relaunches; an unknown grant, or a target that -// could not hold the state either, still adopts. -#[tokio::test] -async fn an_adopted_lane_whose_cache_holds_no_state_relaunches_onto_one_that_does() { - const MIB: u64 = 1024 * 1024; - let id = "cache-grant-d7294f0b"; // its own page dir: the state samples are process-wide - let t = target(id); - crate::inference::slots::note_state_bytes(&kv_page_dir(id), 3_800 * MIB); - let starved = FakeControl::probe(Ok(Some(id.into()))).owned().launched_with_cache(3_248); - assert_eq!( - ensure_model_serving(&starved, &t, false).await, - EnsureOutcome::Spawned { model: id.into() }, - "a 3,248 MiB grant holds no 3,800 MiB state and the target's 4,096 does" - ); - assert_eq!(starved.serves.load(Ordering::SeqCst), 1); - let unknown = FakeControl::probe(Ok(Some(id.into()))).owned(); - assert_eq!(ensure_model_serving(&unknown, &t, false).await, EnsureOutcome::AlreadyServing, "no argv: an unknown grant is not a mismatch"); - let futile = ServingTarget { host_prompt_cache_mib: 3_500, ..t.clone() }; - let starved = FakeControl::probe(Ok(Some(id.into()))).owned().launched_with_cache(3_248); - assert_eq!( - ensure_model_serving(&starved, &futile, false).await, - EnsureOutcome::AlreadyServing, - "a relaunch whose grant holds no state either is not owed" - ); - assert_eq!(starved.serves.load(Ordering::SeqCst), 0); -} - // what this catches: #175 self-heal. A child WE OWN that is compute-wedged (decode // probe fails while /v1/models still 200s — the Metal-GPU-OOM poison) is normally // TRUSTED forever ("decode-verified at wait_ready, trusted thereafter, no per-tick @@ -527,7 +347,7 @@ async fn serve_failure_degrades_with_reason() { #[tokio::test] async fn a_refused_replacement_keeps_a_verified_incumbent_and_only_that() { let healthy = FakeControl::probe(Ok(Some("coder-14b".into()))) - .with_served_window(2048) + .launched_partitioned() .retirement_refused(); assert_eq!(ensure_model_serving(&healthy, &target("coder-14b"), false).await, EnsureOutcome::AlreadyServing); assert_eq!(healthy.serves.load(Ordering::SeqCst), 1, "the replacement was attempted, and refused"); diff --git a/core/continuum-engine/src/inference/planning/serving_plan.rs b/core/continuum-engine/src/inference/planning/serving_plan.rs index 7db879d014..426c2fef72 100644 --- a/core/continuum-engine/src/inference/planning/serving_plan.rs +++ b/core/continuum-engine/src/inference/planning/serving_plan.rs @@ -43,6 +43,7 @@ mod max_lanes; pub use max_lanes::*; mod plan_serving; pub use plan_serving::*; +mod pool; #[cfg(test)] mod tests; diff --git a/core/continuum-engine/src/inference/planning/serving_plan/pool.rs b/core/continuum-engine/src/inference/planning/serving_plan/pool.rs new file mode 100644 index 0000000000..85240c13bd --- /dev/null +++ b/core/continuum-engine/src/inference/planning/serving_plan/pool.rs @@ -0,0 +1,22 @@ +//! The engine's ONE shared KV pool on a budget (2026-11-03, Joel: "Slot counts should never +//! require shutdown"). Under `--kv-unified` every sequence draws on one pool, so the pool is +//! what the budget holds beside the weights and one compute buffer, not windows laid side by +//! side, and not capped at the trained window: each mind's share inside it is bounded where +//! it is published. + +use super::ModelFootprint; + +impl ModelFootprint { + /// Tokens of shared KV `usable_bytes` holds for this model: the one-lane fit without the + /// trained-window cap. 0 when the model has no measured KV cost, so nothing can be fitted. + pub fn pool_within(&self, usable_bytes: u64) -> u32 { + if self.kv_per_token == 0 { + return 0; + } + ModelFootprint { + context_window: u32::MAX, + ..self.clone() + } + .window_within(usable_bytes, 1) + } +} diff --git a/core/continuum-engine/src/inference/serving_holds.rs b/core/continuum-engine/src/inference/serving_holds.rs index e47912daae..21c2cd8d43 100644 --- a/core/continuum-engine/src/inference/serving_holds.rs +++ b/core/continuum-engine/src/inference/serving_holds.rs @@ -1,69 +1,11 @@ -//! The serving HOLDS an activity takes on the live lane: STEADY (no optional re-home while -//! an exam runs on it) and LUDICROUS (serve at Performance for a benchmark's whole run). +//! The serving HOLD an activity takes on the live lane: LUDICROUS (serve at Performance for a +//! benchmark's whole run). The STEADY hold (no re-home under an exam) went with the re-home: +//! the engine launches once and nothing relaunches it for size (2026-11-03). //! Engine facts with RAII guards: an eval in the mind takes them, the serving daemon reads //! them on its tick, and neither names the other's module. use std::sync::atomic::{AtomicUsize, Ordering}; -/// Process-global count of active "hold the live serving lane STEADY" requests. A -/// living-persona benchmark/eval runs ON the shared lane as a co-tenant decode slot — -/// `resources::placement::Placement::ShareLane` (same base already resident ⇒ no second -/// weight copy). The one thing that breaks it is a grow-back RE-HOME relaunch mid-exam: -/// it connection-refuses every in-flight generation (glass-boxed 2026-07-20: hard-rs 0/8, -/// zero output tokens, the lane bounced under the exam). While any hold is active the -/// daemon SKIPS the OPTIONAL grow-back re-home for an already-correctly-served lane. It -/// does NOT suppress a model/genome CHANGE or a pressure-driven shrink — a real resource -/// emergency still preempts (rare, correct). Zero-cost when no eval runs. -static SERVING_STEADY_HOLDS: AtomicUsize = AtomicUsize::new(0); - -/// RAII: hold the live serving lane steady (suppress the grow-back re-home) until dropped. -/// A living-persona eval binds one for its whole run — the concrete form of `ShareLane`'s -/// "pin the lane for the demand's duration" clause ([[benchmark-is-a-governor-preemption-lease]], -/// the co-tenant/steady case: no second weight copy, just don't bounce the lane). -#[must_use = "the hold releases the instant this guard drops — bind it for the eval's lifetime"] -pub struct ServingSteadyHold { - /// WHO pinned the lane — a run id, "eval", etc. Carried so the acquire and - /// release EVENTS name the holder (Joel 2026-08-08: "emit events for - /// everything — need to know"): a suppressed relaunch with no event is - /// indistinguishable from a planner that never wanted one, and a leaked - /// hold with no holder name is unattributable. - holder: String, -} - -impl ServingSteadyHold { - pub fn acquire(holder: impl Into) -> Self { - let holder = holder.into(); - let holds = SERVING_STEADY_HOLDS.fetch_add(1, Ordering::AcqRel) + 1; - continuum_base::probe!( - target: "continuum_core::modules::serving_daemon", class = "serving.lane.hold", - action = "acquired", - holder = %holder, - holds, - "serving lane pinned STEADY (optional grow-back re-home suppressed while held)" - ); - Self { holder } - } -} - -impl Drop for ServingSteadyHold { - fn drop(&mut self) { - let holds = SERVING_STEADY_HOLDS.fetch_sub(1, Ordering::AcqRel) - 1; - continuum_base::probe!( - target: "continuum_core::modules::serving_daemon", class = "serving.lane.hold", - action = "released", - holder = %self.holder, - holds, - "serving lane steady-hold released" - ); - } -} - -/// True while at least one caller holds the live lane steady — the reconcile's grow-back -/// re-home is suppressed for an already-correctly-served lane. -pub fn serving_held_steady() -> bool { - SERVING_STEADY_HOLDS.load(Ordering::Acquire) > 0 -} - /// LUDICROUS mode (Joel 2026-07-21: "extreme mode for benchmarks or ludicrous lol"). A /// benchmark / project / "the fight" wants the biggest window the model+machine can give — /// not the timid pressure-derived fraction. While any caller holds this, the serving daemon's `host_budget` diff --git a/core/continuum-serving/src/modules/serving_daemon.rs b/core/continuum-serving/src/modules/serving_daemon.rs index a357da4355..15cb7c762c 100644 --- a/core/continuum-serving/src/modules/serving_daemon.rs +++ b/core/continuum-serving/src/modules/serving_daemon.rs @@ -348,46 +348,11 @@ pub struct ServingDaemonModule { /// asked for divides every mind's window for nothing (the 4-slots-for-2- /// personas starvation, 2026-07-10). Default 1 — window-first. lane_demand: Arc, - /// Consecutive ticks the PLAN has exceeded the live lane by at least - /// [`REHOME_MIN_GAIN_PCT`]. Reset the moment it does not. Sustained-ness is - /// what separates a real capacity change from memory jitter — see - /// [`REHOME_SUSTAINED_TICKS`]. - rehome_streak: Arc, - /// Consecutive ticks a sustained re-home has been deferred by a steady hold. - rehome_held_ticks: Arc, - /// The host's swap-in-use at the last grow decision (card 628dc958): a grow-back - /// re-home is refused while this is rising. `u64::MAX` = no reading yet. - last_swap_used: Arc, - /// How many CONSECUTIVE ticks the lane has been below plan while declining to - /// re-home — a clock for the decline probe's cadence and nothing else. - /// - /// It exists because #3751 tried to throttle that probe off `rehome_streak` - /// and silently did not throttle at all. `rehome_streak` counts consecutive - /// ticks of a QUALIFYING GAIN; the declined state is precisely the state where - /// no gain qualifies, so it is pinned at 0 for the whole episode and - /// `streak <= 1` stayed true forever. Measured after that "fix" merged: 411 - /// identical lines, one per 5 s tick. A domain counter is not a logging clock — - /// its reset rule belongs to the domain, and here the domain resets it exactly - /// when we wanted it to count. - decline_log_ticks: Arc, - /// The highest plan window seen in the current re-home streak (0 = none yet). - /// "Sustained" requires the plan to have stopped CLIMBING: a new high resets - /// the streak, so the boot staircase coalesces into one relaunch at its top. - /// A plan that only alternates below a high it already reached is settled - /// enough: both values want the bigger lane (2026-10-07: a lane at 2,304 under - /// a plan alternating 33k/70k never re-homed for an hour, because every rise - /// reset the streak). - rehome_plan_high: Arc, - /// The last [`REHOME_SUSTAINED_TICKS`] plan windows the re-home decision saw: the span of - /// evidence a streak needs. A re-home fires at the best of THESE, not at the streak's - /// all-time high, so one transient high cannot make the fire tick unreachable (see - /// [`at_recent_plan_high`]). - rehome_recent_plans: Arc>>, /// L10 (#438): consecutive plan ticks wanting a DIFFERENT base model than the /// ready incumbent, and which model that was. A model swap re-homes every - /// persona to different weights, so it earns the same sustained-streak bar as - /// the window re-home above — a one-tick nothing-fits fallback (bogus + /// persona to different weights, so it must persist for + /// [`MODEL_CHANGE_SUSTAINED_TICKS`] — a one-tick nothing-fits fallback (bogus /// usable_bytes sample) must never actuate a swap. model_change_streak: Arc, pending_model_change: Arc>>, @@ -407,16 +372,6 @@ pub struct ServingDaemonModule { /// minutes and made every incident archeological (#399). Steady state is /// now silence; the live value stays queryable on demand via `serving/plan`. last_plan_probe: Arc>>, - /// Ticks remaining before another window re-home may fire. Charged to - /// [`REHOME_COOLDOWN_TICKS`] when one fires, decremented every reconcile. - /// Counted in ticks rather than wall-clock deliberately: the rate limit is on - /// the daemon's own decision cadence, so it stays exact under a stopped clock, - /// a suspended host, or a test that drives ticks by hand. - rehome_cooldown: Arc, - /// The `ready_verified_at_ms` stamp of the launch the reconcile last settled on. A - /// stamp it has not seen is a lane that just came READY, and a launch settles AFTER - /// it is ready — see [`ready_edge`]. 0 = none yet. - settled_ready_at_ms: Arc, /// The hold live work puts on the engine, as last published ([`hold`]): kept here, not read /// back from the snapshot, because other publishers replace the snapshot whole, and the /// hold's start must survive them. @@ -582,18 +537,8 @@ impl ServingDaemonModule { pin_store, intent, lane_demand: Arc::new(std::sync::atomic::AtomicU32::new(1)), - rehome_streak: Arc::new(std::sync::atomic::AtomicU32::new(0)), - rehome_held_ticks: Arc::new(std::sync::atomic::AtomicU32::new(0)), - last_swap_used: Arc::new(std::sync::atomic::AtomicU64::new(u64::MAX)), // MAX = no reading yet: unknown is never "rising" - decline_log_ticks: Arc::new(std::sync::atomic::AtomicU32::new(0)), - rehome_plan_high: Arc::new(std::sync::atomic::AtomicU64::new(0)), // 0 = no plan seen in this streak yet - rehome_recent_plans: Arc::new(parking_lot::Mutex::new( - std::collections::VecDeque::new(), - )), model_change_streak: Arc::new(std::sync::atomic::AtomicU32::new(0)), pending_model_change: Arc::new(std::sync::Mutex::new(None)), - rehome_cooldown: Arc::new(std::sync::atomic::AtomicU32::new(0)), - settled_ready_at_ms: Arc::new(std::sync::atomic::AtomicU64::new(0)), serving_hold: Arc::new(parking_lot::Mutex::new(None)), downshift_streak: Arc::new(std::sync::atomic::AtomicU32::new(0)), last_plan_probe: Arc::new(std::sync::Mutex::new(None)), @@ -621,15 +566,12 @@ impl ServingDaemonModule { mod policy; use policy::{ - at_recent_plan_high, below_floor_refuses, decline_should_log, downshift_gate, floor_gate, - grow_refused_while_paging, hold_overridden_by_shortfall, host_floor_of, - incumbent_adoption_plan, incumbent_for_plan, lane_over_its_knee, model_change_gate, - rehome_gain_evidence, roster_short_of_slots, DownshiftVerdict, ModelChangeGate, - DOWNSHIFT_SUSTAINED_TICKS, REHOME_COOLDOWN_TICKS, REHOME_HOLD_DEFER_TICKS, - REHOME_HOLD_OVERRIDE_PCT, REHOME_MIN_GAIN_PCT, REHOME_SUSTAINED_TICKS, + below_floor_refuses, downshift_gate, floor_gate, host_floor_of, incumbent_adoption_plan, + incumbent_for_plan, model_change_gate, DownshiftVerdict, ModelChangeGate, + DOWNSHIFT_SUSTAINED_TICKS, MODEL_CHANGE_SUSTAINED_TICKS, }; pub use policy::{ - knee_model, ready_edge, settles_this_tick, FloorVerdict, COLD_BOOT_BELOW_FLOOR_GRACE, + knee_model, FloorVerdict, COLD_BOOT_BELOW_FLOOR_GRACE, }; mod health; use health::FrozenSlots; @@ -639,7 +581,7 @@ mod publication; #[cfg(test)] use publication::SERVING_SNAPSHOT_EVENT; pub use publication::{published_lanes, VerifiedServingCapture}; -use publication::{snapshot_from_outcome, verified_capture}; +use publication::{seated_share, snapshot_from_outcome, verified_capture}; mod placement; pub use placement::sidecar_window_for_headroom; use placement::{ @@ -672,9 +614,9 @@ pub use budget::{governed_host_budget, live_host_budget, perf_cores, physical_us #[cfg(test)] use budget::{lane_admission_decision, pin_fit_decision}; pub use crate::inference::llama_server::serving_pool_kind; -use crate::inference::serving_holds::{serving_held_steady, serving_ludicrous_active}; +use crate::inference::serving_holds::serving_ludicrous_active; #[cfg(test)] -use crate::inference::serving_holds::{ServingLudicrousHold, ServingSteadyHold}; +use crate::inference::serving_holds::ServingLudicrousHold; mod device_budget; #[cfg(test)] diff --git a/core/continuum-serving/src/modules/serving_daemon/demand.rs b/core/continuum-serving/src/modules/serving_daemon/demand.rs index ab05bbb8af..a0733ce0dd 100644 --- a/core/continuum-serving/src/modules/serving_daemon/demand.rs +++ b/core/continuum-serving/src/modules/serving_daemon/demand.rs @@ -68,6 +68,17 @@ impl ServingDaemonModule { self.lane_demand.load(Ordering::Relaxed).max(1) } + /// The minds seated on this node's shared pool: the population floor, or the live roster + /// when it has grown past it. The floor holds while the live count flickers below it + /// (it read 2, 3 and 4 of four residents on the M5 2026-11-03), so a mind's share moves + /// when the population does and not when a registry read races a respawn. + pub(super) fn seated(&self) -> u32 { + let live = crate::persona::airc_runtime_registry::PersonaAircRuntimeRegistry::try_global() + .map(|r| r.live_personas().len()) + .unwrap_or(0); // JUSTIFIED unwrap_or: no registry yet (boot) = no live roster; the floor stands + self.lane_demand().max(u32::try_from(live).unwrap_or(u32::MAX)) // unwrap_or: a roster past u32 is seated at the most a u32 counts + } + /// Both axes of what this host's minds are asking for — lanes AND the window /// they have actually demanded. The window term is MEASURED /// ([`crate::cognition::working_set`]); `None` there means no turn has been diff --git a/core/continuum-serving/src/modules/serving_daemon/launch.rs b/core/continuum-serving/src/modules/serving_daemon/launch.rs index 579bcfd672..26cbb5213c 100644 --- a/core/continuum-serving/src/modules/serving_daemon/launch.rs +++ b/core/continuum-serving/src/modules/serving_daemon/launch.rs @@ -16,6 +16,23 @@ pub(super) struct ReconcileLaunch { } impl ServingDaemonModule { + /// The engine's one KV pool, sized ONCE when the engine starts and never by a relaunch: + /// every token this host's budget holds beside the weights and one compute buffer, laid out + /// as a sequence for each seated mind plus the scratch traffic beside them, `(per-sequence + /// tokens, sequences)` so `-c` is the pool and `--parallel` the ceiling. Sized from the plan + /// it would have been 1 x 80k on a cold boot that counted two residents (the M5, 2026-11-03 + /// 00:52Z). A model with no measured footprint has no budget fit, so its pool is the plan's + /// windows side by side: a fit, not a constant. + fn engine_pool(&self, model: &crate::model_registry::types::Model, served_ctx: u32, lanes: u32) -> (u32, u32) { + let sequences = self.seated().saturating_add(1).max(lanes); + let fitted = footprint_for(model).map(|fp| fp.pool_within(self.physical_budget().usable_bytes)); + let pool = match fitted.filter(|tokens| *tokens > 0) { + Some(tokens) => tokens, + None => served_ctx.saturating_mul(lanes.max(1)), + }; + (pool / sequences, sequences) + } + pub(super) fn launch_reconciled_plan(&self, launch: ReconcileLaunch) -> Option> { let ReconcileLaunch { operation, @@ -118,11 +135,13 @@ impl ServingDaemonModule { // separates "a bit small" from "structurally cannot cache anything". let one_conversation_mib = prompt_cache.one_conversation_mib; let host_prompt_cache_mib = prompt_cache.mib; + let (per_sequence, sequences) = self.engine_pool(&model, served_ctx, lanes); + let seated = self.seated(); let target = ServingTarget { host_prompt_cache_mib, model, - context_window: served_ctx, - lanes, + context_window: per_sequence, + lanes: sequences, adapters: desired_adapters, // The living persona lane: GPU-resident for throughput (every // offloadable layer). [[LanePlacement]]. @@ -148,7 +167,7 @@ impl ServingDaemonModule { plan_lanes = lanes, plan_window = served_ctx, host_prompt_cache_mib, - "reconcile launch requested from this plan; engine convergence may retain incumbent geometry", + "reconcile launch requested from this plan: the engine relaunches only for a different model, genome, sight, KV decision, binary or a cache not yet on the shared pool", ); let served_resident = self.served_resident.clone(); let division = self.division.clone(); @@ -175,7 +194,6 @@ impl ServingDaemonModule { let persona_floor: Option = self.serving_demand().typical_prompt_floor(); let last_healthy_window = self.last_healthy_window.clone(); let last_healthy_lanes = self.last_healthy_lanes.clone(); - let rehome_cooldown = self.rehome_cooldown.clone(); // ARM the discrete footprint arm's baseline: every tick until the lane is ready // lowers it to the sampled trough (see the field doc — a single read here sees // the dying predecessor). @@ -241,22 +259,6 @@ impl ServingDaemonModule { return; } force_probe.pending = false; - // EVERY LAUNCH GETS THE SETTLE WINDOW A RE-HOME GETS (9/18, the mirror): the - // cooldown was armed only at the re-home fire point, so a boot's first spawn - // could be re-homed 40 s later by its own load transient (the weights counted - // as external before the ledger credited them — 8 lanes declined at tick 1, - // re-homed at tick 3). A lane just launched is not evidence against itself. - if matches!(outcome, EnsureOutcome::Spawned { .. }) { - rehome_cooldown.store(REHOME_COOLDOWN_TICKS, Ordering::Relaxed); - continuum_base::probe!( - target: "continuum_core::modules::serving_daemon", class = "serving.reconcile.window", - decision = "spawn-settling", - plan_lanes = target.lanes, - plan_window = target.context_window, - cooling = REHOME_COOLDOWN_TICKS as u64, - "a fresh launch settles for the same cooldown a re-home gets before any re-home evidence counts" - ); - } // For a ready outcome, read the REAL per-slot window the running // server serves from its own `/props` — the authoritative model // metadata every persona budgets its prompt to. llama.cpp pads the @@ -317,6 +319,14 @@ impl ServingDaemonModule { } EnsureOutcome::Degraded { .. } | EnsureOutcome::Superseded => 0, }; + // ONE SHARED POOL: the engine's `/props` names the whole pool as each sequence's + // window and its sequence ceiling as its slots; every seated mind is published her + // share of it (`seated_share`), so what the readers budget and charge is the pool. + let (served_window, served_lanes) = if served_window > 0 { + seated_share(served_window, seated, target.model.context_window) + } else { + (served_window, served_lanes) + }; // The grant the engine was LAUNCHED with: the spawn fact on the control, or — for // a lane this core did not spawn (ADOPTED; every deploy leaves the lane up for // the next core, so this is the common case, not the rare one) — read off the diff --git a/core/continuum-serving/src/modules/serving_daemon/policy.rs b/core/continuum-serving/src/modules/serving_daemon/policy.rs index 942c4163f8..9d29c2eddf 100644 --- a/core/continuum-serving/src/modules/serving_daemon/policy.rs +++ b/core/continuum-serving/src/modules/serving_daemon/policy.rs @@ -2,53 +2,9 @@ use super::*; -/// The margin, in percent, by which the plan must exceed the LIVE lane before a -/// re-home is worth killing in-flight turns for. -/// -/// RELATIVE, not absolute: the same 2048-token shortfall is a third of a small -/// lane and noise on a large one, so an absolute bar means something different at -/// every window size. -/// -/// MEASURED against 6,322 live `serving.plan` samples (probes.jsonl, 2026-08-06), -/// after BigMama flagged that she had proposed 15% from the shape of the problem -/// with no data behind it: consecutive-sample plan jitter runs p50 0%, p90 1%, with -/// a fat tail (p99 22%, max 106%). 15% sits an order of magnitude above the p90 -/// noise floor while staying far under the 60% shortfall of the real incident. -/// -/// Note which parameter is actually load-bearing, because it is NOT this one: at a -/// 10%, 15% OR 20% bar the longest run of consecutive qualifying rises in the whole -/// sample was 2. The jitter tail is a SPIKE, not a sustained climb, so -/// [`REHOME_SUSTAINED_TICKS`] is what rejects it and this margin only has to clear -/// the p90. Widen it only with evidence; loosening the tick count is the change that -/// would actually let noise through. -pub(super) const REHOME_MIN_GAIN_PCT: u32 = 15; -/// A steady hold (an eval, a detached solve) suppresses the OPTIONAL grow-back — a -/// re-home that would buy a few percent is not worth dropping a held slot for. It does -/// not get to pin a lane serving at a FRACTION of its plan: measured 2026-09-17 07:5xZ -/// on the M5, the boot plan came up 8 lanes × 12,800 under the outgoing server's memory -/// (card 40f53419), the plan wanted 3 × 67,340, and four re-fired control solves held -/// the lane steady for 255 ticks in a row — every one of the 16 minds, the solves -/// included, on a 12.8k window because the solves were "protecting" it. Past this gain -/// the re-home goes ahead and the probe says so; the held work retries its flickered -/// act (the deliberation retry budget exists for exactly one relaunch). -pub(super) const REHOME_HOLD_OVERRIDE_PCT: u32 = 75; -/// A hold DELAYS a smaller re-home, it never denies it: after this many consecutive -/// held ticks (5 s each — about one act of held work) a sustained re-home goes ahead -/// anyway. Measured 2026-09-17 08:3xZ: with the window restored the knee moved 3 → 4 -/// and the plan wanted a fourth lane (+33%, under the override), and the re-fired -/// solves' hold kept 16 minds on 3 lanes — the health line read STARVED for an hour -/// while the planner "owed lanes" it had already planned. -pub(super) const REHOME_HOLD_DEFER_TICKS: u32 = 24; - -/// How many consecutive ticks the plan must exceed the lane by -/// [`REHOME_MIN_GAIN_PCT`] before a re-home is justified. -/// -/// Sustained-ness is the anti-thrash property the old single-sample `live * 2 <= -/// plan` ratio was reaching for, stated directly — and it is deliberately SHORT. -/// It is not what limits the relaunch RATE (that is [`REHOME_COOLDOWN_TICKS`], -/// enforced independently below); it only has to outlast jitter. -/// -/// THE load-bearing parameter, and measured as such: across 6,322 live +/// How many consecutive ticks a plan must name a DIFFERENT model before a ready lane +/// swaps to it (the window and lane re-home this once also gated is gone: one launch, +/// 2026-11-03). It only has to outlast jitter, measured on the plan itself: across 6,322 live /// `serving.plan` samples (probes.jsonl, 2026-08-06) the longest run of consecutive /// qualifying rises was **2**, at a 10%, 15% or 20% margin alike — zero runs of 3 in /// the entire sample. Real plan jitter spikes for a sample or two and falls back; it @@ -59,111 +15,7 @@ pub(super) const REHOME_HOLD_DEFER_TICKS: u32 = 24; /// /// Lowering this to 2 re-admits the entire measured jitter tail. Do not, without /// re-running that measurement against fresher receipts. -pub(super) const REHOME_SUSTAINED_TICKS: u32 = 3; - -/// PURE: record `plan` among the last [`REHOME_SUSTAINED_TICKS`] plans and answer whether it is -/// their high. Bounded by the evidence span, so a high ages out with the evidence it came from -/// and a settled plan's own best tick is always reachable. -pub(super) fn at_recent_plan_high(recent: &mut std::collections::VecDeque, plan: u64) -> bool { - recent.push_back(plan); - while recent.len() > REHOME_SUSTAINED_TICKS as usize { - recent.pop_front(); - } - recent.iter().all(|&seen| plan >= seen) -} - -/// One line per 5 s tick makes the decline probe the defect at the other end, so -/// it speaks on ENTRY and roughly once a minute thereafter. -/// -/// `ticks` MUST be a counter that advances for each consecutive declined tick. -/// Returning false for 0 is deliberate: it makes "the clock never advanced" mean -/// SILENCE rather than "log forever", which is the exact failure #3751 shipped. -pub(super) const DECLINE_LOG_EVERY_TICKS: u32 = 12; // 5 s ticks -> ~1/min -pub(super) fn decline_should_log(ticks: u32) -> bool { - ticks == 1 || (ticks > 0 && ticks % DECLINE_LOG_EVERY_TICKS == 0) -} - -/// Re-home evidence: `(live_space, plan_space, gain, worth_it)` in TOTAL -/// token-space (window × lanes) — never the per-slot window alone. -/// -/// Measured live 2026-09-01: the plan moved to 4 lanes × 47,426 while the -/// running server held 2 × 57,600 — 65% more total space and two more warm -/// slots, but the per-slot window SHRANK, so a window-only gain was negative -/// and the relaunch never fired. Five residents thrashed two slots at -/// hit_rate 0.0 until an operator cycled the server by hand. Lane count must -/// be part of the evidence -/// ([[the-same-bug-at-two-sites-is-a-missing-constraint-not-two-bugs]]). -/// -/// Integer arithmetic that cannot overflow: u64 space on a 1M-token × 8-lane -/// server is ~8e6; ×100 still fits comfortably. -/// A steady hold yields when the plan's space exceeds the live space by -/// [`REHOME_HOLD_OVERRIDE_PCT`] or more — the hold protects a slot, never a starvation. -pub(super) fn hold_overridden_by_shortfall(live_space: u64, gain: u64) -> bool { - live_space > 0 - && gain.saturating_mul(100) >= live_space.saturating_mul(REHOME_HOLD_OVERRIDE_PCT as u64) -} - -pub(super) fn rehome_gain_evidence( - live_window: u32, - live_lanes: u32, - plan_window: u32, - plan_lanes: u32, -) -> (u64, u64, u64, bool) { - let live_space = (live_window as u64).saturating_mul(live_lanes.max(1) as u64); - let plan_space = (plan_window as u64).saturating_mul(plan_lanes.max(1) as u64); - let gain = plan_space.saturating_sub(live_space); - let worth_it = live_space > 0 - && (gain.saturating_mul(100) >= live_space.saturating_mul(REHOME_MIN_GAIN_PCT as u64) - || lane_over_its_knee(live_window, live_lanes, plan_window, plan_lanes)); - (live_space, plan_space, gain, worth_it) -} - -/// The plan trades LANES for WIDTH: fewer slots, each at least as wide. That is the -/// decode knee clamping the roster (`inference::decode_knee`) — the live lane is -/// serving MORE streams than the box decodes at speed, every stream is slow, and the -/// only cure is a relaunch at the knee. Token-space says such a plan is "not a gain" -/// (8 × 51,712 → 7 × 67,340 is +14%, under the margin; → 4 × 67,340 is a LOSS), so -/// without this arm the knee only ever took effect at boot: measured 2026-09-17, the -/// M5 sat at 8 lanes / 7.9 t/s per stream all morning while the knee read 7 and the -/// reconcile declined every tick on the margin. The sustain streak and the cooldown -/// still gate the relaunch; this only makes a knee shrink COUNT as evidence. -pub(super) fn lane_over_its_knee( - live_window: u32, - live_lanes: u32, - plan_window: u32, - plan_lanes: u32, -) -> bool { - live_lanes > 0 && plan_lanes > 0 && plan_lanes < live_lanes && plan_window >= live_window -} - -/// The knee's mirror: the plan wants MORE warm slots than the live lane serves. The plan -/// never asks for more lanes than the roster demands (`lane_cap` is the demand, then the -/// fit), so a plan with more lanes than are live is minds WITHOUT a warm slot — the #266 -/// shape: every turn of an unslotted mind re-prefills cold. Token-space calls such a plan -/// a wash or a loss (measured 2026-09-19 15:4xZ, the M5: a cold boot launched 1 × 161,792 -/// under a transient 44 GB budget; the steady plan said 2 × 67,340 — 17% LESS space — -/// and the reconcile declined it every tick, so a second coder lane could never appear -/// at runtime, and the settled 1-lane geometry then capped the next boot: a one-way -/// ratchet with no mover the other way). The sustain streak, the flat-plan check and the -/// cooldown still gate the relaunch; this only makes a slot shortfall COUNT as evidence. -/// A plan may shrink while the host pages out; it never grows into it. A grow is more -/// KV space than the lane holds; paging out is swap rising since the last decision. -/// `swap_prev == u64::MAX` is "no previous reading" and never reads as rising. The swap -/// LEVEL is not a term (Cormac on #4415): a page in swap already gave up its RAM, so -/// `available` reflects it, and macOS keeps idle pages swapped for hours after the -/// pressure is gone — subtracting the level would under-plan by the whole residue. -pub(super) fn grow_refused_while_paging( - live_space: u64, - plan_space: u64, - swap_prev: u64, - swap_now: u64, -) -> bool { - plan_space > live_space && swap_prev != u64::MAX && swap_now > swap_prev -} - -pub(super) fn roster_short_of_slots(live_lanes: u32, plan_lanes: u32) -> bool { - live_lanes > 0 && plan_lanes > live_lanes -} +pub(super) const MODEL_CHANGE_SUSTAINED_TICKS: u32 = 3; /// Consecutive plan ticks a base-model DOWNSHIFT must persist before it is /// adopted. #368 (2nd occurrence, 2026-08-08): a ~6-second RAM transient at @@ -177,18 +29,6 @@ pub(super) fn roster_short_of_slots(live_lanes: u32, plan_lanes: u32) -> bool { /// [[never-thrash-sticky-hysteresis-on-every-lane]] pub(super) const DOWNSHIFT_SUSTAINED_TICKS: u32 = 3; -/// Ticks a re-home must wait before another may fire, enforced INDEPENDENTLY of -/// the sustained-delta test above. -/// -/// The two guards answer different questions and must not be collapsed into one: -/// sustained-delta asks "is this gain real?", the cooldown asks "may we pay for it -/// yet?". A relaunch kills every in-flight turn on the lane, so the rate limit has -/// to hold even when the evidence is perfect. Anchored to a lane's own readiness -/// budget ([`READY_TIMEOUT`], 90s) in ticks: never start a second re-home before -/// the first could possibly have come up and proven itself. -/// [[never-thrash-sticky-hysteresis-on-every-lane]] -pub(super) const REHOME_COOLDOWN_TICKS: u32 = (READY_TIMEOUT.as_secs() / TICK.as_secs()) as u32; - /// Which model the plan should treat as the incumbent, given what we have already PUBLISHED and /// what we INHERITED from a previous generation of this core. /// @@ -256,27 +96,6 @@ pub(super) fn model_change_gate( } } -/// THE LANE DEMAND IS THE LIVE ROSTER (2026-09-14). `set_lane_demand` runs once at -/// boot with the persona floor and is a no-op afterwards, so a roster that grows to 16 -/// after the decode-ready edge kept planning for the floor: measured 16 resident minds -/// on 3 lanes (2 + scratch) with 40 GB of KV budget idle, a lane every ~20 min per -/// mind, and the "let me take stock" loops that come from re-orienting every turn. -/// The roster is the demand; the boot floor is only its lower bound; a measurement -/// lease still wins while it is held. -/// The tick on which a launch SETTLES: its spawn cooldown reaches zero on this tick with -/// the lane ready and serving. Only a settled geometry is remembered for the next boot. -pub fn settles_this_tick(cooling_before: u32, ready: bool, lanes: u32) -> bool { - cooling_before == 1 && ready && lanes > 0 -} - -/// PURE: has a launch just come READY that the reconcile has not settled on? `settled` is -/// the ready stamp last settled on (0 = none); `now` is the live snapshot's stamp (`None` = -/// not ready). A stamp not seen before is a new launch and re-arms the settle cooldown; -/// the same stamp again, or no stamp, is not. -pub fn ready_edge(settled: u64, now: Option) -> bool { - matches!(now, Some(t) if t != settled) -} - /// The model whose decode knee bounds the plan: the one a lane is serving, else the one /// this box served last (card 29e4ab34 — the boot window before a lane reports its model /// is not "no knee", it is the remembered model's knee). `remembered` is read lazily: it diff --git a/core/continuum-serving/src/modules/serving_daemon/publication.rs b/core/continuum-serving/src/modules/serving_daemon/publication.rs index 1e0de77323..d1e345d693 100644 --- a/core/continuum-serving/src/modules/serving_daemon/publication.rs +++ b/core/continuum-serving/src/modules/serving_daemon/publication.rs @@ -31,8 +31,8 @@ pub(super) fn verified_capture( let launch = server.owned_serving_target()?; if snapshot.active_model.as_deref() != Some(launch.target.model.id.as_str()) || snapshot.adapters != launch.target.adapter_paths() - || snapshot.served_context_window != launch.observed_context_window - || snapshot.lanes != launch.observed_lanes + || (snapshot.served_context_window, snapshot.lanes) + != seated_share(launch.observed_context_window, snapshot.lanes, launch.target.model.context_window) || snapshot.host_prompt_cache_mib != launch.launched_host_prompt_cache_mib || server.owned_engine()? != launch.identity { @@ -53,6 +53,20 @@ pub fn published_lanes(served: Option, target_lanes: u32) -> u32 { served.filter(|n| *n > 0).unwrap_or(target_lanes) } +/// PURE: each seated mind's window inside the engine's one shared pool, and the minds that +/// share it. Under `--kv-unified` the engine's `/props` names the whole pool as every +/// sequence's window; a mind is published her share, capped at the model's trained window, +/// so every reader that charges `lanes x window` charges the pool. The seated count is the +/// node's population, not the plan's per-tick guess (which read 1, 2 and 3 of four residents +/// on the M5 2026-11-03 and relaunched the engine at each). +/// +/// Every seated mind may fill her share at once only with no room for scratch traffic +/// beside them; per-mind grants from demand (#5718's contract) replace this equal share. +pub fn seated_share(served_pool: u32, seated: u32, trained_window: u32) -> (u32, u32) { + let seated = seated.max(1); + ((served_pool / seated).min(trained_window), seated) +} + pub(super) fn snapshot_from_outcome( outcome: &EnsureOutcome, desired: &str, diff --git a/core/continuum-serving/src/modules/serving_daemon/reconcile.rs b/core/continuum-serving/src/modules/serving_daemon/reconcile.rs index 4c6c6cafe4..13261a7ac2 100644 --- a/core/continuum-serving/src/modules/serving_daemon/reconcile.rs +++ b/core/continuum-serving/src/modules/serving_daemon/reconcile.rs @@ -87,12 +87,6 @@ impl ServingDaemonModule { /// against together, so a stale high can never make a later climb read as flat. - pub(super) fn reset_rehome_streak(&self) { - self.rehome_streak.store(0, Ordering::Relaxed); - - self.rehome_plan_high.store(0, Ordering::Relaxed); - } - pub(super) fn reconcile_to_plan(&self) -> Option> { let operation = match ServingOperation::acquire( self.reconciling.clone(), @@ -197,7 +191,6 @@ impl ServingDaemonModule { ); } else { self.model_change_streak.store(0, Ordering::Relaxed); - self.reset_rehome_streak(); self.downshift_streak.store(0, Ordering::Relaxed); *self .pending_model_change @@ -320,410 +313,29 @@ impl ServingDaemonModule { { let live = self.serving_tx.borrow(); - // Already serving the right model AND the right genome set → no - // relaunch. The genome comparison is what makes a freshly-trained gene - // take effect: same model id + new gene = set change = relaunch. + // Already serving the right model AND the right genome set: nothing relaunches. + // ONE LAUNCH (2026-11-03, Joel: "Slot counts should never require shutdown"): the + // engine holds one shared pool sized once, so a plan that wants a wider window or + // more lanes is not a relaunch. The re-home ladder that lived here (sustained + // streaks, cooldowns, plan highs, holds, the cache-size re-home) relaunched the + // M5's engine 40 times. What changes at runtime is each seated mind's share: when + // the population moves, the launch path republishes it (an AlreadyServing ensure). if live.ready && live.active_model.as_deref() == Some(desired.as_str()) && live.adapters == desired_adapter_paths + && live.lanes == self.seated() { - // …UNLESS the running server's per-slot window froze at HALF or - // less of what the current plan affords. A lane spawned under - // transient memory pressure (a benchmark server, a build) keeps - // its starved window forever otherwise — glass-boxed 2026-07-10: - // 14,700 recomputes wandering 3.6k↔22k while the living lane - // stayed frozen at 3.8k and the room degenerated into a greeting - // loop. 2× is deliberate hysteresis (doubling rule): the plan - // breathes with every consumer, and a relaunch kills in-flight - // turns, so only a step-change worth of headroom justifies one. - // One-directional by design — over-served vs a dipped plan is - // the pressure broker's reclaim problem (#79), not a relaunch. - // SUSTAINED-DELTA re-home (replaces the single-sample `live * 2 <= - // plan` ratio; BigMama's call 2026-08-06, she owns the guard). - // - // The old ratio was the cheapest thing that could not thrash against a - // plan derived from FREE MEMORY, which wandered 3.6k<->22k — its own - // comment says "the plan breathes with every consumer", and that was - // true. Demand-derived planning made the plan a peak-tracking - // MEASUREMENT instead, and against a stable signal a 2x bar strands - // everything in the 50-99% band forever: measured live, plan 26,323 vs - // lane 16,384 (62%) held indefinitely while every persona's binding - // read the stale window. - // - // TWO independent guards, deliberately not collapsed into one - // predicate: - // - // 1. SUSTAINED DELTA — is the gain REAL? The plan must exceed the - // lane by [`REHOME_MIN_GAIN_PCT`] for [`REHOME_SUSTAINED_TICKS`] - // consecutive ticks. A dip RESETS the streak, so jitter can never - // accumulate into a relaunch. - // 2. COOLDOWN — may we PAY for it yet? At most one re-home per - // [`REHOME_COOLDOWN_TICKS`], checked separately and answered - // first. A relaunch kills every in-flight turn on the lane, so - // the rate limit must hold even when the evidence is perfect. - // - // Conflating them is how a guard ends up firing on a burst of good - // evidence. (BigMama's spec 2026-08-06 — she owns this guard; the - // outage it came from is hers.) - // A LAUNCH SETTLES AFTER IT IS READY, NOT AFTER IT WAS SPAWNED (2026-09-19 - // 23:13–23:15Z, the M5): the spawn arm charged the cooldown at launch, the - // OLD lane kept serving through the 27B's ~90 s cold load, so every tick of - // the cooldown was spent before the new lane answered — it came ready with - // zero settle left. Its predecessor's freed pages read as a 32 GB budget for - // one minute, the plan said 3 lanes, and a second relaunch fired 15 s after - // the first came ready: 12 settles in the hour, acts 5. The ready stamp is - // the edge that matters: a stamp this reconcile has not settled on re-arms - // the full cooldown (and the streak), so the memory picture the next - // evidence is read from is the one this lane made, not the one it inherited. - if ready_edge( - self.settled_ready_at_ms.load(Ordering::Relaxed), - live.ready_verified_at_ms, - ) { - self.settled_ready_at_ms - .store(live.ready_verified_at_ms.unwrap_or(0), Ordering::Relaxed); // JUSTIFIED unwrap_or: `ready_edge` is true only for Some - self.rehome_cooldown - .store(REHOME_COOLDOWN_TICKS, Ordering::Relaxed); - self.reset_rehome_streak(); - continuum_base::probe!( - target: "continuum_core::modules::serving_daemon", class = "serving.reconcile.window", - decision = "ready-settling", - live_window = live.served_context_window, - live_lanes = live.lanes, - cooling = REHOME_COOLDOWN_TICKS as u64, - "the lane just came ready — it settles for the full cooldown from HERE before any re-home evidence counts" - ); - } - let cooling = self.rehome_cooldown.load(Ordering::Relaxed); - if cooling > 0 { - self.rehome_cooldown.store(cooling - 1, Ordering::Relaxed); - // Lose the streak while cooling rather than banking it: otherwise - // the instant the cooldown lapses we relaunch on evidence gathered - // a minute and a half ago. Re-proving costs 3 ticks and keeps - // "sustained" meaning sustained-NOW. - self.reset_rehome_streak(); - } - // Settlement records an owned candidate. Only terminal usage from this - // exact generation promotes its cache preference; neither transition - // constrains the next plan's lanes or current workload requirement. - let settled_now = settles_this_tick(cooling, live.ready, live.lanes); - if let Some(model) = live.active_model.as_deref() { - let endpoint = crate::ai::openai_endpoints::OpenAiBase::new(&live.base_url); - if let Some(geometry) = crate::inference::slots::directory() - .endpoint(endpoint.root()) - .served_geometry() - .filter(|g| { - g.model_id == model - && g.per_slot_window == live.served_context_window - && g.lanes == live.lanes - }) - { - let observed = crate::inference::resource_admission::PromptSample::geometry_median( - &(self.leased_in_sent)(), - endpoint.root(), - &geometry, - ); - crate::inference::served_window_store::record_reconciled( - geometry, - settled_now, - observed, - ); - } - if settled_now { - // A settled geometry is lanes the hour served: fold it into the - // health window's maximum (the lane-bound rest stands on that). - crate::cognition::health_ledger::note_lanes(live.lanes as u64); - continuum_base::probe!( - target: "continuum_core::modules::serving_daemon", class = "serving.geometry.settled", - model, - per_slot_window = live.served_context_window as u64, - lanes = live.lanes as u64, - "the launch settled — same-generation successful usage may record its cache preference" - ); - } - } - let (live_space, plan_space, gain, worth_it) = - rehome_gain_evidence(live.served_context_window, live.lanes, served_ctx, lanes); - let short_of_slots = roster_short_of_slots(live.lanes, lanes); - // THE CACHE HOLDS NO STATE (Fable and BigMama, 2026-10-11): `--cache-ram` is fixed - // at launch, so a lane launched under a cache smaller than ONE measured state can - // keep nothing, and every switch between minds is a full re-prefill until it - // relaunches (the 5090: 4,288 MiB against ~5.5 GB states, 114 skips, 76% of - // restores cold). That, and only that, is evidence for a re-home on cache size; - // a cache that holds at least one state waits for the next relaunch. It earns the - // same sustained streak and cooldown as the window evidence, and every hold above - // (resident training, an eval) still defers it. - let measured_state = crate::inference::slots::measured_state_bytes( - &crate::inference::llama_server::kv_page_dir(desired.as_str()), - ); - let cache_holds_no_state = - crate::inference::lane_args::launched_cache_holds_no_state( - live.host_prompt_cache_mib, - measured_state, - ) && { - // what a relaunch would launch with: computed only in this rare case - let would_launch_mib = (self.model_resolver)(&desired) - .map(|m| { - derived_prompt_cache_mib( - &desired, - footprint_for(&m).as_ref(), - served_ctx, - lanes, - self.system.memory().total_bytes, - self.system.memory().available_bytes, - self.system.gpu_memory_mode(), - ) - .mib - }) - .unwrap_or(0); // unwrap_or: an unresolvable model would launch nothing better, so no relaunch for size - crate::inference::lane_args::cache_relaunch_needed( - live.host_prompt_cache_mib, - would_launch_mib, - measured_state, - ) - }; - let worth_it = worth_it || short_of_slots || cache_holds_no_state; - // A plan may shrink while the host pages out; it never GROWS into it - // (card 628dc958: six relaunches in 75 min at HIGH with swap climbing, - // each grow feeding on the memory its own relaunch had just freed). The - // gate is a measured DELTA, not a level: swap rising since the last - // decision means the box is short of memory right now, whatever - // `available` reads mid-relaunch. Flat swap lets the grow through — the - // swapped pages are already subtracted from the budget it was planned in. - let swap_now = self.system.snapshot().memory.swap_used_bytes; - let swap_prev = self.last_swap_used.swap(swap_now, Ordering::Relaxed); - if grow_refused_while_paging(live_space, plan_space, swap_prev, swap_now) { - self.reset_rehome_streak(); - continuum_base::probe!( - target: "continuum_core::modules::serving_daemon", class = "serving.reconcile.window", - decision = "refused_while_paging", - swap_prev_mb = swap_prev >> 20, - swap_now_mb = swap_now >> 20, - live_window = live.served_context_window, - plan_window = served_ctx, - live_lanes = live.lanes, - plan_lanes = lanes, - shortfall = gain, - "the plan wants more memory than the lane holds while the host is \ - paging out — a grow here feeds on its own relaunch; shrinks flow, \ - and the grow fires the tick swap stops climbing", - ); - self.acknowledge_verified_target(&live, planned.intent_revision); - return None; - } - // A STILL-CLIMBING plan is not settled (2026-09-02, the boot - // staircase): personas register footprints serially at boot, - // demand climbs in 15%+ stairs, and each stair "sustained" for - // 3 ticks — SIXTEEN model loads in one lane's log, each paying - // the full readiness ladder (the real ~15-minute boot, which - // was never model load: the engine loads in 1.7–6s). Sustained - // now ALSO requires the plan target itself to have stopped - // moving: growth resets the streak, so a monotone climb - // coalesces into ONE relaunch at its top. Steady state is - // unchanged — a stable plan is flat by definition. - // Flat = not a NEW HIGH for this streak: the first observation sets the - // high, a climb past it resets the streak (the boot staircase), and a - // plan moving below it (alternating, settling) keeps counting. - let high = self.rehome_plan_high.load(Ordering::Relaxed); - let plan_flat = high == 0 || plan_space <= high; - if plan_space > high { - self.rehome_plan_high.store(plan_space, Ordering::Relaxed); - } - let streak = if worth_it && cooling == 0 && plan_flat { - self.rehome_streak - .fetch_add(1, Ordering::Relaxed) - .saturating_add(1) - } else { - // Not merely "don't count" — RESET. One tick that does not want - // the bigger window is enough to prove the demand was not - // sustained, and a streak that survives dips is a streak that - // eventually fires on noise. A new high starts the next streak from - // itself; any other reason starts it from nothing. - self.rehome_streak.store(0, Ordering::Relaxed); - if plan_flat { - self.rehome_plan_high.store(0, Ordering::Relaxed); - } - 0 - }; - // Fire only on a tick whose plan IS the high of the streak's evidence (BigMama on - // #4851): the relaunch takes this tick's plan, so firing on a low tick of an - // alternating plan would land the lane at the low value (33k under Kimi's 52k) and - // re-home again; launching the remembered high instead would use a budget this - // tick did not plan. The high is taken over the last REHOME_SUSTAINED_TICKS plans, - // the evidence the streak itself needs, NOT over the whole streak: a high recorded - // once, while a relaunch was still freeing memory (Kimi's node 2026-10-15, - // 109,768, then a plan settled at 33k-87k), made this unreachable, and the lane - // served a 6,144 window until an operator relaunched it (card 5bac4968). - let at_high = at_recent_plan_high(&mut self.rehome_recent_plans.lock(), plan_space); - let starved = streak >= REHOME_SUSTAINED_TICKS && cooling == 0 && at_high; - // NOTE: the guards are re-armed at the FIRE point below, not here — - // `starved` only means the evidence qualifies. A later suppression - // (an eval holding the lane steady) still returns without relaunching, - // and charging a cooldown for a relaunch that never happened would - // rate-limit us out of the one we actually owe. - if !starved { - // A lane running BELOW the plan but above the 2x bar declines to - // grow — silently, until this probe. That silence is the defect: - // measured 2026-08-06 the plan sat stable at 26,323 while the - // live lane served 16,384 (62% — comfortably above half), every - // persona's binding read the stale 16,384, and nothing anywhere - // said so. It looked like the demand-derived window had "grown - // then reverted"; it had never taken hold, and the only thing - // that ever applied a grown plan was a reboot. - // - // The 2x rule itself is NOT being changed here — it came from a - // real outage (a lane frozen at 3.8k while plans wandered - // 3.6k<->22k) and a relaunch kills in-flight turns - // ([[never-thrash-sticky-hysteresis-on-every-lane]]). But its - // stated premise is that "the plan breathes with every consumer", - // and demand-derived planning made the plan STABLE, so against it - // the bar now strands a third of the window indefinitely. That is - // a design call on a guard written from an incident, so it is - // surfaced for the humans who own that history rather than - // quietly re-tuned by me (#332/#333). - // CADENCE, not content. This probe exists because the SILENCE was - // the defect, so it must keep speaking — but at one line per 5 s - // tick it becomes the defect at the other end: measured on BigMama - // 2026-09-05, 192 consecutive identical copies, and a persona's - // `first_token` had to be dug out from underneath them. A chatty - // floor evicts the signal from every bounded view exactly when the - // lane is interesting — the same class that buried a wedge - // declaration and produced a false retraction the same night. - // - // So: every ENTRY into the declined state is logged (streak == 1), - // and it keeps saying so once a minute after that. Nothing is - // suppressed that a reader needs — `decline_ticks` carries the - // duration, so the 47th copy adds no information the 1st lacked. - // (The first version of this comment claimed `streak` carried it. - // It does not: `streak` is pinned at 0 throughout the declined - // state, which is also why that version did not throttle.) - // The 2x rule and this decision are untouched; only how often the - // same unchanged verdict repeats itself. - let over_knee = lane_over_its_knee( - live.served_context_window, - live.lanes, - served_ctx, - lanes, - ); - let declined = live_space < plan_space || over_knee || short_of_slots; - let decline_ticks = if declined { - self.decline_log_ticks - .fetch_add(1, Ordering::Relaxed) - .saturating_add(1) - } else { - self.decline_log_ticks.store(0, Ordering::Relaxed); - 0 - }; - if declined && decline_should_log(decline_ticks) { - continuum_base::probe!( - target: "continuum_core::modules::serving_daemon", class = "serving.reconcile.window", - decision = "declined", - live_window = live.served_context_window, - plan_window = served_ctx, - live_lanes = live.lanes, - plan_lanes = lanes, - shortfall = gain, - over_knee, - streak, - decline_ticks, - needs_streak = REHOME_SUSTAINED_TICKS, - min_gain_pct = REHOME_MIN_GAIN_PCT, - cooling, - "lane is serving BELOW plan (or OVER its decode knee) and has not yet earned a re-home: the evidence must persist, not just appear", - ); - } - self.acknowledge_verified_target(&live, planned.intent_revision); - return None; - } - // A living-persona eval is a co-tenant decode slot on THIS lane - // (`ShareLane`). Growing its window means a relaunch, and a relaunch - // connection-refuses the exam's in-flight generations (hard-rs 0/8, - // 2026-07-20). The grow-back is OPTIONAL headroom; the exam is not. - // Hold the lane steady until the eval drops its guard — a model/genome - // change or a pressure shrink above still runs (this only gates the - // starved GROW re-home). [[benchmark-is-a-governor-preemption-lease]] - let held_ticks = if serving_held_steady() { - self.rehome_held_ticks - .fetch_add(1, Ordering::Relaxed) - .saturating_add(1) - } else { - self.rehome_held_ticks.store(0, Ordering::Relaxed); - 0 - }; - if serving_held_steady() - && !hold_overridden_by_shortfall(live_space, gain) - && held_ticks < REHOME_HOLD_DEFER_TICKS - { - continuum_base::probe!( - target: "continuum_core::modules::serving_daemon", class = "serving.reconcile.window", - decision = "declined", - live_window = live.served_context_window, - plan_window = served_ctx, - live_lanes = live.lanes, - plan_lanes = lanes, - shortfall = gain, - streak, - needs_streak = REHOME_SUSTAINED_TICKS, - min_gain_pct = REHOME_MIN_GAIN_PCT, - cooling, - "grow-back re-home suppressed: an eval holds the lane steady (co-tenant slot, no relaunch)", - ); - // Streak deliberately NOT reset: the demand is genuinely sustained, - // the exam is simply first in line. When it drops its lease the - // re-home fires on the next tick instead of re-proving from zero. - self.acknowledge_verified_target(&live, planned.intent_revision); - return None; - } - // SYMMETRIC RECEIPT (BigMama's requirement, 2026-08-06): the defect was - // that DECLINING was silent. A fix that makes RELAUNCHING silent has - // moved the silence, not removed it. Same probe class, same fields, both - // outcomes — so one query over `serving.reconcile.window` reads the - // lane's whole decision history, not half of it. - if serving_held_steady() { - self.rehome_held_ticks.store(0, Ordering::Relaxed); - continuum_base::probe!( - target: "continuum_core::modules::serving_daemon", class = "serving.reconcile.window", - decision = "re-homing_over_hold", - live_window = live.served_context_window, - plan_window = served_ctx, - live_lanes = live.lanes, - plan_lanes = lanes, - shortfall = gain, - held_ticks, - hold_override_pct = REHOME_HOLD_OVERRIDE_PCT, - hold_defer_ticks = REHOME_HOLD_DEFER_TICKS, - "a steady hold delays a re-home, never denies it — re-homing over the hold; the held work retries its flickered act", - ); - } - continuum_base::probe!( - target: "continuum_core::modules::serving_daemon", class = "serving.reconcile.window", - decision = "re-homing", - live_window = live.served_context_window, - plan_window = served_ctx, - live_lanes = live.lanes, - plan_lanes = lanes, - shortfall = gain, - streak, - needs_streak = REHOME_SUSTAINED_TICKS, - min_gain_pct = REHOME_MIN_GAIN_PCT, - // Always 0 here (a re-home cannot fire while cooling) — carried - // anyway so BOTH decisions emit the IDENTICAL field set and one - // query over the class gets a uniform schema instead of a shape - // that changes with the outcome. Symmetry is the point. - cooling, - cache_holds_no_state, - "re-homing lane: the plan exceeded it by a real margin, or its launched cache holds no measured state, for a sustained run of ticks", - ); - // Both guards re-armed at the moment we actually commit: the next - // re-home must earn a fresh streak AND outlast a fresh cooldown. - self.reset_rehome_streak(); - self.rehome_cooldown - .store(REHOME_COOLDOWN_TICKS, Ordering::Relaxed); + // The lanes this hour served: the health window's maximum (the lane-bound rest + // stands on it). + crate::cognition::health_ledger::note_lanes(live.lanes as u64); + self.acknowledge_verified_target(&live, planned.intent_revision); + return None; } } // L10 (#438, live 2026-08-15 14:13): a MODEL CHANGE on a READY lane must earn // the same sustained streak the window re-home above already requires. The - // asymmetry was the bug: growing a window (mild) needed REHOME_SUSTAINED_TICKS + // asymmetry was the bug: growing a window (mild) needed MODEL_CHANGE_SUSTAINED_TICKS // of consistent evidence, while swapping the base model (a full teardown that // also re-homes every persona to different WEIGHTS) actuated on a single plan // tick. One bogus usable_bytes sample during the incumbent's own load made the @@ -747,7 +359,7 @@ impl ServingDaemonModule { desired.as_str(), &mut pending, &self.model_change_streak, - REHOME_SUSTAINED_TICKS, + MODEL_CHANGE_SUSTAINED_TICKS, ); match verdict { ModelChangeGate::Defer { streak } => { @@ -757,7 +369,7 @@ impl ServingDaemonModule { live_model = live.active_model.as_deref().unwrap_or(""), plan_model = desired.as_str(), streak = streak as u64, - needs_streak = REHOME_SUSTAINED_TICKS as u64, + needs_streak = MODEL_CHANGE_SUSTAINED_TICKS as u64, "plan wants a DIFFERENT model on a ready lane — the swap must \ persist across ticks before it re-homes minds (#438: a one-tick \ bogus-sample fallback once served citizens a 0.5B)", diff --git a/core/continuum-serving/src/modules/serving_daemon/tests.rs b/core/continuum-serving/src/modules/serving_daemon/tests.rs index b3f9366d97..dccd561a10 100644 --- a/core/continuum-serving/src/modules/serving_daemon/tests.rs +++ b/core/continuum-serving/src/modules/serving_daemon/tests.rs @@ -472,64 +472,6 @@ pub(super) fn inherited_27b() -> LaneRecord { } } -/// A lane whose live per-slot window sits at `live_pct` of what the plan -/// actually affords, ready to have `reconcile_to_plan` driven at it repeatedly. -/// Returns the daemon and the REAL planned window. -/// -/// Two things this fixture exists to get right, both of which a hand-written -/// pair of numbers gets wrong: -/// -/// 1. A plan is capped by MEASURED demand ([`ServingDemand`]). With nothing -/// recorded it falls back to [`BOOTSTRAP_WORKING_SET`] — 16,384, which is -/// exactly the number the live lane was stranded at, so a fixture that skips -/// this reproduces a plan == live and no gain to sustain at all. -/// 2. The planner is free to serve less than the model's max context (host fit, -/// lane split). Asserting against a window we merely ASKED for tests the -/// fixture; deriving the live window from the plan we GOT tests the guard. -pub(super) fn lane_under_plan( - serves: Arc, - plan_model_ctx: u32, - live_pct: u32, -) -> (ServingDaemonModule, u32) { - let daemon = daemon_with(Arc::new(FakeServer::healthy(serves, true))); - // A measured peak is what lets a plan exceed the cold-start prior. - daemon - .working_set() - .record_in_memory(uuid::Uuid::new_v4(), plan_model_ctx, 0); - let budget = HostBudget { - usable_bytes: 45 * GB, - perf_cores: 6, - }; - let candidates = - vec![footprint_from_parts("coder-14b", 9 * GB, plan_model_ctx, true, None).unwrap()]; - daemon.publish_plan(budget, &candidates, &candidates); - let (plan_window, plan_lanes) = { - let plan = daemon.plan_tx.borrow(); - let plan = plan.plan.as_ref().expect("plan published"); - (plan.served_context_window, plan.lanes) - }; - let _ = daemon.serving_tx.send_replace(ServingSnapshot { - ready_verified_at_ms: None, - active_model: Some("coder-14b".into()), - ready: true, - base_url: serving_v1_url(), - adapters: Vec::new(), - served_context_window: plan_window * live_pct / 100, - // Live lanes match the plan's so these fixtures isolate the WINDOW - // dimension of re-home evidence; the lanes dimension has its own test - // (rehome_evidence_counts_lanes_not_just_per_slot_window). - lanes: plan_lanes, - host_prompt_cache_mib: 0, - degraded_reason: None, - vision_ready: false, - vision_base_url: None, - vision_model: None, - loading_model: None, - held_for: None, - }); - (daemon, plan_window) -} - /// Believe-ready snapshot fixture for the liveness-heartbeat tests. pub(super) fn ready_snapshot() -> ServingSnapshot { ServingSnapshot { @@ -604,5 +546,5 @@ mod prompt_cache; mod publication; use publication::test_pin_store; mod reconciliation; -mod rehome; +mod one_launch; mod teacher; diff --git a/core/continuum-serving/src/modules/serving_daemon/tests/budget.rs b/core/continuum-serving/src/modules/serving_daemon/tests/budget.rs index 440c2768ae..8a81aa0b4a 100644 --- a/core/continuum-serving/src/modules/serving_daemon/tests/budget.rs +++ b/core/continuum-serving/src/modules/serving_daemon/tests/budget.rs @@ -51,30 +51,6 @@ fn a_refused_demotion_with_no_plan_adopts_the_inherited_engine_at_its_geometry() ); } -// what this catches (card 628dc958): the plan grew into free memory while the host -// was pushing other processes' pages out to make it, then fed on the memory its own -// relaunch freed — six relaunches in 75 min on the M5 at HIGH. Pure decision. -#[test] -fn a_plan_never_grows_while_the_host_pages_out() { - use super::grow_refused_while_paging; - let gib = |n: u64| n << 30; - // paging out + a bigger plan = refused; flat or falling swap, a shrink, or no - // previous reading (boot on a node that always has swap) flows. - assert!(!grow_refused_while_paging( - 80_000, - 120_000, - u64::MAX, - gib(2) - )); - assert!(grow_refused_while_paging(80_000, 120_000, gib(1), gib(2))); - assert!(!grow_refused_while_paging(80_000, 120_000, gib(2), gib(2))); - assert!(!grow_refused_while_paging(80_000, 120_000, gib(2), gib(1))); - assert!( - !grow_refused_while_paging(120_000, 80_000, gib(1), gib(2)), - "a shrink while paging is the remedy, never refused" - ); -} - // what this catches: a pin SWAPS — serve() kills the incumbent llama-server // child, THEN launches the candidate (never co-resident) — so the fit-check must // credit the outgoing model's weights back into the budget. Without it, swapping @@ -150,14 +126,6 @@ fn pin_swap_down_credits_the_evicted_incumbents_weights() { ); } -// what this catches: the ServingSteadyHold RAII gauge — acquiring sets -// serving_held_steady() true; dropping clears it; nesting is reference-counted so a -// concurrent second eval doesn't release the first's hold. This is the gate that stops -// the grow-back re-home from relaunching the lane under a running eval (hard-rs 0/8). -// regression for the 2026-07-20 shared-lane bounce. -// what this catches (2026-09-17, the M5): a steady hold pinning a boot shape of -// 8 × 12,800 against a plan of 3 × 67,340 for 255 ticks. The hold yields to a -// shortfall of REHOME_HOLD_OVERRIDE_PCT or more; a few-percent grow-back stays held. // what this catches: a machine-specific constant sizing every plan. The plan fills the mode's // fraction of the sustained budget, the same on unified and discrete memory; the M5's 2026-10-29 // plan withheld a flat 12 GiB on top (three lanes for four residents, 17 s median slot wait). @@ -190,46 +158,6 @@ fn a_foundry_headroom_of_one_still_keeps_the_process_overhead() { ); } -#[test] -fn a_steady_hold_yields_to_a_large_shortfall_and_keeps_a_small_one() { - let (live, _plan, gain, _) = rehome_gain_evidence(12_800, 8, 67_340, 3); - assert!( - hold_overridden_by_shortfall(live, gain), - "8 × 12.8k vs 3 × 67k is starvation, not a slot to protect" - ); - let (live, _plan, gain, worth) = rehome_gain_evidence(56_000, 5, 67_000, 5); - assert!(worth, "a ~20% grow-back is worth a re-home in general"); - assert!( - !hold_overridden_by_shortfall(live, gain), - "but not worth dropping a held slot for" - ); - assert!( - !hold_overridden_by_shortfall(0, 1), - "no live space = nothing to compare" - ); -} - -#[test] -fn serving_steady_hold_is_refcounted_and_raii() { - assert!(!serving_held_steady(), "no hold at rest"); - { - let _h1 = ServingSteadyHold::acquire("test"); - assert!(serving_held_steady(), "one hold ⇒ steady"); - { - let _h2 = ServingSteadyHold::acquire("test"); - assert!(serving_held_steady(), "two holds ⇒ still steady"); - } - assert!( - serving_held_steady(), - "inner drop must not release the outer hold" - ); - } - assert!( - !serving_held_steady(), - "all holds dropped ⇒ grow-back resumes" - ); -} - // what this catches: the ServingLudicrousHold RAII gauge — while held, serving plans at // PowerMode::Performance (the whole GPU, biggest window), overriding the timid pressure // read; refcounted so concurrent benchmarks compose; RAII-released so serving reverts to @@ -747,3 +675,52 @@ fn the_live_free_read_keeps_the_same_os_floor_the_planned_term_keeps() { // An over-full box yields zero, never a wrap. assert_eq!(sidecar_admissible_bytes(floor / 2, 31 * GB, physical), 0); } + +// what this catches (card 7c72c0f0, Intel Mac 2026-09-17): the plan's budget is the +// row the lane's PLACEMENT puts its bytes in. A CPU-placed lane budgets against the +// Ram row — the 30 GB the KV actually fills — not the 4 GB Vram row of a card that +// holds nothing of it (nine citizens sized against 5.7 GB on a 34.4 GB box: one warm +// slot, eight exiled to a remote lane). The GPU arm is byte-identical to before. +#[tokio::test] +async fn a_cpu_placed_lane_budgets_against_the_ram_row_not_the_card() { + use crate::inference::llama_server::LanePlacement; + use crate::resources::{DaemonConfig, GovernorConfig, MockCapacitySource, ResourceDaemon}; + let vram = Arc::new(MockCapacitySource::new( + crate::resources::ResourceKind::Vram, + 4_000, + )); + let ram = Arc::new(MockCapacitySource::new( + crate::resources::ResourceKind::Ram, + 30_000, + )); + let daemon = ResourceDaemon::start( + vec![vram, ram], + vec![], + DaemonConfig { + tick_interval: std::time::Duration::from_millis(20), + min_reclaim_budget: std::time::Duration::from_millis(100), + governor: GovernorConfig { + min_dwell_ms: 0, + graceful_grace_ms: 50, + }, + }, + ); + assert_eq!( + LanePlacement::Cpu.pool_kind(), + crate::resources::ResourceKind::Ram + ); + assert_eq!( + LanePlacement::Gpu.pool_kind(), + crate::resources::ResourceKind::Vram + ); + assert_eq!( + governed_pool_ceiling(&daemon, LanePlacement::Cpu.pool_kind()), + Some(30_000), + "a CPU-placed lane plans against the RAM its KV lives in" + ); + assert_eq!( + governed_pool_ceiling(&daemon, LanePlacement::Gpu.pool_kind()), + Some(4_000), + "a GPU-placed lane plans against the card" + ); +} diff --git a/core/continuum-serving/src/modules/serving_daemon/tests/one_launch.rs b/core/continuum-serving/src/modules/serving_daemon/tests/one_launch.rs new file mode 100644 index 0000000000..d6571dc299 --- /dev/null +++ b/core/continuum-serving/src/modules/serving_daemon/tests/one_launch.rs @@ -0,0 +1,123 @@ +#![cfg(test)] + +use super::*; + +// what this catches: the daemon relaunching a ready engine because the plan wants a different +// window or lane count. The M5's plan read 1, 2 and 3 lanes of four residents and its engine +// reloaded 40 times (2026-11-02/03). A ready lane serving the right model and genome to the +// seated population is never relaunched, however far the plan's window drifts; when the +// population moves, the launch path republishes each mind's share without a relaunch. +#[tokio::test] +async fn a_ready_lane_is_never_relaunched_for_its_window_or_lanes() { + let serves = Arc::new(AtomicUsize::new(0)); + let mut server = FakeServer::healthy(serves.clone(), true); + server.active = Some("coder-14b".into()); + let daemon = daemon_with(Arc::new(server)); + let budget = HostBudget { + usable_bytes: 45 * GB, + perf_cores: 6, + }; + let candidates = vec![footprint_from_parts("coder-14b", 9 * GB, 8192, true, None).unwrap()]; + daemon.publish_plan(budget, &candidates, &candidates); + let plan_window = daemon + .plan_tx + .borrow() + .plan + .as_ref() + .expect("plan published") + .served_context_window; + let ready = |lanes: u32| ServingSnapshot { + // test fixture: no live readiness was ever CONFIRMED here. + ready_verified_at_ms: None, + active_model: Some("coder-14b".into()), + ready: true, + base_url: serving_v1_url(), + adapters: Vec::new(), + served_context_window: plan_window / 4, + lanes, + host_prompt_cache_mib: 0, + degraded_reason: None, + vision_ready: false, + vision_base_url: None, + vision_model: None, + loading_model: None, + held_for: None, + }; + let _ = daemon.serving_tx.send_replace(ready(daemon.seated())); + for tick in 0..10 { + assert!( + daemon.reconcile_to_plan().is_none(), + "tick {tick}: a quarter of the plan's window is not a relaunch" + ); + } + let _ = daemon.serving_tx.send_replace(ready(daemon.seated() + 1)); + if let Some(republish) = daemon.reconcile_to_plan() { + republish.await.unwrap(); + } + assert_eq!( + serves.load(Ordering::SeqCst), + 0, + "the population moved: republished, never relaunched" + ); +} + +// what this catches (2026-08-15 14:13, round-killer L10 / #438 live): a plan tick +// whose usable_bytes sample was transiently bogus named the SMALLEST candidate +// (qwen2.5-0.5B) via the nothing-fits arm, and the reconcile swapped the READY +// 27B lane on that single tick — citizens spoke template-token salad into the +// bench room as durable messages every healthy peer then perceived as +// conversation. A base-model swap re-homes minds; it must earn the same +// sustained streak as the (milder) window re-home, target changes must restart +// the count, and recovery (no ready incumbent) must never wait. +#[test] +fn model_swap_on_a_ready_lane_needs_a_sustained_streak() { + use super::{model_change_gate, ModelChangeGate}; + use std::sync::atomic::AtomicU32; + let streak = AtomicU32::new(0); + let mut pending = None; + // One bogus tick wanting the 0.5B: deferred, never actuates. + assert_eq!( + model_change_gate(true, Some("27b"), "0.5b", &mut pending, &streak, 3), + ModelChangeGate::Defer { streak: 1 } + ); + // Next tick the sample healed and the plan wants the incumbent again: + // pending clears, nothing happened. + assert_eq!( + model_change_gate(true, Some("27b"), "27b", &mut pending, &streak, 3), + ModelChangeGate::NotAChange + ); + assert!(pending.is_none()); + // Sustained genuine disagreement commits on the Nth consecutive tick. + assert_eq!( + model_change_gate(true, Some("27b"), "48b", &mut pending, &streak, 3), + ModelChangeGate::Defer { streak: 1 } + ); + assert_eq!( + model_change_gate(true, Some("27b"), "48b", &mut pending, &streak, 3), + ModelChangeGate::Defer { streak: 2 } + ); + assert_eq!( + model_change_gate(true, Some("27b"), "48b", &mut pending, &streak, 3), + ModelChangeGate::Commit { streak: 3 } + ); + // A flapping target restarts the count — 0.5b/48b alternation never commits. + assert_eq!( + model_change_gate(true, Some("27b"), "0.5b", &mut pending, &streak, 3), + ModelChangeGate::Defer { streak: 1 } + ); + assert_eq!( + model_change_gate(true, Some("27b"), "48b", &mut pending, &streak, 3), + ModelChangeGate::Defer { streak: 1 } + ); + // No ready incumbent (boot / post-wedge): commit immediately — recovery + // must not wait out a streak. + let mut p2 = None; + assert_eq!( + model_change_gate(false, Some("27b"), "48b", &mut p2, &streak, 3), + ModelChangeGate::NotAChange + ); + assert_eq!( + model_change_gate(true, None, "48b", &mut p2, &streak, 3), + ModelChangeGate::NotAChange + ); +} diff --git a/core/continuum-serving/src/modules/serving_daemon/tests/publication.rs b/core/continuum-serving/src/modules/serving_daemon/tests/publication.rs index 8c7f879590..d62c4a8b48 100644 --- a/core/continuum-serving/src/modules/serving_daemon/tests/publication.rs +++ b/core/continuum-serving/src/modules/serving_daemon/tests/publication.rs @@ -30,38 +30,6 @@ fn the_admission_gate_counts_the_engines_lanes_not_the_plans() { ); } -// what this catches (2026-09-01 live): the re-home guard measured only the -// per-slot window, so a plan that GREW total token-space by adding lanes -// while trimming per-slot (2×57,600 → 4×47,426, +65% space, +2 warm slots) -// computed a negative gain and never relaunched — five residents thrashed -// two slots at hit_rate 0.0 until an operator cycled the server by hand. -// The evidence currency is window × lanes. -#[test] -fn rehome_evidence_counts_lanes_not_just_per_slot_window() { - use super::rehome_gain_evidence; - // The live incident shape: more lanes, smaller per-slot, bigger total. - let (live, plan, gain, worth_it) = rehome_gain_evidence(57_600, 2, 47_426, 4); - assert_eq!(live, 115_200); - assert_eq!(plan, 189_704); - assert_eq!(gain, 74_504); - assert!( - worth_it, - "65% more total space must qualify as re-home evidence" - ); - // Same total space re-sliced: not evidence (a relaunch kills in-flight turns). - let (_, _, _, worth_it) = rehome_gain_evidence(40_000, 2, 20_000, 4); - assert!(!worth_it, "re-slicing the same space is not a gain"); - // Sub-threshold growth (<15%): not evidence. - let (_, _, _, worth_it) = rehome_gain_evidence(40_000, 2, 44_000, 2); - assert!(!worth_it, "10% is under the 15% margin"); - // A dead lane (0 window) never qualifies — recovery is a different path. - let (_, _, _, worth_it) = rehome_gain_evidence(0, 1, 40_000, 2); - assert!( - !worth_it, - "live_space=0 is the recovery arm's job, not re-home" - ); -} - // what this catches (card 29e4ab34, the M5 2026-09-19 17:20:35Z): the thirteen-second // boot window in which no lane has reported a model. The knee lookup must key on the // remembered model then — otherwise the roster (17 runtimes) goes unclamped into the @@ -138,10 +106,6 @@ fn a_boot_before_any_lane_reports_its_model_reads_the_remembered_models_knee() { cold.lanes, 2, "remembered model applies its knee before boot, not the eight-core maximum" ); - assert!( - roster_short_of_slots(1, cold.lanes), - "a prior one-lane collapse can recover the second slot" - ); } // what this catches (#287 slice 2): the governed host-cache lease inputs are @@ -678,3 +642,15 @@ async fn a_hold_is_published_keeps_its_start_and_is_cleared_on_release() { daemon.publish_hold(&Occupancy::Free); assert_eq!(daemon.serving_tx.borrow().held_for, None, "a released engine is not held"); } + +// what this catches: a seated mind published the engine's whole shared pool as her window +// (every mind budgeting 290k of a 290k pool), or a share that moves with the plan's per-tick +// lane guess. Each seated mind gets an equal share, capped at the model's trained window; the +// readers that charge `lanes x window` then charge the pool. +#[test] +fn each_seated_mind_is_published_her_share_of_the_shared_pool() { + use super::seated_share; + assert_eq!(seated_share(290_560, 4, 262_144), (72_640, 4), "the M5: four residents"); + assert_eq!(seated_share(290_560, 1, 262_144), (262_144, 1), "one mind is capped at the trained window"); + assert_eq!(seated_share(290_560, 0, 262_144), (262_144, 1), "no seated count is one mind, never a divide by zero"); +} diff --git a/core/continuum-serving/src/modules/serving_daemon/tests/reconciliation.rs b/core/continuum-serving/src/modules/serving_daemon/tests/reconciliation.rs index a7576ad6bb..78b0a65af2 100644 --- a/core/continuum-serving/src/modules/serving_daemon/tests/reconciliation.rs +++ b/core/continuum-serving/src/modules/serving_daemon/tests/reconciliation.rs @@ -45,54 +45,6 @@ fn a_reconcile_in_flight_names_its_step_and_a_wedge_is_declared_past_the_bound() )); } -// what this catches (2026-09-19, the M5 pinned at one lane across boots): the store is -// written on the tick a launch SETTLES — cooldown 1 → 0 with the lane serving — and on -// no other tick: not at spawn (cooling = full), not while cooling, not after (0), not -// for a lane that is not ready, not for zero lanes. -#[test] -fn only_the_tick_a_launch_settles_on_remembers_its_geometry() { - use super::{settles_this_tick, REHOME_COOLDOWN_TICKS}; - assert!(settles_this_tick(1, true, 2)); - assert!( - !settles_this_tick(REHOME_COOLDOWN_TICKS, true, 2), - "spawn tick: cooling is full" - ); - assert!(!settles_this_tick(2, true, 2), "still cooling"); - assert!( - !settles_this_tick(0, true, 2), - "already settled — no re-save every tick" - ); - assert!(!settles_this_tick(1, false, 2), "not ready is not settled"); - assert!( - !settles_this_tick(1, true, 0), - "no lanes is nothing to remember" - ); -} - -// what this catches (the M5, 2026-09-19 23:13–23:15Z): the spawn cooldown (18 ticks) was -// spent DURING the 27B's 90 s cold load — the old lane kept serving, so the ticks -// counted — and the new lane came ready with zero settle left; its predecessor's freed -// memory read as a 32 GB budget for a minute, the plan said 3 lanes, and a second -// relaunch fired 15 s after the first came ready (12 settles in the hour, acts 5). A -// launch settles AFTER it is ready: a ready stamp not yet settled on is the edge; the -// same stamp again is not; a not-ready snapshot never is. -#[test] -fn a_launch_settles_after_it_is_ready_not_after_it_was_spawned() { - assert!( - ready_edge(0, Some(1_000)), - "the first ready stamp: settle from here" - ); - assert!( - !ready_edge(1_000, Some(1_000)), - "the same stamp is the same launch" - ); - assert!( - ready_edge(1_000, Some(2_000)), - "a new stamp is a new launch: settle again" - ); - assert!(!ready_edge(1_000, None), "not ready: nothing to settle on"); -} - // what this catches (5090, 2026-09-06 — BigMama's third bug): an empty plan // publishing "idle" while the llama-server stays alive. At the live → empty // transition the daemon takes the lane down exactly once; a second tick with @@ -464,7 +416,7 @@ async fn reconcile_brings_planned_model_up() { *cancelled.pending_model_change.lock().unwrap() = Some("coder-14b".into()); cancelled .model_change_streak - .store(REHOME_SUSTAINED_TICKS, Ordering::Relaxed); + .store(MODEL_CHANGE_SUSTAINED_TICKS, Ordering::Relaxed); cancelled.force_relaunch.store(true, Ordering::Release); let admitted = cancelled.reconcile_to_plan().expect("admitted serve"); tokio::time::timeout(Duration::from_secs(5), entered.notified()) @@ -524,7 +476,7 @@ async fn reconcile_is_noop_when_already_serving() { let verified_reads = server.verified_reads.clone(); let daemon = daemon_with(Arc::new(server)); - // Pretend coder-14b is already up and ready. + // Pretend coder-14b is already up and ready, serving the seated population. let _ = daemon.serving_tx.send_replace(ServingSnapshot { // test fixture: no live readiness was ever CONFIRMED here. ready_verified_at_ms: None, @@ -533,7 +485,7 @@ async fn reconcile_is_noop_when_already_serving() { base_url: serving_v1_url(), adapters: Vec::new(), served_context_window: 11008, - lanes: 4, + lanes: daemon.seated(), host_prompt_cache_mib: 0, degraded_reason: None, vision_ready: false, diff --git a/core/continuum-serving/src/modules/serving_daemon/tests/rehome.rs b/core/continuum-serving/src/modules/serving_daemon/tests/rehome.rs deleted file mode 100644 index 1a42cbb775..0000000000 --- a/core/continuum-serving/src/modules/serving_daemon/tests/rehome.rs +++ /dev/null @@ -1,633 +0,0 @@ -#![cfg(test)] - -use super::*; - -// what this catches: #3751 threw this throttle at `rehome_streak` — the -// RE-HOME GAIN counter — which is stored to 0 for exactly as long as the lane -// is below plan with no qualifying gain. `streak <= 1` was therefore true on -// every tick of the declined episode and the probe throttled NOTHING: 411 -// identical lines at one per 5 s measured on BigMama 2026-09-05, burying a -// persona's first_token underneath them. The clock a cadence uses must be -// owned by the cadence; a domain counter's reset rule belongs to the domain. -#[test] -fn decline_probe_speaks_on_entry_then_about_once_a_minute() { - assert!( - super::decline_should_log(1), - "entry into the declined state must always speak — the silence was the original defect" - ); - for quiet in [2, 3, 7, 11, 13, 23] { - assert!( - !super::decline_should_log(quiet), - "tick {quiet} adds nothing the 1st line lacked" - ); - } - for loud in [12, 24, 120] { - assert!( - super::decline_should_log(loud), - "tick {loud} is the ~1/min heartbeat" - ); - } - - // A ten-minute episode is 120 ticks: entry plus one per minute, not 120. - let spoken = (1..=120u32) - .filter(|&t| super::decline_should_log(t)) - .count(); - assert_eq!(spoken, 11, "entry + 10 minutes of heartbeat over 120 ticks"); - - // The defect itself, stated as a property: a clock that never advances - // must be SILENT, not infinitely chatty. `0 % 12 == 0` would make the - // naive form log forever, which is how the first fix passed review. - assert!( - !super::decline_should_log(0), - "a counter that never advanced means we have not entered the state, not that we should shout" - ); -} - -// what this catches (2026-09-17, the M5 at 8 lanes / 7.9 t/s all morning): a plan -// that trades lanes for width is the decode knee clamping the roster, and it is -// evidence even when token-space calls it a wash or a loss — otherwise the knee -// only ever applies at boot. Re-slicing the same space at the SAME lane count, or a -// plan with more lanes, still needs the space margin. -#[test] -fn a_lane_over_its_knee_is_rehome_evidence_whatever_the_token_space_says() { - use super::{lane_over_its_knee, rehome_gain_evidence}; - // The live shape: 8 × 51,712 → 7 × 67,340 (+14%, under the margin) qualifies. - let (_, _, _, worth_it) = rehome_gain_evidence(51_712, 8, 67_340, 7); - assert!( - worth_it, - "one lane over the knee is a relaunch, not a rounding error" - ); - // The knee at 4: 8 × 51,712 → 4 × 67,340 is a LOSS of space and still qualifies. - let (_, _, _, worth_it) = rehome_gain_evidence(51_712, 8, 67_340, 4); - assert!( - worth_it, - "fewer, wider lanes is the knee — space is not the currency here" - ); - // Fewer lanes but NARROWER is a pressure shrink, not a knee: not this arm. - assert!(!lane_over_its_knee(51_712, 8, 40_000, 4)); - // Same lanes / more lanes: the space margin still rules. - assert!(!lane_over_its_knee(40_000, 2, 44_000, 2)); - assert!(!lane_over_its_knee(57_600, 2, 47_426, 4)); - let (_, _, _, worth_it) = rehome_gain_evidence(40_000, 2, 44_000, 2); - assert!( - !worth_it, - "10% at the same lane count is still under the margin" - ); -} - -// what this catches (2026-09-19 15:4xZ, the M5 stuck at one lane): the knee's mirror. -// A cold boot launched 1 × 161,792 under a transient budget; the steady plan said -// 2 × 67,340 — a 17% LOSS of token-space — and token-space alone declined it every -// tick, so the roster's second coder lane could never appear at runtime, and the -// settled 1-lane geometry then capped every later boot. A plan with more lanes than -// are live is minds without a warm slot; that is evidence whatever the space says. -// Fewer or equal lanes is not this arm (the knee and the margin rule those), and a -// dead lane (0 live lanes) is recovery's job, never re-home's. -#[test] -fn a_roster_short_of_warm_slots_is_rehome_evidence_whatever_the_token_space_says() { - use super::{rehome_gain_evidence, roster_short_of_slots}; - assert!( - roster_short_of_slots(1, 2), - "1 × 161k → 2 × 67k: a second warm slot for the roster" - ); - let (_, _, _, by_space) = rehome_gain_evidence(161_792, 1, 67_340, 2); - assert!( - !by_space, - "token-space alone calls the second lane a loss — the arm above is what carries it" - ); - assert!( - roster_short_of_slots(2, 4), - "2 × 40k → 4 × 20k: two more slots the roster asked for" - ); - assert!( - !roster_short_of_slots(2, 2), - "the same count is the margin's business" - ); - assert!( - !roster_short_of_slots(8, 4), - "fewer lanes is the knee's business" - ); - assert!( - !roster_short_of_slots(0, 2), - "a dead lane is recovery, not re-home" - ); -} - -// what this catches (2026-08-15 14:13, round-killer L10 / #438 live): a plan tick -// whose usable_bytes sample was transiently bogus named the SMALLEST candidate -// (qwen2.5-0.5B) via the nothing-fits arm, and the reconcile swapped the READY -// 27B lane on that single tick — citizens spoke template-token salad into the -// bench room as durable messages every healthy peer then perceived as -// conversation. A base-model swap re-homes minds; it must earn the same -// sustained streak as the (milder) window re-home, target changes must restart -// the count, and recovery (no ready incumbent) must never wait. -#[test] -fn model_swap_on_a_ready_lane_needs_a_sustained_streak() { - use super::{model_change_gate, ModelChangeGate}; - use std::sync::atomic::AtomicU32; - let streak = AtomicU32::new(0); - let mut pending = None; - // One bogus tick wanting the 0.5B: deferred, never actuates. - assert_eq!( - model_change_gate(true, Some("27b"), "0.5b", &mut pending, &streak, 3), - ModelChangeGate::Defer { streak: 1 } - ); - // Next tick the sample healed and the plan wants the incumbent again: - // pending clears, nothing happened. - assert_eq!( - model_change_gate(true, Some("27b"), "27b", &mut pending, &streak, 3), - ModelChangeGate::NotAChange - ); - assert!(pending.is_none()); - // Sustained genuine disagreement commits on the Nth consecutive tick. - assert_eq!( - model_change_gate(true, Some("27b"), "48b", &mut pending, &streak, 3), - ModelChangeGate::Defer { streak: 1 } - ); - assert_eq!( - model_change_gate(true, Some("27b"), "48b", &mut pending, &streak, 3), - ModelChangeGate::Defer { streak: 2 } - ); - assert_eq!( - model_change_gate(true, Some("27b"), "48b", &mut pending, &streak, 3), - ModelChangeGate::Commit { streak: 3 } - ); - // A flapping target restarts the count — 0.5b/48b alternation never commits. - assert_eq!( - model_change_gate(true, Some("27b"), "0.5b", &mut pending, &streak, 3), - ModelChangeGate::Defer { streak: 1 } - ); - assert_eq!( - model_change_gate(true, Some("27b"), "48b", &mut pending, &streak, 3), - ModelChangeGate::Defer { streak: 1 } - ); - // No ready incumbent (boot / post-wedge): commit immediately — recovery - // must not wait out a streak. - let mut p2 = None; - assert_eq!( - model_change_gate(false, Some("27b"), "48b", &mut p2, &streak, 3), - ModelChangeGate::NotAChange - ); - assert_eq!( - model_change_gate(true, None, "48b", &mut p2, &streak, 3), - ModelChangeGate::NotAChange - ); -} - -// what this catches: the failure the OLD single-sample `live * 2 <= plan` rule -// could not see. Measured live 2026-08-06: plan 26,323 vs lane 16,384 — a 62% -// lane, comfortably above half — held indefinitely while every persona's binding -// read the stale window and the demand loop's output was silently discarded. -// A real, PERSISTENT gain must eventually re-home no matter where it sits in the -// 50-99% band. (BigMama's call; she owns the guard the ratio came from.) -#[tokio::test] -async fn a_sustained_gain_above_the_old_half_bar_eventually_re_homes() { - let serves = Arc::new(AtomicUsize::new(0)); - // 62% of plan — the live incident's exact ratio, comfortably above the old - // half bar and therefore invisible to the rule this replaces. - let (daemon, plan_window) = lane_under_plan(serves.clone(), 65_536, 62); - // Guard the FIXTURE, not just the guard: if a measured demand had not raised - // the plan above the cold-start prior, plan == live, there would be no gain to - // sustain, and every assertion below would pass for the wrong reason. That is - // exactly how this test failed its first time out. - assert!( - plan_window > daemon.serving_tx.borrow().served_context_window, - "fixture is vacuous: the plan must actually exceed the lane" - ); - - // Below the streak it must hold — a relaunch kills in-flight turns, so an - // instant re-home on first sight is exactly the thrash we are avoiding. - for tick in 1..REHOME_SUSTAINED_TICKS { - assert!( - daemon.reconcile_to_plan().is_none(), - "tick {tick}: must not re-home before the gain has proven itself sustained" - ); - } - assert_eq!( - serves.load(Ordering::SeqCst), - 0, - "no relaunch during the streak" - ); - - assert!( - daemon.reconcile_to_plan().is_some(), - "a gain that persisted for a full lane-readiness window MUST re-home — \ - this is the 62%-forever case the 2x ratio never caught" - ); -} - -// what this catches: the property the 2x ratio was RIGHT about, which the -// replacement must not lose. A plan that jitters above the bar and falls back -// must never accumulate its way to a relaunch — the outage this guard exists for -// was a lane relaunching against a plan wandering 3.6k<->22k. -#[tokio::test] -async fn a_jittering_gain_never_accumulates_into_a_re_home() { - let serves = Arc::new(AtomicUsize::new(0)); - let (daemon, plan_window) = lane_under_plan(serves.clone(), 65_536, 62); - let live_window = daemon.serving_tx.borrow().served_context_window; - let budget = HostBudget { - usable_bytes: 45 * GB, - perf_cores: 6, - }; - - // Alternate: plenty of headroom, then none. Far MORE ticks than the streak - // needs in total — but never consecutively. - for _ in 0..(REHOME_SUSTAINED_TICKS * 3) { - assert!( - daemon.reconcile_to_plan().is_none(), - "wanting: still below streak" - ); - // A dip: the plan momentarily affords no more than the lane already has. - let small = - vec![footprint_from_parts("coder-14b", 9 * GB, live_window, true, None).unwrap()]; - daemon.publish_plan(budget, &small, &small); - assert!(daemon.reconcile_to_plan().is_none(), "dip: nothing to gain"); - // …and back up. - let big = vec![footprint_from_parts("coder-14b", 9 * GB, plan_window, true, None).unwrap()]; - daemon.publish_plan(budget, &big, &big); - } - assert_eq!( - serves.load(Ordering::SeqCst), - 0, - "jitter must NEVER re-home, however long it goes on — one dip resets the streak" - ); -} - -// what this catches (2026-10-07, the 5090): a lane serving 2,304 under a plan that -// alternated 33k <-> 70k never re-homed for an hour. Every rise reset the streak, -// although BOTH plan values wanted a far bigger lane, so Kimi, needing 52k, could -// not fit while the lane read ready. A plan moving below a high it already reached -// is settled enough: the streak counts and the lane re-homes within a few ticks. -#[tokio::test] -async fn a_lane_far_below_an_alternating_plan_re_homes() { - let serves = Arc::new(AtomicUsize::new(0)); - let (daemon, full) = lane_under_plan(serves.clone(), 65_536, 4); - let live_window = daemon.serving_tx.borrow().served_context_window; - assert!( - live_window * 4 < full / 2, - "fixture: the lane must sit far below both plan values" - ); - let budget = HostBudget { - usable_bytes: 45 * GB, - perf_cores: 6, - }; - let half = vec![footprint_from_parts("coder-14b", 9 * GB, full / 2, true, None).unwrap()]; - let whole = vec![footprint_from_parts("coder-14b", 9 * GB, full, true, None).unwrap()]; - let mut fired_at = None; - for tick in 0..(REHOME_SUSTAINED_TICKS * 4) { - let plan = if tick % 2 == 0 { &half } else { &whole }; - daemon.publish_plan(budget, plan, plan); - if daemon.reconcile_to_plan().is_some() { - fired_at = Some(tick); - break; - } - } - let fired_at = - fired_at.expect("a lane far below both values of an alternating plan must re-home"); - assert!( - fired_at <= REHOME_SUSTAINED_TICKS + 3, - "re-homed only at tick {fired_at}: the alternation still resets the streak" - ); - // and it lands at the HIGH value (the relaunch takes the fire tick's plan): a re-home - // on a low tick would bring her back under her need and owe a second relaunch - assert_eq!( - fired_at % 2, - 1, - "fired on a low tick (half the plan), not the high one" - ); -} - -// what this catches (card 5bac4968, Kimi's node 2026-10-15): one transient high stranding a -// lane. The plan read 109,768 at the post-deploy relaunch tick while memory was still being -// freed, then settled at 33k-87k; the fire tick had to reach that one-off high, never did, and -// her lane served 6,144 until an operator relaunched it. The high is the best of the last -// REHOME_SUSTAINED_TICKS plans, so a spike ages out and the lane re-homes to the settled -// plan; the rule is also pinned on its own, alternating and staircase cases kept above/below. -#[tokio::test] -async fn a_transient_plan_spike_does_not_strand_the_lane_below_the_settled_plan() { - let serves = Arc::new(AtomicUsize::new(0)); - let (daemon, full) = lane_under_plan(serves.clone(), 65_536, 4); - let live_window = daemon.serving_tx.borrow().served_context_window; - let settled_window = full * 3 / 4; - assert!( - live_window * 4 < settled_window / 2, - "fixture: the lane must sit far below the settled plan" - ); - let budget = HostBudget { - usable_bytes: 45 * GB, - perf_cores: 6, - }; - let spike = vec![footprint_from_parts("coder-14b", 9 * GB, full, true, None).unwrap()]; - let settled = - vec![footprint_from_parts("coder-14b", 9 * GB, settled_window, true, None).unwrap()]; - daemon.publish_plan(budget, &spike, &spike); - assert!( - daemon.reconcile_to_plan().is_none(), - "one spike tick is not sustained evidence" - ); - let mut fired_at = None; - for tick in 1..(REHOME_SUSTAINED_TICKS * 4) { - daemon.publish_plan(budget, &settled, &settled); - if daemon.reconcile_to_plan().is_some() { - fired_at = Some(tick); - break; - } - } - let fired_at = - fired_at.expect("a lane far below a settled plan must re-home once the spike ages out"); - assert!( - fired_at <= REHOME_SUSTAINED_TICKS + 1, - "re-homed only at tick {fired_at}: the spike outlived the evidence span" - ); - - let mut recent = std::collections::VecDeque::new(); - assert!( - at_recent_plan_high(&mut recent, 109_768), - "the first plan is its own high" - ); - for (plan, expect) in [ - (87_000, false), - (84_000, false), - (86_000, false), - (87_000, true), - ] { - assert_eq!( - at_recent_plan_high(&mut recent, plan), - expect, - "plan {plan} against {recent:?}" - ); - } - assert!( - recent.len() <= REHOME_SUSTAINED_TICKS as usize, - "bounded by the evidence span" - ); -} - -// what this catches: the boot staircase (2026-09-02) the streak's plan-high rule -// exists for. Personas register serially at boot, so the plan climbs in stairs; -// a re-home per stair was sixteen model loads in one lane's log. While every tick -// is a new high, nothing fires; once the climb stops, exactly one re-home at the top. -#[tokio::test] -async fn a_climbing_plan_coalesces_into_one_re_home_at_its_top() { - let serves = Arc::new(AtomicUsize::new(0)); - let (daemon, top) = lane_under_plan(serves.clone(), 65_536, 4); - let budget = HostBudget { - usable_bytes: 45 * GB, - perf_cores: 6, - }; - let at = |w: u32| vec![footprint_from_parts("coder-14b", 9 * GB, w, true, None).unwrap()]; - for (stair, w) in [ - top / 4, - top * 3 / 8, - top / 2, - top * 5 / 8, - top * 3 / 4, - top * 7 / 8, - top, - ] - .into_iter() - .enumerate() - { - let plan = at(w); - daemon.publish_plan(budget, &plan, &plan); - assert!( - daemon.reconcile_to_plan().is_none(), - "stair {stair}: a climbing plan must not re-home" - ); - } - let plan = at(top); - for tick in 1..REHOME_SUSTAINED_TICKS { - daemon.publish_plan(budget, &plan, &plan); - assert!( - daemon.reconcile_to_plan().is_none(), - "settled tick {tick}: still proving the plan stopped" - ); - } - daemon.publish_plan(budget, &plan, &plan); - assert!( - daemon.reconcile_to_plan().is_some(), - "the climb stopped: one re-home, at its top (no stair above re-homed)" - ); -} - -// what this catches: the cooldown collapsing into the sustained-delta test. The -// two answer different questions — "is the gain real?" vs "may we pay for it -// yet?" — and a relaunch kills every in-flight turn on the lane, so the rate -// limit has to hold even when the evidence is perfect. If the cooldown were -// merely "reset the streak", 3 more qualifying ticks would re-fire in 15s -// instead of 90. (BigMama's requirement 1 of 2, 2026-08-06.) -#[tokio::test] -async fn a_second_re_home_waits_out_the_cooldown_however_good_the_evidence_is() { - let serves = Arc::new(AtomicUsize::new(0)); - let (daemon, _plan) = lane_under_plan(serves.clone(), 65_536, 62); - let starved = daemon.serving_tx.borrow().clone(); - - let mut decision = None; - for _ in 0..REHOME_SUSTAINED_TICKS { - decision = daemon.reconcile_to_plan(); - } - decision - .expect("evidence qualifies by the third tick") - .await - .unwrap(); - assert_eq!( - serves.load(Ordering::SeqCst), - 1, - "the first re-home fires on evidence" - ); - - // Re-pin the lane to its starved window: the relaunch is faked, so nothing - // actually resized. That makes the gain as compelling on every following tick - // as it was on the first — only the cooldown stands between us and a storm. - let _ = daemon.serving_tx.send_replace(starved); - for tick in 0..REHOME_COOLDOWN_TICKS { - assert!( - daemon.reconcile_to_plan().is_none(), - "cooldown tick {tick}: perfect evidence must still not buy a second relaunch" - ); - } - assert_eq!( - serves.load(Ordering::SeqCst), - 1, - "exactly one relaunch per cooldown window" - ); - - // Cooldown spent — the gain must now re-prove itself from zero before firing. - for tick in 0..(REHOME_SUSTAINED_TICKS - 1) { - assert!( - daemon.reconcile_to_plan().is_none(), - "post-cooldown tick {tick}: the streak was lost while cooling, re-prove it" - ); - } - assert!( - daemon.reconcile_to_plan().is_some(), - "once cooled AND re-proven, the still-stranded lane re-homes again" - ); -} - -// what this catches: a margin expressed as an absolute token count. The same -// 2,048-token shortfall is a third of a small lane and rounding error on a large -// one — an absolute bar means something different at every window size, so the -// relative margin is the property, not an implementation detail of it. -#[tokio::test] -async fn the_margin_is_relative_so_the_same_shortfall_decides_differently_by_lane_size() { - // A lane at 93% of plan: the shortfall is ~7.5% of what it serves — real - // tokens, but under the bar however long it persists. - let quiet = Arc::new(AtomicUsize::new(0)); - let (near_plan, _) = lane_under_plan(quiet.clone(), 65_536, 93); - for _ in 0..(REHOME_SUSTAINED_TICKS * 3) { - near_plan.reconcile_to_plan(); - } - assert_eq!( - quiet.load(Ordering::SeqCst), - 0, - "a 7.5% shortfall is not worth killing in-flight turns for, however long it holds" - ); - - // A lane at 67% of the SAME plan: the shortfall is ~49% of what it serves — - // half a mind again, a step change. - let loud = Arc::new(AtomicUsize::new(0)); - let (far_below, _) = lane_under_plan(loud.clone(), 65_536, 67); - let mut decision = None; - for _ in 0..REHOME_SUSTAINED_TICKS { - decision = far_below.reconcile_to_plan(); - } - decision.expect("a 49% shortfall qualifies").await.unwrap(); - assert_eq!( - loud.load(Ordering::SeqCst), - 1, - "half the lane's own window again IS a step change — re-home" - ); -} - -// what this catches: a lane whose per-slot window froze at ≤ HALF the -// currently-planned window gets RE-HOMED (relaunched) even though model + -// genome match. A server spawned under transient memory pressure (a scratch -// benchmark server) otherwise keeps its starved window forever — 2026-07-10: -// the living Devstral froze at 3.8k/slot on a 131k model while 14,700 plan -// recomputes wandered above it, and the room degenerated into a greeting -// loop. Within 2× of the plan → hysteresis holds, no relaunch churn. -#[tokio::test] -async fn reconcile_re_homes_a_starved_window_but_holds_within_hysteresis() { - let serves = Arc::new(AtomicUsize::new(0)); - let daemon = daemon_with(Arc::new(FakeServer::healthy(serves.clone(), true))); - - let budget = HostBudget { - usable_bytes: 45 * GB, - perf_cores: 6, - }; - let candidates = vec![footprint_from_parts("coder-14b", 9 * GB, 8192, true, None).unwrap()]; - daemon.publish_plan(budget, &candidates, &candidates); - let (plan_window, plan_lanes) = { - let plan = daemon.plan_tx.borrow(); - let plan = plan.plan.as_ref().expect("plan published"); - (plan.served_context_window, plan.lanes) - }; - - // Same model + genome, but the live slot froze far below the plan. - let _ = daemon.serving_tx.send_replace(ServingSnapshot { - // test fixture: no live readiness was ever CONFIRMED here. - ready_verified_at_ms: None, - active_model: Some("coder-14b".into()), - ready: true, - base_url: serving_v1_url(), - adapters: Vec::new(), - served_context_window: plan_window / 4, - lanes: plan_lanes, - host_prompt_cache_mib: 0, - degraded_reason: None, - vision_ready: false, - vision_base_url: None, - vision_model: None, - loading_model: None, - held_for: None, - }); - // A quarter of the plan is a 300% shortfall — far past the margin — but the - // gain must still PERSIST before it buys a relaunch (BigMama's sustained-delta - // replacement for the original 2x ratio, 2026-08-06). - for tick in 1..REHOME_SUSTAINED_TICKS { - assert!( - daemon.reconcile_to_plan().is_none(), - "tick {tick}: even a starved lane must prove the gain is sustained" - ); - } - daemon - .reconcile_to_plan() - .expect("starved window must trigger a re-home") - .await - .unwrap(); - assert_eq!(serves.load(Ordering::SeqCst), 1, "one relaunch"); - - // Within hysteresis (> half the plan) → hold, no churn. - let _ = daemon.serving_tx.send_replace(ServingSnapshot { - // test fixture: no live readiness was ever CONFIRMED here. - ready_verified_at_ms: None, - active_model: Some("coder-14b".into()), - ready: true, - base_url: serving_v1_url(), - adapters: Vec::new(), - served_context_window: plan_window / 2 + 256, - lanes: plan_lanes, - host_prompt_cache_mib: 0, - degraded_reason: None, - vision_ready: false, - vision_base_url: None, - vision_model: None, - loading_model: None, - held_for: None, - }); - assert!( - daemon.reconcile_to_plan().is_none(), - "within 2\u{d7} of the plan the lane holds — no relaunch churn" - ); - assert_eq!(serves.load(Ordering::SeqCst), 1, "still one relaunch"); -} - -// what this catches (card 7c72c0f0, Intel Mac 2026-09-17): the plan's budget is the -// row the lane's PLACEMENT puts its bytes in. A CPU-placed lane budgets against the -// Ram row — the 30 GB the KV actually fills — not the 4 GB Vram row of a card that -// holds nothing of it (nine citizens sized against 5.7 GB on a 34.4 GB box: one warm -// slot, eight exiled to a remote lane). The GPU arm is byte-identical to before. -#[tokio::test] -async fn a_cpu_placed_lane_budgets_against_the_ram_row_not_the_card() { - use crate::inference::llama_server::LanePlacement; - use crate::resources::{DaemonConfig, GovernorConfig, MockCapacitySource, ResourceDaemon}; - let vram = Arc::new(MockCapacitySource::new( - crate::resources::ResourceKind::Vram, - 4_000, - )); - let ram = Arc::new(MockCapacitySource::new( - crate::resources::ResourceKind::Ram, - 30_000, - )); - let daemon = ResourceDaemon::start( - vec![vram, ram], - vec![], - DaemonConfig { - tick_interval: std::time::Duration::from_millis(20), - min_reclaim_budget: std::time::Duration::from_millis(100), - governor: GovernorConfig { - min_dwell_ms: 0, - graceful_grace_ms: 50, - }, - }, - ); - assert_eq!( - LanePlacement::Cpu.pool_kind(), - crate::resources::ResourceKind::Ram - ); - assert_eq!( - LanePlacement::Gpu.pool_kind(), - crate::resources::ResourceKind::Vram - ); - assert_eq!( - governed_pool_ceiling(&daemon, LanePlacement::Cpu.pool_kind()), - Some(30_000), - "a CPU-placed lane plans against the RAM its KV lives in" - ); - assert_eq!( - governed_pool_ceiling(&daemon, LanePlacement::Gpu.pool_kind()), - Some(4_000), - "a GPU-placed lane plans against the card" - ); -} From 3084ab775bfe91e325d934184300fe15981d6cb7 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 2 Nov 2026 21:09:06 -0600 Subject: [PATCH 2/3] The shared pool is its own owner: llama_server::shared_pool puts --kv-unified on a launch and reads it back off a running engine's argv (lane_args untouched) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/inference/lane_args.rs | 15 ++++++----- .../src/inference/llama_server.rs | 1 + .../inference/llama_server/control_impl.rs | 2 +- .../src/inference/llama_server/prepare.rs | 3 ++- .../src/inference/llama_server/shared_pool.rs | 25 +++++++++++++++++++ .../llama_server/tests/engine_install.rs | 6 ++--- 6 files changed, 39 insertions(+), 13 deletions(-) create mode 100644 core/continuum-engine/src/inference/llama_server/shared_pool.rs diff --git a/core/continuum-engine/src/inference/lane_args.rs b/core/continuum-engine/src/inference/lane_args.rs index c8e4790c90..022bfb66c0 100644 --- a/core/continuum-engine/src/inference/lane_args.rs +++ b/core/continuum-engine/src/inference/lane_args.rs @@ -312,18 +312,17 @@ pub fn base_invocation( host.to_string(), arg("--port"), port.to_string(), - // ONE SHARED POOL (2026-11-03): `-c` is the whole KV pool and `--parallel` the - // most sequences that may draw on it; under `--kv-unified` each sequence can use - // the whole pool and an idle one holds none. Both are fixed for the process's - // life: which minds hold how much is decided at runtime, never by a relaunch (the - // M5 loaded its model 40 times as the slot count moved 1 -> 2 -> 1, every - // reload wiping every mind's cache). `--parallel` stays explicit: llama.cpp's - // default is 4. See `served_total_ctx` / `parallel_lanes`. + // llama-server's `-c` is the TOTAL KV cache, split evenly across the + // `--parallel` slots; each request only sees `-c / n_parallel` tokens. + // The plan's `context_window` is PER-LANE, so the total we must request + // is `context_window * lanes` — then each of `lanes` slots holds exactly + // one planned window. We pass `--parallel` EXPLICITLY (never inherit + // llama.cpp's default, which is 4 and silently quartered the window in + // the prior bug). See `served_total_ctx` / `parallel_lanes`. arg("-c"), total_ctx.to_string(), arg("--parallel"), lanes.to_string(), - arg("--kv-unified"), // KV PREFIX REUSE across a persona's turns. `cache_prompt:true` (sent // per-request) only reuses a slot's prior content when the *exact* // prefix still sits in that slot; with the volatile grounding tail diff --git a/core/continuum-engine/src/inference/llama_server.rs b/core/continuum-engine/src/inference/llama_server.rs index c852efca6e..a10abd3ab8 100644 --- a/core/continuum-engine/src/inference/llama_server.rs +++ b/core/continuum-engine/src/inference/llama_server.rs @@ -55,6 +55,7 @@ pub use liveness::{ mod convergence_attempt; mod reconcile; +mod shared_pool; pub use reconcile::{ensure_model_serving, ensure_model_serving_if_current}; mod smoke; diff --git a/core/continuum-engine/src/inference/llama_server/control_impl.rs b/core/continuum-engine/src/inference/llama_server/control_impl.rs index 851de27274..de71097277 100644 --- a/core/continuum-engine/src/inference/llama_server/control_impl.rs +++ b/core/continuum-engine/src/inference/llama_server/control_impl.rs @@ -337,7 +337,7 @@ impl LlamaServerControl for LlamaServerProcess { let (_host, port) = split_host_port(&self.root); let record = crate::inference::lane_registry::live_lane().filter(|r| r.port == port)?; let argv = crate::inference::lane_process::command_args(record.pid)?; - Some(argv.iter().any(|a| a == "--kv-unified" || a == "-kvu")) + Some(super::shared_pool::launched_on_shared_pool(&argv)) } fn wedge_flag(&self) -> Option { diff --git a/core/continuum-engine/src/inference/llama_server/prepare.rs b/core/continuum-engine/src/inference/llama_server/prepare.rs index d70e065d17..ead8f568a3 100644 --- a/core/continuum-engine/src/inference/llama_server/prepare.rs +++ b/core/continuum-engine/src/inference/llama_server/prepare.rs @@ -274,7 +274,7 @@ impl LlamaServerProcess { target.adapters.iter().map(|a| a.path.clone()).collect(); let expert_ot = target.expert_ot_value(); - let mut invocation = crate::inference::lane_args::base_invocation( + let invocation = crate::inference::lane_args::base_invocation( &gguf, &target.model.id, &host, @@ -311,6 +311,7 @@ impl LlamaServerProcess { max_ubatch: target.model.serving.max_ubatch, reasoning_budget: target.model.serving.reasoning_budget, }); + let mut invocation = super::shared_pool::on_shared_pool(invocation); // MoE glass-box env seam (#278): when expert paging is active, the DAEMON // hands the fork its capture + plan file locations. Previously these envs // existed only when an operator hand-exported them before booting the diff --git a/core/continuum-engine/src/inference/llama_server/shared_pool.rs b/core/continuum-engine/src/inference/llama_server/shared_pool.rs new file mode 100644 index 0000000000..6b0a942554 --- /dev/null +++ b/core/continuum-engine/src/inference/llama_server/shared_pool.rs @@ -0,0 +1,25 @@ +//! ONE SHARED POOL (2026-11-03, Joel: "Slot counts should never require shutdown"). The +//! engine starts with `--kv-unified`: `-c` is one KV pool and `--parallel` the most sequences +//! that may draw on it; each sequence can use the whole pool and an idle one holds none. Which +//! minds hold how much is decided at runtime, never by a relaunch: the M5 loaded its model 40 +//! times as the plan's slot count moved 1 -> 2 -> 1, every reload wiping every mind's cache. +//! +//! The one owner of that decision: it puts the flag on a launch, and reads it back off a +//! running engine's argv so the reconcile can move an engine on fixed slots to the pool once. + +use crate::inference::lane_args::LaneInvocation; + +/// llama-server's switch for one KV pool shared by every sequence (`-kvu` is its short form). +const SHARED_POOL: &str = "--kv-unified"; +const SHARED_POOL_SHORT: &str = "-kvu"; + +/// Launch on the shared pool: every sequence draws on all of `-c`. +pub(super) fn on_shared_pool(mut invocation: LaneInvocation) -> LaneInvocation { + invocation.args.push(SHARED_POOL.to_string()); + invocation +} + +/// Was this argv launched on the shared pool? +pub(super) fn launched_on_shared_pool(argv: &[String]) -> bool { + argv.iter().any(|a| a == SHARED_POOL || a == SHARED_POOL_SHORT) +} diff --git a/core/continuum-engine/src/inference/llama_server/tests/engine_install.rs b/core/continuum-engine/src/inference/llama_server/tests/engine_install.rs index f3f3efb667..c7a24b6288 100644 --- a/core/continuum-engine/src/inference/llama_server/tests/engine_install.rs +++ b/core/continuum-engine/src/inference/llama_server/tests/engine_install.rs @@ -116,12 +116,12 @@ fn the_engine_launches_on_one_shared_pool() { let mut planned = target("pool-fixture"); planned.context_window = 58_112; planned.lanes = 5; - let invocation = crate::inference::lane_args::base_invocation( + let invocation = super::super::shared_pool::on_shared_pool(crate::inference::lane_args::base_invocation( Path::new("fixture.gguf"), planned.model_id(), "127.0.0.1", 1, planned.parallel_lanes(), planned.served_total_ctx(), planned.host_prompt_cache_mib, Path::new("pages"), - ); + )); assert_eq!(invocation.value_of("-c"), Some("290560")); assert_eq!(invocation.value_of("--parallel"), Some("5")); - assert!(invocation.has("--kv-unified")); + assert!(super::super::shared_pool::launched_on_shared_pool(&invocation.args), "the launch and the read-back agree"); } From 35efbe08dbb2cb8b4959f81691d2eae753fd9547 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Mon, 2 Nov 2026 21:48:07 -0600 Subject: [PATCH 3/3] Review fixes (Cormac + an independent read): the pool is what serving may hold at rest, each sequence its share - The pool is sized from the at-rest serving budget (physical at the current mode, less every other consumer's residency on the board, less the prompt cache on unified memory), laid out by the plan's own per-lane arithmetic (`window_within(at_rest, sequences)`). Each sequence fits its compute and never exceeds the trained window: no multi-million-token pool on a hybrid model, and no pool that ignores the sidecar, the cache or training. pool.rs is deleted. - The sequences are the seated minds, the minds leased in at the last plan, and scratch. - Each sequence is published its share of the engine's own pool and sequence count (`sequence_share`), only when the engine is known to be on the shared pool. An unmigrated engine publishes its per-slot window as served. Shares never sum past the pool, so scratch keeps its share (a full pool fails the whole decode batch). The daemon needs no republish rule. - An unreadable argv probes `serving.pool.unknown`. - `served_window_store` records again from the ready path, at the published share, matched to samples on the engine's own shape. - The exam no longer waits for a grow-relaunch that cannot come; the now-dead `wait_for_serving_window_settle` is deleted. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/exam_serving.rs | 40 ++------ .../src/inference/llama_server.rs | 3 +- .../src/inference/llama_server/external.rs | 36 -------- .../src/inference/llama_server/reconcile.rs | 13 ++- .../src/inference/planning/serving_plan.rs | 1 - .../inference/planning/serving_plan/pool.rs | 22 ----- .../src/modules/serving_daemon.rs | 2 +- .../src/modules/serving_daemon/launch.rs | 92 ++++++++++++------- .../src/modules/serving_daemon/publication.rs | 26 +++--- .../src/modules/serving_daemon/reconcile.rs | 28 +++++- .../serving_daemon/tests/one_launch.rs | 15 +-- .../serving_daemon/tests/publication.rs | 20 ++-- .../serving_daemon/tests/reconciliation.rs | 4 +- 13 files changed, 137 insertions(+), 165 deletions(-) delete mode 100644 core/continuum-engine/src/inference/planning/serving_plan/pool.rs diff --git a/core/continuum-academy/src/cognition/exam_serving.rs b/core/continuum-academy/src/cognition/exam_serving.rs index 81e701b59e..5098563beb 100644 --- a/core/continuum-academy/src/cognition/exam_serving.rs +++ b/core/continuum-academy/src/cognition/exam_serving.rs @@ -5,17 +5,10 @@ //! The living-persona benchmark used to grab a bare hold and *assume* it was a //! co-tenant slot; the comment said "= `Placement::ShareLane`" but nothing computed it. This //! module makes it real: it runs the model-aware admission kernel ([`plan_placement`]), and -//! for a share it drives the GROW → SETTLE sequence: -//! 1. **GROW** — declare LUDICROUS ([`ServingLudicrousHold`] → `PowerMode::Performance`), so -//! the daemon re-plans the shared lane to the biggest window the machine fits. Never a -//! starved boot-window (the 2048-eco incident). -//! 2. **SETTLE** — wait for any grow-relaunch to finish -//! ([`wait_for_serving_window_settle`](crate::inference::llama_server::wait_for_serving_window_settle)). -//! A naive "force Performance then run" thrashes: acquiring Ludicrous is itself a re-plan -//! → relaunch, and a relaunch mid-exam connection-refuses every generation (the reverted -//! `95dcec669`). Settling BEFORE the tasks run absorbs that relaunch once, up front. -//! Nothing relaunches the engine for size since 2026-11-03 (one launch, a shared pool), so no -//! pin is needed once the exam runs. +//! for a share it declares LUDICROUS ([`ServingLudicrousHold`] → `PowerMode::Performance`) for +//! the exam's run. Nothing relaunches the engine for a window since 2026-11-03 (one launch, a +//! shared pool), so there is no grow-relaunch to absorb and no pin to hold; the exam's larger +//! window becomes a grant request (S2). //! The verdict is CARRIED for observability + the curriculum ledger. //! //! The `SpawnLane`/`CpuSpill` arms are the rails a DIFFERENT-base exam or a grid placement @@ -24,20 +17,10 @@ //! [[proctored-exam-session-dependable-benchmark]] [[serving-mode-follows-activity-ludicrous-to-dream]] //! [[benchmark-window-must-be-big-not-a-clamped-prompt]] [[lane-admission-planner-scenario-driven]] -use std::time::Duration; use crate::inference::serving_holds::ServingLudicrousHold; use crate::resources::placement::{plan_placement, LaneDemand, Placement, ResidentLane}; -/// How long to watch for a grow-relaunch to START (lane goes not-ready) after declaring -/// Ludicrous. Must EXCEED the serving daemon's 5s re-plan `TICK` so a relaunch has time to -/// fire; if none does in this window, the lane was already at the target window (no grow). -const LUDICROUS_SETTLE_GRACE: Duration = Duration::from_secs(8); - -/// Bound for the whole grow-relaunch to finish (kill + respawn + model reload). A 24B reload -/// is tens of seconds; generous so a real grow always completes, but never hangs the exam. -const LUDICROUS_SETTLE_TIMEOUT: Duration = Duration::from_secs(180); - /// The verdict the exam ACQUIRE reached — carried for observability + the curriculum ledger, /// so the strategic decision behind every measurement is inspectable. #[derive(Debug, Clone, PartialEq, Eq)] @@ -142,21 +125,14 @@ impl ExamServingContext { } } - /// GROW (declare Ludicrous) → SETTLE. The Ludicrous hold is taken FIRST and kept, so - /// `host_budget` plans at Performance for the whole exam, and the exam starts on a settled - /// window. + /// Declare Ludicrous for the exam: `host_budget` plans at Performance for its whole run. + /// Nothing relaunches the engine for a window since one launch (2026-11-03), so there is no + /// grow to wait for; the exam's larger window becomes a grant request (S2). async fn grow_settle() -> ExamHold { let ludicrous = ServingLudicrousHold::acquire(); - let settled = crate::inference::llama_server::wait_for_serving_window_settle( - LUDICROUS_SETTLE_GRACE, - LUDICROUS_SETTLE_TIMEOUT, - ) - .await; continuum_base::probe!( class = "exam.acquire.ludicrous", - settled_window = settled.unwrap_or(0), - settled = settled.is_some(), - "exam lane grown to Ludicrous (Performance) and settled before pinning" + "exam serving declared Ludicrous (Performance) for its run" ); ExamHold { _ludicrous: ludicrous, diff --git a/core/continuum-engine/src/inference/llama_server.rs b/core/continuum-engine/src/inference/llama_server.rs index a10abd3ab8..42c5977bb5 100644 --- a/core/continuum-engine/src/inference/llama_server.rs +++ b/core/continuum-engine/src/inference/llama_server.rs @@ -97,7 +97,6 @@ use engine_install::{ }; mod snapshot; pub mod serving_hold; -use snapshot::SERVING_STATE; pub use snapshot::{ await_ready_serving, await_snapshot_resettle, current_serving, has_reconciled, install_serving_state, mark_first_reconcile, serving_state_receiver, MultimodalSupport, @@ -107,7 +106,7 @@ mod vision; pub use vision::vision_lane_ready; use vision::{main_lane_mmproj_decision_for, MainLaneMmproj}; mod external; -pub use external::{external_serving_pin, probe_external_serving, wait_for_serving_window_settle}; +pub use external::{external_serving_pin, probe_external_serving}; mod progress; pub(crate) use progress::{ diff --git a/core/continuum-engine/src/inference/llama_server/external.rs b/core/continuum-engine/src/inference/llama_server/external.rs index b70a9b0e6d..e4533c95ad 100644 --- a/core/continuum-engine/src/inference/llama_server/external.rs +++ b/core/continuum-engine/src/inference/llama_server/external.rs @@ -170,39 +170,3 @@ pub async fn probe_external_serving(timeout: Duration) -> Option Option { - let mut rx = SERVING_STATE.get()?.clone(); - let start = std::time::Instant::now(); - // Phase 1: did a relaunch start (lane went not-ready) within the grace window? - let relaunched = tokio::time::timeout(settle_grace, rx.wait_for(|s| !s.ready)) - .await - .is_ok(); - if !relaunched { - // No relaunch — the window was already at target. Return it if ready. - let s = rx.borrow_and_update(); - return s.ready.then_some(s.served_context_window); - } - // Phase 2: wait for the relaunched lane to come back decode-ready. Bind the timeout result - // before matching so its `watch::Ref` temporary drops before `rx` does (else E0597). - let remaining = timeout.saturating_sub(start.elapsed()); - let waited = tokio::time::timeout(remaining, rx.wait_for(|s| s.is_live())).await; - match waited { - Ok(Ok(guard)) => Some(guard.served_context_window), - _ => None, - } -} diff --git a/core/continuum-engine/src/inference/llama_server/reconcile.rs b/core/continuum-engine/src/inference/llama_server/reconcile.rs index 41170383f1..9662d07037 100644 --- a/core/continuum-engine/src/inference/llama_server/reconcile.rs +++ b/core/continuum-engine/src/inference/llama_server/reconcile.rs @@ -180,7 +180,18 @@ async fn serve_or_adopt( // 2026-11-03) is moved to the shared pool by one relaunch; after that no window, // lane or cache change ever relaunches it. Unknown (no argv, a fake) is not a // mismatch. - let pool_ok = ctrl.launched_on_shared_pool().unwrap_or(true); // unwrap_or: unknown (no argv, a fake) is not a mismatch + let pool_ok = match ctrl.launched_on_shared_pool() { + Some(on_pool) => on_pool, + None => { + // Unknown is not a mismatch (no spurious relaunch), but it is said, so a + // node left on fixed slots is findable (Cormac on #5720). + continuum_base::probe!(target: "continuum_core::inference::llama_server", class = "serving.pool.unknown", + model = target.model_id(), + "the running engine's argv is unreadable: whether it is on the shared pool is unknown, so it is kept as it is" + ); + true + } + }; // THE ENGINE ITSELF — the fourth operand (card 7c5f139d). A deploy installs the // engine the pin names (install-llama-server.sh, stamp-gated, atomic), but every // deploy leaves the lane up for the next core, so an adopted lane keeps running diff --git a/core/continuum-engine/src/inference/planning/serving_plan.rs b/core/continuum-engine/src/inference/planning/serving_plan.rs index 426c2fef72..7db879d014 100644 --- a/core/continuum-engine/src/inference/planning/serving_plan.rs +++ b/core/continuum-engine/src/inference/planning/serving_plan.rs @@ -43,7 +43,6 @@ mod max_lanes; pub use max_lanes::*; mod plan_serving; pub use plan_serving::*; -mod pool; #[cfg(test)] mod tests; diff --git a/core/continuum-engine/src/inference/planning/serving_plan/pool.rs b/core/continuum-engine/src/inference/planning/serving_plan/pool.rs deleted file mode 100644 index 85240c13bd..0000000000 --- a/core/continuum-engine/src/inference/planning/serving_plan/pool.rs +++ /dev/null @@ -1,22 +0,0 @@ -//! The engine's ONE shared KV pool on a budget (2026-11-03, Joel: "Slot counts should never -//! require shutdown"). Under `--kv-unified` every sequence draws on one pool, so the pool is -//! what the budget holds beside the weights and one compute buffer, not windows laid side by -//! side, and not capped at the trained window: each mind's share inside it is bounded where -//! it is published. - -use super::ModelFootprint; - -impl ModelFootprint { - /// Tokens of shared KV `usable_bytes` holds for this model: the one-lane fit without the - /// trained-window cap. 0 when the model has no measured KV cost, so nothing can be fitted. - pub fn pool_within(&self, usable_bytes: u64) -> u32 { - if self.kv_per_token == 0 { - return 0; - } - ModelFootprint { - context_window: u32::MAX, - ..self.clone() - } - .window_within(usable_bytes, 1) - } -} diff --git a/core/continuum-serving/src/modules/serving_daemon.rs b/core/continuum-serving/src/modules/serving_daemon.rs index 15cb7c762c..5aa28e8b01 100644 --- a/core/continuum-serving/src/modules/serving_daemon.rs +++ b/core/continuum-serving/src/modules/serving_daemon.rs @@ -581,7 +581,7 @@ mod publication; #[cfg(test)] use publication::SERVING_SNAPSHOT_EVENT; pub use publication::{published_lanes, VerifiedServingCapture}; -use publication::{seated_share, snapshot_from_outcome, verified_capture}; +use publication::{sequence_share, snapshot_from_outcome, verified_capture}; mod placement; pub use placement::sidecar_window_for_headroom; use placement::{ diff --git a/core/continuum-serving/src/modules/serving_daemon/launch.rs b/core/continuum-serving/src/modules/serving_daemon/launch.rs index 26cbb5213c..2fa593ec26 100644 --- a/core/continuum-serving/src/modules/serving_daemon/launch.rs +++ b/core/continuum-serving/src/modules/serving_daemon/launch.rs @@ -16,21 +16,47 @@ pub(super) struct ReconcileLaunch { } impl ServingDaemonModule { - /// The engine's one KV pool, sized ONCE when the engine starts and never by a relaunch: - /// every token this host's budget holds beside the weights and one compute buffer, laid out - /// as a sequence for each seated mind plus the scratch traffic beside them, `(per-sequence - /// tokens, sequences)` so `-c` is the pool and `--parallel` the ceiling. Sized from the plan - /// it would have been 1 x 80k on a cold boot that counted two residents (the M5, 2026-11-03 - /// 00:52Z). A model with no measured footprint has no budget fit, so its pool is the plan's - /// windows side by side: a fit, not a constant. - fn engine_pool(&self, model: &crate::model_registry::types::Model, served_ctx: u32, lanes: u32) -> (u32, u32) { - let sequences = self.seated().saturating_add(1).max(lanes); - let fitted = footprint_for(model).map(|fp| fp.pool_within(self.physical_budget().usable_bytes)); - let pool = match fitted.filter(|tokens| *tokens > 0) { + /// The engine's one KV pool, sized ONCE when the engine starts and never by a relaunch, as + /// `(per-sequence tokens, sequences)` so `-c` is the pool and `--parallel` the ceiling. + /// + /// The sequences: every seated mind, the minds leased in from other nodes at the last plan, + /// and the scratch traffic beside them. The pool: what serving may hold AT REST (the + /// physical budget at the current mode, less every other consumer's measured residency on + /// the board, less the prompt cache's grant where it is the same memory), laid out by the + /// plan's own arithmetic, so each sequence fits its compute and never exceeds the trained + /// window. Not the live plan budget, which counts the outgoing engine against itself, and + /// not the cold plan's window x lanes, which was 1 x 80k on a boot that counted two + /// residents (the M5, 2026-11-03 00:52Z). A model with no measured footprint has no fit, + /// so its sequences take the plan's window: a fit, not a constant. + fn engine_pool( + &self, + model: &crate::model_registry::types::Model, + served_ctx: u32, + lanes: u32, + host_prompt_cache_mib: u32, + ) -> (u32, u32) { + let leased_in = LAST_LEASED_IN_PEAK.load(Ordering::Relaxed); + let sequences = self.seated().saturating_add(1).saturating_add(leased_in).max(lanes); + let kind = serving_pool_kind(); + let others: u64 = self + .resource_daemon + .board() + .attributions + .iter() + .filter(|a| a.consumer_id != SERVING_CONSUMER_ID && a.kind == kind) + .map(|a| a.bytes) + .sum(); + let cache = match self.system.gpu_memory_mode() { + Some(crate::gpu::monitor::MemoryMode::Unified) => u64::from(host_prompt_cache_mib) << 20, + _ => 0, + }; + let at_rest = self.physical_budget().usable_bytes.saturating_sub(others).saturating_sub(cache); + let fitted = footprint_for(model).map(|fp| fp.window_within(at_rest, sequences)); + let per_sequence = match fitted.filter(|tokens| *tokens > 0) { Some(tokens) => tokens, - None => served_ctx.saturating_mul(lanes.max(1)), + None => served_ctx, }; - (pool / sequences, sequences) + (per_sequence, sequences) } pub(super) fn launch_reconciled_plan(&self, launch: ReconcileLaunch) -> Option> { @@ -44,9 +70,9 @@ impl ServingDaemonModule { desired_adapters, desired_adapter_paths, } = launch; - // Past the no-relaunch guard a relaunch WILL happen: the window it takes is the plan's - // through the sticky, wedge-heal and physical-fit laws (`launch_window`, the one owner the - // tick's page seed reads too), each step that moved it reported here. + // Past the no-relaunch guard the ensure runs: it adopts a serving engine, or launches one + // whose window starts from the plan's through the sticky, wedge-heal and physical-fit laws + // (`launch_window`, the one owner the tick's page seed reads too), each step reported here. let window = self.launch_window(&desired, served_ctx, lanes); if window.floored != window.sticky { continuum_base::probe!( @@ -135,8 +161,7 @@ impl ServingDaemonModule { // separates "a bit small" from "structurally cannot cache anything". let one_conversation_mib = prompt_cache.one_conversation_mib; let host_prompt_cache_mib = prompt_cache.mib; - let (per_sequence, sequences) = self.engine_pool(&model, served_ctx, lanes); - let seated = self.seated(); + let (per_sequence, sequences) = self.engine_pool(&model, served_ctx, lanes, host_prompt_cache_mib); let target = ServingTarget { host_prompt_cache_mib, model, @@ -319,14 +344,17 @@ impl ServingDaemonModule { } EnsureOutcome::Degraded { .. } | EnsureOutcome::Superseded => 0, }; - // ONE SHARED POOL: the engine's `/props` names the whole pool as each sequence's - // window and its sequence ceiling as its slots; every seated mind is published her - // share of it (`seated_share`), so what the readers budget and charge is the pool. - let (served_window, served_lanes) = if served_window > 0 { - seated_share(served_window, seated, target.model.context_window) - } else { - (served_window, served_lanes) - }; + // ONE SHARED POOL: an engine on it names the whole pool as each sequence's window + // in `/props`; each sequence is published its share (`sequence_share`), so what the + // readers budget and charge is the pool. An engine not known to be on it publishes + // its per-slot window as served. + let (served_window, served_lanes) = + match (served_window > 0, server.launched_on_shared_pool()) { + (true, Some(true)) => { + sequence_share(served_window, served_lanes, target.model.context_window) + } + _ => (served_window, served_lanes), + }; // The grant the engine was LAUNCHED with: the spawn fact on the control, or — for // a lane this core did not spawn (ADOPTED; every deploy leaves the lane up for // the next core, so this is the common case, not the rare one) — read off the @@ -401,10 +429,12 @@ impl ServingDaemonModule { served_window = served_window as u64, served_lanes = served_lanes as u64, "the running engine holds LESS host prompt cache than today's \ - decision wants — `--cache-ram` is fixed at spawn, so this gap \ - closes only on a relaunch (card ab27b914). Read \ - `below_one_conversation`: true means the grant cannot retain a \ - single prefix and reuse is structurally impossible, not merely poor" + decision wants — `--cache-ram` is fixed at spawn and the engine is \ + never relaunched for a size (one launch, 2026-11-03), so the gap \ + stands until its next launch; the cache becomes a runtime grant \ + with the seat API. Read `below_one_conversation`: true means the \ + grant cannot retain a single prefix and reuse is structurally \ + impossible, not merely poor" ), None => continuum_base::probe!( target: "continuum_core::modules::serving_daemon", class = "serving.prompt_cache.divergence_closed", @@ -414,7 +444,7 @@ impl ServingDaemonModule { was_held_mib = previous.as_ref().map(|(_, h, _, _)| *h).unwrap_or(0) as u64, // unwrap_or: no prior state recorded was_wanted_mib = previous.as_ref().map(|(_, _, w, _)| *w).unwrap_or(0) as u64, // unwrap_or: as above "the prompt-cache divergence closed — the engine's grant now meets \ - today's decision (a relaunch, or the target fell back to it)" + today's decision (a new launch, or the target fell back to it)" ), } } diff --git a/core/continuum-serving/src/modules/serving_daemon/publication.rs b/core/continuum-serving/src/modules/serving_daemon/publication.rs index d1e345d693..065cac8246 100644 --- a/core/continuum-serving/src/modules/serving_daemon/publication.rs +++ b/core/continuum-serving/src/modules/serving_daemon/publication.rs @@ -32,7 +32,7 @@ pub(super) fn verified_capture( if snapshot.active_model.as_deref() != Some(launch.target.model.id.as_str()) || snapshot.adapters != launch.target.adapter_paths() || (snapshot.served_context_window, snapshot.lanes) - != seated_share(launch.observed_context_window, snapshot.lanes, launch.target.model.context_window) + != sequence_share(launch.observed_context_window, launch.observed_lanes, launch.target.model.context_window) || snapshot.host_prompt_cache_mib != launch.launched_host_prompt_cache_mib || server.owned_engine()? != launch.identity { @@ -53,18 +53,18 @@ pub fn published_lanes(served: Option, target_lanes: u32) -> u32 { served.filter(|n| *n > 0).unwrap_or(target_lanes) } -/// PURE: each seated mind's window inside the engine's one shared pool, and the minds that -/// share it. Under `--kv-unified` the engine's `/props` names the whole pool as every -/// sequence's window; a mind is published her share, capped at the model's trained window, -/// so every reader that charges `lanes x window` charges the pool. The seated count is the -/// node's population, not the plan's per-tick guess (which read 1, 2 and 3 of four residents -/// on the M5 2026-11-03 and relaunched the engine at each). -/// -/// Every seated mind may fill her share at once only with no room for scratch traffic -/// beside them; per-mind grants from demand (#5718's contract) replace this equal share. -pub fn seated_share(served_pool: u32, seated: u32, trained_window: u32) -> (u32, u32) { - let seated = seated.max(1); - ((served_pool / seated).min(trained_window), seated) +/// PURE: each sequence's window inside the engine's one shared pool, and the sequences. An +/// engine on the pool names the whole pool as every sequence's window in `/props`; each is +/// published its share, capped at the model's trained window, so every reader that charges +/// `lanes x window` charges the pool and never more. The sequences are the engine's own, +/// fixed at its one launch (the seated minds, those leased in, and the scratch traffic), so +/// the share never moves with the plan's per-tick lane guess, and the shares never sum past +/// the pool: a pool every sequence fills at once fails the WHOLE decode batch ("Context size +/// has been exceeded", llama.cpp server-context.cpp; Cormac on #5720). Per-mind grants from +/// measured demand (#5718's contract) replace this equal share. +pub fn sequence_share(served_pool: u32, sequences: u32, trained_window: u32) -> (u32, u32) { + let sequences = sequences.max(1); + ((served_pool / sequences).min(trained_window), sequences) } pub(super) fn snapshot_from_outcome( diff --git a/core/continuum-serving/src/modules/serving_daemon/reconcile.rs b/core/continuum-serving/src/modules/serving_daemon/reconcile.rs index 13261a7ac2..3e2c9f4760 100644 --- a/core/continuum-serving/src/modules/serving_daemon/reconcile.rs +++ b/core/continuum-serving/src/modules/serving_daemon/reconcile.rs @@ -318,16 +318,38 @@ impl ServingDaemonModule { // engine holds one shared pool sized once, so a plan that wants a wider window or // more lanes is not a relaunch. The re-home ladder that lived here (sustained // streaks, cooldowns, plan highs, holds, the cache-size re-home) relaunched the - // M5's engine 40 times. What changes at runtime is each seated mind's share: when - // the population moves, the launch path republishes it (an AlreadyServing ensure). + // M5's engine 40 times. Who holds how much of the pool is decided at runtime. if live.ready && live.active_model.as_deref() == Some(desired.as_str()) && live.adapters == desired_adapter_paths - && live.lanes == self.seated() { // The lanes this hour served: the health window's maximum (the lane-bound rest // stands on it). crate::cognition::health_ledger::note_lanes(live.lanes as u64); + // Remember the shape each mind is served for the next boot's plan: the engine's + // own generation and sequences, at the share published from its pool (its + // `/props` window is the whole pool on the shared engine). Settlement is + // idempotent per generation, so a ready tick may record it. + if let Some(model) = live.active_model.as_deref() { + let endpoint = crate::ai::openai_endpoints::OpenAiBase::new(&live.base_url); + if let Some(geometry) = crate::inference::slots::directory() + .endpoint(endpoint.root()) + .served_geometry() + .filter(|g| g.model_id == model && g.lanes == live.lanes) + { + // Samples carry the engine's own shape: match them on it, record the share. + let observed = crate::inference::resource_admission::PromptSample::geometry_median( + &(self.leased_in_sent)(), + endpoint.root(), + &geometry, + ); + let served = crate::inference::served_window_store::ServedGeometry { + per_slot_window: live.served_context_window, + ..geometry + }; + crate::inference::served_window_store::record_reconciled(served, true, observed); + } + } self.acknowledge_verified_target(&live, planned.intent_revision); return None; } diff --git a/core/continuum-serving/src/modules/serving_daemon/tests/one_launch.rs b/core/continuum-serving/src/modules/serving_daemon/tests/one_launch.rs index d6571dc299..b212ddd61b 100644 --- a/core/continuum-serving/src/modules/serving_daemon/tests/one_launch.rs +++ b/core/continuum-serving/src/modules/serving_daemon/tests/one_launch.rs @@ -5,8 +5,7 @@ use super::*; // what this catches: the daemon relaunching a ready engine because the plan wants a different // window or lane count. The M5's plan read 1, 2 and 3 lanes of four residents and its engine // reloaded 40 times (2026-11-02/03). A ready lane serving the right model and genome to the -// seated population is never relaunched, however far the plan's window drifts; when the -// population moves, the launch path republishes each mind's share without a relaunch. +// population is never relaunched, however far the plan's window or lane count drifts. #[tokio::test] async fn a_ready_lane_is_never_relaunched_for_its_window_or_lanes() { let serves = Arc::new(AtomicUsize::new(0)); @@ -43,22 +42,14 @@ async fn a_ready_lane_is_never_relaunched_for_its_window_or_lanes() { loading_model: None, held_for: None, }; - let _ = daemon.serving_tx.send_replace(ready(daemon.seated())); + let _ = daemon.serving_tx.send_replace(ready(4)); for tick in 0..10 { assert!( daemon.reconcile_to_plan().is_none(), "tick {tick}: a quarter of the plan's window is not a relaunch" ); } - let _ = daemon.serving_tx.send_replace(ready(daemon.seated() + 1)); - if let Some(republish) = daemon.reconcile_to_plan() { - republish.await.unwrap(); - } - assert_eq!( - serves.load(Ordering::SeqCst), - 0, - "the population moved: republished, never relaunched" - ); + assert_eq!(serves.load(Ordering::SeqCst), 0, "never relaunched"); } // what this catches (2026-08-15 14:13, round-killer L10 / #438 live): a plan tick diff --git a/core/continuum-serving/src/modules/serving_daemon/tests/publication.rs b/core/continuum-serving/src/modules/serving_daemon/tests/publication.rs index d62c4a8b48..57aba362ae 100644 --- a/core/continuum-serving/src/modules/serving_daemon/tests/publication.rs +++ b/core/continuum-serving/src/modules/serving_daemon/tests/publication.rs @@ -643,14 +643,16 @@ async fn a_hold_is_published_keeps_its_start_and_is_cleared_on_release() { assert_eq!(daemon.serving_tx.borrow().held_for, None, "a released engine is not held"); } -// what this catches: a seated mind published the engine's whole shared pool as her window -// (every mind budgeting 290k of a 290k pool), or a share that moves with the plan's per-tick -// lane guess. Each seated mind gets an equal share, capped at the model's trained window; the -// readers that charge `lanes x window` then charge the pool. +// what this catches: a sequence published the engine's whole shared pool as its window (every +// mind budgeting 290k of a 290k pool), shares that sum past the pool (a full pool fails the +// whole decode batch), or a share that moves with the plan's per-tick lane guess. Each of the +// engine's own sequences gets an equal share, capped at the model's trained window. #[test] -fn each_seated_mind_is_published_her_share_of_the_shared_pool() { - use super::seated_share; - assert_eq!(seated_share(290_560, 4, 262_144), (72_640, 4), "the M5: four residents"); - assert_eq!(seated_share(290_560, 1, 262_144), (262_144, 1), "one mind is capped at the trained window"); - assert_eq!(seated_share(290_560, 0, 262_144), (262_144, 1), "no seated count is one mind, never a divide by zero"); +fn each_sequence_is_published_its_share_of_the_shared_pool() { + use super::sequence_share; + let (share, sequences) = sequence_share(290_560, 5, 262_144); + assert_eq!((share, sequences), (58_112, 5), "the M5: four residents and the scratch sequence"); + assert!(share * sequences <= 290_560, "the shares fit the pool"); + assert_eq!(sequence_share(290_560, 1, 100_000), (100_000, 1), "one sequence is capped at the trained window"); + assert_eq!(sequence_share(290_560, 0, 262_144), (262_144, 1), "no sequence count is one, never a divide by zero"); } diff --git a/core/continuum-serving/src/modules/serving_daemon/tests/reconciliation.rs b/core/continuum-serving/src/modules/serving_daemon/tests/reconciliation.rs index 78b0a65af2..e9316879fc 100644 --- a/core/continuum-serving/src/modules/serving_daemon/tests/reconciliation.rs +++ b/core/continuum-serving/src/modules/serving_daemon/tests/reconciliation.rs @@ -476,7 +476,7 @@ async fn reconcile_is_noop_when_already_serving() { let verified_reads = server.verified_reads.clone(); let daemon = daemon_with(Arc::new(server)); - // Pretend coder-14b is already up and ready, serving the seated population. + // Pretend coder-14b is already up and ready. let _ = daemon.serving_tx.send_replace(ServingSnapshot { // test fixture: no live readiness was ever CONFIRMED here. ready_verified_at_ms: None, @@ -485,7 +485,7 @@ async fn reconcile_is_noop_when_already_serving() { base_url: serving_v1_url(), adapters: Vec::new(), served_context_window: 11008, - lanes: daemon.seated(), + lanes: 4, host_prompt_cache_mib: 0, degraded_reason: None, vision_ready: false,