From 9d2749fe7f3eec31ae6ba9fd3f8d61f483b39707 Mon Sep 17 00:00:00 2001 From: Matthew Busel Date: Sat, 21 Nov 2026 11:17:16 -0500 Subject: [PATCH] Add a hard dollar cap to CostAccumulator and stop the query loop when it is spent --- Cargo.lock | 19 ++++++++++++++++ Cargo.toml | 1 + crates/engine/src/loop.rs | 7 ++++++ crates/session/Cargo.toml | 1 + crates/session/src/cost.rs | 45 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 73 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 01c95d1..362c729 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1362,6 +1362,7 @@ dependencies = [ "crab-memory", "crab-utils", "image", + "llm-budget", "serde", "serde_json", "tempfile", @@ -3553,6 +3554,24 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" +[[package]] +name = "llm-budget" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc5da5b440da690a3fe3cbef4e3a7a52a3ad5f7c37b456feb3d048abf384244" +dependencies = [ + "llm-prices", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "llm-prices" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8687beff4d5ceb2b1a5fc5f242df4f2c107ca92609f47d30fab584591157d9dd" + [[package]] name = "lock_api" version = "0.4.14" diff --git a/Cargo.toml b/Cargo.toml index 44dd8fa..9e445e0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,6 +49,7 @@ supports-hyperlinks = "3" # ─── Error Handling ─── thiserror = "2" +llm-budget = { version = "0.10.0", default-features = false } anyhow = "1" # ─── Logging / Tracing ─── diff --git a/crates/engine/src/loop.rs b/crates/engine/src/loop.rs index 4ca3061..fb4641a 100644 --- a/crates/engine/src/loop.rs +++ b/crates/engine/src/loop.rs @@ -215,6 +215,13 @@ pub async fn query_loop( return Ok(()); } + if cost_tracker.budget_exhausted() { + return Err(crab_core::Error::Other(format!( + "cost budget exhausted: ${:.4} spent", + cost_tracker.total_cost_usd() + ))); + } + // Check context usage: first try upgrading to a larger-context model // variant; fall through to compaction if no upgrade is available. try_upgrade_or_compact( diff --git a/crates/session/Cargo.toml b/crates/session/Cargo.toml index 92f7f66..a66eb22 100644 --- a/crates/session/Cargo.toml +++ b/crates/session/Cargo.toml @@ -16,6 +16,7 @@ serde_json.workspace = true base64.workspace = true image.workspace = true thiserror.workspace = true +llm-budget.workspace = true tracing.workspace = true [dev-dependencies] diff --git a/crates/session/src/cost.rs b/crates/session/src/cost.rs index 45fbff8..8caa02b 100644 --- a/crates/session/src/cost.rs +++ b/crates/session/src/cost.rs @@ -1,5 +1,8 @@ use std::fmt; use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use llm_budget::budget::AtomicBudget; use serde::{Deserialize, Serialize}; @@ -219,6 +222,8 @@ pub struct CostAccumulator { pub total_cost_usd: f64, /// Number of API calls recorded. pub api_calls: u64, + /// Optional hard dollar cap, shareable with sub-agents. + budget: Option>, } impl CostAccumulator { @@ -233,6 +238,9 @@ impl CostAccumulator { self.total_cache_creation_tokens += usage.cache_creation_tokens; self.total_cost_usd += cost; self.api_calls += 1; + if let Some(budget) = &self.budget { + budget.charge_force(cost); + } } /// Record usage with a pre-calculated cost (for callers that already know the cost). @@ -243,6 +251,27 @@ impl CostAccumulator { self.total_cache_creation_tokens += usage.cache_creation_tokens; self.total_cost_usd += cost; self.api_calls += 1; + if let Some(budget) = &self.budget { + budget.charge_force(cost); + } + } + + /// Attach a hard dollar cap. Pass the same `Arc` to sub-agent + /// accumulators so the whole team draws from one budget. + #[must_use] + pub fn with_budget(mut self, budget: Arc) -> Self { + self.budget = Some(budget); + self + } + + /// The attached dollar cap, if any. + pub fn budget(&self) -> Option<&Arc> { + self.budget.as_ref() + } + + /// Whether the attached dollar cap has been reached. + pub fn budget_exhausted(&self) -> bool { + self.budget.as_ref().is_some_and(|b| b.is_exhausted()) } pub fn merge(&mut self, other: &Self) { @@ -291,6 +320,7 @@ impl CostAccumulator { total_cache_creation_tokens: summary.cache_creation_tokens, total_cost_usd: summary.total_cost_usd, api_calls: summary.api_calls, + budget: None, } } @@ -363,6 +393,21 @@ pub fn load_cost_summary(path: &Path) -> crab_core::Result> mod tests { use super::*; + #[test] + fn shared_budget_caps_parent_and_sub_agent() { + let budget = Arc::new(AtomicBudget::new(0.05).unwrap()); + let mut parent = CostAccumulator::default().with_budget(Arc::clone(&budget)); + let mut worker = CostAccumulator::default().with_budget(Arc::clone(&budget)); + let usage = TokenUsage::default(); + parent.record(&usage, 0.03); + assert!(!parent.budget_exhausted()); + worker.record(&usage, 0.03); + assert!(parent.budget_exhausted()); + assert!(worker.budget_exhausted()); + assert!((budget.spent_usd() - 0.06).abs() < 1e-9); + assert!(!CostAccumulator::default().budget_exhausted()); + } + #[test] fn default_is_zero() { let acc = CostAccumulator::default();