diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs index 48028fdd24..18b5b4020f 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty.rs @@ -103,7 +103,6 @@ mod read_receipt; pub use read_receipt::ReadReceipt; use self::reply_claim::*; mod verdict; -mod prefill_during_tool; mod tool_surface; use super::tool_surface::{SelectedSurface, ToolSurface}; @@ -239,8 +238,6 @@ pub struct LlmDeliberationFaculty { held_blocks: parking_lot::Mutex>, /// A measurement fork's (`fork_eval_cycle`): its turns warm their own page, never hers. forked: bool, - /// Her prompt, prefilled into her slot while her tool runs (`prefill_during_tool.rs`). - prefix_warm: prefill_during_tool::PendingPrefix, } impl LlmDeliberationFaculty { @@ -275,7 +272,6 @@ impl LlmDeliberationFaculty { held_blocks: parking_lot::Mutex::new(std::collections::HashMap::new()), reading: Default::default(), forked: false, - prefix_warm: Default::default(), } } diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prefill_during_tool.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prefill_during_tool.rs deleted file mode 100644 index 54b7accdd9..0000000000 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prefill_during_tool.rs +++ /dev/null @@ -1,193 +0,0 @@ -//! Prefill during the tool (card 377d4afa; CONTINUUM-ENGINE.md 2.4: the act is a dependency graph, -//! independent passes overlap). -//! -//! When her act dispatches a tool, the prompt she just sent is already known, and her view only -//! appends within an epoch, so it is the head of her next prompt (replay of the M5 captures, -//! 2026-11-13: every tool continuation's prompt began with the whole previous one). The -//! [`WarmPrefix`] pass prefills it into her page's slot WHILE the tool runs, through the same -//! adapter path and admission as any of her turns: a one-token generation with the prompt cache on, -//! holding no serving lane (it is adapter-owned work) and waiting for a decode permit like any -//! request. Where her slot kept her KV, the engine finds it whole and the pass costs one token; -//! where another mind took the slot, the pass pages or prefills it back before her result lands. -//! -//! Her next generation subscribes to the pass's artifact, never a timer: settled ready, it starts -//! on a warm prefix and the probe credits the prefill that ran inside the tool; failed, abandoned -//! or superseded, she prefills as before and the probe says why. Her next generation asks only once -//! her tool's result is in her view, so a pass already settled then was warm before the result. - -use continuum_kernel::runtime::stage::{ - spawn_when_ready, Arrival, DependentStage, Inputs, Settled, Subscribes, TopicName, -}; - -use super::*; -use crate::ai::adapter::PromptCache; -use crate::ai::inference_error::InferenceError; -use crate::ai::types::{DispatchTerms, Think}; -use crate::inference::slots::PageKey; - -/// The artifact the warm pass produces and her next generation subscribes to. -const PREFIX_WARM: TopicName = TopicName("cognition/prefix.warm"); - -/// Her previous prompt, prefilled into her slot while her tool ran: the engine's own receipt. -#[derive(Debug)] -pub(super) struct PrefixWarm { - /// The prompt tokens the slot now holds for her (reused plus prefilled by the pass). - prefix_tokens: u32, - /// What the pass prefilled: zero when her slot had kept her KV. - prefill: std::time::Duration, -} - -/// Why the pass left nothing to credit: her next generation prefills as it always did. -#[derive(Debug)] -pub(super) enum PrefixMiss { - /// The engine refused or failed the pass. - Refused(InferenceError), - /// The engine answered without its timing receipt, so no warmth can be claimed. - Unmeasured, -} - -/// The warm pass. It depends on nothing but the dispatch that spawns it. -struct WarmPrefix { - adapter: Arc, - request: TextGenerationRequest, -} - -#[async_trait] -impl DependentStage for WarmPrefix { - type Inputs = (); - type Produces = PrefixWarm; - type Fails = PrefixMiss; - - fn produces(&self) -> TopicName { - PREFIX_WARM - } - - async fn run(self, _inputs: <() as Inputs>::Settled) -> Result { - let response = self - .adapter - .generate_under(self.request, DispatchTerms::thinking(Think::ModelDefault)) - .await - .map_err(PrefixMiss::Refused)?; - let timing = response.timing.ok_or(PrefixMiss::Unmeasured)?; - let prefill = std::time::Duration::try_from_secs_f64(timing.prefill_ms / 1000.0) - .map_err(|_| PrefixMiss::Unmeasured)?; - Ok(PrefixWarm { prefix_tokens: timing.cached_tokens.saturating_add(timing.prefill_tokens), prefill }) - } -} - -/// The pass in flight for her page, until her next generation takes it. -struct Warming { - page: PageKey, - warm: Subscribes, -} - -/// The faculty's one pending warm pass. -#[derive(Default)] -pub(super) struct PendingPrefix(parking_lot::Mutex>); - -/// Her next generation found no warmth to credit, and why. -fn missed(reason: &'static str, persona: &str) { - continuum_base::probe!( - class = "delib.prefill.during_tool.missed", - persona = %persona, - reason = reason, - "her prefix was not warmed during the tool: her next generation prefills it as before" - ); -} - -impl LlmDeliberationFaculty { - /// Her act dispatched its tool: warm the prompt she just sent (`template` with `view`'s messages) into - /// her page's slot while the tool runs. Never blocks the act; a newer pass supersedes an older - /// one nobody took. It names the same view end as her act (`view_messages`): a warm pass that - /// named none made the engine forget where her next prompt diverges, so her saved page dropped - /// that checkpoint and her next act re-prefilled from the head (the M5, 2026-11-16: 83 of 95 - /// view-end-less pages followed a warm pass; ~100k-token re-prefills). - pub(super) fn prefill_during_tool( - &self, - adapter: &Arc, - room: Uuid, - template: Option<&TextGenerationRequest>, - view: &DeliberationPromptView, - ) { - let (Some(page), Some(template), PromptCache::PinnedSlot) = (self.page(room), template, adapter.prompt_cache()) else { - return; - }; - let request = warm_request(template, &view.messages, view.resumes_at()); - let pass = WarmPrefix { adapter: Arc::clone(adapter), request }; - let warm = spawn_when_ready(pass, ()); - if self.prefix_warm.0.lock().replace(Warming { page, warm }).is_some() { - missed("superseded", &self.persona_name); - } - } - - /// Her next generation's subscription to the warm pass for `room`'s page: it starts when the - /// pass has settled, whatever it settled with. - pub(super) async fn prefix_warm_settled(&self, room: Uuid) { - let page = self.page(room); - let taken = { - let mut pending = self.prefix_warm.0.lock(); - let ours = pending.as_ref().is_some_and(|warming| Some(warming.page) == page); - if ours { pending.take() } else { None } - }; - let Some(mut warming) = taken else { - return; - }; - let met = warming.warm.settled().await; - match met.settled { - Settled::Ready(warm) => { - let (warmed_before_result, saved) = match met.arrival { - Arrival::AlreadySettled => (true, warm.prefill), - Arrival::WaitedFor(waited) => (false, warm.prefill.saturating_sub(waited)), - }; - continuum_base::probe!( - class = "delib.prefill.during_tool", - persona = %self.persona_name, - prefix_tokens = warm.prefix_tokens as u64, - warmed_before_result = warmed_before_result, - saved_ms = saved.as_millis() as u64, - "her prefix was prefilled while her tool ran" - ); - } - Settled::Failed(miss) => match &*miss { - PrefixMiss::Refused(error) => { - continuum_base::probe!( - class = "delib.prefill.during_tool.missed", - persona = %self.persona_name, - reason = "refused", - error = ?error, - "the engine refused her warm pass: her next generation prefills as before" - ); - } - PrefixMiss::Unmeasured => missed("unmeasured", &self.persona_name), - }, - Settled::Abandoned => missed("abandoned", &self.persona_name), - } - } -} - -/// The warm pass's request: her act's template and prompt, her act's view end, one token. -fn warm_request(template: &TextGenerationRequest, messages: &[ChatMessage], view_messages: Option) -> TextGenerationRequest { - let mut request = TextGenerationRequest::clone(template); - request.messages = messages.to_vec(); - request.view_messages = view_messages; - request.max_tokens = Some(1); - request.request_id = Some(Uuid::new_v4().to_string()); - request -} - -#[cfg(test)] -mod tests { - use super::*; - - // what this catches: the warm pass sending her prompt with no view end, which made the engine - // forget where her next prompt diverges (regression, the M5 2026-11-16: ~100k-token re-prefills) - #[test] - fn the_warm_pass_names_her_acts_view_end() { - let template = TextGenerationRequest { view_messages: None, max_tokens: Some(900), ..Default::default() }; - let messages = vec![ChatMessage::text("system", "s"), ChatMessage::text("user", "board"), ChatMessage::text("user", "pick")]; - let warm = warm_request(&template, &messages, Some(2)); - assert_eq!(warm.view_messages, Some(2), "the warm pass carries her act's view end"); - assert_eq!(warm.max_tokens, Some(1), "it decodes one token"); - assert_eq!(warm.messages.len(), 3, "it sends the prompt she just sent"); - } -} diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs index 9830a176ae..f90b92bea6 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/act_verdicts.rs @@ -667,3 +667,29 @@ async fn empty_prose_with_no_tools_is_a_pass() { .expect("verdict"); assert_eq!(c.decision, Some(Decision::pass())); } + +// what this catches: a one-token "warm" request sent between her act and her next generation (the +// deleted prefill_during_tool). It re-sent the prompt she was served, so the engine truncated her +// generated reasoning and call out of her KV and her next generation recomputed them (the M5, +// 2026-11-17). Her act, then her next generation: exactly two calls, neither a one-token pass. +#[tokio::test] +async fn her_act_and_her_next_generation_are_the_only_requests_on_her_slot() { + let call = ToolCall { id: "t1".to_string(), name: "code/read".to_string(), input: json!({ "path": "deploy.md" }) }; + let adapter = Arc::new(ScriptedAdapter { + prompt_cache: crate::ai::adapter::PromptCache::PinnedSlot, + ..ScriptedAdapter::new(vec![ + make_response(FinishReason::ToolUse, "", Some(vec![call])), + make_response(FinishReason::Stop, "deploy.md says it landed", None), + ]) + }); + let faculty = LlmDeliberationFaculty::new(Uuid::new_v4(), "Ivar", "You are Ivar.", Arc::clone(&adapter) as Arc) + .with_tools(vec![read_tool()]) + .with_context_window(32_768); + let ws = Workspace::new("teammate asks: did the deploy fix land?"); + let first = faculty.contribute(&ws).await.expect("verdict"); + assert!(matches!(first.decision, Some(Decision::Act { .. })), "her act dispatches the tool"); + faculty.contribute(&ws).await.expect("verdict"); + let seen = adapter.seen.lock().expect("fixture request log"); + assert_eq!(seen.len(), 2, "her act, then her next generation: nothing between them on her slot"); + assert!(seen.iter().all(|request| request.max_tokens != Some(1)), "no one-token pass truncates what she generated"); +} diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/mod.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/mod.rs index 2b912a18a5..2fb0b876f2 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/mod.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/mod.rs @@ -13,4 +13,3 @@ mod act_output_room; mod unpriced_need; -mod prefill_during_tool; diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/prefill_during_tool.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/prefill_during_tool.rs deleted file mode 100644 index e6ec8f490b..0000000000 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/prefill_during_tool.rs +++ /dev/null @@ -1,70 +0,0 @@ -#![cfg(test)] - -//! Prefill during the tool (`prefill_during_tool.rs`): her act warms the prompt she just sent -//! into her slot while the tool runs, and her next generation starts only once that warm pass -//! has settled. Event order only, never elapsed time. - -use super::*; - -fn act() -> TextGenerationResponse { - let call = ToolCall { id: "t1".to_string(), name: "code/read".to_string(), input: json!({ "path": "deploy.md" }) }; - make_response(FinishReason::ToolUse, "", Some(vec![call])) -} - -fn warmed() -> TextGenerationResponse { - let mut warm = make_response(FinishReason::Length, "", None); - warm.timing = Some(crate::ai::types::GenerationTiming { cached_tokens: 900, ..Default::default() }); - warm -} - -fn ivar(adapter: Arc) -> LlmDeliberationFaculty { - LlmDeliberationFaculty::new(Uuid::new_v4(), "Ivar", "You are Ivar.", adapter) - .with_tools(vec![read_tool()]) - .with_context_window(32_768) -} - -fn caching(responses: Vec) -> Arc { - Arc::new(ScriptedAdapter { prompt_cache: crate::ai::adapter::PromptCache::PinnedSlot, ..ScriptedAdapter::new(responses) }) -} - -// what this catches: the warm pass sending anything but the prompt she just sent (then the -// engine warms a prefix her next prompt does not begin with), and her next generation reaching -// the engine before the pass settled (then the two race for her slot and the pass buys nothing). -#[tokio::test] -async fn her_next_generation_starts_after_the_pass_warmed_the_prompt_she_sent() { - let adapter = caching(vec![act(), warmed(), make_response(FinishReason::Stop, "deploy.md says it landed", None)]); - let faculty = ivar(Arc::clone(&adapter)); - let ws = Workspace::new("teammate asks: did the deploy fix land?"); - let first = faculty.contribute(&ws).await.expect("verdict"); - assert!(matches!(first.decision, Some(Decision::Act { .. })), "her act dispatches the tool"); - faculty.contribute(&ws).await.expect("verdict"); - - let seen = adapter.seen.lock().expect("fixture request log"); - assert_eq!(seen.len(), 3, "her act, the warm pass, then her next generation"); - assert_eq!(seen[1].max_tokens, Some(1), "the pass only prefills"); - let sent = |at: usize| serde_json::to_value(&seen[at].messages).ok(); - assert_eq!(sent(1), sent(0), "the pass warms exactly the prompt she sent"); - assert_ne!(seen[2].max_tokens, Some(1), "her next generation came after the pass settled"); -} - -// what this catches: a failed pass that blocks or drops her next generation: she must prefill -// normally, and an adapter that keeps no prompt must never be sent a pass at all. -#[tokio::test] -async fn a_refused_pass_degrades_to_a_normal_prefill_and_no_cache_means_no_pass() { - let adapter = caching(vec![act(), make_response(FinishReason::Stop, "done", None)]); - *adapter.on_request.lock().expect("fixture hook") = Some(Box::new(|request: &TextGenerationRequest| { - (request.max_tokens == Some(1)).then(|| crate::ai::inference_error::InferenceError::Unavailable("engine refused the pass".into())) - })); - let faculty = ivar(Arc::clone(&adapter)); - let ws = Workspace::new("teammate asks: did the deploy fix land?"); - faculty.contribute(&ws).await.expect("verdict"); - let next = faculty.contribute(&ws).await.expect("her next generation still runs"); - assert!(next.decision.is_some(), "the refused pass cost her nothing but the pass"); - assert_eq!(adapter.call_count(), 3, "her act, the refused pass, her next generation"); - - let plain = Arc::new(ScriptedAdapter::new(vec![act(), make_response(FinishReason::Stop, "done", None)])); - let faculty = ivar(Arc::clone(&plain)); - faculty.contribute(&ws).await.expect("verdict"); - faculty.contribute(&ws).await.expect("verdict"); - assert_eq!(plain.call_count(), 2, "no prompt cache, no pass"); -} 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 63195c569f..2a2c0627f8 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 @@ -351,7 +351,6 @@ impl LlmDeliberationFaculty { // A rebuilt request with no max_tokens keeps the last one sent (the read of the // previous value is also what keeps the initializer honest). sent_allowance = request.max_tokens.or(sent_allowance); - self.prefix_warm_settled(ws.room_id).await; // her prefix, warmed while her last tool ran let result = self .generate_for_workspace(ws, &binding, fit_window, request, terms, allocation, receipts) .await?; @@ -841,7 +840,6 @@ impl LlmDeliberationFaculty { return Some(v); } if !calls.is_empty() { - self.prefill_during_tool(&binding.adapter, ws.room_id, request_template.as_ref(), &view); return Some(self.act_verdict(calls, &resp, ws.activity_room_id)); } }