From d4a264f9f8f40d9989ad31b1e53defd3e78e50fa Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 3 Nov 2026 19:56:17 -0600 Subject: [PATCH 1/3] One determiner of a mind's window: capacity::mind_window decides it, and the turn and its capacity readiness ask it (card de7bb6e8) On the M5 (0b2854327, 01:39-01:51Z) two owners fought over Aiko's window: the re-home reconciler bound her grant (20,817), then every turn adopted the adapter's live window, the serving snapshot's per-sequence share (18,380), back into her binding (contribute.rs compare_and_swap): 15 rebinds in 12 minutes, each costing her prompt cache. Joel: 'need one centralized determiner'. - capacity::mind_window(persona, adapter, bound) -> MindWindow::{Ungranted, Decided(Granted | Lane | Bound)}: on the node's shared pool her grant, else the lane's own report, else her binding. A decided window always has a size (no Option, no panic); ungranted has none. - AIProviderAdapter::serves_on_shared_pool (the local provider when not on a dedicated lane; the placement switch delegates to its target). On the shared pool the snapshot's per-sequence window is nobody's. - The turn (contribute.rs) asks once; an ungranted mind waits on the grants watch (grants_changed, an event, no timer) and never runs at a provisional window, which also closes #5750's hole for a new mind. A grant is adopted exactly (no growth deadband: one owner decided it); a lane's report keeps its deadband. - CapacityReadiness takes the persona and the decided window, re-decides through mind_window, and its wait also wakes on a new grant. - Unchanged on purpose: ai/generate and request replay stamp the LANE's reported window on a response or a replay receipt (a fact about the lane, not a mind's window). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../verdict/contribute.rs | 25 ++++++- .../src/cognition/workspace/capacity.rs | 56 ++++++++++++---- .../src/ai/adapter/inference_device.rs | 8 +++ .../src/ai/openai_adapter/provider.rs | 4 ++ .../src/capacity/mind_window.rs | 66 +++++++++++++++++++ core/continuum-engine/src/capacity/mod.rs | 1 + .../src/capacity/window_grant.rs | 6 ++ .../src/persona/placement_switch/adapter.rs | 4 ++ 8 files changed, 158 insertions(+), 12 deletions(-) create mode 100644 core/continuum-engine/src/capacity/mind_window.rs diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs index cd22108d67..588a40d605 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs @@ -42,9 +42,28 @@ impl LlmDeliberationFaculty { // triple. [[fallbacks-are-illegal-fail-loud]] [[never-thrash-sticky-hysteresis-on-every-lane]] // Retain the capacity observation that precedes assembly. Sampling again // after an await could mistake newly grown capacity for the refused one. + // Her window, from the one determiner (card de7bb6e8). On the shared pool it is her grant; + // with no grant yet her turn waits for one on the grants watch, never at a provisional size. + let decided = loop { + use crate::capacity::mind_window::{grants_changed, mind_window, MindWindow}; + match mind_window(self.persona_id, loaded.adapter.as_ref(), loaded.context_window) { + MindWindow::Ungranted => { + continuum_base::probe!( + class = "delib.window.ungranted", + persona = %self.persona_name, + "no grant on the shared pool yet: this turn waits for one" + ); + grants_changed().await; + } + MindWindow::Decided(decided) => break decided, + } + }; + let decided_window = decided.tokens(); let capacity_readiness = Arc::new(crate::cognition::workspace::CapacityReadiness::new( + self.persona_id, self.binding.clone(), loaded.clone(), + decided_window, )); let binding = { // ONE live source, no clamp. The window this turn budgets to is the live @@ -62,7 +81,11 @@ impl LlmDeliberationFaculty { // reduction is authoritative immediately: reply reserve is requested // output, not spare capacity that can absorb a smaller served window. // The existing quantized history eviction still controls prefix churn. - let deadband = loaded.context_window / 8; + // A grant is exact (one owner decided it); only a lane's own report keeps a growth deadband. + let deadband = match decided { + crate::capacity::mind_window::Decided::Granted(_) => 0, + _ => loaded.context_window / 8, + }; let adopt = effective < loaded.context_window || effective.saturating_sub(loaded.context_window) > deadband; if !adopt { diff --git a/core/continuum-cognition/src/cognition/workspace/capacity.rs b/core/continuum-cognition/src/cognition/workspace/capacity.rs index 4d34d0efc7..5ae38b41ad 100644 --- a/core/continuum-cognition/src/cognition/workspace/capacity.rs +++ b/core/continuum-cognition/src/cognition/workspace/capacity.rs @@ -77,6 +77,7 @@ impl std::ops::Deref for CapacityRefusal { #[derive(Clone)] pub struct CapacityReadiness { + persona: uuid::Uuid, handle: crate::cognition::model_binding::ModelBindingHandle, observed: std::sync::Arc, target: std::sync::Arc, @@ -85,18 +86,27 @@ pub struct CapacityReadiness { fitted_window: Option, } impl CapacityReadiness { + /// The readiness of `persona`'s turn at `window`, the window [`mind_window`] decided for her + /// (the caller waits out an ungranted window before building a turn, so there is always one). + /// + /// [`mind_window`]: crate::capacity::mind_window::mind_window pub fn new( + persona: uuid::Uuid, handle: crate::cognition::model_binding::ModelBindingHandle, observed: std::sync::Arc, + window: u32, ) -> Self { let target = observed .adapter .generation_target() .unwrap_or_else(|| observed.adapter.clone()); // No forwarding target means the bound adapter itself serves. - let live_window = observed.adapter.live_served_window(); - let window = live_window.unwrap_or(observed.context_window); // Fixed bindings declare their own window. - let dynamic_window = live_window.is_some(); + // A granted or lane-reported window moves on its own; a bound one moves only with the binding. + let dynamic_window = !matches!( + crate::capacity::mind_window::mind_window(persona, observed.adapter.as_ref(), observed.context_window), + crate::capacity::mind_window::MindWindow::Decided(crate::capacity::mind_window::Decided::Bound(_)) + ); Self { + persona, handle, observed, target, @@ -133,10 +143,17 @@ impl CapacityReadiness { if !std::sync::Arc::ptr_eq(&self.target, &target) { return Some("placement"); } - current.adapter.live_served_window().map_or_else( - || !self.dynamic_window && self.window_changed(current.context_window), - |window| self.window_changed(window), - ).then_some("window") + // Her window as the one determiner decides it now: ungranted is a change (her turn waits), + // a bound window counts only when this observation was bound too. + let now = crate::capacity::mind_window::mind_window(self.persona, current.adapter.as_ref(), current.context_window); + match now { + crate::capacity::mind_window::MindWindow::Ungranted => true, + crate::capacity::mind_window::MindWindow::Decided(crate::capacity::mind_window::Decided::Bound(window)) => { + !self.dynamic_window && self.window_changed(window) + } + crate::capacity::mind_window::MindWindow::Decided(decided) => self.window_changed(decided.tokens()), + } + .then_some("window") } pub async fn wait(&self) { let mut binding_changes = self.handle.subscribe(); @@ -144,6 +161,8 @@ impl CapacityReadiness { let current = self.handle.load_full(); let window = current.adapter.live_served_window(); let adapter_change = current.adapter.capacity_changed(window); + // A mind on the shared pool's window is her grant: a new grant is a capacity change. + let grants_change = crate::capacity::mind_window::grants_changed(); if self.changed() { return; } @@ -154,6 +173,7 @@ impl CapacityReadiness { if result.is_err() { return std::future::pending::<()>().await; } } _ = adapter_change => {} + _ = grants_change => {} } } } @@ -162,6 +182,20 @@ impl CapacityReadiness { #[cfg(test)] mod tests { use super::*; + + /// A readiness at the window the one determiner decides for this binding (a test adapter is + /// never on the shared pool, so it is always decided). + fn readiness(handle: &crate::cognition::model_binding::ModelBindingHandle) -> CapacityReadiness { + let persona = uuid::Uuid::from_u128(1); + let observed = handle.load_full(); + let crate::capacity::mind_window::MindWindow::Decided(decided) = + crate::capacity::mind_window::mind_window(persona, observed.adapter.as_ref(), observed.context_window) + else { + panic!("a test adapter is never on the shared pool") + }; + let window = decided.tokens(); + CapacityReadiness::new(persona, handle.clone(), observed, window) + } use crate::cognition::model_binding::{ModelBinding, ModelBindingState}; use std::sync::Arc; @@ -191,8 +225,8 @@ mod tests { model: Some("bound".into()), context_window: 4096, })); - let one = CapacityReadiness::new(handle.clone(), handle.load_full()); - let two = CapacityReadiness::new(handle.clone(), handle.load_full()); + let one = readiness(&handle); + let two = readiness(&handle); handle.store(Arc::new(ModelBinding { adapter: adapter.clone(), model: Some("bound".into()), @@ -222,7 +256,7 @@ mod tests { let handle = Arc::new(ModelBindingState::new(ModelBinding { adapter: adapter.clone(), model: Some("bound".into()), context_window: 32768, })); - let refused = CapacityReadiness::new(handle.clone(), handle.load_full()) + let refused = readiness(&handle) .with_fit_window(16384); assert!(tokio::time::timeout(std::time::Duration::from_secs(1), refused.wait()).await.is_err(), "unchanged stale nominal capacity is not growth"); @@ -230,7 +264,7 @@ mod tests { adapter, model: Some("bound".into()), context_window: 24576, })); tokio::time::timeout(std::time::Duration::from_secs(1), refused.wait()).await.unwrap(); - let refused_again = CapacityReadiness::new(handle.clone(), handle.load_full()) + let refused_again = readiness(&handle) .with_fit_window(16384); assert!(tokio::time::timeout(std::time::Duration::from_secs(1), refused_again.wait()).await.is_err(), "a fresh refusal does not retry the same changed advertisement again"); diff --git a/core/continuum-engine/src/ai/adapter/inference_device.rs b/core/continuum-engine/src/ai/adapter/inference_device.rs index 39d9efe8bf..ea2eca619a 100644 --- a/core/continuum-engine/src/ai/adapter/inference_device.rs +++ b/core/continuum-engine/src/ai/adapter/inference_device.rs @@ -467,6 +467,14 @@ pub trait AIProviderAdapter: Send + Sync { None } + /// Whether this adapter's requests go to the node's own shared-pool engine. There a mind's + /// window is her grant, decided by [`crate::capacity::mind_window::mind_window`], and the + /// lane's per-sequence window is nobody's. Default `false`: a remote, dedicated, cloud or + /// in-process adapter. + fn serves_on_shared_pool(&self) -> bool { + false + } + /// Wait for a semantic capacity observation to change, without generating or /// polling. Live adapters subscribe before rechecking; fixed bindings have /// no capacity events and are woken by their binding owner instead. diff --git a/core/continuum-engine/src/ai/openai_adapter/provider.rs b/core/continuum-engine/src/ai/openai_adapter/provider.rs index 406007088f..4d5be3c4d1 100644 --- a/core/continuum-engine/src/ai/openai_adapter/provider.rs +++ b/core/continuum-engine/src/ai/openai_adapter/provider.rs @@ -137,6 +137,10 @@ impl AIProviderAdapter for OpenAICompatibleAdapter { /// without a clamp. A not-ready / zero snapshot → `None` (the binding window /// stands until the next ready tick). Mirrors the `!self.dedicated_lane` /// readiness-guard exemption above — same lane, same authority. + fn serves_on_shared_pool(&self) -> bool { + !self.dedicated_lane && self.config.single_resident_model + } + fn live_served_window(&self) -> Option { if self.dedicated_lane || !self.config.single_resident_model { return None; diff --git a/core/continuum-engine/src/capacity/mind_window.rs b/core/continuum-engine/src/capacity/mind_window.rs new file mode 100644 index 0000000000..f1598f230a --- /dev/null +++ b/core/continuum-engine/src/capacity/mind_window.rs @@ -0,0 +1,66 @@ +//! The one determiner of a mind's window (card de7bb6e8; Joel, 2026-11-04: "need one centralized +//! determiner"). Every reader of a mind's window asks [`mind_window`]; none reads an adapter's +//! lane window or the serving snapshot as hers. On the M5 (0b2854327) two owners fought over +//! Aiko's window: the re-home reconciler bound her grant (20,817), then each turn adopted the +//! snapshot's per-sequence window (18,380) back into her binding, 15 rebinds in 12 minutes. + +use crate::ai::adapter::AIProviderAdapter; +use crate::inference::planning::window_allocator::Tokens; + +/// A mind's window, decided once per question: decided, or not granted yet. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MindWindow { + /// On the shared pool with no grant yet: she has no window, and her turn waits for one on + /// the grants watch ([`grants_changed`]); never a provisional number. + Ungranted, + Decided(Decided), +} + +/// A decided window and who decided it. It always has a size. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Decided { + /// On the node's shared pool: her grant (`window_grant`). + Granted(Tokens), + /// A lane that reports its own window (a remote responder's slot). + Lane(Tokens), + /// A lane whose window is her binding's (a dedicated lane pinned from its own `/props`, + /// cloud, in-process). + Bound(u32), +} + +impl Decided { + pub fn tokens(self) -> u32 { + match self { + Self::Granted(t) | Self::Lane(t) => t.get(), + Self::Bound(w) => w, + } + } +} + +/// The window of mind `persona`, whose requests go to `adapter` and whose binding says `bound`. +pub fn mind_window(persona: uuid::Uuid, adapter: &dyn AIProviderAdapter, bound: u32) -> MindWindow { + if adapter.serves_on_shared_pool() { + return match super::window_grant::current_grant(persona).and_then(Tokens::new) { + Some(granted) => MindWindow::Decided(Decided::Granted(granted)), + None => MindWindow::Ungranted, + }; + } + match adapter.live_served_window().and_then(Tokens::new) { + Some(reported) => MindWindow::Decided(Decided::Lane(reported)), + None => MindWindow::Decided(Decided::Bound(bound)), + } +} + +/// Resolves when the serving daemon publishes new grants: what an ungranted mind waits on, and +/// what a mind on the shared pool watches for a changed window. Pending forever when no grants +/// are installed in this process (nothing will ever grant). +pub async fn grants_changed() { + match super::window_grant::grants_receiver() { + Some(mut rx) => { + if rx.changed().await.is_err() { + std::future::pending::<()>().await; + } + } + None => std::future::pending::<()>().await, + } +} diff --git a/core/continuum-engine/src/capacity/mod.rs b/core/continuum-engine/src/capacity/mod.rs index be8982ab0e..d466b0be17 100644 --- a/core/continuum-engine/src/capacity/mod.rs +++ b/core/continuum-engine/src/capacity/mod.rs @@ -56,6 +56,7 @@ pub mod score; pub mod serving_pager; pub mod settlement; pub mod sim; +pub mod mind_window; pub mod window_grant; pub mod window_sim; pub mod system_profile; diff --git a/core/continuum-engine/src/capacity/window_grant.rs b/core/continuum-engine/src/capacity/window_grant.rs index 1b6175b6e1..aa15c00b78 100644 --- a/core/continuum-engine/src/capacity/window_grant.rs +++ b/core/continuum-engine/src/capacity/window_grant.rs @@ -45,6 +45,12 @@ pub fn install_grants(rx: tokio::sync::watch::Receiver>) -> b GRANTS.set(rx).is_ok() } +/// A receiver of the published grants, for a waiter that must wake when they change +/// ([`super::mind_window::grants_changed`]). `None` before the serving daemon installs them. +pub fn grants_receiver() -> Option>> { + GRANTS.get().cloned() +} + /// Her current grant on this node's engine: `None` before the daemon installs its grants, before /// the engine serves, or while she has none yet. A `watch` borrow, no I/O. pub fn current_grant(persona: uuid::Uuid) -> Option { diff --git a/core/continuum-mind/src/persona/placement_switch/adapter.rs b/core/continuum-mind/src/persona/placement_switch/adapter.rs index d763bb2002..067de5bb28 100644 --- a/core/continuum-mind/src/persona/placement_switch/adapter.rs +++ b/core/continuum-mind/src/persona/placement_switch/adapter.rs @@ -526,6 +526,10 @@ impl AIProviderAdapter for PlacementSwitch { fn live_served_window(&self) -> Option { self.current().live_served_window() } + + fn serves_on_shared_pool(&self) -> bool { + self.current().serves_on_shared_pool() + } /// Asked of the adapter her request actually goes to, like every other capability here: a /// home lane on our fork's gateway may take her learned tool head, a remote seat may not. /// Left to the trait default, every resident read `false` behind this switch, so the head From b5c80dd8828dcf3bb0414ee1e0df15cbfb91ab27 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 3 Nov 2026 20:08:26 -0600 Subject: [PATCH 2/3] The placement fixture asks the one determiner; derive InferenceDevice's Default; drop a no-op cast (clippy in touched files) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../llm_deliberation_faculty/verdict/contribute.rs | 2 +- core/continuum-engine/src/ai/adapter/inference_device.rs | 8 ++------ core/continuum-mind/src/persona/placement_switch/tests.rs | 8 +++++++- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs index 588a40d605..d2ab0af58c 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs @@ -541,7 +541,7 @@ impl LlmDeliberationFaculty { // rent. Only when the lane measured timings (same honesty rule as // delib.generate.cache: a fabricated attribution is a lying receipt). if let Some(t) = resp.timing.as_ref() { - let cached = t.cached_tokens as u32; + let cached = t.cached_tokens; // Her last turn's shape — what the next work call's occupancy bound is read from. LAST_TURN_SHAPE.insert( self.persona_id, diff --git a/core/continuum-engine/src/ai/adapter/inference_device.rs b/core/continuum-engine/src/ai/adapter/inference_device.rs index ea2eca619a..4c6ad29da6 100644 --- a/core/continuum-engine/src/ai/adapter/inference_device.rs +++ b/core/continuum-engine/src/ai/adapter/inference_device.rs @@ -6,11 +6,12 @@ use super::*; /// /// Default: Gpu (enforced now — no silent CPU fallback). /// Auto (try GPU, explicit CPU fallback) is reserved for future opt-in. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum InferenceDevice { /// GPU-accelerated inference only. Metal (Mac) / CUDA (Nvidia) / /// ROCm (AMD) / Vulkan (everyone else). If no GPU adapter can serve /// the model → hard error, never silent CPU. + #[default] Gpu, /// CPU-only inference. Candle / future CPU adapter. Currently only /// reachable when caller EXPLICITLY requests it (training pipelines, @@ -23,11 +24,6 @@ pub enum InferenceDevice { Auto, } -impl Default for InferenceDevice { - fn default() -> Self { - InferenceDevice::Gpu - } -} /// AI provider adapter configuration #[derive(Debug, Clone)] diff --git a/core/continuum-mind/src/persona/placement_switch/tests.rs b/core/continuum-mind/src/persona/placement_switch/tests.rs index e94cedb34d..0b9919819c 100644 --- a/core/continuum-mind/src/persona/placement_switch/tests.rs +++ b/core/continuum-mind/src/persona/placement_switch/tests.rs @@ -751,7 +751,13 @@ async fn capacity_park_resumes_when_local_1_5b_routes_to_larger_remote_seat() { let binding = Arc::new(ModelBindingState::new(ModelBinding { adapter: route.clone(), model: Some("local-1.5B".into()), context_window: 32768, })); - let refusal = CapacityReadiness::new(binding.clone(), binding.load_full()); + // The window the one determiner decides for this binding (the fixture lanes are not the shared pool). + let crate::capacity::mind_window::MindWindow::Decided(decided) = + crate::capacity::mind_window::mind_window(uuid::Uuid::from_u128(1), binding.load_full().adapter.as_ref(), 32768) + else { + panic!("a fixture lane is never on the shared pool") + }; + let refusal = CapacityReadiness::new(uuid::Uuid::from_u128(1), binding.clone(), binding.load_full(), decided.tokens()); let local_target = route.generation_target().unwrap(); assert_eq!(refusal.observed_window(), 32768); assert!(!refusal.changed()); From fbcdd21f8fc59558ed412f8115d1dae92a10c055 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 3 Nov 2026 20:56:21 -0600 Subject: [PATCH 3/3] Measure before parking, one writer per binding, a missing grants watch is refused: Cormac's three on #5752 (and a spin it exposed) 1. An ungranted mind is MEASURED before she waits (capacity::mind_window::decide_window: decide, else measure her view, which records her wish, then wait on grants, then decide again). Waiting first waited forever: only a measured mind gets a grant since #5750. Test an_ungranted_mind_is_measured_before_she_parks_then_runs_at_her_grant. 2. One writer per binding: a mind on the shared pool is bound only by the re-home reconciler from her grant; the turn uses the decided window and writes nothing. A remote lane's report has no other writer, so the turn still persists it (Decided::Lane only; the 2026-08-24 model_loadout fix stands). 3. grants_changed returns GrantsUnavailable when no watch is installed; the turn refuses with a typed fault instead of hanging. Test no_grants_watch_is_a_typed_refusal_never_a_hang. Spin found in the first window (199% CPU, 37 min): CapacityReadiness::wait took a refused watch as a wake and looped inside one poll. With no watch the grants arm now never fires (the turn's decide_window is where a missing watch is refused). Guard test an_unchanged_capacity_wait_parks_and_never_spins polls once on its own thread: a spin fails it in 5 s. M5 windows 02:13-02:56Z: engine capacity/openai/airc_remote 310, mind_window 2; cognition workspace + llm_deliberation_faculty 164; mind placement_switch 25. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../verdict/contribute.rs | 45 ++++++----- .../src/cognition/workspace/capacity.rs | 37 ++++++++- .../src/capacity/mind_window.rs | 80 ++++++++++++++++--- 3 files changed, 133 insertions(+), 29 deletions(-) diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs index d2ab0af58c..8954bff3bf 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs @@ -42,21 +42,25 @@ impl LlmDeliberationFaculty { // triple. [[fallbacks-are-illegal-fail-loud]] [[never-thrash-sticky-hysteresis-on-every-lane]] // Retain the capacity observation that precedes assembly. Sampling again // after an await could mistake newly grown capacity for the refused one. - // Her window, from the one determiner (card de7bb6e8). On the shared pool it is her grant; - // with no grant yet her turn waits for one on the grants watch, never at a provisional size. - let decided = loop { - use crate::capacity::mind_window::{grants_changed, mind_window, MindWindow}; - match mind_window(self.persona_id, loaded.adapter.as_ref(), loaded.context_window) { - MindWindow::Ungranted => { - continuum_base::probe!( - class = "delib.window.ungranted", - persona = %self.persona_name, - "no grant on the shared pool yet: this turn waits for one" - ); - grants_changed().await; - } - MindWindow::Decided(decided) => break decided, - } + // Her window, from the one determiner (card de7bb6e8). On the shared pool it is her grant. An + // ungranted mind is measured first (her view records her wish, never submitted), then parks on + // the grants watch, then decides again (Cormac on #5752). + let decided = match crate::capacity::mind_window::decide_window( + || crate::capacity::mind_window::mind_window(self.persona_id, loaded.adapter.as_ref(), loaded.context_window), + || { + continuum_base::probe!( + class = "delib.window.ungranted", + persona = %self.persona_name, + "no grant on the shared pool yet: measuring her view, then waiting for one" + ); + let _measured = self.prompt_view_with_visual_feedback(ws, loaded.context_window, PromptCalibration::default(), None); + }, + crate::capacity::mind_window::grants_changed, + ) + .await + { + Ok(decided) => decided, + Err(refused) => return Some(Contribution::deliberation_fault(refused.to_string())), }; let decided_window = decided.tokens(); let capacity_readiness = Arc::new(crate::cognition::workspace::CapacityReadiness::new( @@ -127,9 +131,14 @@ impl LlmDeliberationFaculty { model: loaded.model.clone(), context_window: effective, }); - let _ = self - .binding - .compare_and_swap(&loaded, Arc::clone(&reconciled)); + // ONE WRITER PER BINDING (Cormac on #5752): a mind on the shared pool is bound by the + // re-home reconciler from her grant, so the turn uses the decided window and writes + // nothing; a remote lane's report has no other writer, so the turn persists it. + if let crate::capacity::mind_window::Decided::Lane(_) = decided { + let _ = self + .binding + .compare_and_swap(&loaded, Arc::clone(&reconciled)); + } reconciled } }; diff --git a/core/continuum-cognition/src/cognition/workspace/capacity.rs b/core/continuum-cognition/src/cognition/workspace/capacity.rs index 5ae38b41ad..0ca8ea0a79 100644 --- a/core/continuum-cognition/src/cognition/workspace/capacity.rs +++ b/core/continuum-cognition/src/cognition/workspace/capacity.rs @@ -161,8 +161,15 @@ impl CapacityReadiness { let current = self.handle.load_full(); let window = current.adapter.live_served_window(); let adapter_change = current.adapter.capacity_changed(window); - // A mind on the shared pool's window is her grant: a new grant is a capacity change. - let grants_change = crate::capacity::mind_window::grants_changed(); + // A mind on the shared pool's window is her grant: a new grant is a capacity change. With no + // grants watch in this process there is no such change to wait for, so that arm never + // fires (a refused watch resolving at once would spin this loop; the turn's own + // decide_window is where a missing watch is refused). + let grants_change = async { + if crate::capacity::mind_window::grants_changed().await.is_err() { + std::future::pending::<()>().await; + } + }; if self.changed() { return; } @@ -250,6 +257,32 @@ mod tests { .await .expect("both subscribers observe growth, including pre-poll publication"); } + // what this catches (#5752's first window: 199% CPU for 37 minutes): a readiness wait that + // wakes without a change and spins inside one poll. An unchanged wait parks: its first poll + // returns Pending. Run on its own thread so a spin fails this test in seconds, never hangs CI. + #[test] + fn an_unchanged_capacity_wait_parks_and_never_spins() { + let (sent, received) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().expect("test runtime"); // a test runtime always builds + runtime.block_on(async { + let adapter = Arc::new(crate::ai::HeuristicInferenceAdapter::new()); + let handle = Arc::new(ModelBindingState::new(ModelBinding { + adapter, model: Some("bound".into()), context_window: 32768, + })); + let unchanged = readiness(&handle); + let mut wait = Box::pin(unchanged.wait()); + let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); + let parked = std::future::Future::poll(wait.as_mut(), &mut cx).is_pending(); + let _ = sent.send(parked); // the receiver may have timed out already; nothing to report then + }); + }); + assert_eq!( + received.recv_timeout(std::time::Duration::from_secs(5)), + Ok(true), + "an unchanged wait parks on its first poll; no answer in 5 s means it spins" + ); + } #[tokio::test(start_paused = true)] async fn refit_waits_for_changed_capacity_above_provider_bound() { let adapter = Arc::new(crate::ai::HeuristicInferenceAdapter::new()); diff --git a/core/continuum-engine/src/capacity/mind_window.rs b/core/continuum-engine/src/capacity/mind_window.rs index f1598f230a..5485d5a219 100644 --- a/core/continuum-engine/src/capacity/mind_window.rs +++ b/core/continuum-engine/src/capacity/mind_window.rs @@ -51,16 +51,78 @@ pub fn mind_window(persona: uuid::Uuid, adapter: &dyn AIProviderAdapter, bound: } } -/// Resolves when the serving daemon publishes new grants: what an ungranted mind waits on, and -/// what a mind on the shared pool watches for a changed window. Pending forever when no grants -/// are installed in this process (nothing will ever grant). -pub async fn grants_changed() { - match super::window_grant::grants_receiver() { - Some(mut rx) => { - if rx.changed().await.is_err() { - std::future::pending::<()>().await; +/// No grants watch is installed in this process, so a mind on the shared pool can never be granted +/// a window here: a typed refusal, never a wait on a watch that cannot fire (Cormac on #5752). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct GrantsUnavailable; + +impl std::fmt::Display for GrantsUnavailable { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("no grants are published in this process: a mind on the shared pool has no window") + } +} + +/// Resolves when the serving daemon publishes new grants: what an ungranted mind waits on, and what a +/// mind on the shared pool watches for a changed window. +pub async fn grants_changed() -> Result<(), GrantsUnavailable> { + let mut rx = super::window_grant::grants_receiver().ok_or(GrantsUnavailable)?; + rx.changed().await.map_err(|_| GrantsUnavailable) +} + +/// Decide her window. An ungranted mind is MEASURED first (`measure` builds her view, which records +/// her wish, so the next grants tick can grant her), then waits for new grants and decides again: +/// measure, park, wake, decide (Cormac on #5752: a wait before the measurement waits forever). +pub async fn decide_window(decide: D, mut measure: M, wait: W) -> Result +where + D: Fn() -> MindWindow, + M: FnMut(), + W: Fn() -> F, + F: std::future::Future>, +{ + loop { + match decide() { + MindWindow::Decided(decided) => return Ok(decided), + MindWindow::Ungranted => { + measure(); + wait().await?; } } - None => std::future::pending::<()>().await, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::inference::planning::window_allocator::test_tokens as t; + use std::cell::Cell; + + // what this catches (Cormac on #5752): a new mind that waits for a grant before anything measures + // her, so she is never granted. She is measured, then parks, then is granted and runs. + #[tokio::test] + async fn an_ungranted_mind_is_measured_before_she_parks_then_runs_at_her_grant() { + let measured = Cell::new(0); + let woke = Cell::new(0); + let decided = decide_window( + || match measured.get() { + 0 => MindWindow::Ungranted, + _ => MindWindow::Decided(Decided::Granted(t(20_817))), + }, + || measured.set(measured.get() + 1), + || { + assert_eq!(measured.get(), 1, "measured before she parks"); + woke.set(woke.get() + 1); + async { Ok(()) } + }, + ) + .await; + assert_eq!(decided, Ok(Decided::Granted(t(20_817)))); + assert_eq!((measured.get(), woke.get()), (1, 1), "one measurement, one wait, then her grant"); + } + + // what this catches: a turn hanging silently on a watch that can never fire. + #[tokio::test] + async fn no_grants_watch_is_a_typed_refusal_never_a_hang() { + let decided = decide_window(|| MindWindow::Ungranted, || {}, || async { Err(GrantsUnavailable) }).await; + assert_eq!(decided, Err(GrantsUnavailable)); } }