Skip to main content

adk_core/
budget.rs

1//! Run budgets: limits on model calls, tokens, cost, wall time, tool calls and units.
2//!
3//! A [`RunBudget`] states the limits for one run. A [`BudgetTracker`] holds the
4//! shared counters for those limits. `Runner` creates one tracker per run from
5//! [`RunConfig::budget`](crate::RunConfig::budget) and stores it in
6//! [`RunConfig::budget_tracker`](crate::RunConfig::budget_tracker); because the
7//! run configuration travels with the invocation, transfer targets, workflow
8//! sub-agents and agents behind an agent tool all count against the same `Arc`.
9//!
10//! # Enforcement points
11//!
12//! | Checkpoint | Limits checked |
13//! |------------|----------------|
14//! | Before every model call ([`BudgetTracker::begin_model_call`]) | model calls, total tokens, cost, wall time; tool calls already over the limit |
15//! | Before every tool dispatch ([`BudgetTracker::begin_tool_calls`]) | tool calls, total tokens, cost, wall time |
16//! | Before every call billed in units ([`ModelCallScope::meter`](crate::ModelCallScope::meter)) | total tokens, cost, wall time; the per-unit caps of the units the call declares |
17//! | After every non-partial event ([`BudgetTracker::record_event`]) | usage the call sites did not meter |
18//!
19//! A limit is *reached* when usage equals or exceeds it; a reached limit blocks
20//! new work of that kind. Limits are checked before a call starts, so a single
21//! model call can take usage past a limit; no further call starts after that.
22//!
23//! # Usage accounting
24//!
25//! Built-in tools the provider runs itself ([`UsageMetadata::builtin_tool_uses`])
26//! count as tool calls when the model call's usage is recorded. They cannot be
27//! reserved in advance, so a model call can take the tool-call count past its
28//! limit; the next model call is then refused.
29//!
30//! Each model call is metered once, from the first non-partial response that
31//! carries usage. Partial streaming chunks never add to the totals — Gemini
32//! repeats cumulative usage on every chunk, so counting chunks would multiply
33//! the spend.
34//!
35//! When a cost cap is set and a response has no known cost, the tracker fails
36//! closed and stops the run with `cost unknown for model …`. Use
37//! [`RunBudget::allow_unpriced_models`] to count such responses as zero cost.
38//!
39//! Calls billed in units other than tokens — images, audio, characters — are metered
40//! through [`ModelCallScope::meter`](crate::ModelCallScope::meter): their cost counts
41//! against the cost limit, their tokens against the token limit, and every unit is kept
42//! in [`BudgetTracker::units`]. They are not model calls. A unit call with no known price
43//! is refused before it is sent when a cost cap applies.
44//!
45//! # Per-unit caps
46//!
47//! [`RunBudget::max_units`] caps a unit — images, frames, pages — across the run. A call
48//! billed in units declares the most it can use ([`UsageCall::with_units`](crate::UsageCall::with_units)),
49//! and the tracker holds that amount before the call starts, as it reserves a model call:
50//! a hold that would take a unit past its cap refuses the call with `budget.units`, before
51//! any request, naming the unit and the cap. The call commits what it used and returns the
52//! rest of its hold; a call that fails returns all of it. A call that declares no units is
53//! not held, and its units count once it commits.
54//!
55//! # Example
56//!
57//! ```
58//! use std::time::Duration;
59//! use adk_core::{BudgetTracker, RunBudget, RunConfig};
60//!
61//! let budget = RunBudget::new()
62//!     .max_model_calls(20)
63//!     .max_cost_usd(50.0)
64//!     .max_wall_time(Duration::from_secs(600));
65//! assert_eq!(budget.max_cost_micro_usd, Some(50_000_000));
66//!
67//! let config = RunConfig::builder().budget(budget.clone()).build();
68//! assert_eq!(config.budget, Some(budget.clone()));
69//!
70//! let tracker = BudgetTracker::new(budget);
71//! assert!(tracker.begin_tool_calls(1).is_ok());
72//! assert_eq!(tracker.usage().tool_calls, 1);
73//! ```
74
75use crate::{
76    AdkError, ErrorCategory, ErrorComponent, ErrorDetails, Event, Llm, LlmRequest, LlmResponse,
77    LlmResponseStream, Result, UsageMetadata, UsageUnit, UsageVector,
78};
79use futures::Stream;
80use std::collections::BTreeMap;
81use std::fmt;
82use std::pin::Pin;
83use std::sync::atomic::{AtomicU64, Ordering};
84use std::sync::{Arc, Mutex};
85use std::task::{Context, Poll};
86use std::time::{Duration, Instant};
87
88/// Event-level `provider_metadata` key marking an event whose model usage and
89/// tool calls are already counted by a [`BudgetTracker`].
90///
91/// Call sites that meter a model call set it on the events they emit for that
92/// call, so [`BudgetTracker::record_event`] does not count the usage twice.
93pub const BUDGET_RECORDED_KEY: &str = "adk.budget.recorded";
94
95/// Event-level `provider_metadata` key naming the exhausted limit on the event
96/// that explains why a run stopped. See [`budget_exceeded_event`].
97pub const BUDGET_LIMIT_KEY: &str = "adk.budget.limit";
98
99/// Resource limits for one run.
100///
101/// Every limit is optional; `None` leaves that resource unlimited. Build one
102/// with the chained setters and attach it with
103/// [`RunConfigBuilder::budget`](crate::RunConfigBuilder::budget) or
104/// `RunnerConfigBuilder::budget`.
105///
106/// # Example
107///
108/// ```
109/// use std::time::Duration;
110/// use adk_core::RunBudget;
111///
112/// let budget = RunBudget::new()
113///     .max_model_calls(10)
114///     .max_total_tokens(200_000)
115///     .max_cost_micro_usd(2_500_000)
116///     .max_wall_time(Duration::from_secs(120))
117///     .max_tool_calls(25);
118/// assert_eq!(budget.max_tool_calls, Some(25));
119/// assert!(!budget.allow_unpriced_models);
120/// ```
121///
122/// A budget serializes in camelCase with the wall time in milliseconds and the per-unit caps
123/// keyed by unit, so it travels in a durable run's input
124/// (`{"runLimits": {"budget": {"maxModelCalls": 10, "maxWallTimeMs": 120000, "maxUnits": {"images": 20}}}}`).
125#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
126#[serde(rename_all = "camelCase", default)]
127#[non_exhaustive]
128pub struct RunBudget {
129    /// Maximum model calls started in the run.
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub max_model_calls: Option<u64>,
132    /// Maximum input plus output tokens reported by the models.
133    #[serde(skip_serializing_if = "Option::is_none")]
134    pub max_total_tokens: Option<u64>,
135    /// Maximum cost in millionths of a US dollar.
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub max_cost_micro_usd: Option<u64>,
138    /// Maximum wall-clock time since the tracker was created.
139    #[serde(
140        rename = "maxWallTimeMs",
141        with = "optional_millis",
142        skip_serializing_if = "Option::is_none"
143    )]
144    pub max_wall_time: Option<Duration>,
145    /// Maximum tool calls dispatched in the run.
146    #[serde(skip_serializing_if = "Option::is_none")]
147    pub max_tool_calls: Option<u64>,
148    /// Count responses with no known cost as zero cost instead of stopping.
149    ///
150    /// Only consulted when [`max_cost_micro_usd`](Self::max_cost_micro_usd) is
151    /// set. The default `false` stops the run, because an unpriced model would
152    /// otherwise spend without limit under a cost cap.
153    #[serde(skip_serializing_if = "std::ops::Not::not")]
154    pub allow_unpriced_models: bool,
155    /// Maximum usage of each capped unit across the calls billed in units, such as
156    /// `{images: 20}`. A unit with no entry is unlimited. See the
157    /// [module documentation](self#per-unit-caps).
158    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
159    pub max_units: BTreeMap<UsageUnit, u64>,
160}
161
162/// `Option<Duration>` as whole milliseconds.
163mod optional_millis {
164    use std::time::Duration;
165
166    use serde::{Deserialize, Deserializer, Serializer};
167
168    pub(super) fn serialize<S: Serializer>(
169        value: &Option<Duration>,
170        serializer: S,
171    ) -> Result<S::Ok, S::Error> {
172        match value {
173            Some(duration) => {
174                serializer.serialize_u64(u64::try_from(duration.as_millis()).unwrap_or(u64::MAX))
175            }
176            None => serializer.serialize_none(),
177        }
178    }
179
180    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
181        deserializer: D,
182    ) -> Result<Option<Duration>, D::Error> {
183        Ok(Option::<u64>::deserialize(deserializer)?.map(Duration::from_millis))
184    }
185}
186
187impl RunBudget {
188    /// Creates a budget with no limits.
189    pub fn new() -> Self {
190        Self::default()
191    }
192
193    /// Limits the number of model calls.
194    pub fn max_model_calls(mut self, max: u64) -> Self {
195        self.max_model_calls = Some(max);
196        self
197    }
198
199    /// Limits the input plus output tokens reported by the models.
200    pub fn max_total_tokens(mut self, max: u64) -> Self {
201        self.max_total_tokens = Some(max);
202        self
203    }
204
205    /// Limits the cost in millionths of a US dollar.
206    pub fn max_cost_micro_usd(mut self, max: u64) -> Self {
207        self.max_cost_micro_usd = Some(max);
208        self
209    }
210
211    /// Limits the cost in US dollars, stored as micro-USD.
212    ///
213    /// Negative and non-finite values become a zero cap.
214    pub fn max_cost_usd(self, max: f64) -> Self {
215        self.max_cost_micro_usd(usd_to_micro(max))
216    }
217
218    /// Limits the wall-clock time of the run.
219    pub fn max_wall_time(mut self, max: Duration) -> Self {
220        self.max_wall_time = Some(max);
221        self
222    }
223
224    /// Limits the number of tool calls.
225    pub fn max_tool_calls(mut self, max: u64) -> Self {
226        self.max_tool_calls = Some(max);
227        self
228    }
229
230    /// Counts responses with no known cost as zero cost under a cost cap.
231    ///
232    /// Use this for local or self-hosted models that have no per-token price.
233    pub fn allow_unpriced_models(mut self) -> Self {
234        self.allow_unpriced_models = true;
235        self
236    }
237
238    /// Limits the usage of `unit` across the run's calls billed in units.
239    ///
240    /// A call that declares it would take the unit past `max` is refused with
241    /// `budget.units` before it starts.
242    ///
243    /// # Example
244    ///
245    /// ```
246    /// use adk_core::{RunBudget, UsageUnit};
247    ///
248    /// let budget = RunBudget::new().max_units(UsageUnit::Images, 20).max_units(UsageUnit::Frames, 600);
249    /// assert_eq!(budget.max_units.get(&UsageUnit::Images), Some(&20));
250    /// assert_eq!(
251    ///     serde_json::to_value(&budget).unwrap(),
252    ///     serde_json::json!({ "maxUnits": { "images": 20, "frames": 600 } })
253    /// );
254    /// ```
255    pub fn max_units(mut self, unit: UsageUnit, max: u64) -> Self {
256        self.max_units.insert(unit, max);
257        self
258    }
259
260    /// Returns `true` when no limit is set.
261    pub fn is_unlimited(&self) -> bool {
262        self.max_model_calls.is_none()
263            && self.max_total_tokens.is_none()
264            && self.max_cost_micro_usd.is_none()
265            && self.max_wall_time.is_none()
266            && self.max_tool_calls.is_none()
267            && self.max_units.is_empty()
268    }
269
270    /// The stricter of `self` and `other`: each limit is the smaller of the two, a limit
271    /// only one of them sets applies, and unpriced models count as free only when every
272    /// budget that caps cost allows it. A budget a run's input carries narrows the runner's this way, so it can
273    /// only take resources away.
274    ///
275    /// # Example
276    ///
277    /// ```
278    /// use std::time::Duration;
279    /// use adk_core::RunBudget;
280    ///
281    /// let runner = RunBudget::new().max_model_calls(50).max_wall_time(Duration::from_secs(600));
282    /// let run = RunBudget::new().max_model_calls(10).max_cost_micro_usd(500_000);
283    /// let narrowed = runner.narrowed(&run);
284    /// assert_eq!(narrowed.max_model_calls, Some(10));
285    /// assert_eq!(narrowed.max_cost_micro_usd, Some(500_000));
286    /// assert_eq!(narrowed.max_wall_time, Some(Duration::from_secs(600)));
287    /// ```
288    #[must_use]
289    pub fn narrowed(&self, other: &RunBudget) -> RunBudget {
290        fn min<T: Ord + Copy>(a: Option<T>, b: Option<T>) -> Option<T> {
291            match (a, b) {
292                (Some(a), Some(b)) => Some(a.min(b)),
293                (a, b) => a.or(b),
294            }
295        }
296        RunBudget {
297            max_model_calls: min(self.max_model_calls, other.max_model_calls),
298            max_total_tokens: min(self.max_total_tokens, other.max_total_tokens),
299            max_cost_micro_usd: min(self.max_cost_micro_usd, other.max_cost_micro_usd),
300            max_wall_time: min(self.max_wall_time, other.max_wall_time),
301            max_tool_calls: min(self.max_tool_calls, other.max_tool_calls),
302            max_units: UsageUnit::ALL
303                .into_iter()
304                .filter_map(|unit| {
305                    min(self.max_units.get(&unit).copied(), other.max_units.get(&unit).copied())
306                        .map(|max| (unit, max))
307                })
308                .collect(),
309            // The flag means something only under a cost cap, so the cap's own budget sets it.
310            allow_unpriced_models: match (
311                self.max_cost_micro_usd.is_some(),
312                other.max_cost_micro_usd.is_some(),
313            ) {
314                (true, false) => self.allow_unpriced_models,
315                (false, true) => other.allow_unpriced_models,
316                (true, true) | (false, false) => {
317                    self.allow_unpriced_models && other.allow_unpriced_models
318                }
319            },
320        }
321    }
322}
323
324/// The resource a budget check found exhausted.
325#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
326#[non_exhaustive]
327pub enum BudgetLimit {
328    /// [`RunBudget::max_model_calls`].
329    ModelCalls,
330    /// [`RunBudget::max_total_tokens`], or token usage the provider did not report.
331    TotalTokens,
332    /// [`RunBudget::max_cost_micro_usd`], or a cost no price is known for.
333    Cost,
334    /// [`RunBudget::max_wall_time`].
335    WallTime,
336    /// [`RunBudget::max_tool_calls`].
337    ToolCalls,
338    /// The unit's entry in [`RunBudget::max_units`].
339    Units(UsageUnit),
340}
341
342impl BudgetLimit {
343    /// Stable identifier used in error details and event metadata.
344    pub const fn as_str(self) -> &'static str {
345        match self {
346            Self::ModelCalls => "model_calls",
347            Self::TotalTokens => "total_tokens",
348            Self::Cost => "cost_micro_usd",
349            Self::WallTime => "wall_time_ms",
350            Self::ToolCalls => "tool_calls",
351            Self::Units(unit) => match unit {
352                UsageUnit::InputTokens => "units.inputTokens",
353                UsageUnit::OutputTokens => "units.outputTokens",
354                UsageUnit::Images => "units.images",
355                UsageUnit::AudioMillis => "units.audioMillis",
356                UsageUnit::VideoMillis => "units.videoMillis",
357                UsageUnit::Characters => "units.characters",
358                UsageUnit::Pages => "units.pages",
359                UsageUnit::Requests => "units.requests",
360                UsageUnit::Frames => "units.frames",
361            },
362        }
363    }
364}
365
366impl fmt::Display for BudgetLimit {
367    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368        f.write_str(self.as_str())
369    }
370}
371
372/// A budget violation: which limit, how much was used, and the maximum.
373///
374/// Converts into an [`AdkError`] with category
375/// [`ErrorCategory::ResourceExhausted`] and a `budget.*` code.
376#[derive(Debug, Clone, PartialEq, Eq)]
377pub struct BudgetExceeded {
378    limit: BudgetLimit,
379    used: u64,
380    max: u64,
381    code: &'static str,
382    message: String,
383}
384
385impl BudgetExceeded {
386    fn reached(limit: BudgetLimit, used: u64, max: u64) -> Self {
387        let (code, message) = match limit {
388            BudgetLimit::ModelCalls => (
389                "budget.model_calls",
390                format!("budget exhausted: {used} of {max} model calls used"),
391            ),
392            BudgetLimit::TotalTokens => {
393                ("budget.total_tokens", format!("budget exhausted: {used} of {max} tokens used"))
394            }
395            BudgetLimit::Cost => (
396                "budget.cost",
397                format!(
398                    "budget exhausted: {} of {} spent",
399                    format_micro_usd(used),
400                    format_micro_usd(max)
401                ),
402            ),
403            BudgetLimit::WallTime => (
404                "budget.wall_time",
405                format!("budget exhausted: {used}ms of {max}ms wall time elapsed"),
406            ),
407            BudgetLimit::ToolCalls => {
408                ("budget.tool_calls", format!("budget exhausted: {used} of {max} tool calls used"))
409            }
410            BudgetLimit::Units(unit) => {
411                ("budget.units", format!("budget exhausted: {used} of {max} {unit} used"))
412            }
413        };
414        Self { limit, used, max, code, message }
415    }
416
417    fn units(unit: UsageUnit, used: u64, requested: u64, max: u64) -> Self {
418        Self {
419            limit: BudgetLimit::Units(unit),
420            used,
421            max,
422            code: "budget.units",
423            message: format!(
424                "budget exhausted: the call would bring {unit} to {}, past the run's cap of \
425                 {max} {unit}, so it was not sent; raise RunBudget::max_units for {unit} or \
426                 start a new run",
427                used.saturating_add(requested)
428            ),
429        }
430    }
431
432    fn tool_batch(used: u64, requested: u64, max: u64) -> Self {
433        Self {
434            limit: BudgetLimit::ToolCalls,
435            used,
436            max,
437            code: "budget.tool_calls",
438            message: format!(
439                "budget exhausted: {requested} tool calls requested with {used} of {max} already used"
440            ),
441        }
442    }
443
444    fn unpriced(model: &str, used: u64, max: u64) -> Self {
445        Self {
446            limit: BudgetLimit::Cost,
447            used,
448            max,
449            code: "budget.cost_unknown",
450            message: format!(
451                "cost unknown for model '{model}': the budget has a cost cap of {} and no price is known for this model; set UsageMetadata::cost in the provider or opt out with RunBudget::allow_unpriced_models()",
452                format_micro_usd(max)
453            ),
454        }
455    }
456
457    fn unpriced_units(model: &str, used: u64, max: u64) -> Self {
458        Self {
459            limit: BudgetLimit::Cost,
460            used,
461            max,
462            code: "budget.cost_unknown",
463            message: format!(
464                "cost unknown for '{model}': the budget has a cost cap of {} and no per-unit price is known for this call, so it was not sent; add the price to the pricing catalog or opt out with RunBudget::allow_unpriced_models()",
465                format_micro_usd(max)
466            ),
467        }
468    }
469
470    fn untokened(model: &str, used: u64, max: u64) -> Self {
471        Self {
472            limit: BudgetLimit::TotalTokens,
473            used,
474            max,
475            code: "budget.tokens_unknown",
476            message: format!(
477                "token usage unknown for model '{model}': the provider reported no usage and the budget has a token cap of {max}"
478            ),
479        }
480    }
481
482    /// The exhausted limit.
483    pub fn limit(&self) -> BudgetLimit {
484        self.limit
485    }
486
487    /// Usage when the violation was detected, in the limit's unit.
488    pub fn used(&self) -> u64 {
489        self.used
490    }
491
492    /// The configured maximum, in the limit's unit.
493    pub fn max(&self) -> u64 {
494        self.max
495    }
496
497    /// Stable error code, for example `budget.cost` or `budget.cost_unknown`.
498    pub fn code(&self) -> &'static str {
499        self.code
500    }
501
502    /// Human-readable explanation.
503    pub fn message(&self) -> &str {
504        &self.message
505    }
506}
507
508impl fmt::Display for BudgetExceeded {
509    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510        f.write_str(&self.message)
511    }
512}
513
514impl std::error::Error for BudgetExceeded {}
515
516impl From<BudgetExceeded> for AdkError {
517    fn from(exceeded: BudgetExceeded) -> Self {
518        let mut details = ErrorDetails::default();
519        details.metadata.insert("limit".to_string(), exceeded.limit.as_str().into());
520        details.metadata.insert("used".to_string(), exceeded.used.into());
521        details.metadata.insert("max".to_string(), exceeded.max.into());
522        if let BudgetLimit::Units(unit) = exceeded.limit {
523            details.metadata.insert("unit".to_string(), unit.as_str().into());
524        }
525        AdkError::new(
526            ErrorComponent::Agent,
527            ErrorCategory::ResourceExhausted,
528            exceeded.code,
529            exceeded.message,
530        )
531        .with_details(details)
532    }
533}
534
535/// A snapshot of the usage counted by a [`BudgetTracker`].
536#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
537pub struct BudgetUsage {
538    /// Model calls started.
539    pub model_calls: u64,
540    /// Input plus output tokens reported.
541    pub total_tokens: u64,
542    /// Cost in millionths of a US dollar.
543    pub cost_micro_usd: u64,
544    /// Tool calls dispatched.
545    pub tool_calls: u64,
546    /// Wall-clock time since the tracker was created.
547    pub elapsed: Duration,
548}
549
550/// Shared, thread-safe counters for one [`RunBudget`].
551///
552/// Clone the `Arc`, never the tracker: every holder of the same `Arc` counts
553/// against the same limits. A tracker created with
554/// [`with_parent`](Self::with_parent) also counts against its parent, so a
555/// team budget nested in a run budget enforces both.
556///
557/// # Example
558///
559/// ```
560/// use std::sync::Arc;
561/// use adk_core::{BudgetLimit, BudgetTracker, RunBudget};
562///
563/// let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_model_calls(1)));
564/// let meter = tracker.begin_model_call("gemini-3.8-flash").unwrap();
565/// drop(meter);
566///
567/// let exceeded = tracker.begin_model_call("gemini-3.8-flash").unwrap_err();
568/// assert_eq!(exceeded.limit(), BudgetLimit::ModelCalls);
569/// assert_eq!(tracker.usage().model_calls, 1);
570/// ```
571#[derive(Debug)]
572pub struct BudgetTracker {
573    budget: RunBudget,
574    started_at: Instant,
575    model_calls: AtomicU64,
576    total_tokens: AtomicU64,
577    cost_micro_usd: AtomicU64,
578    tool_calls: AtomicU64,
579    units: Mutex<UnitCounts>,
580    exceeded: Mutex<Option<BudgetExceeded>>,
581    parent: Option<Arc<BudgetTracker>>,
582}
583
584/// Units counted by a [`BudgetTracker`]: what calls used, and what open calls and carved
585/// slices hold against the per-unit caps.
586#[derive(Debug, Default)]
587struct UnitCounts {
588    used: UsageVector,
589    held: UsageVector,
590}
591
592impl BudgetTracker {
593    /// Creates a tracker for `budget` with zero usage, starting the wall clock now.
594    pub fn new(budget: RunBudget) -> Self {
595        Self::resume(budget, BudgetUsage::default(), None)
596    }
597
598    /// Creates a tracker that also counts against, and is limited by, `parent`.
599    pub fn with_parent(budget: RunBudget, parent: Arc<BudgetTracker>) -> Self {
600        Self::resume(budget, BudgetUsage::default(), Some(parent))
601    }
602
603    /// Creates a tracker that continues from previously recorded usage.
604    ///
605    /// The wall clock starts `usage.elapsed` in the past, so a resumed run keeps
606    /// its elapsed time. Usage is not added to `parent`.
607    pub fn resume(
608        budget: RunBudget,
609        usage: BudgetUsage,
610        parent: Option<Arc<BudgetTracker>>,
611    ) -> Self {
612        let now = Instant::now();
613        Self {
614            budget,
615            started_at: now.checked_sub(usage.elapsed).unwrap_or(now),
616            model_calls: AtomicU64::new(usage.model_calls),
617            total_tokens: AtomicU64::new(usage.total_tokens),
618            cost_micro_usd: AtomicU64::new(usage.cost_micro_usd),
619            tool_calls: AtomicU64::new(usage.tool_calls),
620            units: Mutex::new(UnitCounts::default()),
621            exceeded: Mutex::new(None),
622            parent,
623        }
624    }
625
626    /// The limits this tracker enforces.
627    pub fn budget(&self) -> &RunBudget {
628        &self.budget
629    }
630
631    /// The parent tracker, if this tracker was created with one.
632    pub fn parent(&self) -> Option<&Arc<BudgetTracker>> {
633        self.parent.as_ref()
634    }
635
636    /// Usage counted so far by this tracker.
637    pub fn usage(&self) -> BudgetUsage {
638        BudgetUsage {
639            model_calls: self.model_calls.load(Ordering::SeqCst),
640            total_tokens: self.total_tokens.load(Ordering::SeqCst),
641            cost_micro_usd: self.cost_micro_usd.load(Ordering::SeqCst),
642            tool_calls: self.tool_calls.load(Ordering::SeqCst),
643            elapsed: self.started_at.elapsed(),
644        }
645    }
646
647    /// Usage counted by this tracker per [`UsageUnit`]: the input and output tokens of
648    /// model calls, and every unit of the calls metered through
649    /// [`ModelCallScope::meter`](crate::ModelCallScope::meter).
650    ///
651    /// A tracker created with [`resume`](Self::resume) starts with no units, so its
652    /// per-unit caps count from the resume.
653    ///
654    /// # Example
655    ///
656    /// ```
657    /// use std::sync::Arc;
658    /// use adk_core::{
659    ///     BudgetTracker, LlmResponse, RunBudget, UsageMetadata, UsageUnit, UsageVector,
660    /// };
661    ///
662    /// let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
663    /// let mut meter = tracker.begin_model_call("gemini-3.8-flash").unwrap();
664    /// let mut response = LlmResponse::default();
665    /// response.usage_metadata = Some(UsageMetadata {
666    ///     prompt_token_count: 120,
667    ///     candidates_token_count: 30,
668    ///     total_token_count: 150,
669    ///     ..Default::default()
670    /// });
671    /// meter.observe(&response);
672    /// assert_eq!(
673    ///     tracker.units(),
674    ///     UsageVector::new().with(UsageUnit::InputTokens, 120).with(UsageUnit::OutputTokens, 30)
675    /// );
676    /// ```
677    pub fn units(&self) -> UsageVector {
678        self.units.lock().unwrap_or_else(|e| e.into_inner()).used.clone()
679    }
680
681    /// The first unknown-usage violation recorded by this tracker or an ancestor.
682    ///
683    /// A response with no known cost under a cost cap, or no usage under a token
684    /// cap, cannot be read back from the counters, so it is recorded and every
685    /// later check fails with it. Limits reached by usage are recomputed at each
686    /// check instead.
687    pub fn exceeded(&self) -> Option<BudgetExceeded> {
688        let own = self.exceeded.lock().unwrap_or_else(|e| e.into_inner()).clone();
689        own.or_else(|| self.parent.as_ref().and_then(|parent| parent.exceeded()))
690    }
691
692    /// Checks that no token, cost or wall-time limit is reached.
693    ///
694    /// # Errors
695    ///
696    /// Returns the violation when a limit is reached in this tracker or an
697    /// ancestor, or when a violation was recorded earlier.
698    pub fn check(&self) -> std::result::Result<(), BudgetExceeded> {
699        self.check_chain(Strictness::Reached)
700    }
701
702    /// Reserves one model call, after checking every limit that gates it.
703    ///
704    /// The returned [`ModelCallMeter`] records the call's usage when it sees
705    /// the first non-partial response carrying usage, or when it is dropped.
706    ///
707    /// # Errors
708    ///
709    /// Returns the violation when the model-call, token, cost or wall-time
710    /// limit is reached in this tracker or an ancestor.
711    pub fn begin_model_call(
712        self: &Arc<Self>,
713        model: impl Into<String>,
714    ) -> std::result::Result<ModelCallMeter, BudgetExceeded> {
715        self.check()?;
716        // Provider-executed built-in tools are counted after the fact, so a turn can
717        // overshoot the tool-call limit; the next model call is refused instead.
718        self.check_chain(Strictness::Exceeded)?;
719        self.reserve(Counter::ModelCalls, 1)?;
720        Ok(ModelCallMeter {
721            tracker: Arc::clone(self),
722            model: model.into(),
723            fallback: None,
724            responses_seen: false,
725            settled: false,
726        })
727    }
728
729    /// Checks the limits that gate a call billed in units ([`ModelCallScope::meter`](crate::ModelCallScope::meter))
730    /// and holds the `units` it declares against the per-unit caps.
731    ///
732    /// The call is not a model call. `priced` is `false` when no price is known for the
733    /// call: a cost cap that does not
734    /// [`allow_unpriced_models`](RunBudget::allow_unpriced_models) then refuses it, before
735    /// it is sent. Settle the hold with [`record_units`](Self::record_units) or
736    /// [`release_units`](Self::release_units).
737    pub(crate) fn begin_usage(
738        &self,
739        model: &str,
740        priced: bool,
741        units: &UsageVector,
742    ) -> std::result::Result<(), BudgetExceeded> {
743        self.check()?;
744        self.check_chain(Strictness::Exceeded)?;
745        if !priced {
746            self.refuse_unpriced(model)?;
747        }
748        self.hold_units(units)
749    }
750
751    /// Holds `units` in this tracker and its ancestors, all or nothing: a unit that the hold
752    /// would take past its cap anywhere in the chain refuses the whole hold.
753    fn hold_units(&self, units: &UsageVector) -> std::result::Result<(), BudgetExceeded> {
754        if units.is_empty() {
755            return Ok(());
756        }
757        {
758            let mut counts = self.units.lock().unwrap_or_else(|e| e.into_inner());
759            for (unit, amount) in units.iter() {
760                if let Some(&max) = self.budget.max_units.get(&unit) {
761                    let used = counts.used.get(unit).saturating_add(counts.held.get(unit));
762                    if used.saturating_add(amount) > max {
763                        return Err(BudgetExceeded::units(unit, used, amount, max));
764                    }
765                }
766            }
767            counts.held.merge(units);
768        }
769        if let Some(parent) = &self.parent
770            && let Err(violation) = parent.hold_units(units)
771        {
772            self.units.lock().unwrap_or_else(|e| e.into_inner()).held.subtract(units);
773            return Err(violation);
774        }
775        Ok(())
776    }
777
778    /// Returns `held` units of a call that did not complete, in this tracker and its
779    /// ancestors.
780    pub(crate) fn release_units(&self, held: &UsageVector) {
781        if held.is_empty() {
782            return;
783        }
784        self.units.lock().unwrap_or_else(|e| e.into_inner()).held.subtract(held);
785        if let Some(parent) = &self.parent {
786            parent.release_units(held);
787        }
788    }
789
790    fn refuse_unpriced(&self, model: &str) -> std::result::Result<(), BudgetExceeded> {
791        if let Some(max) = self.budget.max_cost_micro_usd
792            && !self.budget.allow_unpriced_models
793        {
794            let used = self.cost_micro_usd.load(Ordering::SeqCst);
795            return Err(BudgetExceeded::unpriced_units(model, used, max));
796        }
797        match &self.parent {
798            Some(parent) => parent.refuse_unpriced(model),
799            None => Ok(()),
800        }
801    }
802
803    /// Counts what a call billed in units used — its cost, its tokens, and every unit — in
804    /// place of the `held` units it declared.
805    pub(crate) fn record_units(
806        &self,
807        model: &str,
808        held: &UsageVector,
809        units: &UsageVector,
810        cost: Option<u64>,
811    ) {
812        self.add(Counter::TotalTokens, units.tokens());
813        match cost {
814            Some(cost) => self.add(Counter::Cost, cost),
815            None => self.flag_unpriced(model),
816        }
817        self.settle_units(held, units);
818    }
819
820    /// Replaces `held` units with `used` ones, in this tracker and its ancestors, under one
821    /// lock per tracker so a concurrent hold never sees both or neither.
822    fn settle_units(&self, held: &UsageVector, used: &UsageVector) {
823        if held.is_empty() && used.is_empty() {
824            return;
825        }
826        {
827            let mut counts = self.units.lock().unwrap_or_else(|e| e.into_inner());
828            counts.held.subtract(held);
829            counts.used.merge(used);
830        }
831        if let Some(parent) = &self.parent {
832            parent.settle_units(held, used);
833        }
834    }
835
836    /// Reserves `count` tool calls, after checking every limit that gates them.
837    ///
838    /// The reservation is all or nothing: a batch that does not fit in the
839    /// remaining tool-call budget reserves nothing.
840    ///
841    /// # Errors
842    ///
843    /// Returns the violation when the batch does not fit, or when the token,
844    /// cost or wall-time limit is reached in this tracker or an ancestor.
845    pub fn begin_tool_calls(&self, count: u64) -> std::result::Result<(), BudgetExceeded> {
846        self.check()?;
847        if count == 0 {
848            return Ok(());
849        }
850        self.reserve(Counter::ToolCalls, count)
851    }
852
853    /// Returns `count` reserved tool calls that did not run, in this tracker and its
854    /// ancestors.
855    ///
856    /// An agent releases the calls it held for confirmation: a held call has not run, and
857    /// it is reserved again when a later run resumes it, so it counts once.
858    ///
859    /// # Example
860    ///
861    /// ```
862    /// use adk_core::{BudgetTracker, RunBudget};
863    ///
864    /// let tracker = BudgetTracker::new(RunBudget::new().max_tool_calls(1));
865    /// tracker.begin_tool_calls(1).unwrap();
866    /// tracker.release_tool_calls(1);
867    /// assert_eq!(tracker.usage().tool_calls, 0);
868    /// assert!(tracker.begin_tool_calls(1).is_ok());
869    /// ```
870    pub fn release_tool_calls(&self, count: u64) {
871        if count == 0 {
872            return;
873        }
874        let _ = self.tool_calls.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |used| {
875            Some(used.saturating_sub(count))
876        });
877        if let Some(parent) = &self.parent {
878            parent.release_tool_calls(count);
879        }
880    }
881
882    /// Tool calls left before the tool-call limit is reached, across this tracker
883    /// and its ancestors. `None` when no tracker in the chain limits tool calls.
884    ///
885    /// # Example
886    ///
887    /// ```
888    /// use adk_core::{BudgetTracker, RunBudget};
889    ///
890    /// let tracker = BudgetTracker::new(RunBudget::new().max_tool_calls(3));
891    /// tracker.begin_tool_calls(2).unwrap();
892    /// assert_eq!(tracker.tool_calls_remaining(), Some(1));
893    /// assert_eq!(BudgetTracker::new(RunBudget::new()).tool_calls_remaining(), None);
894    /// ```
895    pub fn tool_calls_remaining(&self) -> Option<u64> {
896        let own = self
897            .budget
898            .max_tool_calls
899            .map(|max| max.saturating_sub(self.tool_calls.load(Ordering::SeqCst)));
900        let parent = self.parent.as_ref().and_then(|parent| parent.tool_calls_remaining());
901        match (own, parent) {
902            (Some(own), Some(parent)) => Some(own.min(parent)),
903            (own, parent) => own.or(parent),
904        }
905    }
906
907    /// What is left of each limit across this tracker and its ancestors: for every limit
908    /// the chain sets, the smallest of `max − used`; `None` where no tracker limits it. A
909    /// unit's units held by open calls count as used. `allow_unpriced_models` is this
910    /// tracker's own.
911    ///
912    /// # Example
913    ///
914    /// ```
915    /// use std::sync::Arc;
916    /// use adk_core::{BudgetTracker, RunBudget};
917    ///
918    /// let run = Arc::new(BudgetTracker::new(RunBudget::new().max_tool_calls(10)));
919    /// let team = BudgetTracker::with_parent(RunBudget::new().max_model_calls(4), run);
920    /// team.begin_tool_calls(3).unwrap();
921    /// let left = team.remaining();
922    /// assert_eq!((left.max_tool_calls, left.max_model_calls), (Some(7), Some(4)));
923    /// assert_eq!(left.max_cost_micro_usd, None);
924    /// ```
925    pub fn remaining(&self) -> RunBudget {
926        let usage = self.usage();
927        let left = |max: Option<u64>, used: u64| max.map(|max| max.saturating_sub(used));
928        let own = RunBudget {
929            max_model_calls: left(self.budget.max_model_calls, usage.model_calls),
930            max_total_tokens: left(self.budget.max_total_tokens, usage.total_tokens),
931            max_cost_micro_usd: left(self.budget.max_cost_micro_usd, usage.cost_micro_usd),
932            max_wall_time: self.budget.max_wall_time.map(|max| max.saturating_sub(usage.elapsed)),
933            max_tool_calls: left(self.budget.max_tool_calls, usage.tool_calls),
934            allow_unpriced_models: self.budget.allow_unpriced_models,
935            max_units: {
936                let counts = self.units.lock().unwrap_or_else(|e| e.into_inner());
937                self.budget
938                    .max_units
939                    .iter()
940                    .map(|(&unit, &max)| {
941                        let used = counts.used.get(unit).saturating_add(counts.held.get(unit));
942                        (unit, max.saturating_sub(used))
943                    })
944                    .collect()
945            },
946        };
947        match &self.parent {
948            Some(parent) => {
949                let mut chain = own.narrowed(&parent.remaining());
950                chain.allow_unpriced_models = self.budget.allow_unpriced_models;
951                chain
952            }
953            None => own,
954        }
955    }
956
957    /// Carves a budget for work that spends on counters of its own — a background
958    /// sub-agent's durable run — out of what this tracker and its ancestors have left, so
959    /// the two together never spend more than the chain allows.
960    ///
961    /// | Limit | The slice |
962    /// |-------|-----------|
963    /// | Asked for and limited by the chain | The smaller of the ask and what is left |
964    /// | Asked for, not limited by the chain | The ask |
965    /// | Not asked for, limited by the chain | Half of what is left |
966    /// | Neither | Unlimited |
967    /// | Wall time | The smaller of the ask and what is left; not reserved, since it is not spent |
968    ///
969    /// Each unit of [`RunBudget::max_units`] is carved the same way. Model calls, tokens,
970    /// cost, tool calls and units of the slice that the chain limits count as used by this
971    /// tracker and its ancestors from now on, whether the work spends them or not. Unpriced models count as free in the slice only when the chain allows it under a
972    /// cost cap, or when no tracker in the chain caps cost and the ask allows it.
973    ///
974    /// # Errors
975    ///
976    /// Returns the exhausted limit when the chain has nothing left of a limit it sets, or
977    /// a violation was recorded; nothing is reserved then.
978    ///
979    /// # Example
980    ///
981    /// ```
982    /// use adk_core::{BudgetTracker, RunBudget};
983    ///
984    /// let parent = BudgetTracker::new(RunBudget::new().max_model_calls(30).max_cost_micro_usd(1_000_000));
985    /// let slice = parent.carve(&RunBudget::new().max_model_calls(10)).unwrap();
986    /// assert_eq!(slice.max_model_calls, Some(10));
987    /// assert_eq!(slice.max_cost_micro_usd, Some(500_000), "half of what is left");
988    /// assert_eq!(parent.remaining().max_model_calls, Some(20));
989    /// assert_eq!(parent.remaining().max_cost_micro_usd, Some(500_000));
990    /// ```
991    pub fn carve(&self, ask: &RunBudget) -> std::result::Result<RunBudget, BudgetExceeded> {
992        self.check()?;
993        let left = self.remaining();
994        let pick = |ask: Option<u64>, left: Option<u64>| match (ask, left) {
995            (Some(ask), Some(left)) => Some(ask.min(left)),
996            (Some(ask), None) => Some(ask),
997            (None, Some(left)) => Some(left.div_ceil(2)),
998            (None, None) => None,
999        };
1000        let capped = left.max_cost_micro_usd.is_some();
1001        let slice = RunBudget {
1002            max_model_calls: pick(ask.max_model_calls, left.max_model_calls),
1003            max_total_tokens: pick(ask.max_total_tokens, left.max_total_tokens),
1004            max_cost_micro_usd: pick(ask.max_cost_micro_usd, left.max_cost_micro_usd),
1005            max_wall_time: match (ask.max_wall_time, left.max_wall_time) {
1006                (Some(ask), Some(left)) => Some(ask.min(left)),
1007                (ask, left) => ask.or(left),
1008            },
1009            max_tool_calls: pick(ask.max_tool_calls, left.max_tool_calls),
1010            allow_unpriced_models: if capped {
1011                self.unpriced_allowed_in_chain()
1012            } else {
1013                ask.allow_unpriced_models
1014            },
1015            max_units: UsageUnit::ALL
1016                .into_iter()
1017                .filter_map(|unit| {
1018                    pick(ask.max_units.get(&unit).copied(), left.max_units.get(&unit).copied())
1019                        .map(|max| (unit, max))
1020                })
1021                .collect(),
1022        };
1023        let usage = self.usage();
1024        let exhausted = |limit: BudgetLimit, slice: Option<u64>, used: u64| {
1025            (slice == Some(0)).then(|| BudgetExceeded::reached(limit, used, used))
1026        };
1027        if let Some(violation) = exhausted(
1028            BudgetLimit::ModelCalls,
1029            slice.max_model_calls.filter(|_| left.max_model_calls.is_some()),
1030            usage.model_calls,
1031        )
1032        .or_else(|| {
1033            exhausted(
1034                BudgetLimit::TotalTokens,
1035                slice.max_total_tokens.filter(|_| left.max_total_tokens.is_some()),
1036                usage.total_tokens,
1037            )
1038        })
1039        .or_else(|| {
1040            exhausted(
1041                BudgetLimit::Cost,
1042                slice.max_cost_micro_usd.filter(|_| left.max_cost_micro_usd.is_some()),
1043                usage.cost_micro_usd,
1044            )
1045        })
1046        .or_else(|| {
1047            exhausted(
1048                BudgetLimit::ToolCalls,
1049                slice.max_tool_calls.filter(|_| left.max_tool_calls.is_some()),
1050                usage.tool_calls,
1051            )
1052        })
1053        .or_else(|| {
1054            (slice.max_wall_time == Some(Duration::ZERO)).then(|| {
1055                let elapsed = duration_ms(usage.elapsed);
1056                BudgetExceeded::reached(BudgetLimit::WallTime, elapsed, elapsed)
1057            })
1058        })
1059        .or_else(|| {
1060            left.max_units.keys().find(|unit| slice.max_units.get(unit) == Some(&0)).map(|&unit| {
1061                let used = self.units().get(unit);
1062                BudgetExceeded::reached(BudgetLimit::Units(unit), used, used)
1063            })
1064        }) {
1065            return Err(violation);
1066        }
1067        // The unit hold comes first: it is the one reservation a concurrent call can refuse.
1068        self.hold_units(
1069            &slice
1070                .max_units
1071                .iter()
1072                .filter(|(unit, _)| left.max_units.contains_key(unit))
1073                .map(|(&unit, &max)| (unit, max))
1074                .collect(),
1075        )?;
1076        let reserve = |counter: Counter, slice: Option<u64>, limited: Option<u64>| {
1077            if let (Some(amount), Some(_)) = (slice, limited) {
1078                self.add(counter, amount);
1079            }
1080        };
1081        reserve(Counter::ModelCalls, slice.max_model_calls, left.max_model_calls);
1082        reserve(Counter::TotalTokens, slice.max_total_tokens, left.max_total_tokens);
1083        reserve(Counter::Cost, slice.max_cost_micro_usd, left.max_cost_micro_usd);
1084        reserve(Counter::ToolCalls, slice.max_tool_calls, left.max_tool_calls);
1085        Ok(slice)
1086    }
1087
1088    /// Whether every tracker in the chain that caps cost counts unpriced models as free.
1089    fn unpriced_allowed_in_chain(&self) -> bool {
1090        let own = self.budget.max_cost_micro_usd.is_none() || self.budget.allow_unpriced_models;
1091        own && self.parent.as_ref().is_none_or(|parent| parent.unpriced_allowed_in_chain())
1092    }
1093
1094    /// Counts usage carried by an event that no call site metered.
1095    ///
1096    /// Partial events and events already marked with [`BUDGET_RECORDED_KEY`]
1097    /// are skipped. Otherwise the event's usage counts as one model call and its
1098    /// function calls as tool calls, and the event is marked so an outer
1099    /// tracker does not count it again. Use this where events from agents that
1100    /// call models directly — custom or remote agents — pass through.
1101    ///
1102    /// # Errors
1103    ///
1104    /// Returns the violation when a recorded violation exists or when usage now
1105    /// exceeds a limit.
1106    pub fn record_event(&self, event: &mut Event) -> std::result::Result<(), BudgetExceeded> {
1107        if event.llm_response.partial || event.provider_metadata.contains_key(BUDGET_RECORDED_KEY) {
1108            return self.check_chain(Strictness::Exceeded);
1109        }
1110        let usage = event.llm_response.usage_metadata.clone();
1111        let tool_calls = event.tool_calls().len() as u64;
1112        if usage.is_none() && tool_calls == 0 {
1113            return self.check_chain(Strictness::Exceeded);
1114        }
1115        if let Some(usage) = usage {
1116            self.add(Counter::ModelCalls, 1);
1117            let model =
1118                event.llm_response.model.clone().unwrap_or_else(|| "unattributed".to_string());
1119            self.record_usage(&model, Some(&usage));
1120        }
1121        self.add(Counter::ToolCalls, tool_calls);
1122        event.provider_metadata.insert(BUDGET_RECORDED_KEY.to_string(), "true".to_string());
1123        self.check_chain(Strictness::Exceeded)
1124    }
1125
1126    fn check_chain(&self, strictness: Strictness) -> std::result::Result<(), BudgetExceeded> {
1127        if let Some(exceeded) = self.exceeded.lock().unwrap_or_else(|e| e.into_inner()).clone() {
1128            return Err(exceeded);
1129        }
1130        if let Some(violation) = self.limit_violation(strictness) {
1131            return Err(violation);
1132        }
1133        match &self.parent {
1134            Some(parent) => parent.check_chain(strictness),
1135            None => Ok(()),
1136        }
1137    }
1138
1139    fn limit_violation(&self, strictness: Strictness) -> Option<BudgetExceeded> {
1140        let usage = self.usage();
1141        let over = |used: u64, max: u64| match strictness {
1142            Strictness::Reached => used >= max,
1143            Strictness::Exceeded => used > max,
1144        };
1145        if let Some(max) = self.budget.max_total_tokens
1146            && over(usage.total_tokens, max)
1147        {
1148            return Some(BudgetExceeded::reached(
1149                BudgetLimit::TotalTokens,
1150                usage.total_tokens,
1151                max,
1152            ));
1153        }
1154        if let Some(max) = self.budget.max_cost_micro_usd
1155            && over(usage.cost_micro_usd, max)
1156        {
1157            return Some(BudgetExceeded::reached(BudgetLimit::Cost, usage.cost_micro_usd, max));
1158        }
1159        if let Some(max) = self.budget.max_wall_time {
1160            let elapsed = duration_ms(usage.elapsed);
1161            let max = duration_ms(max);
1162            if over(elapsed, max) {
1163                return Some(BudgetExceeded::reached(BudgetLimit::WallTime, elapsed, max));
1164            }
1165        }
1166        if strictness == Strictness::Exceeded {
1167            if let Some(max) = self.budget.max_model_calls
1168                && usage.model_calls > max
1169            {
1170                return Some(BudgetExceeded::reached(
1171                    BudgetLimit::ModelCalls,
1172                    usage.model_calls,
1173                    max,
1174                ));
1175            }
1176            if let Some(max) = self.budget.max_tool_calls
1177                && usage.tool_calls > max
1178            {
1179                return Some(BudgetExceeded::reached(
1180                    BudgetLimit::ToolCalls,
1181                    usage.tool_calls,
1182                    max,
1183                ));
1184            }
1185        }
1186        None
1187    }
1188
1189    fn remember(&self, violation: BudgetExceeded) -> BudgetExceeded {
1190        let mut slot = self.exceeded.lock().unwrap_or_else(|e| e.into_inner());
1191        slot.get_or_insert(violation).clone()
1192    }
1193
1194    fn counter(&self, counter: Counter) -> &AtomicU64 {
1195        match counter {
1196            Counter::ModelCalls => &self.model_calls,
1197            Counter::ToolCalls => &self.tool_calls,
1198            Counter::TotalTokens => &self.total_tokens,
1199            Counter::Cost => &self.cost_micro_usd,
1200        }
1201    }
1202
1203    fn reserve(&self, counter: Counter, count: u64) -> std::result::Result<(), BudgetExceeded> {
1204        let max = match counter {
1205            Counter::ModelCalls => self.budget.max_model_calls,
1206            Counter::ToolCalls => self.budget.max_tool_calls,
1207            Counter::TotalTokens | Counter::Cost => None,
1208        };
1209        let atomic = self.counter(counter);
1210        let reserved = atomic.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |used| {
1211            let next = used.saturating_add(count);
1212            match max {
1213                Some(max) if next > max => None,
1214                _ => Some(next),
1215            }
1216        });
1217        if let Err(used) = reserved {
1218            let max = max.unwrap_or_default();
1219            let violation = match counter {
1220                Counter::ToolCalls if count > 1 => BudgetExceeded::tool_batch(used, count, max),
1221                Counter::ToolCalls => BudgetExceeded::reached(BudgetLimit::ToolCalls, used, max),
1222                Counter::ModelCalls | Counter::TotalTokens | Counter::Cost => {
1223                    BudgetExceeded::reached(BudgetLimit::ModelCalls, used, max)
1224                }
1225            };
1226            return Err(violation);
1227        }
1228        if let Some(parent) = &self.parent
1229            && let Err(violation) = parent.reserve(counter, count)
1230        {
1231            atomic.fetch_sub(count, Ordering::SeqCst);
1232            return Err(violation);
1233        }
1234        Ok(())
1235    }
1236
1237    fn add(&self, counter: Counter, amount: u64) {
1238        if amount == 0 {
1239            return;
1240        }
1241        let atomic = self.counter(counter);
1242        let _ = atomic.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |used| {
1243            Some(used.saturating_add(amount))
1244        });
1245        if let Some(parent) = &self.parent {
1246            parent.add(counter, amount);
1247        }
1248    }
1249
1250    /// Adds one call's usage to this tracker and its ancestors.
1251    fn record_usage(&self, model: &str, usage: Option<&UsageMetadata>) {
1252        match usage {
1253            Some(usage) => {
1254                self.add(Counter::TotalTokens, u64::try_from(usage.total_token_count).unwrap_or(0));
1255                self.add(Counter::ToolCalls, usage.builtin_tool_use_count());
1256                let count = |tokens: i32| u64::try_from(tokens).unwrap_or(0);
1257                self.settle_units(
1258                    &UsageVector::new(),
1259                    &UsageVector::new()
1260                        .with(UsageUnit::InputTokens, count(usage.prompt_token_count))
1261                        .with(UsageUnit::OutputTokens, count(usage.candidates_token_count)),
1262                );
1263                match usage.cost {
1264                    Some(cost) => self.add(Counter::Cost, usd_to_micro(cost)),
1265                    None => self.flag_unpriced(model),
1266                }
1267            }
1268            None => {
1269                self.flag_unpriced(model);
1270                self.flag_untokened(model);
1271            }
1272        }
1273    }
1274
1275    fn flag_unpriced(&self, model: &str) {
1276        if let Some(max) = self.budget.max_cost_micro_usd
1277            && !self.budget.allow_unpriced_models
1278        {
1279            let used = self.cost_micro_usd.load(Ordering::SeqCst);
1280            self.remember(BudgetExceeded::unpriced(model, used, max));
1281        }
1282        if let Some(parent) = &self.parent {
1283            parent.flag_unpriced(model);
1284        }
1285    }
1286
1287    fn flag_untokened(&self, model: &str) {
1288        if let Some(max) = self.budget.max_total_tokens {
1289            let used = self.total_tokens.load(Ordering::SeqCst);
1290            self.remember(BudgetExceeded::untokened(model, used, max));
1291        }
1292        if let Some(parent) = &self.parent {
1293            parent.flag_untokened(model);
1294        }
1295    }
1296}
1297
1298#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1299enum Strictness {
1300    /// Usage equal to the limit fails: gates new work.
1301    Reached,
1302    /// Only usage above the limit fails: audits work that already happened.
1303    Exceeded,
1304}
1305
1306#[derive(Debug, Clone, Copy)]
1307enum Counter {
1308    ModelCalls,
1309    ToolCalls,
1310    TotalTokens,
1311    Cost,
1312}
1313
1314/// Records the usage of one model call into a [`BudgetTracker`].
1315///
1316/// Feed every response of the call to [`observe`](Self::observe). The meter
1317/// records once: at the first non-partial response that carries usage, or —
1318/// when the stream ends early or carries usage only on partial chunks — when
1319/// the meter is dropped, from the last usage it saw. Created by
1320/// [`BudgetTracker::begin_model_call`].
1321#[derive(Debug)]
1322pub struct ModelCallMeter {
1323    tracker: Arc<BudgetTracker>,
1324    model: String,
1325    fallback: Option<(String, UsageMetadata)>,
1326    responses_seen: bool,
1327    settled: bool,
1328}
1329
1330impl ModelCallMeter {
1331    /// Observes one response of the call.
1332    pub fn observe(&mut self, response: &LlmResponse) {
1333        if self.settled {
1334            return;
1335        }
1336        self.responses_seen = true;
1337        let Some(usage) = &response.usage_metadata else {
1338            return;
1339        };
1340        let model = response.model.clone().unwrap_or_else(|| self.model.clone());
1341        if response.partial {
1342            self.fallback = Some((model, usage.clone()));
1343            return;
1344        }
1345        self.settled = true;
1346        self.tracker.record_usage(&model, Some(usage));
1347    }
1348
1349    /// Returns `true` once the call's usage has been recorded.
1350    pub fn is_settled(&self) -> bool {
1351        self.settled
1352    }
1353
1354    /// Records the call now, from the best usage observed so far.
1355    pub fn finish(mut self) {
1356        self.settle();
1357    }
1358
1359    fn settle(&mut self) {
1360        if self.settled {
1361            return;
1362        }
1363        self.settled = true;
1364        if !self.responses_seen {
1365            return;
1366        }
1367        match self.fallback.take() {
1368            Some((model, usage)) => self.tracker.record_usage(&model, Some(&usage)),
1369            None => self.tracker.record_usage(&self.model, None),
1370        }
1371    }
1372}
1373
1374impl Drop for ModelCallMeter {
1375    fn drop(&mut self) {
1376        self.settle();
1377    }
1378}
1379
1380/// Wraps a model response stream so that `meter` observes every response and
1381/// records the call when the stream ends or is dropped.
1382pub fn meter_stream(stream: LlmResponseStream, meter: ModelCallMeter) -> LlmResponseStream {
1383    Box::pin(MeteredStream { inner: stream, meter: Some(meter) })
1384}
1385
1386struct MeteredStream {
1387    inner: LlmResponseStream,
1388    meter: Option<ModelCallMeter>,
1389}
1390
1391impl Stream for MeteredStream {
1392    type Item = Result<LlmResponse>;
1393
1394    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1395        let item = self.inner.as_mut().poll_next(cx);
1396        match &item {
1397            Poll::Ready(Some(Ok(response))) => {
1398                if let Some(meter) = self.meter.as_mut() {
1399                    meter.observe(response);
1400                }
1401            }
1402            Poll::Ready(None) => {
1403                self.meter.take();
1404            }
1405            Poll::Ready(Some(Err(_))) | Poll::Pending => {}
1406        }
1407        item
1408    }
1409}
1410
1411/// Calls `model` under `tracker`, when there is one.
1412///
1413/// Reserves the call before it starts and meters the returned stream. Agents
1414/// that call models directly use this so their calls count against the run
1415/// budget.
1416///
1417/// # Errors
1418///
1419/// Returns a [`ErrorCategory::ResourceExhausted`] error when the budget does
1420/// not allow another model call, or the model's own error.
1421///
1422/// # Example
1423///
1424/// ```rust,ignore
1425/// let tracker = ctx.run_config().budget_tracker.clone();
1426/// let stream = adk_core::generate_with_budget(model.as_ref(), request, false, tracker.as_ref()).await?;
1427/// ```
1428pub async fn generate_with_budget(
1429    model: &dyn Llm,
1430    request: LlmRequest,
1431    stream: bool,
1432    tracker: Option<&Arc<BudgetTracker>>,
1433) -> Result<LlmResponseStream> {
1434    let Some(tracker) = tracker else {
1435        return model.generate_content(request, stream).await;
1436    };
1437    let meter = tracker.begin_model_call(model.name())?;
1438    let responses = model.generate_content(request, stream).await?;
1439    Ok(meter_stream(responses, meter))
1440}
1441
1442/// Builds the event that explains why a run stopped on a budget.
1443///
1444/// Returns `None` unless `error` has category
1445/// [`ErrorCategory::ResourceExhausted`]. The event is non-partial and
1446/// turn-complete, carries the error code and message in
1447/// `llm_response.error_code` / `error_message`, and names the limit under
1448/// [`BUDGET_LIMIT_KEY`].
1449///
1450/// # Example
1451///
1452/// ```
1453/// use adk_core::{AdkError, BudgetTracker, RunBudget, budget_exceeded_event};
1454///
1455/// let tracker = BudgetTracker::new(RunBudget::new().max_tool_calls(0));
1456/// let error: AdkError = tracker.begin_tool_calls(1).unwrap_err().into();
1457/// let event = budget_exceeded_event("inv-1", "assistant", &error).unwrap();
1458/// assert_eq!(event.llm_response.error_code.as_deref(), Some("budget.tool_calls"));
1459/// assert_eq!(event.provider_metadata["adk.budget.limit"], "tool_calls");
1460/// ```
1461pub fn budget_exceeded_event(invocation_id: &str, author: &str, error: &AdkError) -> Option<Event> {
1462    if error.category != ErrorCategory::ResourceExhausted {
1463        return None;
1464    }
1465    let mut event = Event::new(invocation_id);
1466    event.author = author.to_string();
1467    event.llm_response.partial = false;
1468    event.llm_response.turn_complete = true;
1469    event.llm_response.finish_reason = Some(crate::FinishReason::Other);
1470    event.llm_response.error_code = Some(error.code.to_string());
1471    event.llm_response.error_message = Some(error.message.clone());
1472    if let Some(limit) = error.details.metadata.get("limit").and_then(|value| value.as_str()) {
1473        event.provider_metadata.insert(BUDGET_LIMIT_KEY.to_string(), limit.to_string());
1474    }
1475    Some(event)
1476}
1477
1478fn usd_to_micro(usd: f64) -> u64 {
1479    if !usd.is_finite() || usd <= 0.0 {
1480        return 0;
1481    }
1482    let micro = (usd * 1_000_000.0).round();
1483    if micro >= u64::MAX as f64 { u64::MAX } else { micro as u64 }
1484}
1485
1486fn duration_ms(duration: Duration) -> u64 {
1487    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
1488}
1489
1490fn format_micro_usd(micro: u64) -> String {
1491    format!("${}.{:06}", micro / 1_000_000, micro % 1_000_000)
1492}
1493
1494#[cfg(test)]
1495mod tests {
1496    use super::*;
1497    use crate::{Content, Part};
1498
1499    fn usage(total: i32, cost: Option<f64>) -> UsageMetadata {
1500        UsageMetadata {
1501            prompt_token_count: total / 2,
1502            candidates_token_count: total - total / 2,
1503            total_token_count: total,
1504            cost,
1505            ..Default::default()
1506        }
1507    }
1508
1509    fn response(partial: bool, usage: Option<UsageMetadata>) -> LlmResponse {
1510        LlmResponse {
1511            partial,
1512            usage_metadata: usage,
1513            model: Some("gemini-3.7-flash".to_string()),
1514            ..Default::default()
1515        }
1516    }
1517
1518    #[test]
1519    fn builtin_tool_uses_count_as_tool_calls_and_refuse_the_next_turn_once_over() {
1520        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_tool_calls(2)));
1521        let mut searched = usage(10, Some(0.0));
1522        searched.builtin_tool_uses = vec![crate::BuiltinToolUse::new("web_search", 2)];
1523        let mut meter = tracker.begin_model_call("m").unwrap();
1524        meter.observe(&response(false, Some(searched.clone())));
1525        drop(meter);
1526        assert_eq!(tracker.usage().tool_calls, 2);
1527        assert_eq!(tracker.tool_calls_remaining(), Some(0));
1528        // Reaching the limit still allows a model turn that answers without tools.
1529        let mut meter = tracker.begin_model_call("m").unwrap();
1530        meter.observe(&response(false, Some(searched)));
1531        drop(meter);
1532        assert_eq!(tracker.usage().tool_calls, 4);
1533        let error = tracker.begin_model_call("m").unwrap_err();
1534        assert_eq!(error.limit(), BudgetLimit::ToolCalls);
1535    }
1536
1537    #[test]
1538    fn tool_calls_remaining_takes_the_tightest_ancestor() {
1539        let parent = Arc::new(BudgetTracker::new(RunBudget::new().max_tool_calls(1)));
1540        let child = BudgetTracker::with_parent(RunBudget::new().max_tool_calls(5), parent);
1541        assert_eq!(child.tool_calls_remaining(), Some(1));
1542        child.begin_tool_calls(1).unwrap();
1543        assert_eq!(child.tool_calls_remaining(), Some(0));
1544    }
1545
1546    #[test]
1547    fn model_call_limit_blocks_the_next_call() {
1548        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_model_calls(2)));
1549        tracker.begin_model_call("m").unwrap().finish();
1550        tracker.begin_model_call("m").unwrap().finish();
1551        let error = tracker.begin_model_call("m").unwrap_err();
1552        assert_eq!(error.limit(), BudgetLimit::ModelCalls);
1553        assert_eq!(tracker.usage().model_calls, 2);
1554    }
1555
1556    #[test]
1557    fn partial_chunks_do_not_add_usage() {
1558        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
1559        let mut meter = tracker.begin_model_call("gemini-3.7-flash").unwrap();
1560        // Gemini repeats cumulative usage on every chunk.
1561        meter.observe(&response(true, Some(usage(100, Some(0.001)))));
1562        meter.observe(&response(true, Some(usage(150, Some(0.0015)))));
1563        meter.observe(&response(false, Some(usage(200, Some(0.002)))));
1564        meter.observe(&response(false, Some(usage(200, Some(0.002)))));
1565        drop(meter);
1566        let usage = tracker.usage();
1567        assert_eq!((usage.model_calls, usage.total_tokens, usage.cost_micro_usd), (1, 200, 2_000));
1568    }
1569
1570    #[test]
1571    fn a_cut_stream_records_its_last_partial_usage() {
1572        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
1573        let mut meter = tracker.begin_model_call("m").unwrap();
1574        meter.observe(&response(true, Some(usage(100, Some(0.001)))));
1575        meter.observe(&response(true, Some(usage(150, Some(0.0015)))));
1576        drop(meter);
1577        assert_eq!(tracker.usage().total_tokens, 150);
1578        assert_eq!(tracker.usage().cost_micro_usd, 1_500);
1579    }
1580
1581    #[test]
1582    fn cost_cap_stops_once_reached() {
1583        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_cost_usd(0.003)));
1584        for _ in 0..3 {
1585            let mut meter = tracker.begin_model_call("m").unwrap();
1586            meter.observe(&response(false, Some(usage(10, Some(0.001)))));
1587        }
1588        let error = tracker.begin_model_call("m").unwrap_err();
1589        assert_eq!(error.limit(), BudgetLimit::Cost);
1590        assert_eq!(error.code(), "budget.cost");
1591        assert_eq!(error.used(), 3_000);
1592        assert!(tracker.begin_tool_calls(1).is_err());
1593    }
1594
1595    #[test]
1596    fn unknown_cost_under_a_cap_fails_closed() {
1597        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_cost_usd(10.0)));
1598        let mut meter = tracker.begin_model_call("mystery-model").unwrap();
1599        meter.observe(&response(false, Some(usage(10, None))));
1600        let error = tracker.begin_model_call("mystery-model").unwrap_err();
1601        assert_eq!(error.code(), "budget.cost_unknown");
1602        assert!(error.message().contains("cost unknown for model 'gemini-3.7-flash'"));
1603
1604        let allowed = Arc::new(BudgetTracker::new(
1605            RunBudget::new().max_cost_usd(10.0).allow_unpriced_models(),
1606        ));
1607        let mut meter = allowed.begin_model_call("mystery-model").unwrap();
1608        meter.observe(&response(false, Some(usage(10, None))));
1609        drop(meter);
1610        assert!(allowed.begin_model_call("mystery-model").is_ok());
1611    }
1612
1613    #[test]
1614    fn missing_usage_under_a_token_cap_fails_closed() {
1615        let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_total_tokens(100)));
1616        let mut meter = tracker.begin_model_call("silent").unwrap();
1617        meter.observe(&response(false, None));
1618        drop(meter);
1619        assert_eq!(tracker.check().unwrap_err().code(), "budget.tokens_unknown");
1620    }
1621
1622    #[test]
1623    fn tool_batches_are_all_or_nothing() {
1624        let tracker = BudgetTracker::new(RunBudget::new().max_tool_calls(3));
1625        tracker.begin_tool_calls(2).unwrap();
1626        let error = tracker.begin_tool_calls(2).unwrap_err();
1627        assert_eq!(error.limit(), BudgetLimit::ToolCalls);
1628        assert_eq!(tracker.usage().tool_calls, 2);
1629        tracker.begin_tool_calls(1).unwrap();
1630        assert!(tracker.begin_tool_calls(1).is_err());
1631    }
1632
1633    #[test]
1634    fn wall_time_is_checked_at_every_checkpoint() {
1635        let tracker = Arc::new(BudgetTracker::resume(
1636            RunBudget::new().max_wall_time(Duration::from_millis(50)),
1637            BudgetUsage { elapsed: Duration::from_millis(60), ..Default::default() },
1638            None,
1639        ));
1640        assert_eq!(tracker.begin_model_call("m").unwrap_err().limit(), BudgetLimit::WallTime);
1641        assert_eq!(tracker.begin_tool_calls(1).unwrap_err().limit(), BudgetLimit::WallTime);
1642    }
1643
1644    #[test]
1645    fn child_trackers_count_against_their_parent() {
1646        let parent = Arc::new(BudgetTracker::new(RunBudget::new().max_model_calls(2)));
1647        let child = Arc::new(BudgetTracker::with_parent(
1648            RunBudget::new().max_model_calls(5),
1649            parent.clone(),
1650        ));
1651        child.begin_model_call("m").unwrap().finish();
1652        parent.begin_model_call("m").unwrap().finish();
1653        let error = child.begin_model_call("m").unwrap_err();
1654        assert_eq!(error.limit(), BudgetLimit::ModelCalls);
1655        // The failed parent reservation rolled the child back.
1656        assert_eq!(child.usage().model_calls, 1);
1657        assert_eq!(parent.usage().model_calls, 2);
1658    }
1659
1660    #[test]
1661    fn record_event_counts_unmetered_events_once() {
1662        let tracker = BudgetTracker::new(RunBudget::new());
1663        let mut event = Event::new("inv");
1664        event.llm_response.usage_metadata = Some(usage(40, Some(0.004)));
1665        event.llm_response.content = Some(Content {
1666            role: "model".to_string(),
1667            parts: vec![Part::FunctionCall {
1668                name: "lookup".to_string(),
1669                args: serde_json::json!({}),
1670                id: None,
1671                thought_signature: None,
1672            }],
1673        });
1674        tracker.record_event(&mut event).unwrap();
1675        tracker.record_event(&mut event).unwrap();
1676        let mut partial = Event::new("inv");
1677        partial.llm_response.partial = true;
1678        partial.llm_response.usage_metadata = Some(usage(999, Some(9.0)));
1679        tracker.record_event(&mut partial).unwrap();
1680        let usage = tracker.usage();
1681        assert_eq!(
1682            (usage.model_calls, usage.total_tokens, usage.cost_micro_usd, usage.tool_calls),
1683            (1, 40, 4_000, 1)
1684        );
1685        assert_eq!(event.provider_metadata[BUDGET_RECORDED_KEY], "true");
1686    }
1687
1688    #[test]
1689    fn violations_convert_to_resource_exhausted_errors() {
1690        let tracker = BudgetTracker::new(RunBudget::new().max_tool_calls(0));
1691        let error: AdkError = tracker.begin_tool_calls(1).unwrap_err().into();
1692        assert_eq!(error.category, ErrorCategory::ResourceExhausted);
1693        assert_eq!(error.code, "budget.tool_calls");
1694        assert!(!error.is_retryable());
1695        assert_eq!(error.details.metadata["limit"], "tool_calls");
1696        let event = budget_exceeded_event("inv", "agent", &error).unwrap();
1697        assert!(!event.llm_response.partial);
1698        assert_eq!(event.llm_response.error_message.as_deref(), Some(error.message.as_str()));
1699        assert!(budget_exceeded_event("inv", "agent", &AdkError::agent("other")).is_none());
1700    }
1701
1702    #[tokio::test]
1703    async fn metered_streams_record_on_completion() {
1704        let tracker = Arc::new(BudgetTracker::new(RunBudget::new()));
1705        let meter = tracker.begin_model_call("m").unwrap();
1706        let responses: Vec<Result<LlmResponse>> = vec![
1707            Ok(response(true, Some(usage(5, Some(0.0005))))),
1708            Ok(response(false, Some(usage(10, Some(0.001))))),
1709        ];
1710        let stream = meter_stream(Box::pin(futures::stream::iter(responses)), meter);
1711        let collected: Vec<_> = futures::StreamExt::collect(stream).await;
1712        assert_eq!(collected.len(), 2);
1713        assert_eq!(tracker.usage().total_tokens, 10);
1714        assert_eq!(tracker.usage().cost_micro_usd, 1_000);
1715    }
1716
1717    #[test]
1718    fn a_carved_slice_never_takes_the_chain_past_its_limits() {
1719        let run = Arc::new(BudgetTracker::new(RunBudget::new().max_model_calls(10)));
1720        let team = BudgetTracker::with_parent(RunBudget::new().max_tool_calls(6), Arc::clone(&run));
1721        let slice = team.carve(&RunBudget::new().max_model_calls(4).max_tool_calls(100)).unwrap();
1722        assert_eq!(slice.max_model_calls, Some(4));
1723        assert_eq!(slice.max_tool_calls, Some(6), "the team's tool limit caps the ask");
1724        // The slice counts in every tracker of the chain.
1725        assert_eq!(run.usage().model_calls, 4);
1726        assert_eq!(team.remaining().max_tool_calls, Some(0));
1727        assert_eq!(team.remaining().max_model_calls, Some(6));
1728        // Nothing of a limited resource left: the carve fails and reserves nothing.
1729        let refused = team.carve(&RunBudget::new()).unwrap_err();
1730        assert_eq!(refused.limit(), BudgetLimit::ToolCalls);
1731        assert_eq!(run.usage().model_calls, 4);
1732    }
1733
1734    #[test]
1735    fn a_slice_counts_unpriced_models_as_free_only_where_the_chain_does() {
1736        let capped = BudgetTracker::new(RunBudget::new().max_cost_micro_usd(1_000));
1737        let ask = RunBudget::new().allow_unpriced_models();
1738        assert!(!capped.carve(&ask).unwrap().allow_unpriced_models);
1739        let lenient =
1740            BudgetTracker::new(RunBudget::new().max_cost_micro_usd(1_000).allow_unpriced_models());
1741        assert!(lenient.carve(&RunBudget::new()).unwrap().allow_unpriced_models);
1742        let open = BudgetTracker::new(RunBudget::new());
1743        assert!(open.carve(&ask).unwrap().allow_unpriced_models);
1744        assert_eq!(open.carve(&RunBudget::new()).unwrap(), RunBudget::new());
1745    }
1746
1747    #[test]
1748    fn a_budget_round_trips_with_its_wall_time_in_milliseconds() {
1749        let budget =
1750            RunBudget::new().max_model_calls(3).max_wall_time(Duration::from_millis(1_500));
1751        let json = serde_json::to_value(&budget).unwrap();
1752        assert_eq!(json, serde_json::json!({ "maxModelCalls": 3, "maxWallTimeMs": 1500 }));
1753        assert_eq!(serde_json::from_value::<RunBudget>(json).unwrap(), budget);
1754        assert_eq!(
1755            serde_json::from_value::<RunBudget>(serde_json::json!({})).unwrap(),
1756            RunBudget::new()
1757        );
1758    }
1759
1760    fn images(count: u64) -> UsageVector {
1761        UsageVector::new().with(UsageUnit::Images, count)
1762    }
1763
1764    #[test]
1765    fn a_unit_hold_past_its_cap_is_refused_naming_the_unit_and_the_cap() {
1766        let tracker = BudgetTracker::new(RunBudget::new().max_units(UsageUnit::Images, 2));
1767        tracker.begin_usage("sam-3.1", true, &images(1)).unwrap();
1768        tracker.record_units("sam-3.1", &images(1), &images(1), Some(2_500));
1769        tracker.begin_usage("sam-3.1", true, &images(1)).unwrap();
1770        let refused = tracker.begin_usage("sam-3.1", true, &images(1)).unwrap_err();
1771        assert_eq!(refused.limit(), BudgetLimit::Units(UsageUnit::Images));
1772        assert_eq!((refused.used(), refused.max()), (2, 2));
1773        assert_eq!(refused.code(), "budget.units");
1774        assert!(refused.message().contains("cap of 2 images"), "{}", refused.message());
1775        let error = AdkError::from(refused);
1776        assert_eq!(error.details.metadata["limit"], "units.images");
1777        assert_eq!(error.details.metadata["unit"], "images");
1778        // The open hold counts against the cap; returning it frees the room.
1779        tracker.release_units(&images(1));
1780        assert!(tracker.begin_usage("sam-3.1", true, &images(1)).is_ok());
1781        assert_eq!(tracker.units(), images(1), "only committed units are usage");
1782    }
1783
1784    #[test]
1785    fn a_commit_replaces_the_hold_with_what_the_call_used() {
1786        let tracker = BudgetTracker::new(RunBudget::new().max_units(UsageUnit::Frames, 100));
1787        let frames = |count| UsageVector::new().with(UsageUnit::Frames, count);
1788        tracker.begin_usage("sam-3.1", true, &frames(80)).unwrap();
1789        assert_eq!(tracker.remaining().max_units[&UsageUnit::Frames], 20);
1790        tracker.record_units("sam-3.1", &frames(80), &frames(30), Some(6_000));
1791        assert_eq!(tracker.remaining().max_units[&UsageUnit::Frames], 70);
1792        assert_eq!(tracker.units(), frames(30));
1793    }
1794
1795    #[test]
1796    fn uncapped_units_and_undeclared_calls_are_never_held_back() {
1797        let tracker = BudgetTracker::new(RunBudget::new().max_units(UsageUnit::Images, 1));
1798        tracker
1799            .begin_usage("tts", true, &UsageVector::new().with(UsageUnit::Characters, 9_000))
1800            .unwrap();
1801        tracker.record_units("sam-3.1", &UsageVector::new(), &images(3), Some(0));
1802        // Undeclared usage still counts, so the next declaring call sees the cap reached.
1803        assert!(tracker.begin_usage("sam-3.1", true, &UsageVector::new()).is_ok());
1804        assert_eq!(
1805            tracker.begin_usage("sam-3.1", true, &images(1)).unwrap_err().limit(),
1806            BudgetLimit::Units(UsageUnit::Images)
1807        );
1808    }
1809
1810    #[test]
1811    fn a_child_hold_is_refused_by_its_parents_cap_and_holds_nothing() {
1812        let run = Arc::new(BudgetTracker::new(RunBudget::new().max_units(UsageUnit::Pages, 5)));
1813        let team = BudgetTracker::with_parent(
1814            RunBudget::new().max_units(UsageUnit::Pages, 10),
1815            Arc::clone(&run),
1816        );
1817        let pages = |count| UsageVector::new().with(UsageUnit::Pages, count);
1818        team.begin_usage("ocr", true, &pages(4)).unwrap();
1819        let refused = team.begin_usage("ocr", true, &pages(2)).unwrap_err();
1820        assert_eq!((refused.limit(), refused.max()), (BudgetLimit::Units(UsageUnit::Pages), 5));
1821        assert_eq!(team.remaining().max_units[&UsageUnit::Pages], 1);
1822        team.record_units("ocr", &pages(4), &pages(4), Some(0));
1823        assert_eq!((team.units(), run.units()), (pages(4), pages(4)));
1824    }
1825
1826    #[test]
1827    fn unit_caps_narrow_carve_and_round_trip() {
1828        let runner = RunBudget::new().max_units(UsageUnit::Images, 50);
1829        let run =
1830            RunBudget::new().max_units(UsageUnit::Images, 20).max_units(UsageUnit::Frames, 600);
1831        let narrowed = runner.narrowed(&run);
1832        assert_eq!(
1833            narrowed,
1834            RunBudget::new().max_units(UsageUnit::Images, 20).max_units(UsageUnit::Frames, 600)
1835        );
1836        assert!(!narrowed.is_unlimited());
1837
1838        let parent = BudgetTracker::new(narrowed.clone());
1839        let slice = parent.carve(&RunBudget::new().max_units(UsageUnit::Images, 8)).unwrap();
1840        assert_eq!(slice.max_units[&UsageUnit::Images], 8);
1841        assert_eq!(slice.max_units[&UsageUnit::Frames], 300, "half of what is left");
1842        assert_eq!(parent.remaining().max_units[&UsageUnit::Images], 12);
1843        assert_eq!(parent.units(), UsageVector::new(), "a carved slice is held, not used");
1844        let exhausted = BudgetTracker::new(RunBudget::new().max_units(UsageUnit::Images, 0));
1845        assert_eq!(
1846            exhausted.carve(&RunBudget::new()).unwrap_err().limit(),
1847            BudgetLimit::Units(UsageUnit::Images)
1848        );
1849
1850        let json = serde_json::to_value(&narrowed).unwrap();
1851        assert_eq!(json, serde_json::json!({ "maxUnits": { "images": 20, "frames": 600 } }));
1852        assert_eq!(serde_json::from_value::<RunBudget>(json).unwrap(), narrowed);
1853    }
1854}