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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,32 @@ 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. 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(
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
Expand All @@ -62,7 +85,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 {
Expand Down Expand Up @@ -104,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
}
};
Expand Down Expand Up @@ -518,7 +550,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,
Expand Down
89 changes: 78 additions & 11 deletions core/continuum-cognition/src/cognition/workspace/capacity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<crate::cognition::model_binding::ModelBinding>,
target: std::sync::Arc<dyn crate::ai::adapter::AIProviderAdapter>,
Expand All @@ -85,18 +86,27 @@ pub struct CapacityReadiness {
fitted_window: Option<u32>,
}
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<crate::cognition::model_binding::ModelBinding>,
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,
Expand Down Expand Up @@ -133,17 +143,33 @@ 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();
loop {
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. 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;
}
Expand All @@ -154,6 +180,7 @@ impl CapacityReadiness {
if result.is_err() { return std::future::pending::<()>().await; }
}
_ = adapter_change => {}
_ = grants_change => {}
}
}
}
Expand All @@ -162,6 +189,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;

Expand Down Expand Up @@ -191,8 +232,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()),
Expand All @@ -216,21 +257,47 @@ 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());
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");
handle.store(Arc::new(ModelBinding {
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");
Expand Down
16 changes: 10 additions & 6 deletions core/continuum-engine/src/ai/adapter/inference_device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -23,11 +24,6 @@ pub enum InferenceDevice {
Auto,
}

impl Default for InferenceDevice {
fn default() -> Self {
InferenceDevice::Gpu
}
}

/// AI provider adapter configuration
#[derive(Debug, Clone)]
Expand Down Expand Up @@ -467,6 +463,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.
Expand Down
4 changes: 4 additions & 0 deletions core/continuum-engine/src/ai/openai_adapter/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u32> {
if self.dedicated_lane || !self.config.single_resident_model {
return None;
Expand Down
Loading
Loading