From 36f8e8b6a5caf51e67ee69ad58456d6eeb7eebf1 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 28 Oct 2026 08:07:24 -0500 Subject: [PATCH 1/2] The prefill throttle is deleted: one engine's prefills draw no extra memory, and the gate serialized them One llama-server context reserves its worst-case compute graph once, at load, and packs every slot's tokens into each llama_decode, so concurrent prefills in one engine draw no transient memory beyond it. The throttle (#56) guarded that non-existent spike from live free GPU, which on unified memory is system RAM: on the M5 it held 1 permit 22.5% and 2 permits 49.4% of 87 minutes for four minds, and a mind that already held a lane waited a median 24.6 s (p90 83 s, 5,914 s in total over 161 acts) before her model call (2026-10-28, build 7ace74020; delib.gate.lane_acquired -> delib.gate.prefill_acquired). The per-prefill bytes the plan publishes stay, as inference::prefill_spike, for grid placement (capacity::lease::decide_render_lane). Removed: the semaphore, its live reconcile on the serving tick, and the second permit in GenerationAdmission. 430 lines out, 25 in. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../llm_deliberation_faculty/admission.rs | 15 +- .../llm_deliberation_faculty/tests/mod.rs | 24 +- core/continuum-engine/src/capacity/lease.rs | 2 +- core/continuum-engine/src/inference/mod.rs | 2 +- .../src/inference/prefill_spike.rs | 25 + .../src/inference/prefill_throttle.rs | 430 ------------------ .../src/inference/resource_admission/lanes.rs | 7 +- .../src/modules/serving_daemon/planning.rs | 2 +- .../src/modules/serving_daemon/tick.rs | 10 - .../EXPERT-PAGING-GOVERNOR-SEAM.md | 2 +- 10 files changed, 40 insertions(+), 479 deletions(-) create mode 100644 core/continuum-engine/src/inference/prefill_spike.rs delete mode 100644 core/continuum-engine/src/inference/prefill_throttle.rs diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/admission.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/admission.rs index 2efdc8e4ce..f65fa5aded 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/admission.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/admission.rs @@ -6,7 +6,6 @@ pub(super) enum GenerationAdmission { AdapterOwned, SharedLocal { _lane: crate::inference::resource_admission::ServingLanePermit, - _prefill: tokio::sync::OwnedSemaphorePermit, }, } @@ -170,20 +169,10 @@ impl LlmDeliberationFaculty { continuum_base::probe!( class = "delib.gate.lane_acquired", persona = %self.persona_name, - "lane admission granted — prefill slot next" + "lane admission granted — issuing the model call" ); crate::cognition::health_ledger::note_lane_granted_to(self.persona_id); - // #56 prefill throttle: under live external GPU pressure (a game, the browser) - // fewer than the served lane count may PREFILL concurrently — the instant valve - // for the 2026-07-16 compute-buffer OOM. Same fit rule the capacity sim proves; - // no pressure → target == lanes → this never waits. Released with the block. - let _prefill = crate::inference::prefill_throttle::acquire_prefill_slot().await; - continuum_base::probe!( - class = "delib.gate.prefill_acquired", - persona = %self.persona_name, - "prefill slot granted — issuing the model call" - ); - Some(GenerationAdmission::SharedLocal { _lane, _prefill }) + Some(GenerationAdmission::SharedLocal { _lane }) } } diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/mod.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/mod.rs index 9f1eb44a19..01705e96ce 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/mod.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/mod.rs @@ -188,51 +188,39 @@ mod verdicts; mod turn_bound; -// what this catches (6780e79b): remote calls never poll local lane/prefill admission; -// falling home waits for both resources and cancellation releases a partial lease. +// what this catches (6780e79b): remote calls never poll local lane admission; falling home +// waits for the lane, and cancelling a waiting admission leaves the lane reusable. #[tokio::test] async fn remote_admission_bypasses_busy_local_resources_and_home_reacquires() { use super::admission::{admit_target, GenerationAdmission}; use crate::ai::adapter::GenerationAdmissionOwner; use crate::inference::resource_admission::{LaneAdmission, LanePriority}; - use crate::inference::prefill_throttle::PrefillThrottle; use std::future::Future; use std::task::{Context, Poll, Waker}; let lanes: &'static LaneAdmission = Box::leak(Box::new(LaneAdmission::new())); lanes.set_served_lane_count(1); - let prefill = PrefillThrottle::with_lanes(1); let held_lane = lanes.acquire_serving_lane(None, LanePriority::Directed, None).await; - let held_prefill = prefill.acquire_prefill_slot().await; let polls = std::cell::Cell::new(0); let local = || async { polls.set(polls.get() + 1); let lane = lanes.acquire_serving_lane(None, LanePriority::Directed, None).await; - let prefill = prefill.acquire_prefill_slot().await; - Some(GenerationAdmission::SharedLocal { _lane: lane, _prefill: prefill }) + Some(GenerationAdmission::SharedLocal { _lane: lane }) }; let mut cx = Context::from_waker(Waker::noop()); let mut remote = Box::pin(admit_target(GenerationAdmissionOwner::Adapter, local())); assert!(matches!(remote.as_mut().poll(&mut cx), Poll::Ready(Some(GenerationAdmission::AdapterOwned)))); - assert_eq!(polls.get(), 0, "remote dispatch must not enter either local queue"); + assert_eq!(polls.get(), 0, "remote dispatch must not enter the local queue"); drop(remote); let mut home = Box::pin(admit_target(GenerationAdmissionOwner::SharedLocal, local())); assert!(home.as_mut().poll(&mut cx).is_pending(), "local lane is occupied"); + drop(home); // cancelled while waiting for the lane drop(held_lane); - assert!(home.as_mut().poll(&mut cx).is_pending(), "prefill still occupied"); - drop(home); // cancelled while holding lane and waiting for prefill - let mut next_lane = Box::pin(lanes.acquire_serving_lane(None, LanePriority::Directed, None)); - let Poll::Ready(released) = next_lane.as_mut().poll(&mut cx) else { - panic!("cancelling partial admission must release its lane"); - }; - drop(released); - drop(next_lane); - drop(held_prefill); let admission = admit_target(GenerationAdmissionOwner::SharedLocal, local()).await; assert!(matches!(admission, Some(GenerationAdmission::SharedLocal { .. }))); drop(admission); - // A completed/cancelled call leaves both resources reusable, not just the lane. + // A completed call leaves the lane reusable. let next = admit_target(GenerationAdmissionOwner::SharedLocal, local()).await; assert!(matches!(next, Some(GenerationAdmission::SharedLocal { .. }))); } diff --git a/core/continuum-engine/src/capacity/lease.rs b/core/continuum-engine/src/capacity/lease.rs index 325eec9806..8584e92edc 100644 --- a/core/continuum-engine/src/capacity/lease.rs +++ b/core/continuum-engine/src/capacity/lease.rs @@ -127,7 +127,7 @@ pub fn decide_lane( /// lane owns peer identity); nil only weakens self-exclusion from the heard /// set, and we do not currently hear our own offers. pub fn decide_render_lane(leasability: Leasability) -> LaneDecision { - let spike = crate::inference::prefill_throttle::published_spike_bytes(); + let spike = crate::inference::prefill_spike::published_bytes(); let free = crate::resources::ResourceDaemon::global() .and_then(|d| { d.board() diff --git a/core/continuum-engine/src/inference/mod.rs b/core/continuum-engine/src/inference/mod.rs index 1add702e94..39296e047d 100644 --- a/core/continuum-engine/src/inference/mod.rs +++ b/core/continuum-engine/src/inference/mod.rs @@ -48,7 +48,7 @@ pub mod engine_slots; pub mod lane_footprint; pub mod prefill_knee; pub mod prefill_rate; -pub mod prefill_throttle; +pub mod prefill_spike; pub mod served_window_store; pub mod serving_rates; pub mod lane_registry; diff --git a/core/continuum-engine/src/inference/prefill_spike.rs b/core/continuum-engine/src/inference/prefill_spike.rs new file mode 100644 index 0000000000..0e37cdde05 --- /dev/null +++ b/core/continuum-engine/src/inference/prefill_spike.rs @@ -0,0 +1,25 @@ +//! The served model's per-prefill compute-buffer bytes, published by the serving plan and +//! read by grid placement (`capacity::lease::decide_render_lane`). +//! +//! This was the prefill throttle (#56): a semaphore that let only as many served lanes +//! prefill at once as live free GPU could hold one compute-buffer spike each. One +//! llama-server context reserves its worst-case compute graph once, at load, and packs +//! every slot's tokens into each `llama_decode`, so concurrent prefills in one engine draw +//! no extra transient memory. The throttle guarded nothing and serialized prefill: on the +//! M5 it held 1 permit 22.5% and 2 permits 49.4% of 87 minutes for four minds, and a mind +//! that already held a lane waited a median 24.6 s (p90 83 s) for it before her model call +//! (2026-10-28, build 7ace74020, 161 acts). The fact it carried stays; the gate is gone. + +use std::sync::atomic::{AtomicU64, Ordering}; + +static SPIKE_BYTES: AtomicU64 = AtomicU64::new(0); + +/// Publish the served model's per-prefill compute-buffer bytes (0 = unknown). +pub fn publish(spike_bytes: u64) { + SPIKE_BYTES.store(spike_bytes, Ordering::Release); +} + +/// The last published per-prefill bytes; 0 until a plan publishes one. +pub fn published_bytes() -> u64 { + SPIKE_BYTES.load(Ordering::Acquire) +} diff --git a/core/continuum-engine/src/inference/prefill_throttle.rs b/core/continuum-engine/src/inference/prefill_throttle.rs deleted file mode 100644 index 4f9d41e27b..0000000000 --- a/core/continuum-engine/src/inference/prefill_throttle.rs +++ /dev/null @@ -1,430 +0,0 @@ -//! The instant safety valve (#56): concurrent-prefill admission derived from LIVE free GPU. -//! -//! This is the sim's `capacity::FitPolicy` running in production — the knob the 2026-07-16 -//! compute-buffer OOM proved missing. The serving PLAN sizes lanes for the world it saw at -//! reconcile time; between reconciles, an external consumer (a game, the browser) can eat the -//! headroom those lanes assumed, and N concurrent prefill spikes (each drawing a transient -//! `ModelFootprint::compute_buffer_per_lane()` from free GPU) then overflow what is ACTUALLY -//! free. Reaction-cost ladder (design §4): re-planning lanes is the expensive knob (server -//! respawn, hysteresis); this throttle is the cheap one — how many of the served lanes may -//! PREFILL at once flexes instantly, both directions, with the live number. -//! -//! Shape: no new task, no new monitor. The serving daemon's existing tick calls -//! [`reconcile`] with the resource board's `available(Vram)` (a lock-free watch read that -//! already nets external pressure and grants); [`publish_serving`] gives the throttle its two -//! demand facts (per-spike bytes, served lanes) on every plan publish. Admission holds a -//! permit for the model-call window via `resource_admission::acquire_serving_lane`. Grow is -//! `add_permits` (instant); shrink is `forget_permits` (instant for idle permits; permits held -//! by in-flight prefills can't be revoked — you can't un-run a prefill — so the remainder is a -//! DEBT the next tick's reconcile retries, self-healing as calls finish). - -use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex, OnceLock}; - -use crate::capacity::{AllocationPolicy, DeviceCapacity, FitPolicy, LeaseRequest}; - -/// Process-global throttle: the resource it gates (ONE shared serving target's transient -/// compute-buffer headroom) is process-global, same granularity argument as the lane gate. -static THROTTLE: OnceLock = OnceLock::new(); - -/// Consecutive reconciles a GROW must persist before it applies (≈15s at the serving -/// daemon's 5s cadence). Shrink is exempt — the safety direction is always instant. -/// Asymmetric hysteresis, observed necessary live 2026-07-16 within minutes of first boot: -/// `available(Vram)` rides the fit boundary tick to tick (UMA free wobbles with caches/KV) -/// and the grant flapped 1↔2 every 5s. Fail-safe fast, recover deliberate. -/// [[never-thrash-sticky-hysteresis-on-every-lane]] -const GROW_STICKINESS_TICKS: usize = 3; - -/// Spikes of headroom a GROW must fit under, where holding/shrinking needs only ONE. -/// -/// The deadband. Stickiness alone cannot stop a boundary oscillation, and live evidence -/// 2026-08-13 says it didn't: the grant walked `1→4→4→1→1→4→4→1` with a ~20s period — -/// exactly `GROW_STICKINESS_TICKS` ticks to climb, one tick to fall. Slowing the climb only -/// sets the frequency; it cannot remove the flip, because grow and shrink were deciding -/// against the SAME threshold, so a free-VRAM value resting on the fit boundary satisfies it -/// one tick and fails it the next, forever. -/// -/// A control loop that must not chatter needs its two directions to disagree about where the -/// line is. Shrink keeps the tight margin (one spike — the safety direction is unchanged and -/// still instant). Grow must clear a STRICTER bar: room for the target lanes plus a second -/// spike. Between those two thresholds is a band where neither direction fires, and the -/// measurement noise lives entirely inside it. -/// -/// Expressed in spikes, not bytes, so it scales with whatever model is resident — the same -/// unit `FitPolicy::safety_margin_bytes` already speaks. [[never-thrash]] -const GROW_MARGIN_SPIKES: u64 = 2; - -pub struct PrefillThrottle { - sem: Arc, - /// Permits conceptually installed (a Semaphore only exposes AVAILABLE). Shrink debt is - /// `installed − target` that `forget_permits` couldn't collect yet. - installed: AtomicUsize, - /// Transient compute-buffer bytes ONE concurrent prefill draws from free GPU — published - /// from the served plan's footprint. 0 = unpublished (throttle stays at the lane count). - spike_bytes: AtomicU64, - /// The served lane count — the demand ceiling the fit is clamped to. - want_lanes: AtomicUsize, - /// Consecutive reconciles that wanted a grow — gate for [`GROW_STICKINESS_TICKS`]. - grow_streak: AtomicUsize, - /// Serializes reconcile's read-modify-write on (installed, semaphore). - reconcile_lock: Mutex<()>, -} - -fn throttle() -> &'static PrefillThrottle { - THROTTLE.get_or_init(|| { - // Boot fallback: before any plan publishes, gate at the same count the lane - // semaphores use, so behavior is exactly pre-throttle until facts arrive. - PrefillThrottle::with_lanes(super::resource_admission::boot_lane_count()) - }) -} - -/// Publish the served plan's demand facts: the per-prefill transient spike and the lane -/// count. Called by the serving daemon on every plan publish, right where it publishes the -/// lane count — ONE source of truth, no second path. -pub fn publish_serving(spike_bytes: u64, lanes: usize) { - throttle().publish_serving(spike_bytes, lanes); -} - -/// Re-derive the concurrent-prefill grant from LIVE free GPU bytes and apply it to the gate. -/// Called on the serving daemon's tick (cheap: watch read + atomics + at most one semaphore -/// op). Returns the applied target for probes/tests. -/// -/// The fit rule is the SAME `capacity::FitPolicy` the simulator proves scenarios against — -/// sim == prod at the policy seam. Safety margin: one spike of headroom, so measurement -/// jitter of one lane never turns a fit into an overflow. -/// The plan-published per-prefill spike bytes (0 = no plan yet). The SAME live -/// value the throttle fits with — exposed so the lane decision (#108 step 2) -/// prices "can local serve one more?" with one spike truth, never a second -/// estimate ([[the compression principle]]). -pub fn published_spike_bytes() -> u64 { - throttle().published_spike_bytes() -} - -pub fn reconcile(gpu_free_bytes_live: u64) -> usize { - throttle().reconcile(gpu_free_bytes_live) -} - -impl PrefillThrottle { - /// An INDEPENDENT throttle over `lanes` permits. - /// - /// Production has exactly one (the process-global [`throttle`]) because the resource it - /// gates — one serving target's transient compute-buffer headroom — really is - /// process-global. Tests get their OWN, which is the entire point: the global is an - /// instance of this type, not the definition of it. - /// - /// Why this constructor exists (2026-08-06): every behavior below used to be a free - /// function reaching into a `OnceLock`, so the tests exercised shared state. The - /// `OnceLock` is initialized ONCE, by whichever test touches it first, with that - /// moment's `boot_lane_count()` — which made the suite ORDER-DEPENDENT. Adding unrelated - /// tests elsewhere shifted scheduling and `shrink_debt_drains_as_inflight_prefills_finish` - /// went red in the full suite while passing in isolation. That is not a flake: the - /// assertions are `assert_eq!` on integer permit counts, and a predicate with no clock in - /// it cannot fail from load. Second instance of this exact class in one day — the - /// heartbeat's `ms_since_real_decode` was the first — so the cure is the same one: - /// per-owner state, with the global as the production default. - pub fn with_lanes(lanes: usize) -> Self { - let lanes = lanes.max(1); - Self { - sem: Arc::new(tokio::sync::Semaphore::new(lanes)), - installed: AtomicUsize::new(lanes), - spike_bytes: AtomicU64::new(0), - want_lanes: AtomicUsize::new(lanes), - grow_streak: AtomicUsize::new(0), - reconcile_lock: Mutex::new(()), - } - } - - /// See [`publish_serving`]. - pub fn publish_serving(&self, spike_bytes: u64, lanes: usize) { - self.spike_bytes.store(spike_bytes, Ordering::Release); - self.want_lanes.store(lanes.max(1), Ordering::Release); - } - - /// See [`published_spike_bytes`]. - pub fn published_spike_bytes(&self) -> u64 { - self.spike_bytes.load(Ordering::Acquire) - } - - /// See [`reconcile`] — the fit rule lives HERE so the global and a test instance can - /// never drift into two different policies. - pub fn reconcile(&self, gpu_free_bytes_live: u64) -> usize { - let spike = self.spike_bytes.load(Ordering::Acquire); - let want = self.want_lanes.load(Ordering::Acquire).max(1); - if spike == 0 { - // No plan published yet — no fit facts, hold at the lane count (pre-throttle). - // Both thresholds are the same number, so there is no deadband and the behaviour - // is exactly the pre-deadband one: settle on `want`. - return self.apply(want, want); - } - let cap = DeviceCapacity { - // The fit rule only reads the live-free axis; the others are not sourced here. - gpu_total_bytes: 0, - gpu_free_bytes_live, - system_ram_free_bytes: 0, - }; - let req = LeaseRequest { - consumer: "prefill".into(), - want_concurrency: want as u32, - spike_bytes: spike, - }; - // HOLD threshold — the tight margin. What we may keep running RIGHT NOW. Falling - // below this is the safety direction and still shrinks instantly, unchanged. - let hold = FitPolicy { - safety_margin_bytes: spike, - } - .grant(&cap, &req) - .concurrency as usize; - // GROW threshold — the strict margin, one extra spike of headroom. Clearing this is - // what it takes to ADD a permit. `hold >= grow` always, and the gap between them is - // the deadband that absorbs boundary noise instead of converting it into a flip. - let grow = FitPolicy { - safety_margin_bytes: spike.saturating_mul(GROW_MARGIN_SPIKES), - } - .grant(&cap, &req) - .concurrency as usize; - - self.apply(hold, grow) - } - - /// See [`acquire_prefill_slot`]. - pub async fn acquire_prefill_slot(&self) -> tokio::sync::OwnedSemaphorePermit { - self.sem - .clone() - .acquire_owned() - .await - .expect("prefill semaphore is never closed") - } - - /// See [`installed_permits`]. - pub fn installed_permits(&self) -> usize { - self.installed.load(Ordering::Acquire) - } - - /// Apply a target permit count, asymmetrically: SHRINK is instant (collect what's idle - /// now, leave the rest as debt later reconciles drain as in-flight prefills finish); - /// GROW only lands after [`GROW_STICKINESS_TICKS`] consecutive reconciles wanted it — - /// sustained headroom, not one optimistic reading. Never blocks, never revokes running - /// work, never thrashes on a boundary-riding live number. - fn apply(&self, hold: usize, grow: usize) -> usize { - // a resident model may always run ONE prefill (residency decision) - let hold = hold.max(1); - let grow = grow.max(1); - let _g = self - .reconcile_lock - .lock() - .expect("prefill reconcile lock never poisoned"); - let installed = self.installed.load(Ordering::Acquire); - // THE DEADBAND, resolved against the authoritative `installed` under the lock — not - // against a value read before it, which would be a race the moment reconcile gains a - // second caller. - let target = if hold < installed { - hold // below what we may keep — shed now, tight margin, instant - } else { - // Safe to stay put. Climb only on the STRICT fit, and never propose fewer than we - // already hold — otherwise the strict threshold becomes a second shrink path and - // re-creates the very oscillation the deadband exists to remove. - grow.max(installed) - }; - if target > installed { - // The recovery direction: deliberate. One tick of headroom is often UMA cache - // wobble; demand the signal persist before paying the flap. - let streak = self.grow_streak.fetch_add(1, Ordering::AcqRel) + 1; - if streak >= GROW_STICKINESS_TICKS { - self.sem.add_permits(target - installed); - self.installed.store(target, Ordering::Release); - self.grow_streak.store(0, Ordering::Release); - } - } else { - self.grow_streak.store(0, Ordering::Release); - if target < installed { - // The safety direction: instant, always. - let forgotten = self.sem.forget_permits(installed - target); - self.installed - .store(installed - forgotten, Ordering::Release); - } - } - let now = self.installed.load(Ordering::Acquire); - // Glass box: the valve speaks ONLY when it moves — a steady grant is silence, a - // shrink under pressure / regrow / debt-drain each leave one auditable line. - if now != installed { - continuum_base::probe!( - class = "serving.prefill_throttle", - from = installed, - to = now, - target = target, - "concurrent-prefill grant re-derived from live VRAM", - ); - } - now - } -} - -/// Acquire one concurrent-prefill slot for the model-call window. Await under pressure — -/// the call proceeds when a slot frees or reconcile grows the gate back. -pub async fn acquire_prefill_slot() -> tokio::sync::OwnedSemaphorePermit { - throttle().acquire_prefill_slot().await -} - -/// Permits currently installed (post-debt) — for probes and tests. -pub fn installed_permits() -> usize { - throttle().installed_permits() -} - -#[cfg(test)] -mod tests { - use super::*; - - const GB: u64 = 1024 * 1024 * 1024; - - /// Bring a FRESH throttle to `lanes` permits by sustaining headroom. - /// - /// No serialization lock and no floor-reset dance any more: each test owns its instance, - /// so there is no sibling to race and no prior state to undo. The lock this replaced - /// existed because both tests held permits from ONE process-global semaphore — test A's - /// shrink could steal the permits test B was awaiting, deadlocking the suite (observed - /// live, exit 144). Owning the state deletes that failure mode rather than scheduling - /// around it, and it also deletes the ORDER-DEPENDENCE that made - /// `shrink_debt_drains_as_inflight_prefills_finish` red in the full suite while green in - /// isolation on 2026-08-06. - fn grow_to(t: &PrefillThrottle, lanes: usize, free: u64) -> usize { - let mut last = t.installed_permits(); - for _ in 0..GROW_STICKINESS_TICKS { - last = t.reconcile(free); - } - assert_eq!(last, lanes, "sustained headroom grows to the fit"); - last - } - - // what this catches: THE DEADBAND — a boundary-riding free-VRAM reading must move the - // grant ZERO times, not once per wobble. Measured live 2026-08-13 with stickiness already - // in place: `1→4→4→1→1→4→4→1`, ~20s period (GROW_STICKINESS_TICKS up, ONE tick down). - // Stickiness sets the frequency of a flap; only two different thresholds can remove it. - // Here 11GB and 9GB straddle the 4-lane HOLD line (10GB) — pre-deadband that alternation - // is the flap itself, 11→4 then 9→3 forever. With grow needing 12GB the pair settles at 3 - // and never moves again. If GROW_MARGIN_SPIKES is ever lowered to 1 this goes red. - #[tokio::test] - async fn a_wobble_narrower_than_one_spike_never_moves_the_grant() { - let t = PrefillThrottle::with_lanes(1); - t.publish_serving(2 * GB, 4); // spike 2GB, plan wants 4 lanes - - // Settle under the STRICT fit: 11GB grants (11−4)/2 = 3, not the (11−2)/2 = 4 the - // hold line alone would have allowed. Climbing conservatively is the point. - let mut settled = 0; - for _ in 0..GROW_STICKINESS_TICKS { - settled = t.reconcile(11 * GB); - } - assert_eq!(settled, 3, "grow uses the strict margin: (11−4)/2 = 3"); - - // Now oscillate ACROSS the 4-lane hold boundary the old code flapped on. Every tick - // must be a no-op: 9GB still holds 3 ((9−2)/2 = 3), and 11GB still cannot reach 4. - for tick in 0..8 { - let free = if tick % 2 == 0 { 9 * GB } else { 11 * GB }; - assert_eq!( - t.reconcile(free), - 3, - "tick {tick} at {}GB moved the grant — the deadband leaks", - free / GB - ); - } - } - - // what this catches: the deadband must NOT blunt the safety direction. Real pressure — - // a drop below the HOLD line, not wobble around it — still sheds on the very next tick. - #[tokio::test] - async fn real_pressure_still_sheds_instantly_through_the_deadband() { - let t = PrefillThrottle::with_lanes(1); - t.publish_serving(2 * GB, 4); - grow_to(&t, 4, 13 * GB); - assert_eq!( - t.reconcile(7 * GB), - 2, - "a genuine drop shrinks on the FIRST tick — (7−2)/2 = 2, tight margin, unchanged" - ); - } - - // what this catches: THE LIVE SAFETY VALVE — the exact 2026-07-16 OOM shape, gated, WITH - // the asymmetry the first live boot proved necessary. Plan serves 4 lanes, ~2GB spikes. - // A game eating the GPU (free → 7GB) shrinks admission to (7−2)/2 = 2 on the VERY NEXT - // reconcile — the safety direction is instant, no plan re-publish, no server respawn. - // The game closing regrows to 4 only after GROW_STICKINESS_TICKS consecutive reconciles - // — one optimistic reading is UMA wobble, not recovery (observed live: the grant flapped - // 1↔2 every 5s tick riding the fit boundary). If shrink loses its immediacy the OOM is - // back; if grow loses its stickiness the thrash is back. - #[tokio::test] - async fn shrink_is_instant_grow_requires_sustained_headroom() { - // OUR OWN throttle. No process-global, so these tests are order-INDEPENDENT and can - // run in parallel — the whole reason `with_lanes` exists. - let t = PrefillThrottle::with_lanes(1); - t.publish_serving(2 * GB, 4); - grow_to(&t, 4, 13 * GB); - - // Game opens: shrink lands on the FIRST reconcile that sees the pressure. - assert_eq!(t.reconcile(7 * GB), 2, "shrink is instant: (7−2)/2 = 2"); - - // Game closes: one good reading does NOT regrow (boundary-riding wobble)… - assert_eq!( - t.reconcile(13 * GB), - 2, - "one optimistic tick is not recovery" - ); - assert_eq!(t.reconcile(13 * GB), 2, "nor two"); - // …and a dip in between resets the streak — the signal must be SUSTAINED. - assert_eq!(t.reconcile(7 * GB), 2, "a relapse resets the grow streak"); - assert_eq!(t.reconcile(13 * GB), 2); - assert_eq!(t.reconcile(13 * GB), 2); - assert_eq!( - t.reconcile(13 * GB), - 4, - "three consecutive good ticks → regrown to demand" - ); - - // The applied grant is enforced, not advisory: under pressure only 2 slots grant. - assert_eq!(t.reconcile(7 * GB), 2); - let a = t.acquire_prefill_slot().await; - let b = t.acquire_prefill_slot().await; - assert!( - t.sem.clone().try_acquire_owned().is_err(), - "a third concurrent prefill must wait while pressure holds" - ); - drop((a, b)); - } - - // what this catches: shrink DEBT self-healing. Permits held by in-flight prefills can't - // be revoked (you can't un-run a prefill), so a shrink under load collects what it can - // and the remainder drains on later reconciles as calls finish. If the debt bookkeeping - // drifted (double-forget or lost debt), the gate would end up permanently too tight or - // too loose — both are real failures (starved serving / OOM window reopened). - #[tokio::test] - async fn shrink_debt_drains_as_inflight_prefills_finish() { - // OUR OWN throttle. No process-global, so these tests are order-INDEPENDENT and can - // run in parallel — the whole reason `with_lanes` exists. - let t = PrefillThrottle::with_lanes(1); - t.publish_serving(2 * GB, 4); - grow_to(&t, 4, 13 * GB); - - // 3 prefills in flight; heavy pressure wants target 1. - let a = t.acquire_prefill_slot().await; - let b = t.acquire_prefill_slot().await; - let c = t.acquire_prefill_slot().await; - // (4−2)/2 = 1: only the 1 idle permit is collectable now → installed 4→3, debt 2. - assert_eq!( - t.reconcile(4 * GB), - 3, - "collects the idle permit; in-flight can't be revoked" - ); - - drop(a); // one prefill finishes → its permit returns → collectable - assert_eq!(t.reconcile(4 * GB), 2, "debt drains as calls finish"); - drop(b); - assert_eq!( - t.reconcile(4 * GB), - 1, - "down to the target — one lane always runs" - ); - - // Floor: even under absurd pressure the gate never goes below 1 (a resident model - // may always run one prefill — going below is a residency decision, not admission). - drop(c); - assert_eq!(t.reconcile(0), 1, "never below one"); - } -} diff --git a/core/continuum-engine/src/inference/resource_admission/lanes.rs b/core/continuum-engine/src/inference/resource_admission/lanes.rs index c23d6745e9..64a582bf15 100644 --- a/core/continuum-engine/src/inference/resource_admission/lanes.rs +++ b/core/continuum-engine/src/inference/resource_admission/lanes.rs @@ -89,8 +89,7 @@ fn directed_pending() -> bool { /// serializes THIS module, but a cross-module guard could bump it mid-loop". This file had /// already learned the lesson once and applied it to the in-flight Gauge, stating the /// principle outright: *the race is gone at the SOURCE, not merely serialized*. That cure -/// reached one of three cases. This applies it to the other two, and to the sibling -/// [`crate::inference::prefill_throttle`] the same day. +/// reached one of three cases. This applies it to the other two. /// /// Lazy semaphores capture the latest lane count on first use. If first use precedes /// serving, a later publication collects surplus boot permits without interrupting @@ -171,7 +170,7 @@ pub fn resident_departed(persona: uuid::Uuid) { /// serving daemon calls this on every reconcile. Sizes the admission semaphores exactly: /// the lazy-init captures it at boot, and a LATER increase (roster grows, more personas /// demand lanes) grows the live semaphores via `add_permits`. Decreases collect idle -/// permits immediately, as in `PrefillThrottle`; held permits become shrink debt. +/// permits immediately, as a resized semaphore must; held permits become shrink debt. /// The serving daemon retries idle debt every tick; acquisition also retires debt /// before granting a transferred permit, so queued demand cannot defeat shrink. /// No running permit is revoked or awaited by the publisher. @@ -181,7 +180,7 @@ pub fn set_served_lane_count(lanes: usize) { /// Reconcile installed permits without waiting for running calls. The difference /// between installed and a smaller target is debt retried on the next serving tick. -/// Caller holds the owner resize lock, matching `PrefillThrottle`'s accounting. +/// Caller holds the owner resize lock, the installed-permit accounting. pub(super) fn resize_semaphore_to(sem: &tokio::sync::Semaphore, installed: &AtomicUsize, target: usize) { let cur = installed.load(Ordering::Acquire); if target > cur { diff --git a/core/continuum-serving/src/modules/serving_daemon/planning.rs b/core/continuum-serving/src/modules/serving_daemon/planning.rs index 91b7b52ec6..5da370b7b5 100644 --- a/core/continuum-serving/src/modules/serving_daemon/planning.rs +++ b/core/continuum-serving/src/modules/serving_daemon/planning.rs @@ -593,7 +593,7 @@ impl ServingDaemonModule { ); } let spike = spike_of_served.unwrap_or(0); - crate::inference::prefill_throttle::publish_serving(spike, plan.lanes as usize); + crate::inference::prefill_spike::publish(spike); // send_replace keeps the latest even with no live receivers yet. self.publish_plan_snapshot(intent_revision, Some(plan)); } diff --git a/core/continuum-serving/src/modules/serving_daemon/tick.rs b/core/continuum-serving/src/modules/serving_daemon/tick.rs index ed37ad558e..17a7cc9f74 100644 --- a/core/continuum-serving/src/modules/serving_daemon/tick.rs +++ b/core/continuum-serving/src/modules/serving_daemon/tick.rs @@ -80,16 +80,6 @@ impl ServiceModule for ServingDaemonModule { // tick, hysteresis-gated; a sustained failure flips not-ready and the next reconcile // respawns the lane. let _ = self.spawn_health_heartbeat_if_due(); - // The cheap knob on the reaction ladder (#56): re-derive the concurrent-prefill - // grant from the board's LIVE VRAM availability (lock-free watch read, already net - // of external pressure + grants). Flexes both directions every tick — the instant - // valve for the 2026-07-16 compute-buffer OOM; re-planning above stays the slow, - // hysteresis-guarded knob. Ungoverned VRAM (no monitor) → no live number → the - // throttle holds at the lane count rather than guessing. - if let Some(available) = governed_vram_ceiling(&self.resource_daemon) { - // Probes on CHANGE only, inside the throttle — a steady grant is silence. - let _granted = crate::inference::prefill_throttle::reconcile(available); - } // #287: for a ready MoE serve, re-derive the governed host-cache lease from the // LIVE working set (KV grows as slots fill) and publish it through the sticky // band to the per-port plan file — the actuator her ResidencyCache polls. diff --git a/docs/architecture/EXPERT-PAGING-GOVERNOR-SEAM.md b/docs/architecture/EXPERT-PAGING-GOVERNOR-SEAM.md index bc7825ee04..cbdcf25087 100644 --- a/docs/architecture/EXPERT-PAGING-GOVERNOR-SEAM.md +++ b/docs/architecture/EXPERT-PAGING-GOVERNOR-SEAM.md @@ -1,7 +1,7 @@ # Expert Paging — the governor seam *M5 (Fable) design note for BigMama's paging lane, 2026-07-25. The governor -machinery is mine (`capacity/lease.rs`, `resources/`, `inference/prefill_throttle.rs`); +machinery is mine (`capacity/lease.rs`, `resources/`, `inference/prefill_spike.rs`); the llama.cpp/CUDA/disk mechanics are BigMama's. This doc is the contract between them so we build to one shape.* From 9c2403b4229a48e102f72c5c998d49e7f4f43c2d Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 28 Oct 2026 08:05:31 -0500 Subject: [PATCH 2/2] The reserved lane is lent to work whenever nothing directed is pending: no engine slot idles for a mention The loan required a work call to fit the interactive wait budget (60 s). A resident's model call has a median of 71 s, so the reserve was never lent: one of four engine slots sat idle while the fourth resident queued for a lane, a median 25.7 s and p90 131 s per model call (M5, 176 acts, 2026-10-28, build 7ace74020; admission.lane.granted). A directed arrival now takes the next lane any call releases. The loan is still a try-acquire on a free lane, never a park, and a pending directed line still re-arms it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/llm_deliberation_faculty.rs | 3 +-- .../src/inference/resource_admission/lanes.rs | 18 ++++---------- .../inference/resource_admission/metrics.rs | 24 +++++++------------ .../src/inference/resource_admission/tests.rs | 23 +++++++----------- 4 files changed, 23 insertions(+), 45 deletions(-) diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs index e8c18c9576..9288c45e75 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs @@ -529,8 +529,7 @@ impl LlmDeliberationFaculty { /// cached last turn at this box's measured prefill rate, plus her last output at its /// measured decode rate. Read from her LAST turn's shape (`LAST_TURN_SHAPE`) — the /// prompt is rendered after the gate, so the previous turn is the honest predictor. - /// `None` when any term is unmeasured: an absence is not a number, and the reserve is - /// then not lent (`resource_admission::reserve_lendable`). + /// `None` when any term is unmeasured: an absence is not a number (the probe says so). fn expected_occupancy(&self) -> Option { expected_occupancy_for(self.persona_id) } diff --git a/core/continuum-engine/src/inference/resource_admission/lanes.rs b/core/continuum-engine/src/inference/resource_admission/lanes.rs index 64a582bf15..482b015985 100644 --- a/core/continuum-engine/src/inference/resource_admission/lanes.rs +++ b/core/continuum-engine/src/inference/resource_admission/lanes.rs @@ -420,9 +420,8 @@ impl LaneAdmission { let directed = priority.is_directed(); // Non-directed reserves within the (lanes-1) budget FIRST, so the physical-lane // acquire below can never let non-directed work starve a directed caller — - // EXCEPT a work call whose occupancy is bounded inside the directed wait budget - // while nothing directed is pending: it may be LENT the reserved lane, because the - // guarantee is the wait, not the lane (`reserve_lendable`). THE LOAN NEVER PARKS + // EXCEPT that while nothing directed is pending a work call is LENT the reserved + // lane (`reserve_lendable`): a slot never idles for a mention. THE LOAN NEVER PARKS // (Cormac's condition on #4250): it is a try-acquire on a physical lane that is // free RIGHT NOW — a lent call that had to wait on the FIFO physical semaphore // would put a later directed arrival behind its whole occupancy (2× the budget @@ -436,13 +435,7 @@ impl LaneAdmission { Some(p) => (Some(p), None), None => { let reserve_exists = self.nondirected_budget() < self.lane_count(); - let budget = crate::inference::prefill_rate::INTERACTIVE_TTFT; - let lendable = reserve_exists - && reserve_lendable( - expected_occupancy, - directed_pending(), - budget, - ); + let lendable = reserve_exists && reserve_lendable(directed_pending()); let lent = if lendable { self.try_acquire_resized( self.serving_lanes(), @@ -456,9 +449,8 @@ impl LaneAdmission { Some(lane) => { continuum_base::probe!( class = "admission.lane.reserve_lent_to_work", - expected_ms = expected_occupancy.map(|d| d.as_millis() as u64).unwrap_or(0), // unwrap_or: lendable implies Some; 0 cannot occur - budget_ms = budget.as_millis() as u64, - "a free reserved lane is lent to a bounded work call, never parked for — a directed arrival waits at most the call's occupancy" + expected_ms = ?expected_occupancy.map(|d| d.as_millis()), + "the reserved lane is lent to work while nothing directed is pending: no slot idles for a mention; a directed arrival takes the next lane released" ); (None, Some(lane)) } diff --git a/core/continuum-engine/src/inference/resource_admission/metrics.rs b/core/continuum-engine/src/inference/resource_admission/metrics.rs index 41093b8ada..da161090b2 100644 --- a/core/continuum-engine/src/inference/resource_admission/metrics.rs +++ b/core/continuum-engine/src/inference/resource_admission/metrics.rs @@ -391,22 +391,16 @@ pub fn lane_wait_bound( .clamp(LANE_WAIT_FLOOR, LANE_WAIT_CEILING), ) } -/// PURE: may a WORK call be lent the lane reserved for directed calls? Only while no -/// directed line is pending for any citizen here, and only when the call's expected -/// occupancy — prefill of its uncached prompt at the measured prefill rate plus its -/// decode at the measured decode rate — fits inside the directed wait budget, so the -/// most a directed arrival can wait is that bound. Unknown occupancy lends nothing. +/// PURE: may a WORK call be lent the lane reserved for directed calls? Whenever no directed +/// line is pending here. A directed arrival then takes the next lane any call releases. /// -/// Measured 2026-09-20 on the M5 (2 lanes): the reserve of lanes−1 left ONE non-directed -/// lane for four minds at 3–6 min a turn — 11 grants an hour with a lane idle for a -/// mention that came once all night. The reserve stays a guarantee; it is now stated in -/// the seconds a directed call may wait, not in lanes. -pub fn reserve_lendable( - expected: Option, - directed_pending: bool, - budget: std::time::Duration, -) -> bool { - !directed_pending && expected.is_some_and(|e| e <= budget) +/// The old rule also required the call to fit the interactive wait budget. No resident act +/// does (median model call 71 s), so the reserve was never lent: one of four engine slots +/// sat idle for a mention while the fourth resident queued, a median 25.7 s and p90 131 s +/// per model call (M5, 176 acts, 2026-10-28, build 7ace74020). An idle slot is never the +/// price of a guarantee for an event that comes a few times a day. +pub fn reserve_lendable(directed_pending: bool) -> bool { + !directed_pending } /// A bounded ring of wait samples (ms), newest kept, read as (p50, count) so an empty ring /// is UNMEASURED — never "0 ms". One shape for every queue a node measures about itself. diff --git a/core/continuum-engine/src/inference/resource_admission/tests.rs b/core/continuum-engine/src/inference/resource_admission/tests.rs index 5e67dbb42d..16f3686f7f 100644 --- a/core/continuum-engine/src/inference/resource_admission/tests.rs +++ b/core/continuum-engine/src/inference/resource_admission/tests.rs @@ -715,22 +715,15 @@ fn the_queues_estimate_is_a_floor_under_her_own_measured_turn_never_a_ceiling() assert!(act > bound, "the act must outlast the lane wait it contains"); } -// what this catches (the M5, 2026-09-20; Cormac's design word): the reserve is a WAIT -// guarantee in seconds. A work call is lent the reserved lane only when its occupancy -// is known and fits the directed budget and nothing directed is pending; an unknown -// occupancy, a pending directed line, or an occupancy past the budget lends nothing. -// (The loan itself is a try-acquire on a FREE physical lane — never a park; that lives -// in `acquire_serving_lane`, where a parked loan would put a directed arrival behind -// the whole occupancy.) +// what this catches (the M5, 2026-10-28): a reserved lane idling for a mention while work +// queues. Lent whenever nothing directed is pending, whatever the call's length (a 71 s +// median act never fit the old budget, so the reserve was never lent); a pending directed +// line re-arms it. (The loan itself is a try-acquire on a FREE physical lane, never a park; +// that lives in `acquire_serving_lane`.) #[test] -fn the_reserved_lane_is_lent_only_to_bounded_work_while_nothing_directed_is_pending() { - use std::time::Duration; - let budget = Duration::from_secs(60); - assert!(reserve_lendable(Some(Duration::from_secs(40)), false, budget)); - assert!(!reserve_lendable(Some(Duration::from_secs(40)), true, budget), "a pending directed line re-arms the reserve"); - assert!(!reserve_lendable(Some(Duration::from_secs(154)), false, budget), "a 154 s turn (the M5 tonight) may not take the reserve"); - assert!(!reserve_lendable(None, false, budget), "unknown occupancy is not a number"); - assert!(reserve_lendable(Some(budget), false, budget), "exactly the budget fits"); +fn the_reserved_lane_is_lent_to_work_whenever_nothing_directed_is_pending() { + assert!(reserve_lendable(false), "no slot idles for a mention that is not pending"); + assert!(!reserve_lendable(true), "a pending directed line re-arms the reserve"); } // what this catches: the health line's directed-wait numbers are nearest-rank