From 0ebde8faa832d7f3aa22d9d307d8ce17b577b031 Mon Sep 17 00:00:00 2001 From: Jonathan Mohrbacher Date: Fri, 20 Nov 2026 11:33:00 -0500 Subject: [PATCH 1/2] [NO-JIRA] Cache-miss breaker: stop a Gemini delegate whose prompt cache stopped hitting Vertex sometimes stops serving one session from its prompt cache, so every call re-reads the whole context at full price while concurrent sessions hit 97-99% (workstation-ke9f). A stuck session usually stays stuck; a fresh one gets a fresh chance. This ports opencode's cache-miss-breaker plugin (workstation#840) to goose delegates. Rule: 10 consecutive model calls at >=50K prompt tokens with zero cache reads (a hit resets; a smaller call neither counts nor resets), on a Gemini model that has reported a cache hit in this process. On trip, the trip step's response decides: a request for any tool other than recipe__final_output cancels the delegate (a child token, never the parent's) and fails it with a message telling the lead to re-dispatch once as a new delegate. A final answer is let through. It is a step observer over the delegate's AgentEvent stream, in both event loops: get_agent_messages (the legacy loop goose-serve runs today) and ForegroundSubagentRunner::run_to_end (state machine). agent.rs is untouched. GOOSE_CACHE_MISS_BREAKER=off disables it; GOOSE_CACHE_MISS_BREAKER_STEPS and GOOSE_CACHE_MISS_BREAKER_MIN_CONTEXT override the thresholds. --- .github/workflows/patched-release.yml | 2 +- crates/goose/src/agents/cache_miss_breaker.rs | 416 ++++++++++++++++++ crates/goose/src/agents/mod.rs | 3 +- crates/goose/src/agents/subagent_handler.rs | 177 +++++++- 4 files changed, 592 insertions(+), 6 deletions(-) create mode 100644 crates/goose/src/agents/cache_miss_breaker.rs diff --git a/.github/workflows/patched-release.yml b/.github/workflows/patched-release.yml index c552b1b17e42..15583c0bb698 100644 --- a/.github/workflows/patched-release.yml +++ b/.github/workflows/patched-release.yml @@ -55,7 +55,7 @@ jobs: - name: Test patched modules run: | F=code-mode,tree-sitter,aws-providers,telemetry,otel,rustls-tls,live-voice,system-keyring,platform-apps,chat-recall,scheduler,acp-http,online-model-meta - cargo test --release -p goose --features "$F" --lib -- gcpvertexai session_context test_parent_link_is_visible_to_providers gcpauth process_group cache_ttl max_turns_from_meta test_add_final_output_tool rolling self_compact compact_kind global_skill mcp_client_startup_timeout turn_error subagent_policy subdirectory_hints deliver_subdirectory_hints requeue_after_history_replacement message_id_from_meta agent_capabilities_advertise_truncate_from_message truncate_conversation_from_message requeue_hints_missing_from + cargo test --release -p goose --features "$F" --lib -- gcpvertexai session_context test_parent_link_is_visible_to_providers gcpauth process_group cache_ttl max_turns_from_meta test_add_final_output_tool rolling self_compact compact_kind global_skill mcp_client_startup_timeout turn_error subagent_policy subdirectory_hints deliver_subdirectory_hints requeue_after_history_replacement message_id_from_meta agent_capabilities_advertise_truncate_from_message truncate_conversation_from_message requeue_hints_missing_from cache_miss_breaker cargo test --release -p goose --features "$F" --test acp_server_test -- test_session_settings test_prompt_max_turns_bounds_run test_prompt_self_compact test_recipe_session_after_reload_never_lists_self_compact_and_resume test_prompt_turn_error test_prompt_message_id_and_truncate_from_message cargo test --release -p goose --features "$F" --test rolling_memory cargo test --release -p goose --features "$F" --test self_compact diff --git a/crates/goose/src/agents/cache_miss_breaker.rs b/crates/goose/src/agents/cache_miss_breaker.rs new file mode 100644 index 000000000000..c24177badf2b --- /dev/null +++ b/crates/goose/src/agents/cache_miss_breaker.rs @@ -0,0 +1,416 @@ +// Modified by Jonathan Mohrbacher, 2026: cache-miss breaker for Gemini delegates. +//! Stop a Gemini delegate whose prompt cache has stopped hitting. +//! +//! Vertex sometimes stops serving a single session from its prompt cache: every +//! call re-reads the whole context at full price, while concurrent sessions on +//! the same model hit 97-99% (workstation-ke9f; about $117 of one day's $170). +//! A stuck session usually stays stuck, and a fresh session gets a fresh chance. +//! +//! The rule (same as opencode's cache-miss-breaker plugin): count consecutive +//! model calls with at least `min_context` prompt tokens and zero cache reads. +//! A call with any cache read resets the count; a smaller call neither counts nor +//! resets. At `trip_steps` in a row the delegate is stopped, but only for a +//! Gemini model that has reported a cache hit in this process before (a model +//! that never reports cache reads would otherwise always trip). +//! +//! It is a step observer over the delegate's `AgentEvent` stream, so it needs +//! nothing from the agent loop beyond `AgentEvent::Usage` (one per provider +//! call) and `AgentEvent::Message`. Delegates are the only callers, so a +//! top-level session is never stopped. +//! +//! Env: `GOOSE_CACHE_MISS_BREAKER=off` disables it; +//! `GOOSE_CACHE_MISS_BREAKER_STEPS` and `GOOSE_CACHE_MISS_BREAKER_MIN_CONTEXT` +//! override the thresholds. + +use crate::agents::final_output_tool::FINAL_OUTPUT_TOOL_NAME; +use crate::agents::AgentEvent; +use crate::conversation::message::{Message, MessageContent}; +use goose_providers::conversation::token_usage::ProviderUsage; +use rmcp::model::Role; +use std::collections::HashSet; +use std::sync::{Mutex, OnceLock}; + +pub const TRIP_STEPS: u32 = 10; +pub const MIN_CONTEXT: i64 = 50_000; + +/// One delegate's run of uncached calls. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Streak { + pub count: u32, + pub cost: f64, + pub context: i64, +} + +/// The pure trip condition, for one session. +#[derive(Debug)] +pub struct Detector { + trip_steps: u32, + min_context: i64, + streak: Streak, + tripped: bool, +} + +impl Detector { + pub fn new(trip_steps: u32, min_context: i64) -> Self { + Self { + trip_steps: trip_steps.max(1), + min_context, + streak: Streak::default(), + tripped: false, + } + } + + /// Record one model call. `context` is all prompt tokens, cache reads included + /// (goose's `input_tokens`). True exactly once, on the call that trips. + pub fn step(&mut self, context: i64, cache_read: i64, cost: f64) -> bool { + if self.tripped { + return false; + } + if cache_read > 0 { + self.streak = Streak::default(); + return false; + } + if context < self.min_context { + return false; + } + self.streak.count += 1; + self.streak.cost += cost; + self.streak.context = context; + if self.streak.count < self.trip_steps { + return false; + } + self.tripped = true; + true + } + + pub fn streak(&self) -> &Streak { + &self.streak + } +} + +/// Models that have reported a cache read in this process. +fn models_with_cache() -> &'static Mutex> { + static SEEN: OnceLock>> = OnceLock::new(); + SEEN.get_or_init(|| Mutex::new(HashSet::new())) +} + +fn is_gemini(model: &str) -> bool { + model + .rsplit('/') + .next() + .is_some_and(|m| m.to_ascii_lowercase().starts_with("gemini")) +} + +fn env_number(key: &str) -> Option { + std::env::var(key).ok().and_then(|v| v.trim().parse().ok()) +} + +/// What the delegate's event loop should do after an event. +#[derive(Debug, PartialEq, Eq)] +pub enum Verdict { + Continue, + /// Cancel the delegate now and fail it with [`Breaker::stop_message`]. + Stop, +} + +/// Per-delegate observer. Feed it every event of the delegate's stream. +#[derive(Debug)] +pub struct Breaker { + session_id: String, + detector: Option, + model: String, + /// The current step (since the last usage) asked for a tool other than final output. + step_wants_tools: bool, + tripped: bool, + stopped: bool, +} + +impl Breaker { + pub fn from_env(session_id: &str) -> Self { + let off = std::env::var("GOOSE_CACHE_MISS_BREAKER") + .map(|v| matches!(v.trim(), "off" | "0" | "false")) + .unwrap_or(false); + let detector = (!off).then(|| { + Detector::new( + env_number("GOOSE_CACHE_MISS_BREAKER_STEPS").unwrap_or(TRIP_STEPS), + env_number("GOOSE_CACHE_MISS_BREAKER_MIN_CONTEXT").unwrap_or(MIN_CONTEXT), + ) + }); + Self::with_detector(session_id, detector) + } + + pub fn with_detector(session_id: &str, detector: Option) -> Self { + Self { + session_id: session_id.to_string(), + detector, + model: String::new(), + step_wants_tools: false, + tripped: false, + stopped: false, + } + } + + pub fn observe(&mut self, event: &AgentEvent) -> Verdict { + match event { + AgentEvent::Usage(usage) => self.observe_usage(usage), + AgentEvent::Message(message) => self.observe_message(message), + _ => Verdict::Continue, + } + } + + fn observe_usage(&mut self, usage: &ProviderUsage) -> Verdict { + // Providers report usage after (Gemini) or before a step's messages; a step's + // tool requests seen before its usage belong to it. + let step_wants_tools = std::mem::take(&mut self.step_wants_tools); + let Some(detector) = self.detector.as_mut() else { + return Verdict::Continue; + }; + if !is_gemini(&usage.model) { + return Verdict::Continue; + } + let read = i64::from(usage.usage.cache_read_input_tokens.unwrap_or(0)); + let context = i64::from(usage.usage.input_tokens.unwrap_or(0)); + { + let mut seen = models_with_cache() + .lock() + .unwrap_or_else(|e| e.into_inner()); + if read > 0 { + seen.insert(usage.model.clone()); + } else if !seen.contains(&usage.model) { + // A model that has never reported a cache hit here may just not report cache. + return Verdict::Continue; + } + } + if detector.step(context, read, usage.cost.unwrap_or(0.0)) { + self.tripped = true; + self.model = usage.model.clone(); + let s = detector.streak(); + tracing::warn!( + session_id = %self.session_id, + model = %self.model, + "cache-miss-breaker: tripped: {} consecutive uncached calls at ~{}K context, ${:.2}", + s.count, + s.context / 1000, + s.cost + ); + if step_wants_tools { + return self.stop(); + } + } + Verdict::Continue + } + + fn stop(&mut self) -> Verdict { + self.stopped = true; + tracing::warn!(session_id = %self.session_id, "cache-miss-breaker: stopping delegate"); + Verdict::Stop + } + + /// The trip step's own response decides: more tools means stop before running + /// them; a final answer (text, or the final-output tool) is let through. + /// Whichever of the step's usage and its tool request comes second stops it. + fn observe_message(&mut self, message: &Message) -> Verdict { + if self.stopped || message.role != Role::Assistant { + return Verdict::Continue; + } + let wants_more = message.content.iter().any(|c| match c { + MessageContent::ToolRequest(req) => req + .tool_call + .as_ref() + .map_or(true, |call| call.name != FINAL_OUTPUT_TOOL_NAME), + _ => false, + }); + if !wants_more { + return Verdict::Continue; + } + if !self.tripped { + self.step_wants_tools = true; + return Verdict::Continue; + } + self.stop() + } + + pub fn stopped(&self) -> bool { + self.stopped + } + + /// The failure the lead sees. `last_response` is the delegate's last assistant text. + pub fn stop_message(&self, last_response: Option<&str>) -> String { + let s = self + .detector + .as_ref() + .map(|d| d.streak().clone()) + .unwrap_or_default(); + stop_message(&self.session_id, &self.model, &s, last_response) + } +} + +pub fn stop_message( + session_id: &str, + model: &str, + streak: &Streak, + last_response: Option<&str>, +) -> String { + let mut lines = vec![ + format!( + "STOPPED by the cache-miss breaker: delegate {session_id} ({model}) made {} consecutive model calls with no prompt-cache hits at ~{}K context (${:.2} for those calls).", + streak.count, + streak.context / 1000, + streak.cost + ), + "This is almost certainly a Vertex-side fault that sticks to one session (workstation-ke9f), not something wrong with the task. Its work is UNFINISHED; check its working directory for partial edits or commits before continuing.".to_string(), + "Delegate it again ONCE as a NEW delegate (do not resume this one): the same instructions plus what it already did, with \"re-dispatch #1 after cache-miss breaker\" in them. If that delegate is stopped too, do not dispatch a third time: report it.".to_string(), + ]; + if let Some(text) = last_response.map(str::trim).filter(|t| !t.is_empty()) { + lines.push("--- its last output ---".to_string()); + lines.push(text.to_string()); + } + lines.join("\n") +} + +/// The delegate's last non-empty assistant text, for the stop message. +pub fn last_assistant_text(messages: &[Message]) -> Option { + messages + .iter() + .rev() + .filter(|m| m.role == Role::Assistant) + .map(Message::as_concat_text) + .find(|t| !t.trim().is_empty()) +} + +/// Typed error so the foreground runner can recognise a breaker stop. +#[derive(Debug)] +pub struct Stopped(pub String); + +impl std::fmt::Display for Stopped { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for Stopped {} + +#[cfg(test)] +mod tests { + use super::*; + use goose_providers::conversation::token_usage::Usage; + + fn usage(model: &str, input: i32, read: i32) -> AgentEvent { + let mut provider_usage = ProviderUsage::new( + model.to_string(), + Usage { + input_tokens: Some(input), + output_tokens: Some(100), + total_tokens: Some(input + 100), + cache_read_input_tokens: Some(read), + cache_write_input_tokens: None, + }, + ); + provider_usage.cost = Some(0.05); + AgentEvent::Usage(provider_usage) + } + + fn tool_call(name: &str) -> AgentEvent { + AgentEvent::Message(Message::assistant().with_tool_request( + "call-1", + Ok(rmcp::model::CallToolRequestParams::new(name.to_string())), + )) + } + + #[test] + fn trips_on_the_tenth_consecutive_uncached_large_call() { + let mut d = Detector::new(TRIP_STEPS, MIN_CONTEXT); + for _ in 0..9 { + assert!(!d.step(60_000, 0, 0.1)); + } + assert!(d.step(60_000, 0, 0.1)); + assert_eq!(d.streak().count, 10); + assert!((d.streak().cost - 1.0).abs() < 1e-9); + assert!(!d.step(60_000, 0, 0.1), "trips only once"); + } + + #[test] + fn a_cache_read_resets_and_small_calls_neither_count_nor_reset() { + let mut d = Detector::new(TRIP_STEPS, MIN_CONTEXT); + for _ in 0..9 { + d.step(60_000, 0, 0.0); + } + assert!(!d.step(60_000, 1, 0.0), "a hit resets"); + assert_eq!(d.streak().count, 0); + for _ in 0..9 { + d.step(60_000, 0, 0.0); + } + assert!(!d.step(49_999, 0, 0.0), "below the floor does not count"); + assert_eq!(d.streak().count, 9, "and does not reset"); + assert!(d.step(50_000, 0, 0.0)); + } + + #[test] + fn breaker_stops_at_the_trip_steps_next_tool_call() { + let model = "gemini-test-trips"; + let mut b = Breaker::with_detector("child", Some(Detector::new(3, 1000))); + // The process must have seen this model hit the cache. + assert_eq!(b.observe(&usage(model, 2000, 1500)), Verdict::Continue); + // Usage reported before the step's message: the trip waits for its tool request. + for _ in 0..3 { + assert_eq!(b.observe(&usage(model, 2000, 0)), Verdict::Continue); + } + assert_eq!(b.observe(&tool_call("developer__shell")), Verdict::Stop); + assert!(b.stopped()); + assert_eq!(b.observe(&tool_call("developer__shell")), Verdict::Continue); + let msg = b.stop_message(Some("edited a.rs")); + assert!(msg.contains("STOPPED by the cache-miss breaker"), "{msg}"); + assert!(msg.contains("3 consecutive model calls"), "{msg}"); + assert!( + msg.contains("re-dispatch #1 after cache-miss breaker"), + "{msg}" + ); + assert!(msg.ends_with("edited a.rs"), "{msg}"); + } + + #[test] + fn breaker_stops_when_usage_follows_the_tool_request() { + // Gemini streams the step's message first and its usage last. + let model = "gemini-test-usage-last"; + let mut b = Breaker::with_detector("child", Some(Detector::new(3, 1000))); + b.observe(&usage(model, 2000, 1500)); + for _ in 0..2 { + assert_eq!(b.observe(&tool_call("developer__shell")), Verdict::Continue); + assert_eq!(b.observe(&usage(model, 2000, 0)), Verdict::Continue); + } + assert_eq!(b.observe(&tool_call("developer__shell")), Verdict::Continue); + assert_eq!(b.observe(&usage(model, 2000, 0)), Verdict::Stop); + } + + #[test] + fn breaker_lets_a_final_answer_through() { + let model = "gemini-test-final"; + let mut b = Breaker::with_detector("child", Some(Detector::new(1, 1000))); + b.observe(&usage(model, 2000, 1500)); + b.observe(&usage(model, 2000, 0)); + assert_eq!( + b.observe(&tool_call(FINAL_OUTPUT_TOOL_NAME)), + Verdict::Continue + ); + assert_eq!( + b.observe(&AgentEvent::Message(Message::assistant().with_text("done"))), + Verdict::Continue + ); + assert!(!b.stopped()); + } + + #[test] + fn breaker_ignores_non_gemini_and_models_never_seen_caching() { + let mut b = Breaker::with_detector("child", Some(Detector::new(1, 1000))); + b.observe(&usage("claude-opus-5-5", 2000, 0)); + assert_eq!(b.observe(&tool_call("developer__shell")), Verdict::Continue); + b.observe(&usage("gemini-test-never-cached", 2000, 0)); + assert_eq!(b.observe(&tool_call("developer__shell")), Verdict::Continue); + let mut off = Breaker::with_detector("child", None); + off.observe(&usage("gemini-test-trips", 2000, 0)); + assert_eq!( + off.observe(&tool_call("developer__shell")), + Verdict::Continue + ); + } +} diff --git a/crates/goose/src/agents/mod.rs b/crates/goose/src/agents/mod.rs index 99815553342f..dbbe9299397c 100644 --- a/crates/goose/src/agents/mod.rs +++ b/crates/goose/src/agents/mod.rs @@ -1,5 +1,6 @@ -// Modified by Jonathan Mohrbacher, 2026: self-compaction module; turn-error module; export deliver_subdirectory_hints and deliver_subdirectory_hints_recording. +// Modified by Jonathan Mohrbacher, 2026: self-compaction module; turn-error module; export deliver_subdirectory_hints and deliver_subdirectory_hints_recording; cache-miss breaker module. mod agent; +pub mod cache_miss_breaker; pub mod container; pub mod execute_commands; pub mod extension; diff --git a/crates/goose/src/agents/subagent_handler.rs b/crates/goose/src/agents/subagent_handler.rs index 8192ca778717..3cfd8961ae9b 100644 --- a/crates/goose/src/agents/subagent_handler.rs +++ b/crates/goose/src/agents/subagent_handler.rs @@ -1,6 +1,7 @@ -// Modified by Jonathan Mohrbacher, 2026: subagent policy: with GOOSE_SUBAGENT_DEFAULT_RECIPE set, an extension that fails to start fails the delegate. +// Modified by Jonathan Mohrbacher, 2026: subagent policy: with GOOSE_SUBAGENT_DEFAULT_RECIPE set, an extension that fails to start fails the delegate; cache-miss breaker stops a Gemini delegate whose prompt cache stopped hitting. use crate::{ agents::{ + cache_miss_breaker, final_output_tool::FinalOutputTool, state_machine::{trailing_error, MAX_TURNS_MESSAGE}, subagent_task_config::TaskConfig, @@ -245,11 +246,18 @@ impl ForegroundSubagentRunner { self.use_login_shell_path, ) .await?; + // A child token, so the breaker can stop this delegate without touching its parent. + let cancel = cancel.child_token(); + let mut breaker = cache_miss_breaker::Breaker::from_env(&subagent.id); let mut events = agent - .stream_state_machine_session(session_config, cancel) + .stream_state_machine_session(session_config, cancel.clone()) .await?; while let Some(event) = events.next().await { - event?; + if breaker.observe(&event?) == cache_miss_breaker::Verdict::Stop { + cancel.cancel(); + drain_after_stop(&mut events).await; + return Err(cache_miss_breaker::Stopped(breaker.stop_message(None)).into()); + } } Ok(()) } @@ -267,6 +275,10 @@ impl ForegroundSubagentRunner { return SubagentOutcome::Completed(output); } if let Err(error) = run_result { + if error.is::() { + let last = messages.and_then(|m| cache_miss_breaker::last_assistant_text(m)); + return SubagentOutcome::Failed(with_last_output(error.to_string(), last)); + } return SubagentOutcome::Failed(error.to_string()); } if let Some(error) = subagent.conversation.as_ref().and_then(trailing_error) { @@ -432,6 +444,11 @@ fn get_agent_messages(params: SubagentRunParams) -> AgentMessagesFuture { retry_config: recipe.retry, }; + // A child token, so the breaker can stop this delegate without touching its parent. + let cancel = cancellation_token + .map(|token| token.child_token()) + .unwrap_or_default(); + let mut breaker = cache_miss_breaker::Breaker::from_env(&session_id); let mut stream = crate::session_context::with_session_id(Some(session_id.to_string()), async { agent @@ -439,7 +456,7 @@ fn get_agent_messages(params: SubagentRunParams) -> AgentMessagesFuture { user_message, session_config, crate::agents::state_machine::enabled(), - cancellation_token, + Some(cancel.clone()), ) .await }) @@ -447,6 +464,14 @@ fn get_agent_messages(params: SubagentRunParams) -> AgentMessagesFuture { .map_err(|e| anyhow!("Failed to get reply from agent: {}", e))?; while let Some(message_result) = stream.next().await { + if let Ok(event) = &message_result { + if breaker.observe(event) == cache_miss_breaker::Verdict::Stop { + cancel.cancel(); + drain_after_stop(&mut stream).await; + let last = cache_miss_breaker::last_assistant_text(conversation.messages()); + return Err(anyhow!(breaker.stop_message(last.as_deref()))); + } + } match message_result { Ok(AgentEvent::Message(msg)) => { if let Some(ref callback) = on_message { @@ -485,6 +510,28 @@ fn get_agent_messages(params: SubagentRunParams) -> AgentMessagesFuture { }) } +/// Let a cancelled delegate's stream wind down so its session is saved cleanly, but +/// never wait long: a stopped delegate must not hold its parent's tool call. +async fn drain_after_stop(stream: &mut S) +where + S: futures::Stream + Unpin, +{ + let drain = async { while stream.next().await.is_some() {} }; + if tokio::time::timeout(std::time::Duration::from_secs(30), drain) + .await + .is_err() + { + debug!("cache-miss-breaker: delegate stream did not end within 30s of cancel"); + } +} + +fn with_last_output(message: String, last: Option) -> String { + match last.map(|t| t.trim().to_string()).filter(|t| !t.is_empty()) { + Some(text) => format!("{message}\n--- its last output ---\n{text}"), + None => message, + } +} + async fn build_subagent_prompt( agent: &Agent, max_turns: usize, @@ -787,4 +834,126 @@ mod tests { } } } + + /// Replays a stuck delegate: every call after the first comes back at 60K + /// context with no cache read, and every response asks for another tool. + #[derive(Debug)] + struct UncachedGeminiProvider { + calls: Arc, + } + + #[async_trait::async_trait] + impl crate::providers::base::Provider for UncachedGeminiProvider { + fn get_name(&self) -> &str { + "gcp_vertex_ai" + } + + async fn stream( + &self, + _model_config: &goose_providers::model::ModelConfig, + _system: &str, + _messages: &[Message], + _tools: &[rmcp::model::Tool], + ) -> std::result::Result< + crate::providers::base::MessageStream, + goose_providers::errors::ProviderError, + > { + let n = self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let read = if n == 0 { 40_000 } else { 0 }; + let message = Message::assistant() + .with_text(format!("step {n}")) + .with_tool_request( + format!("call-{n}"), + Ok(CallToolRequestParams::new("nosuch__tool".to_string())), + ); + let mut usage = goose_providers::conversation::token_usage::Usage::new( + Some(60_000), + Some(10), + None, + ); + usage.cache_read_input_tokens = Some(read); + let usage = goose_providers::conversation::token_usage::ProviderUsage::new( + "gemini-test-replay".to_string(), + usage, + ); + Ok(Box::pin(futures::stream::iter(vec![ + Ok((Some(message), None)), + Ok((None, Some(usage))), + ]))) + } + } + + #[tokio::test] + #[serial] + async fn cache_miss_breaker_stops_a_stuck_gemini_delegate_and_tells_the_lead() { + let _env = env_lock::lock_env([ + ("GOOSE_CACHE_MISS_BREAKER", None::<&str>), + ("GOOSE_CACHE_MISS_BREAKER_STEPS", Some("3")), + ("GOOSE_CACHE_MISS_BREAKER_MIN_CONTEXT", None), + ("GOOSE_SUBAGENT_DEFAULT_RECIPE", None), + ]); + let temp_dir = tempfile::TempDir::new().unwrap(); + let session_manager = Arc::new(SessionManager::new(temp_dir.path().to_path_buf())); + let session = session_manager + .create_session( + temp_dir.path().to_path_buf(), + "stuck-child".to_string(), + SessionType::SubAgent, + crate::config::GooseMode::Auto, + ) + .await + .unwrap(); + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let provider = Arc::new(UncachedGeminiProvider { + calls: calls.clone(), + }); + let parent_cancel = CancellationToken::new(); + let params = SubagentRunParams { + config: AgentConfig::new( + session_manager.clone(), + PermissionManager::instance(), + None, + crate::config::GooseMode::Auto, + true, + GoosePlatform::GooseCli, + ), + recipe: Recipe::builder() + .version("1.0.0") + .title("T") + .description("T") + .instructions("work forever") + .build() + .unwrap(), + task_config: TaskConfig::new( + provider, + goose_providers::model::ModelConfig::new("gemini-test-replay"), + &session.id, + temp_dir.path(), + vec![], + ) + .with_max_turns(Some(50)), + return_last_only: true, + session_id: session.id.clone(), + cancellation_token: Some(parent_cancel.clone()), + on_message: None, + notification_tx: None, + }; + + let err = run_subagent_task(params).await.unwrap_err().to_string(); + + assert!(err.contains("STOPPED by the cache-miss breaker"), "{err}"); + assert!(err.contains("3 consecutive model calls"), "{err}"); + assert!(err.contains("~60K context"), "{err}"); + assert!( + err.contains("re-dispatch #1 after cache-miss breaker"), + "{err}" + ); + assert!(err.contains("--- its last output ---\nstep 3"), "{err}"); + // One seeding call with a cache hit, then exactly three uncached ones. + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 4); + assert!( + !parent_cancel.is_cancelled(), + "the parent's token is untouched" + ); + } } From 15d197d05a11052f399058fefc8204931d8a5f18 Mon Sep 17 00:00:00 2001 From: Jonathan Mohrbacher Date: Fri, 20 Nov 2026 11:47:51 -0500 Subject: [PATCH 2/2] cache-miss breaker: detect usage order, defer the state-machine stop to tool results, keep a delivered final output, re-arm on a hit --- crates/goose/src/agents/cache_miss_breaker.rs | 234 ++++++++++++++---- crates/goose/src/agents/subagent_handler.rs | 7 +- 2 files changed, 195 insertions(+), 46 deletions(-) diff --git a/crates/goose/src/agents/cache_miss_breaker.rs b/crates/goose/src/agents/cache_miss_breaker.rs index c24177badf2b..c7e5d17693a5 100644 --- a/crates/goose/src/agents/cache_miss_breaker.rs +++ b/crates/goose/src/agents/cache_miss_breaker.rs @@ -11,7 +11,10 @@ //! A call with any cache read resets the count; a smaller call neither counts nor //! resets. At `trip_steps` in a row the delegate is stopped, but only for a //! Gemini model that has reported a cache hit in this process before (a model -//! that never reports cache reads would otherwise always trip). +//! that never reports cache reads would otherwise always trip). Only delegates +//! feed that set, and it starts empty at each goose-serve start, so a delegate +//! stuck from its first call is counted only from the first hit any Gemini +//! delegate in the process reports (opencode seeds it from every session). //! //! It is a step observer over the delegate's `AgentEvent` stream, so it needs //! nothing from the agent loop beyond `AgentEvent::Usage` (one per provider @@ -63,11 +66,14 @@ impl Detector { /// Record one model call. `context` is all prompt tokens, cache reads included /// (goose's `input_tokens`). True exactly once, on the call that trips. pub fn step(&mut self, context: i64, cache_read: i64, cost: f64) -> bool { - if self.tripped { - return false; - } if cache_read > 0 { + // A hit re-arms it: a delegate that tripped on its final answer and kept + // going (it was never stopped) gets counted afresh. self.streak = Streak::default(); + self.tripped = false; + return false; + } + if self.tripped { return false; } if context < self.min_context { @@ -113,16 +119,39 @@ pub enum Verdict { Stop, } +/// Which a provider reports first within one model call. Gemini (google format) +/// streams the message parts and then the usage; OpenAI-style providers send the +/// usage with or before the message, so agent.rs yields it first. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Order { + MessageFirst, + UsageFirst, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum State { + Watching, + /// Tripped; the trip step's response has not asked for more tools (yet). + Tripped, + /// Tripped on a step that asked for tools; stop once their results are in. + AwaitingToolResults, + Stopped, +} + /// Per-delegate observer. Feed it every event of the delegate's stream. #[derive(Debug)] pub struct Breaker { session_id: String, detector: Option, model: String, - /// The current step (since the last usage) asked for a tool other than final output. + order: Option, + /// Message-first only: the current step asked for a tool other than final output. step_wants_tools: bool, - tripped: bool, - stopped: bool, + /// Wait for the trip step's tool results before stopping (the state machine + /// runs a step's tools concurrently with reporting its usage; the legacy loop + /// has already finished them by the time it yields the usage). + defer_to_tool_results: bool, + state: State, } impl Breaker { @@ -144,27 +173,46 @@ impl Breaker { session_id: session_id.to_string(), detector, model: String::new(), + order: None, step_wants_tools: false, - tripped: false, - stopped: false, + defer_to_tool_results: false, + state: State::Watching, } } + /// For the state-machine loop: let the trip step's tools finish first. + pub fn deferring_to_tool_results(mut self) -> Self { + self.defer_to_tool_results = true; + self + } + pub fn observe(&mut self, event: &AgentEvent) -> Verdict { + if self.state == State::Stopped || self.detector.is_none() { + return Verdict::Continue; + } match event { - AgentEvent::Usage(usage) => self.observe_usage(usage), - AgentEvent::Message(message) => self.observe_message(message), + AgentEvent::Usage(usage) => { + self.order.get_or_insert(Order::UsageFirst); + self.observe_usage(usage) + } + AgentEvent::Message(message) => { + if message.role == Role::Assistant { + self.order.get_or_insert(Order::MessageFirst); + } + self.observe_message(message) + } _ => Verdict::Continue, } } fn observe_usage(&mut self, usage: &ProviderUsage) -> Verdict { - // Providers report usage after (Gemini) or before a step's messages; a step's - // tool requests seen before its usage belong to it. - let step_wants_tools = std::mem::take(&mut self.step_wants_tools); - let Some(detector) = self.detector.as_mut() else { - return Verdict::Continue; - }; + // Message-first: the tool requests seen since the last usage are this step's. + let step_wants_tools = + std::mem::take(&mut self.step_wants_tools) && self.order == Some(Order::MessageFirst); + if self.state == State::AwaitingToolResults { + // Results never showed up as a message; do not let another call through. + return self.stop(); + } if !is_gemini(&usage.model) { return Verdict::Continue; } @@ -181,36 +229,59 @@ impl Breaker { return Verdict::Continue; } } - if detector.step(context, read, usage.cost.unwrap_or(0.0)) { - self.tripped = true; - self.model = usage.model.clone(); - let s = detector.streak(); - tracing::warn!( - session_id = %self.session_id, - model = %self.model, - "cache-miss-breaker: tripped: {} consecutive uncached calls at ~{}K context, ${:.2}", - s.count, - s.context / 1000, - s.cost - ); - if step_wants_tools { - return self.stop(); - } + if read > 0 && self.state == State::Tripped { + // The cache recovered before the delegate asked for more tools. + self.state = State::Watching; + } + let Some(detector) = self.detector.as_mut() else { + return Verdict::Continue; + }; + if !detector.step(context, read, usage.cost.unwrap_or(0.0)) { + return Verdict::Continue; } - Verdict::Continue + self.model = usage.model.clone(); + let s = detector.streak(); + tracing::warn!( + session_id = %self.session_id, + model = %self.model, + "cache-miss-breaker: tripped: {} consecutive uncached calls at ~{}K context, ${:.2}", + s.count, + s.context / 1000, + s.cost + ); + if !step_wants_tools { + self.state = State::Tripped; + return Verdict::Continue; + } + if self.defer_to_tool_results { + self.state = State::AwaitingToolResults; + return Verdict::Continue; + } + self.stop() } fn stop(&mut self) -> Verdict { - self.stopped = true; + self.state = State::Stopped; tracing::warn!(session_id = %self.session_id, "cache-miss-breaker: stopping delegate"); Verdict::Stop } - /// The trip step's own response decides: more tools means stop before running - /// them; a final answer (text, or the final-output tool) is let through. - /// Whichever of the step's usage and its tool request comes second stops it. + /// The trip step's own response decides: a request for more tools stops the + /// delegate before its next model call; a final answer (text, or the + /// final-output tool) is let through. fn observe_message(&mut self, message: &Message) -> Verdict { - if self.stopped || message.role != Role::Assistant { + if self.state == State::AwaitingToolResults { + let has_results = message + .content + .iter() + .any(|c| matches!(c, MessageContent::ToolResponse(_))); + return if has_results { + self.stop() + } else { + Verdict::Continue + }; + } + if message.role != Role::Assistant { return Verdict::Continue; } let wants_more = message.content.iter().any(|c| match c { @@ -223,15 +294,21 @@ impl Breaker { if !wants_more { return Verdict::Continue; } - if !self.tripped { - self.step_wants_tools = true; - return Verdict::Continue; + match self.state { + State::Tripped if self.defer_to_tool_results => { + self.state = State::AwaitingToolResults; + Verdict::Continue + } + State::Tripped => self.stop(), + _ => { + self.step_wants_tools = true; + Verdict::Continue + } } - self.stop() } pub fn stopped(&self) -> bool { - self.stopped + self.state == State::Stopped } /// The failure the lead sees. `last_response` is the delegate's last assistant text. @@ -351,10 +428,13 @@ mod tests { let mut b = Breaker::with_detector("child", Some(Detector::new(3, 1000))); // The process must have seen this model hit the cache. assert_eq!(b.observe(&usage(model, 2000, 1500)), Verdict::Continue); - // Usage reported before the step's message: the trip waits for its tool request. - for _ in 0..3 { + // Usage reported before the step's message (OpenAI-style): the previous + // step's tool request must not stop the trip step, only its own does. + for _ in 0..2 { assert_eq!(b.observe(&usage(model, 2000, 0)), Verdict::Continue); + assert_eq!(b.observe(&tool_call("developer__shell")), Verdict::Continue); } + assert_eq!(b.observe(&usage(model, 2000, 0)), Verdict::Continue); assert_eq!(b.observe(&tool_call("developer__shell")), Verdict::Stop); assert!(b.stopped()); assert_eq!(b.observe(&tool_call("developer__shell")), Verdict::Continue); @@ -373,6 +453,7 @@ mod tests { // Gemini streams the step's message first and its usage last. let model = "gemini-test-usage-last"; let mut b = Breaker::with_detector("child", Some(Detector::new(3, 1000))); + b.observe(&tool_call("developer__shell")); b.observe(&usage(model, 2000, 1500)); for _ in 0..2 { assert_eq!(b.observe(&tool_call("developer__shell")), Verdict::Continue); @@ -382,6 +463,69 @@ mod tests { assert_eq!(b.observe(&usage(model, 2000, 0)), Verdict::Stop); } + #[test] + fn usage_first_trip_step_with_a_final_answer_is_let_through() { + let model = "gemini-test-usage-first-final"; + let mut b = Breaker::with_detector("child", Some(Detector::new(2, 1000))); + b.observe(&usage(model, 2000, 1500)); + b.observe(&tool_call("developer__shell")); + b.observe(&usage(model, 2000, 0)); + b.observe(&tool_call("developer__shell")); + assert_eq!(b.observe(&usage(model, 2000, 0)), Verdict::Continue); + assert_eq!( + b.observe(&AgentEvent::Message(Message::assistant().with_text("done"))), + Verdict::Continue + ); + assert!(!b.stopped()); + } + + #[test] + fn deferred_breaker_waits_for_the_trip_steps_tool_results() { + let model = "gemini-test-deferred"; + let mut b = Breaker::with_detector("child", Some(Detector::new(1, 1000))) + .deferring_to_tool_results(); + b.observe(&tool_call("developer__shell")); + b.observe(&usage(model, 2000, 1500)); + assert_eq!(b.observe(&tool_call("developer__shell")), Verdict::Continue); + assert_eq!(b.observe(&usage(model, 2000, 0)), Verdict::Continue); + let results = Message::user() + .with_tool_response("call-1", Ok(rmcp::model::CallToolResult::success(vec![]))); + assert_eq!(b.observe(&AgentEvent::Message(results)), Verdict::Stop); + } + + #[test] + fn deferred_breaker_never_lets_another_call_through() { + let model = "gemini-test-deferred-fallback"; + let mut b = Breaker::with_detector("child", Some(Detector::new(1, 1000))) + .deferring_to_tool_results(); + b.observe(&tool_call("developer__shell")); + b.observe(&usage(model, 2000, 1500)); + b.observe(&tool_call("developer__shell")); + b.observe(&usage(model, 2000, 0)); + assert_eq!(b.observe(&usage(model, 2000, 0)), Verdict::Stop); + } + + #[test] + fn a_cache_hit_after_a_text_only_trip_rearms_the_breaker() { + let model = "gemini-test-rearm"; + let mut b = Breaker::with_detector("child", Some(Detector::new(1, 1000))); + b.observe(&AgentEvent::Message( + Message::assistant().with_text("thinking"), + )); + b.observe(&usage(model, 2000, 1500)); + b.observe(&AgentEvent::Message( + Message::assistant().with_text("text only"), + )); + assert_eq!(b.observe(&usage(model, 2000, 0)), Verdict::Continue); + b.observe(&usage(model, 2000, 1500)); + assert_eq!(b.observe(&tool_call("developer__shell")), Verdict::Continue); + assert_eq!( + b.observe(&usage(model, 2000, 0)), + Verdict::Stop, + "trips again" + ); + } + #[test] fn breaker_lets_a_final_answer_through() { let model = "gemini-test-final"; diff --git a/crates/goose/src/agents/subagent_handler.rs b/crates/goose/src/agents/subagent_handler.rs index 3cfd8961ae9b..dd2d66f6db84 100644 --- a/crates/goose/src/agents/subagent_handler.rs +++ b/crates/goose/src/agents/subagent_handler.rs @@ -248,7 +248,8 @@ impl ForegroundSubagentRunner { .await?; // A child token, so the breaker can stop this delegate without touching its parent. let cancel = cancel.child_token(); - let mut breaker = cache_miss_breaker::Breaker::from_env(&subagent.id); + let mut breaker = + cache_miss_breaker::Breaker::from_env(&subagent.id).deferring_to_tool_results(); let mut events = agent .stream_state_machine_session(session_config, cancel.clone()) .await?; @@ -468,6 +469,10 @@ fn get_agent_messages(params: SubagentRunParams) -> AgentMessagesFuture { if breaker.observe(event) == cache_miss_breaker::Verdict::Stop { cancel.cancel(); drain_after_stop(&mut stream).await; + // The trip step may have delivered the final output alongside other tools. + if let Some(output) = get_final_output(&agent, has_response_schema).await { + return Ok((conversation, Some(output))); + } let last = cache_miss_breaker::last_assistant_text(conversation.messages()); return Err(anyhow!(breaker.stop_message(last.as_deref()))); }