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 8954bff3bf..b36f8af4fc 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 @@ -55,7 +55,7 @@ impl LlmDeliberationFaculty { ); let _measured = self.prompt_view_with_visual_feedback(ws, loaded.context_window, PromptCalibration::default(), None); }, - crate::capacity::mind_window::grants_changed, + crate::capacity::mind_window::grants_waiter, ) .await { diff --git a/core/continuum-cognition/src/cognition/workspace/capacity.rs b/core/continuum-cognition/src/cognition/workspace/capacity.rs index 0ca8ea0a79..dedcaf6c3b 100644 --- a/core/continuum-cognition/src/cognition/workspace/capacity.rs +++ b/core/continuum-cognition/src/cognition/workspace/capacity.rs @@ -165,10 +165,18 @@ impl CapacityReadiness { // 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; + // A mind on the shared pool's window is her grant: a NEWER grant is a capacity change. + // The waiter is taken before the check below and marks the current grants seen, so it + // parks on unchanged grants (a clone that did not spun this loop: 339% CPU on the M5). + // With no grants watch there is no such change, and the arm never fires. + let waiter = crate::capacity::mind_window::grants_waiter(); + let grants_change = async move { + if let Ok(waiter) = waiter { + if waiter.await.is_ok() { + return; + } } + std::future::pending::<()>().await }; if self.changed() { return; diff --git a/core/continuum-engine/src/capacity/mind_window.rs b/core/continuum-engine/src/capacity/mind_window.rs index 5485d5a219..49884cd3e4 100644 --- a/core/continuum-engine/src/capacity/mind_window.rs +++ b/core/continuum-engine/src/capacity/mind_window.rs @@ -11,7 +11,7 @@ use crate::inference::planning::window_allocator::Tokens; #[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. + /// the grants watch ([`grants_waiter`]); never a provisional number. Ungranted, Decided(Decided), } @@ -64,27 +64,50 @@ impl std::fmt::Display for GrantsUnavailable { /// 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) +/// +/// Take it BEFORE deciding (`grants_waiter`), so a grant published between the decision and the wait +/// still wakes her. +pub fn grants_waiter() -> Result>, GrantsUnavailable> { + super::window_grant::grants_receiver().map(|rx| GrantsWaiter::new(rx).changed()).ok_or(GrantsUnavailable) +} + +/// A wait for grants NEWER than those current when it was made. The receiver is a clone of the +/// installed one, which never marks a value seen, so the clone marks the current grants seen first: +/// without that, `changed()` resolves at once on every call, and an ungranted mind looped measure, +/// wake, ungranted with nothing changed (the M5 core at 339% CPU on d39469463, Atlas 751 times in a +/// minute). +struct GrantsWaiter(tokio::sync::watch::Receiver>); + +impl GrantsWaiter { + fn new(mut rx: tokio::sync::watch::Receiver>) -> Self { + rx.borrow_and_update(); + Self(rx) + } + + /// Resolves when newer grants are published; `GrantsUnavailable` when the sender is gone. + async fn changed(mut self) -> Result<(), GrantsUnavailable> { + self.0.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 +/// her wish, so the next grants tick can grant her), then waits for NEWER grants and decides again +/// (Cormac on #5752). The waiter is taken before each decision, so no publish between the two is lost. +/// No grants watch is a refusal only when she is ungranted: a decided window needs none. +pub async fn decide_window(decide: D, mut measure: M, subscribe: S) -> Result where D: Fn() -> MindWindow, M: FnMut(), - W: Fn() -> F, - F: std::future::Future>, + S: Fn() -> Result, + W: std::future::Future>, { loop { + let waiter = subscribe(); match decide() { MindWindow::Decided(decided) => return Ok(decided), MindWindow::Ungranted => { measure(); - wait().await?; + waiter?.await?; } } } @@ -96,33 +119,62 @@ mod tests { use crate::inference::planning::window_allocator::test_tokens as t; use std::cell::Cell; + fn grants(by_mind: &[(uuid::Uuid, u32)]) -> Option { + Some(super::super::window_grant::PoolGrants { + pool_tokens: 200_000, + per_sequence_cap: 200_000, + by_mind: by_mind.iter().copied().collect(), + }) + } + + // what this catches (the M5 core at 339% CPU on d39469463): a waiter over grants that never + // change resolving at once. A clone of a receiver that never marked a value seen did, so an + // ungranted mind spun. Unchanged grants park the waiter; only a newer publish wakes it. + #[tokio::test] + async fn a_waiter_parks_on_unchanged_grants_and_wakes_on_a_newer_publish() { + let (sender, installed) = tokio::sync::watch::channel(grants(&[])); + let waiter = GrantsWaiter::new(installed.clone()); + let mut waiting = Box::pin(waiter.changed()); + let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); + assert!(std::future::Future::poll(waiting.as_mut(), &mut cx).is_pending(), "unchanged grants: it parks"); + let _ = sender.send(grants(&[(uuid::Uuid::from_u128(4), 14_860)])); // the receiver is held above + assert_eq!(waiting.await, Ok(()), "a newer publish wakes it"); + } + // 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. + // her. She is measured, then parks, then is granted and runs; and a grant published between her + // decision and her wait is not lost (the waiter is taken first). #[tokio::test] - async fn an_ungranted_mind_is_measured_before_she_parks_then_runs_at_her_grant() { + async fn an_ungranted_mind_is_measured_parks_then_runs_at_her_grant() { + let her = uuid::Uuid::from_u128(4); + let (sender, installed) = tokio::sync::watch::channel(grants(&[])); let measured = Cell::new(0); - let woke = Cell::new(0); + let granted = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let decided = decide_window( - || match measured.get() { - 0 => MindWindow::Ungranted, - _ => MindWindow::Decided(Decided::Granted(t(20_817))), + || match granted.load(std::sync::atomic::Ordering::SeqCst) { + false => MindWindow::Ungranted, + true => MindWindow::Decided(Decided::Granted(t(14_860))), }, - || measured.set(measured.get() + 1), || { - assert_eq!(measured.get(), 1, "measured before she parks"); - woke.set(woke.get() + 1); - async { Ok(()) } + measured.set(measured.get() + 1); + // the serving tick that grants her runs after she is measured + granted.store(true, std::sync::atomic::Ordering::SeqCst); + let _ = sender.send(grants(&[(her, 14_860)])); // the receiver is held by the waiter }, + || Ok(GrantsWaiter::new(installed.clone()).changed()), ) .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"); + assert_eq!(decided, Ok(Decided::Granted(t(14_860)))); + assert_eq!(measured.get(), 1, "measured once, then granted"); } - // what this catches: a turn hanging silently on a watch that can never fire. + // what this catches: a turn hanging on a watch that can never fire, and a decided window refused + // only because no watch exists. #[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)); + async fn no_grants_watch_refuses_only_an_ungranted_mind() { + let refused = decide_window(|| MindWindow::Ungranted, || {}, || Err::>, _>(GrantsUnavailable)).await; + assert_eq!(refused, Err(GrantsUnavailable)); + let bound = decide_window(|| MindWindow::Decided(Decided::Bound(8_192)), || {}, || Err::>, _>(GrantsUnavailable)).await; + assert_eq!(bound, Ok(Decided::Bound(8_192)), "a bound window needs no grants watch"); } } diff --git a/core/continuum-engine/src/capacity/window_grant.rs b/core/continuum-engine/src/capacity/window_grant.rs index aa15c00b78..7fa3289470 100644 --- a/core/continuum-engine/src/capacity/window_grant.rs +++ b/core/continuum-engine/src/capacity/window_grant.rs @@ -46,7 +46,7 @@ pub fn install_grants(rx: tokio::sync::watch::Receiver>) -> b } /// 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. +/// ([`super::mind_window::grants_waiter`]). `None` before the serving daemon installs them. pub fn grants_receiver() -> Option>> { GRANTS.get().cloned() }