Skip to main content

stateknot_core/
budget.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Finite, layered execution budgets and monotonic usage accounting.
5
6use std::{collections::BTreeMap, fmt, slice};
7
8use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
9use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
10use thiserror::Error;
11
12use crate::{ByteCount, CurrencyCode, ExecutionCount, Money, Timestamp, TokenCount};
13
14/// Maximum number of independently configured layers resolved into one budget.
15pub const MAX_BUDGET_LAYERS: usize = 16;
16
17/// Maximum number of currencies tracked by one run budget.
18pub const MAX_COST_CURRENCIES: usize = 16;
19
20/// A bounded set of monetary ceilings keyed by currency.
21///
22/// Values serialize in ascending currency-code order. A missing currency is not
23/// unlimited: a charge in an unlisted currency is rejected by budget
24/// evaluation. An empty set permits no priced charge. `StateKnot` never
25/// performs implicit currency conversion.
26#[derive(Clone, Default, Eq, Hash, PartialEq)]
27pub struct CostLimits(Box<[Money]>);
28
29impl CostLimits {
30    /// Validates and constructs currency-specific cost ceilings.
31    ///
32    /// # Errors
33    ///
34    /// Returns [`CostCollectionError`] when a currency is repeated or the
35    /// currency-count ceiling is exceeded. Empty input is valid and denies all
36    /// priced charges.
37    pub fn try_new<I>(values: I) -> Result<Self, CostCollectionError>
38    where
39        I: IntoIterator<Item = Money>,
40    {
41        collect_costs(values).map(Self)
42    }
43
44    /// Returns the number of independently budgeted currencies.
45    #[must_use]
46    pub const fn len(&self) -> usize {
47        self.0.len()
48    }
49
50    /// Returns whether no priced currency is permitted.
51    #[must_use]
52    pub const fn is_empty(&self) -> bool {
53        self.0.is_empty()
54    }
55
56    /// Returns limits in ascending currency-code order.
57    pub fn iter(&self) -> slice::Iter<'_, Money> {
58        self.0.iter()
59    }
60
61    /// Returns the ceiling for one currency when configured.
62    #[must_use]
63    pub fn get(&self, currency: CurrencyCode) -> Option<Money> {
64        self.0
65            .binary_search_by_key(&currency, |money| money.currency())
66            .ok()
67            .map(|index| self.0[index])
68    }
69
70    fn most_restrictive(&self, other: &Self) -> Self {
71        let values = self
72            .iter()
73            .filter_map(|left| {
74                other.get(left.currency()).map(|right| {
75                    Money::new(left.currency(), left.micro_units().min(right.micro_units()))
76                })
77            })
78            .collect::<Vec<_>>()
79            .into_boxed_slice();
80        Self(values)
81    }
82}
83
84impl fmt::Debug for CostLimits {
85    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
86        formatter.debug_tuple("CostLimits").field(&self.0).finish()
87    }
88}
89
90impl<'a> IntoIterator for &'a CostLimits {
91    type Item = &'a Money;
92    type IntoIter = slice::Iter<'a, Money>;
93
94    fn into_iter(self) -> Self::IntoIter {
95        self.iter()
96    }
97}
98
99impl TryFrom<Vec<Money>> for CostLimits {
100    type Error = CostCollectionError;
101
102    fn try_from(values: Vec<Money>) -> Result<Self, Self::Error> {
103        Self::try_new(values)
104    }
105}
106
107impl Serialize for CostLimits {
108    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
109    where
110        S: Serializer,
111    {
112        serializer.collect_seq(self.iter())
113    }
114}
115
116impl<'de> Deserialize<'de> for CostLimits {
117    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
118    where
119        D: Deserializer<'de>,
120    {
121        deserializer.deserialize_seq(CostLimitsVisitor)
122    }
123}
124
125struct CostLimitsVisitor;
126
127impl<'de> de::Visitor<'de> for CostLimitsVisitor {
128    type Value = CostLimits;
129
130    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
131        write!(
132            formatter,
133            "an array containing at most {MAX_COST_CURRENCIES} unique currency limits"
134        )
135    }
136
137    fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
138    where
139        A: de::SeqAccess<'de>,
140    {
141        let mut values = Vec::with_capacity(
142            sequence
143                .size_hint()
144                .unwrap_or_default()
145                .min(MAX_COST_CURRENCIES),
146        );
147        while let Some(value) = sequence.next_element::<Money>()? {
148            if values.len() == MAX_COST_CURRENCIES {
149                return Err(de::Error::custom(CostCollectionError::TooMany {
150                    max: MAX_COST_CURRENCIES,
151                    observed: MAX_COST_CURRENCIES + 1,
152                }));
153            }
154            values.push(value);
155        }
156        Self::Value::try_new(values).map_err(de::Error::custom)
157    }
158}
159
160impl JsonSchema for CostLimits {
161    fn schema_name() -> std::borrow::Cow<'static, str> {
162        "CostLimits".into()
163    }
164
165    fn schema_id() -> std::borrow::Cow<'static, str> {
166        concat!(module_path!(), "::CostLimits").into()
167    }
168
169    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
170        json_schema!({
171            "type": "array",
172            "items": generator.subschema_for::<Money>(),
173            "minItems": 0,
174            "maxItems": 16,
175            "uniqueItems": true,
176            "description": "Currency codes must be unique; StateKnot serializes entries in ascending currency order."
177        })
178    }
179}
180
181/// Known accumulated monetary charges keyed by currency.
182///
183/// An empty value means no *known* charge. It does not represent unpriced
184/// provider activity; [`BudgetUsage::unpriced_cost_events`] tracks that state
185/// explicitly.
186#[derive(Clone, Default, Eq, Hash, PartialEq)]
187pub struct KnownCosts(Box<[Money]>);
188
189impl KnownCosts {
190    /// Validates and constructs known charges.
191    ///
192    /// # Errors
193    ///
194    /// Returns [`CostCollectionError`] for duplicate currencies or excessive
195    /// currency cardinality. Empty input is valid.
196    pub fn try_new<I>(values: I) -> Result<Self, CostCollectionError>
197    where
198        I: IntoIterator<Item = Money>,
199    {
200        collect_costs(values).map(Self)
201    }
202
203    /// Returns an empty known-cost ledger.
204    #[must_use]
205    pub fn empty() -> Self {
206        Self::default()
207    }
208
209    /// Returns the number of currencies with known accumulated cost.
210    #[must_use]
211    pub const fn len(&self) -> usize {
212        self.0.len()
213    }
214
215    /// Returns whether no known monetary cost has been recorded.
216    #[must_use]
217    pub const fn is_empty(&self) -> bool {
218        self.0.is_empty()
219    }
220
221    /// Returns known charges in ascending currency-code order.
222    pub fn iter(&self) -> slice::Iter<'_, Money> {
223        self.0.iter()
224    }
225
226    /// Returns the accumulated charge for one currency when present.
227    #[must_use]
228    pub fn get(&self, currency: CurrencyCode) -> Option<Money> {
229        self.0
230            .binary_search_by_key(&currency, |money| money.currency())
231            .ok()
232            .map(|index| self.0[index])
233    }
234
235    fn checked_accumulate(&self, other: &Self) -> Result<Self, CostCollectionError> {
236        let mut values: BTreeMap<CurrencyCode, Money> = BTreeMap::new();
237        for money in self.iter().chain(other.iter()).copied() {
238            if let Some(existing) = values.get_mut(&money.currency()) {
239                let micro_units = existing
240                    .micro_units()
241                    .checked_add(money.micro_units())
242                    .ok_or(CostCollectionError::Overflow {
243                        currency: money.currency(),
244                    })?;
245                *existing = Money::new(money.currency(), micro_units);
246            } else {
247                if values.len() == MAX_COST_CURRENCIES {
248                    return Err(CostCollectionError::TooMany {
249                        max: MAX_COST_CURRENCIES,
250                        observed: MAX_COST_CURRENCIES + 1,
251                    });
252                }
253                values.insert(money.currency(), money);
254            }
255        }
256        Ok(Self(
257            values.into_values().collect::<Vec<_>>().into_boxed_slice(),
258        ))
259    }
260}
261
262impl fmt::Debug for KnownCosts {
263    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
264        formatter.debug_tuple("KnownCosts").field(&self.0).finish()
265    }
266}
267
268impl<'a> IntoIterator for &'a KnownCosts {
269    type Item = &'a Money;
270    type IntoIter = slice::Iter<'a, Money>;
271
272    fn into_iter(self) -> Self::IntoIter {
273        self.iter()
274    }
275}
276
277impl TryFrom<Vec<Money>> for KnownCosts {
278    type Error = CostCollectionError;
279
280    fn try_from(values: Vec<Money>) -> Result<Self, Self::Error> {
281        Self::try_new(values)
282    }
283}
284
285impl Serialize for KnownCosts {
286    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
287    where
288        S: Serializer,
289    {
290        serializer.collect_seq(self.iter())
291    }
292}
293
294impl<'de> Deserialize<'de> for KnownCosts {
295    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
296    where
297        D: Deserializer<'de>,
298    {
299        deserializer.deserialize_seq(KnownCostsVisitor)
300    }
301}
302
303struct KnownCostsVisitor;
304
305impl<'de> de::Visitor<'de> for KnownCostsVisitor {
306    type Value = KnownCosts;
307
308    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
309        write!(
310            formatter,
311            "an array containing at most {MAX_COST_CURRENCIES} unique currency charges"
312        )
313    }
314
315    fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
316    where
317        A: de::SeqAccess<'de>,
318    {
319        let mut values = Vec::with_capacity(
320            sequence
321                .size_hint()
322                .unwrap_or_default()
323                .min(MAX_COST_CURRENCIES),
324        );
325        while let Some(value) = sequence.next_element::<Money>()? {
326            if values.len() == MAX_COST_CURRENCIES {
327                return Err(de::Error::custom(CostCollectionError::TooMany {
328                    max: MAX_COST_CURRENCIES,
329                    observed: MAX_COST_CURRENCIES + 1,
330                }));
331            }
332            values.push(value);
333        }
334        Self::Value::try_new(values).map_err(de::Error::custom)
335    }
336}
337
338impl JsonSchema for KnownCosts {
339    fn schema_name() -> std::borrow::Cow<'static, str> {
340        "KnownCosts".into()
341    }
342
343    fn schema_id() -> std::borrow::Cow<'static, str> {
344        concat!(module_path!(), "::KnownCosts").into()
345    }
346
347    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
348        json_schema!({
349            "type": "array",
350            "items": generator.subschema_for::<Money>(),
351            "maxItems": 16,
352            "uniqueItems": true,
353            "description": "Known charges keyed by unique currency; unpriced events are represented separately."
354        })
355    }
356}
357
358fn collect_costs<I>(values: I) -> Result<Box<[Money]>, CostCollectionError>
359where
360    I: IntoIterator<Item = Money>,
361{
362    let mut collected = BTreeMap::new();
363    for money in values {
364        if collected.contains_key(&money.currency()) {
365            return Err(CostCollectionError::DuplicateCurrency {
366                currency: money.currency(),
367            });
368        }
369        if collected.len() == MAX_COST_CURRENCIES {
370            return Err(CostCollectionError::TooMany {
371                max: MAX_COST_CURRENCIES,
372                observed: MAX_COST_CURRENCIES + 1,
373            });
374        }
375        collected.insert(money.currency(), money);
376    }
377    Ok(collected
378        .into_values()
379        .collect::<Vec<_>>()
380        .into_boxed_slice())
381}
382
383/// Validation or arithmetic failure for a currency-keyed cost collection.
384#[derive(Clone, Debug, Eq, Error, PartialEq)]
385#[non_exhaustive]
386pub enum CostCollectionError {
387    /// The same currency appeared more than once.
388    #[error("cost collection repeats currency {currency}")]
389    DuplicateCurrency {
390        /// Repeated currency.
391        currency: CurrencyCode,
392    },
393
394    /// Currency cardinality exceeded the hard v1 ceiling.
395    #[error("cost collection contains at least {observed} currencies; maximum is {max}")]
396    TooMany {
397        /// Maximum accepted distinct currencies.
398        max: usize,
399        /// Minimum distinct count observed before validation stopped.
400        observed: usize,
401    },
402
403    /// Accumulated known cost exceeded the integer representation.
404    #[error("known cost for {currency} overflowed")]
405    Overflow {
406        /// Currency whose accumulator overflowed.
407        currency: CurrencyCode,
408    },
409}
410
411/// Stable budget dimension used by resolution and enforcement errors.
412#[derive(
413    Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
414)]
415#[non_exhaustive]
416#[serde(rename_all = "snake_case")]
417pub enum BudgetDimension {
418    /// Absolute run deadline.
419    Deadline,
420    /// Maximum graph nesting depth observed.
421    GraphDepth,
422    /// Cumulative graph steps committed.
423    GraphSteps,
424    /// Cumulative provider invocation attempts.
425    ModelAttempts,
426    /// Cumulative logical agent/model turns.
427    ModelTurns,
428    /// Inclusive cumulative model input tokens.
429    InputTokens,
430    /// Cached-input subset of cumulative input tokens.
431    CachedInputTokens,
432    /// Reasoning subset of cumulative output tokens.
433    ReasoningTokens,
434    /// Inclusive cumulative model output tokens.
435    OutputTokens,
436    /// Cumulative tool calls.
437    ToolCalls,
438    /// Write-capable subset of cumulative tool calls.
439    WriteCalls,
440    /// Cumulative remote-agent delegations.
441    RemoteAgentDelegations,
442    /// Cumulative retries across bounded retry policies.
443    Retries,
444    /// Maximum concurrently active branches observed.
445    ConcurrentBranches,
446    /// Maximum fan-out produced by one scheduling decision.
447    FanOut,
448    /// Cumulative materialized input bytes.
449    InputBytes,
450    /// Cumulative materialized output bytes.
451    OutputBytes,
452    /// Cumulative durable event bytes.
453    EventBytes,
454    /// Cumulative durable checkpoint bytes.
455    CheckpointBytes,
456    /// Cumulative artifact bytes registered by the run.
457    ArtifactBytes,
458    /// Known monetary cost ceilings keyed by currency.
459    Costs,
460}
461
462/// Optional limits supplied by one configuration or request layer.
463///
464/// Absence means that this layer has no opinion; it never means the resolved
465/// run is unlimited. [`ResolvedBudget::resolve`] requires another layer to
466/// supply every dimension and always chooses the most restrictive value.
467#[derive(Clone, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
468#[serde(deny_unknown_fields)]
469pub struct BudgetLimits {
470    #[serde(skip_serializing_if = "Option::is_none")]
471    deadline: Option<Timestamp>,
472    #[serde(skip_serializing_if = "Option::is_none")]
473    graph_depth: Option<ExecutionCount>,
474    #[serde(skip_serializing_if = "Option::is_none")]
475    graph_steps: Option<ExecutionCount>,
476    #[serde(skip_serializing_if = "Option::is_none")]
477    model_attempts: Option<ExecutionCount>,
478    #[serde(skip_serializing_if = "Option::is_none")]
479    model_turns: Option<ExecutionCount>,
480    #[serde(skip_serializing_if = "Option::is_none")]
481    input_tokens: Option<TokenCount>,
482    #[serde(skip_serializing_if = "Option::is_none")]
483    cached_input_tokens: Option<TokenCount>,
484    #[serde(skip_serializing_if = "Option::is_none")]
485    reasoning_tokens: Option<TokenCount>,
486    #[serde(skip_serializing_if = "Option::is_none")]
487    output_tokens: Option<TokenCount>,
488    #[serde(skip_serializing_if = "Option::is_none")]
489    tool_calls: Option<ExecutionCount>,
490    #[serde(skip_serializing_if = "Option::is_none")]
491    write_calls: Option<ExecutionCount>,
492    #[serde(skip_serializing_if = "Option::is_none")]
493    remote_agent_delegations: Option<ExecutionCount>,
494    #[serde(skip_serializing_if = "Option::is_none")]
495    retries: Option<ExecutionCount>,
496    #[serde(skip_serializing_if = "Option::is_none")]
497    concurrent_branches: Option<ExecutionCount>,
498    #[serde(skip_serializing_if = "Option::is_none")]
499    fan_out: Option<ExecutionCount>,
500    #[serde(skip_serializing_if = "Option::is_none")]
501    input_bytes: Option<ByteCount>,
502    #[serde(skip_serializing_if = "Option::is_none")]
503    output_bytes: Option<ByteCount>,
504    #[serde(skip_serializing_if = "Option::is_none")]
505    event_bytes: Option<ByteCount>,
506    #[serde(skip_serializing_if = "Option::is_none")]
507    checkpoint_bytes: Option<ByteCount>,
508    #[serde(skip_serializing_if = "Option::is_none")]
509    artifact_bytes: Option<ByteCount>,
510    #[serde(skip_serializing_if = "Option::is_none")]
511    costs: Option<CostLimits>,
512}
513
514macro_rules! define_optional_limit_methods {
515    ($(($field:ident, $setter:ident, $type:ty)),+ $(,)?) => {
516        $(
517            #[doc = concat!("Returns this layer's optional `", stringify!($field), "` limit.")]
518            #[must_use]
519            pub const fn $field(&self) -> Option<$type> {
520                self.$field
521            }
522
523            #[doc = concat!("Sets this layer's `", stringify!($field), "` limit.")]
524            #[must_use]
525            pub const fn $setter(mut self, value: $type) -> Self {
526                self.$field = Some(value);
527                self
528            }
529        )+
530    };
531}
532
533impl BudgetLimits {
534    /// Constructs a layer with no limits of its own.
535    #[must_use]
536    pub const fn empty() -> Self {
537        Self {
538            deadline: None,
539            graph_depth: None,
540            graph_steps: None,
541            model_attempts: None,
542            model_turns: None,
543            input_tokens: None,
544            cached_input_tokens: None,
545            reasoning_tokens: None,
546            output_tokens: None,
547            tool_calls: None,
548            write_calls: None,
549            remote_agent_delegations: None,
550            retries: None,
551            concurrent_branches: None,
552            fan_out: None,
553            input_bytes: None,
554            output_bytes: None,
555            event_bytes: None,
556            checkpoint_bytes: None,
557            artifact_bytes: None,
558            costs: None,
559        }
560    }
561
562    /// Returns whether this layer contributes no constraint.
563    #[must_use]
564    pub const fn is_empty(&self) -> bool {
565        self.deadline.is_none()
566            && self.graph_depth.is_none()
567            && self.graph_steps.is_none()
568            && self.model_attempts.is_none()
569            && self.model_turns.is_none()
570            && self.input_tokens.is_none()
571            && self.cached_input_tokens.is_none()
572            && self.reasoning_tokens.is_none()
573            && self.output_tokens.is_none()
574            && self.tool_calls.is_none()
575            && self.write_calls.is_none()
576            && self.remote_agent_delegations.is_none()
577            && self.retries.is_none()
578            && self.concurrent_branches.is_none()
579            && self.fan_out.is_none()
580            && self.input_bytes.is_none()
581            && self.output_bytes.is_none()
582            && self.event_bytes.is_none()
583            && self.checkpoint_bytes.is_none()
584            && self.artifact_bytes.is_none()
585            && self.costs.is_none()
586    }
587
588    define_optional_limit_methods!(
589        (deadline, with_deadline, Timestamp),
590        (graph_depth, with_graph_depth, ExecutionCount),
591        (graph_steps, with_graph_steps, ExecutionCount),
592        (model_attempts, with_model_attempts, ExecutionCount),
593        (model_turns, with_model_turns, ExecutionCount),
594        (input_tokens, with_input_tokens, TokenCount),
595        (cached_input_tokens, with_cached_input_tokens, TokenCount),
596        (reasoning_tokens, with_reasoning_tokens, TokenCount),
597        (output_tokens, with_output_tokens, TokenCount),
598        (tool_calls, with_tool_calls, ExecutionCount),
599        (write_calls, with_write_calls, ExecutionCount),
600        (
601            remote_agent_delegations,
602            with_remote_agent_delegations,
603            ExecutionCount
604        ),
605        (retries, with_retries, ExecutionCount),
606        (
607            concurrent_branches,
608            with_concurrent_branches,
609            ExecutionCount
610        ),
611        (fan_out, with_fan_out, ExecutionCount),
612        (input_bytes, with_input_bytes, ByteCount),
613        (output_bytes, with_output_bytes, ByteCount),
614        (event_bytes, with_event_bytes, ByteCount),
615        (checkpoint_bytes, with_checkpoint_bytes, ByteCount),
616        (artifact_bytes, with_artifact_bytes, ByteCount),
617    );
618
619    /// Returns this layer's optional currency-specific cost ceilings.
620    #[must_use]
621    pub const fn costs(&self) -> Option<&CostLimits> {
622        self.costs.as_ref()
623    }
624
625    /// Sets this layer's currency-specific cost ceilings.
626    #[must_use]
627    pub fn with_costs(mut self, value: CostLimits) -> Self {
628        self.costs = Some(value);
629        self
630    }
631
632    /// Intersects two partial layers without inventing missing values.
633    ///
634    /// When both layers specify costs, their currency allowlists are
635    /// intersected and same-currency ceilings take the minimum. A layer cannot
636    /// introduce a currency absent from another applicable cost layer.
637    #[must_use]
638    pub fn most_restrictive(&self, other: &Self) -> Self {
639        Self {
640            deadline: min_option(self.deadline, other.deadline),
641            graph_depth: min_option(self.graph_depth, other.graph_depth),
642            graph_steps: min_option(self.graph_steps, other.graph_steps),
643            model_attempts: min_option(self.model_attempts, other.model_attempts),
644            model_turns: min_option(self.model_turns, other.model_turns),
645            input_tokens: min_option(self.input_tokens, other.input_tokens),
646            cached_input_tokens: min_option(self.cached_input_tokens, other.cached_input_tokens),
647            reasoning_tokens: min_option(self.reasoning_tokens, other.reasoning_tokens),
648            output_tokens: min_option(self.output_tokens, other.output_tokens),
649            tool_calls: min_option(self.tool_calls, other.tool_calls),
650            write_calls: min_option(self.write_calls, other.write_calls),
651            remote_agent_delegations: min_option(
652                self.remote_agent_delegations,
653                other.remote_agent_delegations,
654            ),
655            retries: min_option(self.retries, other.retries),
656            concurrent_branches: min_option(self.concurrent_branches, other.concurrent_branches),
657            fan_out: min_option(self.fan_out, other.fan_out),
658            input_bytes: min_option(self.input_bytes, other.input_bytes),
659            output_bytes: min_option(self.output_bytes, other.output_bytes),
660            event_bytes: min_option(self.event_bytes, other.event_bytes),
661            checkpoint_bytes: min_option(self.checkpoint_bytes, other.checkpoint_bytes),
662            artifact_bytes: min_option(self.artifact_bytes, other.artifact_bytes),
663            costs: match (&self.costs, &other.costs) {
664                (Some(left), Some(right)) => Some(left.most_restrictive(right)),
665                (Some(value), None) | (None, Some(value)) => Some(value.clone()),
666                (None, None) => None,
667            },
668        }
669    }
670}
671
672fn min_option<T>(left: Option<T>, right: Option<T>) -> Option<T>
673where
674    T: Copy + Ord,
675{
676    match (left, right) {
677        (Some(left), Some(right)) => Some(left.min(right)),
678        (Some(value), None) | (None, Some(value)) => Some(value),
679        (None, None) => None,
680    }
681}
682
683/// A complete, finite run budget after all applicable layers are intersected.
684///
685/// Every dimension is present. Cached input is bounded by inclusive input, and
686/// reasoning is bounded by inclusive output even when a looser redundant
687/// sub-limit was configured.
688#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
689#[serde(deny_unknown_fields)]
690pub struct ResolvedBudget {
691    deadline: Timestamp,
692    graph_depth: ExecutionCount,
693    graph_steps: ExecutionCount,
694    model_attempts: ExecutionCount,
695    model_turns: ExecutionCount,
696    input_tokens: TokenCount,
697    cached_input_tokens: TokenCount,
698    reasoning_tokens: TokenCount,
699    output_tokens: TokenCount,
700    tool_calls: ExecutionCount,
701    write_calls: ExecutionCount,
702    remote_agent_delegations: ExecutionCount,
703    retries: ExecutionCount,
704    concurrent_branches: ExecutionCount,
705    fan_out: ExecutionCount,
706    input_bytes: ByteCount,
707    output_bytes: ByteCount,
708    event_bytes: ByteCount,
709    checkpoint_bytes: ByteCount,
710    artifact_bytes: ByteCount,
711    costs: CostLimits,
712}
713
714macro_rules! define_resolved_getters {
715    ($(($field:ident, $type:ty)),+ $(,)?) => {
716        $(
717            #[doc = concat!("Returns the resolved `", stringify!($field), "` ceiling.")]
718            #[must_use]
719            pub const fn $field(&self) -> $type {
720                self.$field
721            }
722        )+
723    };
724}
725
726impl ResolvedBudget {
727    /// Verifies that this budget does not widen any ceiling of `parent`.
728    ///
729    /// Includes the absolute deadline, every cumulative and high-water limit,
730    /// and exact currency ceilings. An extra currency is rejected even with a
731    /// zero ceiling. This compares immutable limits, not remaining capacity;
732    /// concurrent reservations, live topology, and usage still require atomic
733    /// admission checks. No value is silently clamped.
734    pub fn validate_narrowing(&self, parent: &Self) -> Result<(), BudgetNarrowingError> {
735        macro_rules! check {
736            ($(($field:ident, $dimension:ident)),+ $(,)?) => {
737                $(if self.$field > parent.$field {
738                    return Err(BudgetNarrowingError::Widened {
739                        dimension: BudgetDimension::$dimension,
740                    });
741                })+
742            };
743        }
744        check!(
745            (deadline, Deadline),
746            (graph_depth, GraphDepth),
747            (graph_steps, GraphSteps),
748            (model_attempts, ModelAttempts),
749            (model_turns, ModelTurns),
750            (input_tokens, InputTokens),
751            (cached_input_tokens, CachedInputTokens),
752            (reasoning_tokens, ReasoningTokens),
753            (output_tokens, OutputTokens),
754            (tool_calls, ToolCalls),
755            (write_calls, WriteCalls),
756            (remote_agent_delegations, RemoteAgentDelegations),
757            (retries, Retries),
758            (concurrent_branches, ConcurrentBranches),
759            (fan_out, FanOut),
760            (input_bytes, InputBytes),
761            (output_bytes, OutputBytes),
762            (event_bytes, EventBytes),
763            (checkpoint_bytes, CheckpointBytes),
764            (artifact_bytes, ArtifactBytes),
765        );
766        for limit in &self.costs {
767            let outer = parent.costs.get(limit.currency()).ok_or(
768                BudgetNarrowingError::UnbudgetedCurrency {
769                    currency: limit.currency(),
770                },
771            )?;
772            if limit.micro_units() > outer.micro_units() {
773                return Err(BudgetNarrowingError::CostWidened {
774                    currency: limit.currency(),
775                });
776            }
777        }
778        Ok(())
779    }
780
781    /// Resolves ordered configuration layers by taking each finite minimum.
782    ///
783    /// Layer order does not affect the result. The slice is bounded so an
784    /// untrusted request cannot trigger unbounded configuration work.
785    ///
786    /// # Errors
787    ///
788    /// Returns [`BudgetResolutionError`] for an empty or oversized layer list,
789    /// any missing dimension, or an invalid cost collection.
790    pub fn resolve(layers: &[BudgetLimits]) -> Result<Self, BudgetResolutionError> {
791        if layers.is_empty() {
792            return Err(BudgetResolutionError::EmptyLayers);
793        }
794        if layers.len() > MAX_BUDGET_LAYERS {
795            return Err(BudgetResolutionError::TooManyLayers {
796                max: MAX_BUDGET_LAYERS,
797                actual: layers.len(),
798            });
799        }
800
801        let mut effective = BudgetLimits::empty();
802        for layer in layers {
803            effective = effective.most_restrictive(layer);
804        }
805
806        let input_tokens = required(effective.input_tokens, BudgetDimension::InputTokens)?;
807        let output_tokens = required(effective.output_tokens, BudgetDimension::OutputTokens)?;
808        let tool_calls = required(effective.tool_calls, BudgetDimension::ToolCalls)?;
809        let cached_input_tokens = required(
810            effective.cached_input_tokens,
811            BudgetDimension::CachedInputTokens,
812        )?
813        .min(input_tokens);
814        let reasoning_tokens =
815            required(effective.reasoning_tokens, BudgetDimension::ReasoningTokens)?
816                .min(output_tokens);
817        let write_calls =
818            required(effective.write_calls, BudgetDimension::WriteCalls)?.min(tool_calls);
819
820        Ok(Self {
821            deadline: required(effective.deadline, BudgetDimension::Deadline)?,
822            graph_depth: required(effective.graph_depth, BudgetDimension::GraphDepth)?,
823            graph_steps: required(effective.graph_steps, BudgetDimension::GraphSteps)?,
824            model_attempts: required(effective.model_attempts, BudgetDimension::ModelAttempts)?,
825            model_turns: required(effective.model_turns, BudgetDimension::ModelTurns)?,
826            input_tokens,
827            cached_input_tokens,
828            reasoning_tokens,
829            output_tokens,
830            tool_calls,
831            write_calls,
832            remote_agent_delegations: required(
833                effective.remote_agent_delegations,
834                BudgetDimension::RemoteAgentDelegations,
835            )?,
836            retries: required(effective.retries, BudgetDimension::Retries)?,
837            concurrent_branches: required(
838                effective.concurrent_branches,
839                BudgetDimension::ConcurrentBranches,
840            )?,
841            fan_out: required(effective.fan_out, BudgetDimension::FanOut)?,
842            input_bytes: required(effective.input_bytes, BudgetDimension::InputBytes)?,
843            output_bytes: required(effective.output_bytes, BudgetDimension::OutputBytes)?,
844            event_bytes: required(effective.event_bytes, BudgetDimension::EventBytes)?,
845            checkpoint_bytes: required(
846                effective.checkpoint_bytes,
847                BudgetDimension::CheckpointBytes,
848            )?,
849            artifact_bytes: required(effective.artifact_bytes, BudgetDimension::ArtifactBytes)?,
850            costs: effective.costs.ok_or(BudgetResolutionError::Missing {
851                dimension: BudgetDimension::Costs,
852            })?,
853        })
854    }
855
856    define_resolved_getters!(
857        (deadline, Timestamp),
858        (graph_depth, ExecutionCount),
859        (graph_steps, ExecutionCount),
860        (model_attempts, ExecutionCount),
861        (model_turns, ExecutionCount),
862        (input_tokens, TokenCount),
863        (cached_input_tokens, TokenCount),
864        (reasoning_tokens, TokenCount),
865        (output_tokens, TokenCount),
866        (tool_calls, ExecutionCount),
867        (write_calls, ExecutionCount),
868        (remote_agent_delegations, ExecutionCount),
869        (retries, ExecutionCount),
870        (concurrent_branches, ExecutionCount),
871        (fan_out, ExecutionCount),
872        (input_bytes, ByteCount),
873        (output_bytes, ByteCount),
874        (event_bytes, ByteCount),
875        (checkpoint_bytes, ByteCount),
876        (artifact_bytes, ByteCount),
877    );
878
879    /// Returns resolved currency-specific monetary ceilings.
880    #[must_use]
881    pub const fn costs(&self) -> &CostLimits {
882        &self.costs
883    }
884
885    fn validate(&self) -> Result<(), BudgetResolutionError> {
886        if self.cached_input_tokens > self.input_tokens {
887            return Err(BudgetResolutionError::InvalidSubsetLimit {
888                subset: BudgetDimension::CachedInputTokens,
889                inclusive: BudgetDimension::InputTokens,
890            });
891        }
892        if self.reasoning_tokens > self.output_tokens {
893            return Err(BudgetResolutionError::InvalidSubsetLimit {
894                subset: BudgetDimension::ReasoningTokens,
895                inclusive: BudgetDimension::OutputTokens,
896            });
897        }
898        if self.write_calls > self.tool_calls {
899            return Err(BudgetResolutionError::InvalidSubsetLimit {
900                subset: BudgetDimension::WriteCalls,
901                inclusive: BudgetDimension::ToolCalls,
902            });
903        }
904        Ok(())
905    }
906}
907
908/// An attempted child or delegated budget would widen immutable parent limits.
909#[derive(Clone, Debug, Eq, Error, PartialEq)]
910#[non_exhaustive]
911pub enum BudgetNarrowingError {
912    /// A scalar or deadline ceiling was widened.
913    #[error("delegated budget widens {dimension:?}")]
914    Widened {
915        /// The rejected dimension.
916        dimension: BudgetDimension,
917    },
918    /// The parent did not configure this currency.
919    #[error("delegated budget adds currency {currency}")]
920    UnbudgetedCurrency {
921        /// The rejected currency.
922        currency: CurrencyCode,
923    },
924    /// A configured same-currency amount was widened.
925    #[error("delegated budget widens cost in {currency}")]
926    CostWidened {
927        /// The currency whose ceiling was exceeded.
928        currency: CurrencyCode,
929    },
930}
931
932impl<'de> Deserialize<'de> for ResolvedBudget {
933    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
934    where
935        D: Deserializer<'de>,
936    {
937        #[derive(Deserialize)]
938        #[serde(deny_unknown_fields)]
939        struct Wire {
940            deadline: Timestamp,
941            graph_depth: ExecutionCount,
942            graph_steps: ExecutionCount,
943            model_attempts: ExecutionCount,
944            model_turns: ExecutionCount,
945            input_tokens: TokenCount,
946            cached_input_tokens: TokenCount,
947            reasoning_tokens: TokenCount,
948            output_tokens: TokenCount,
949            tool_calls: ExecutionCount,
950            write_calls: ExecutionCount,
951            remote_agent_delegations: ExecutionCount,
952            retries: ExecutionCount,
953            concurrent_branches: ExecutionCount,
954            fan_out: ExecutionCount,
955            input_bytes: ByteCount,
956            output_bytes: ByteCount,
957            event_bytes: ByteCount,
958            checkpoint_bytes: ByteCount,
959            artifact_bytes: ByteCount,
960            costs: CostLimits,
961        }
962
963        let wire = Wire::deserialize(deserializer)?;
964        let budget = Self {
965            deadline: wire.deadline,
966            graph_depth: wire.graph_depth,
967            graph_steps: wire.graph_steps,
968            model_attempts: wire.model_attempts,
969            model_turns: wire.model_turns,
970            input_tokens: wire.input_tokens,
971            cached_input_tokens: wire.cached_input_tokens,
972            reasoning_tokens: wire.reasoning_tokens,
973            output_tokens: wire.output_tokens,
974            tool_calls: wire.tool_calls,
975            write_calls: wire.write_calls,
976            remote_agent_delegations: wire.remote_agent_delegations,
977            retries: wire.retries,
978            concurrent_branches: wire.concurrent_branches,
979            fan_out: wire.fan_out,
980            input_bytes: wire.input_bytes,
981            output_bytes: wire.output_bytes,
982            event_bytes: wire.event_bytes,
983            checkpoint_bytes: wire.checkpoint_bytes,
984            artifact_bytes: wire.artifact_bytes,
985            costs: wire.costs,
986        };
987        budget.validate().map_err(de::Error::custom)?;
988        Ok(budget)
989    }
990}
991
992fn required<T>(value: Option<T>, dimension: BudgetDimension) -> Result<T, BudgetResolutionError> {
993    value.ok_or(BudgetResolutionError::Missing { dimension })
994}
995
996/// Failure while intersecting partial budget layers.
997#[derive(Clone, Debug, Eq, Error, PartialEq)]
998#[non_exhaustive]
999pub enum BudgetResolutionError {
1000    /// No configuration layer was supplied.
1001    #[error("at least one budget layer is required")]
1002    EmptyLayers,
1003
1004    /// Too many independently supplied layers were requested.
1005    #[error("budget resolution received {actual} layers; maximum is {max}")]
1006    TooManyLayers {
1007        /// Maximum accepted layers.
1008        max: usize,
1009        /// Observed layer count.
1010        actual: usize,
1011    },
1012
1013    /// No layer supplied a finite value for one mandatory dimension.
1014    #[error("resolved budget is missing dimension {dimension:?}")]
1015    Missing {
1016        /// Missing dimension.
1017        dimension: BudgetDimension,
1018    },
1019
1020    /// A serialized subset limit exceeded its inclusive parent limit.
1021    #[error("budget subset {subset:?} exceeds inclusive limit {inclusive:?}")]
1022    InvalidSubsetLimit {
1023        /// Subset dimension.
1024        subset: BudgetDimension,
1025        /// Inclusive parent dimension.
1026        inclusive: BudgetDimension,
1027    },
1028}
1029
1030/// Builder for a validated [`BudgetUsage`] snapshot or delta.
1031#[derive(Clone, Debug, Default)]
1032pub struct BudgetUsageBuilder {
1033    graph_depth: ExecutionCount,
1034    graph_steps: ExecutionCount,
1035    model_attempts: ExecutionCount,
1036    model_turns: ExecutionCount,
1037    input_tokens: TokenCount,
1038    cached_input_tokens: TokenCount,
1039    reasoning_tokens: TokenCount,
1040    output_tokens: TokenCount,
1041    tool_calls: ExecutionCount,
1042    write_calls: ExecutionCount,
1043    remote_agent_delegations: ExecutionCount,
1044    retries: ExecutionCount,
1045    concurrent_branches: ExecutionCount,
1046    fan_out: ExecutionCount,
1047    input_bytes: ByteCount,
1048    output_bytes: ByteCount,
1049    event_bytes: ByteCount,
1050    checkpoint_bytes: ByteCount,
1051    artifact_bytes: ByteCount,
1052    known_costs: KnownCosts,
1053    unpriced_cost_events: ExecutionCount,
1054}
1055
1056macro_rules! define_usage_builder_methods {
1057    ($(($field:ident, $type:ty)),+ $(,)?) => {
1058        $(
1059            #[doc = concat!("Sets the usage builder's `", stringify!($field), "` value.")]
1060            #[must_use]
1061            pub const fn $field(mut self, value: $type) -> Self {
1062                self.$field = value;
1063                self
1064            }
1065        )+
1066    };
1067}
1068
1069impl BudgetUsageBuilder {
1070    define_usage_builder_methods!(
1071        (graph_depth, ExecutionCount),
1072        (graph_steps, ExecutionCount),
1073        (model_attempts, ExecutionCount),
1074        (model_turns, ExecutionCount),
1075        (input_tokens, TokenCount),
1076        (cached_input_tokens, TokenCount),
1077        (reasoning_tokens, TokenCount),
1078        (output_tokens, TokenCount),
1079        (tool_calls, ExecutionCount),
1080        (write_calls, ExecutionCount),
1081        (remote_agent_delegations, ExecutionCount),
1082        (retries, ExecutionCount),
1083        (concurrent_branches, ExecutionCount),
1084        (fan_out, ExecutionCount),
1085        (input_bytes, ByteCount),
1086        (output_bytes, ByteCount),
1087        (event_bytes, ByteCount),
1088        (checkpoint_bytes, ByteCount),
1089        (artifact_bytes, ByteCount),
1090        (unpriced_cost_events, ExecutionCount),
1091    );
1092
1093    /// Sets known currency-specific accumulated charges.
1094    #[must_use]
1095    pub fn known_costs(mut self, value: KnownCosts) -> Self {
1096        self.known_costs = value;
1097        self
1098    }
1099
1100    /// Validates and builds the immutable usage value.
1101    ///
1102    /// # Errors
1103    ///
1104    /// Returns [`BudgetUsageError`] if cached input exceeds inclusive input or
1105    /// reasoning exceeds inclusive output.
1106    pub fn build(self) -> Result<BudgetUsage, BudgetUsageError> {
1107        BudgetUsage::from_builder(self)
1108    }
1109}
1110
1111/// Monotonic run usage with explicit provider-observability gaps.
1112///
1113/// `graph_depth`, `concurrent_branches`, and `fan_out` are high-water marks.
1114/// Every other numeric field is cumulative. Input tokens include cached input;
1115/// output tokens include reasoning. Unpriced provider activity is counted
1116/// separately and never treated as zero cost.
1117#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
1118#[serde(deny_unknown_fields)]
1119pub struct BudgetUsage {
1120    graph_depth: ExecutionCount,
1121    graph_steps: ExecutionCount,
1122    model_attempts: ExecutionCount,
1123    model_turns: ExecutionCount,
1124    input_tokens: TokenCount,
1125    cached_input_tokens: TokenCount,
1126    reasoning_tokens: TokenCount,
1127    output_tokens: TokenCount,
1128    tool_calls: ExecutionCount,
1129    write_calls: ExecutionCount,
1130    remote_agent_delegations: ExecutionCount,
1131    retries: ExecutionCount,
1132    concurrent_branches: ExecutionCount,
1133    fan_out: ExecutionCount,
1134    input_bytes: ByteCount,
1135    output_bytes: ByteCount,
1136    event_bytes: ByteCount,
1137    checkpoint_bytes: ByteCount,
1138    artifact_bytes: ByteCount,
1139    known_costs: KnownCosts,
1140    unpriced_cost_events: ExecutionCount,
1141}
1142
1143macro_rules! define_usage_getters {
1144    ($(($field:ident, $type:ty)),+ $(,)?) => {
1145        $(
1146            #[doc = concat!("Returns recorded `", stringify!($field), "` usage.")]
1147            #[must_use]
1148            pub const fn $field(&self) -> $type {
1149                self.$field
1150            }
1151        )+
1152    };
1153}
1154
1155impl BudgetUsage {
1156    /// Deducts a verified cumulative contribution exactly once, preserving topology peaks.
1157    /// Rejects missing expenditure, currency underflow, and inconsistent inclusive/subset totals.
1158    #[allow(clippy::too_many_lines)]
1159    pub fn checked_subtract_cumulative(
1160        &self,
1161        contribution: &Self,
1162    ) -> Result<Self, BudgetUsageError> {
1163        self.validate_monotonic_after(&contribution.cumulative_only())?;
1164        let mut result = self.clone();
1165        result.graph_steps = self
1166            .graph_steps
1167            .checked_sub(contribution.graph_steps)
1168            .ok_or(BudgetUsageError::Regression {
1169                dimension: BudgetDimension::GraphSteps,
1170            })?;
1171        result.model_attempts = self
1172            .model_attempts
1173            .checked_sub(contribution.model_attempts)
1174            .ok_or(BudgetUsageError::Regression {
1175                dimension: BudgetDimension::ModelAttempts,
1176            })?;
1177        result.model_turns = self
1178            .model_turns
1179            .checked_sub(contribution.model_turns)
1180            .ok_or(BudgetUsageError::Regression {
1181                dimension: BudgetDimension::ModelTurns,
1182            })?;
1183        result.input_tokens = self
1184            .input_tokens
1185            .checked_sub(contribution.input_tokens)
1186            .ok_or(BudgetUsageError::Regression {
1187                dimension: BudgetDimension::InputTokens,
1188            })?;
1189        result.cached_input_tokens = self
1190            .cached_input_tokens
1191            .checked_sub(contribution.cached_input_tokens)
1192            .ok_or(BudgetUsageError::Regression {
1193                dimension: BudgetDimension::CachedInputTokens,
1194            })?;
1195        result.reasoning_tokens = self
1196            .reasoning_tokens
1197            .checked_sub(contribution.reasoning_tokens)
1198            .ok_or(BudgetUsageError::Regression {
1199                dimension: BudgetDimension::ReasoningTokens,
1200            })?;
1201        result.output_tokens = self
1202            .output_tokens
1203            .checked_sub(contribution.output_tokens)
1204            .ok_or(BudgetUsageError::Regression {
1205                dimension: BudgetDimension::OutputTokens,
1206            })?;
1207        result.tool_calls = self.tool_calls.checked_sub(contribution.tool_calls).ok_or(
1208            BudgetUsageError::Regression {
1209                dimension: BudgetDimension::ToolCalls,
1210            },
1211        )?;
1212        result.write_calls = self
1213            .write_calls
1214            .checked_sub(contribution.write_calls)
1215            .ok_or(BudgetUsageError::Regression {
1216                dimension: BudgetDimension::WriteCalls,
1217            })?;
1218        result.remote_agent_delegations = self
1219            .remote_agent_delegations
1220            .checked_sub(contribution.remote_agent_delegations)
1221            .ok_or(BudgetUsageError::Regression {
1222                dimension: BudgetDimension::RemoteAgentDelegations,
1223            })?;
1224        result.retries =
1225            self.retries
1226                .checked_sub(contribution.retries)
1227                .ok_or(BudgetUsageError::Regression {
1228                    dimension: BudgetDimension::Retries,
1229                })?;
1230        result.input_bytes = self
1231            .input_bytes
1232            .checked_sub(contribution.input_bytes)
1233            .ok_or(BudgetUsageError::Regression {
1234                dimension: BudgetDimension::InputBytes,
1235            })?;
1236        result.output_bytes = self
1237            .output_bytes
1238            .checked_sub(contribution.output_bytes)
1239            .ok_or(BudgetUsageError::Regression {
1240                dimension: BudgetDimension::OutputBytes,
1241            })?;
1242        result.event_bytes = self
1243            .event_bytes
1244            .checked_sub(contribution.event_bytes)
1245            .ok_or(BudgetUsageError::Regression {
1246                dimension: BudgetDimension::EventBytes,
1247            })?;
1248        result.checkpoint_bytes = self
1249            .checkpoint_bytes
1250            .checked_sub(contribution.checkpoint_bytes)
1251            .ok_or(BudgetUsageError::Regression {
1252                dimension: BudgetDimension::CheckpointBytes,
1253            })?;
1254        result.artifact_bytes = self
1255            .artifact_bytes
1256            .checked_sub(contribution.artifact_bytes)
1257            .ok_or(BudgetUsageError::Regression {
1258                dimension: BudgetDimension::ArtifactBytes,
1259            })?;
1260        result.unpriced_cost_events = self
1261            .unpriced_cost_events
1262            .checked_sub(contribution.unpriced_cost_events)
1263            .ok_or(BudgetUsageError::Regression {
1264                dimension: BudgetDimension::Costs,
1265            })?;
1266        result.known_costs = KnownCosts::try_new(self.known_costs.iter().map(|cost| {
1267            Money::new(
1268                cost.currency(),
1269                cost.micro_units()
1270                    - contribution
1271                        .known_costs
1272                        .get(cost.currency())
1273                        .map_or(0, Money::micro_units),
1274            )
1275        }))
1276        .map_err(BudgetUsageError::Costs)?;
1277        if result.cached_input_tokens > result.input_tokens {
1278            return Err(BudgetUsageError::SubsetExceedsInclusive {
1279                subset: BudgetDimension::CachedInputTokens,
1280                inclusive: BudgetDimension::InputTokens,
1281            });
1282        }
1283        if result.reasoning_tokens > result.output_tokens {
1284            return Err(BudgetUsageError::SubsetExceedsInclusive {
1285                subset: BudgetDimension::ReasoningTokens,
1286                inclusive: BudgetDimension::OutputTokens,
1287            });
1288        }
1289        if result.write_calls > result.tool_calls {
1290            return Err(BudgetUsageError::SubsetExceedsInclusive {
1291                subset: BudgetDimension::WriteCalls,
1292                inclusive: BudgetDimension::ToolCalls,
1293            });
1294        }
1295        Ok(result)
1296    }
1297
1298    /// Projects only additive expenditure, excluding all three topology peaks.
1299    ///
1300    /// Use this when charging an immediate child's complete subtree to its
1301    /// parent. Child-local peaks cannot describe ancestor depth or simultaneous
1302    /// work; a runtime must observe and enforce that topology separately.
1303    #[must_use]
1304    pub fn cumulative_only(&self) -> Self {
1305        Self {
1306            graph_depth: ExecutionCount::ZERO,
1307            concurrent_branches: ExecutionCount::ZERO,
1308            fan_out: ExecutionCount::ZERO,
1309            ..self.clone()
1310        }
1311    }
1312
1313    /// Rejects a cumulative snapshot that would erase previously recorded work.
1314    ///
1315    /// This checks observations, not deltas or provenance. It does not establish
1316    /// a consistent database snapshot or authorize replacing a durable record.
1317    pub fn validate_monotonic_after(&self, previous: &Self) -> Result<(), BudgetUsageError> {
1318        macro_rules! check {
1319            ($($field:ident => $dimension:ident),+ $(,)?) => { $(
1320                if self.$field < previous.$field {
1321                    return Err(BudgetUsageError::Regression {
1322                        dimension: BudgetDimension::$dimension,
1323                    });
1324                }
1325            )+ };
1326        }
1327        check!(
1328            graph_depth => GraphDepth,
1329            graph_steps => GraphSteps,
1330            model_attempts => ModelAttempts,
1331            model_turns => ModelTurns,
1332            input_tokens => InputTokens,
1333            cached_input_tokens => CachedInputTokens,
1334            reasoning_tokens => ReasoningTokens,
1335            output_tokens => OutputTokens,
1336            tool_calls => ToolCalls,
1337            write_calls => WriteCalls,
1338            remote_agent_delegations => RemoteAgentDelegations,
1339            retries => Retries,
1340            concurrent_branches => ConcurrentBranches,
1341            fan_out => FanOut,
1342            input_bytes => InputBytes,
1343            output_bytes => OutputBytes,
1344            event_bytes => EventBytes,
1345            checkpoint_bytes => CheckpointBytes,
1346            artifact_bytes => ArtifactBytes,
1347            unpriced_cost_events => Costs,
1348        );
1349        for cost in &previous.known_costs {
1350            if self
1351                .known_costs
1352                .get(cost.currency())
1353                .map_or(0, Money::micro_units)
1354                < cost.micro_units()
1355            {
1356                return Err(BudgetUsageError::Regression {
1357                    dimension: BudgetDimension::Costs,
1358                });
1359            }
1360        }
1361        Ok(())
1362    }
1363
1364    /// Returns a builder initialized to zero usage.
1365    #[must_use]
1366    pub fn builder() -> BudgetUsageBuilder {
1367        BudgetUsageBuilder::default()
1368    }
1369
1370    /// Returns a valid all-zero usage snapshot.
1371    #[must_use]
1372    pub fn zero() -> Self {
1373        Self {
1374            graph_depth: ExecutionCount::ZERO,
1375            graph_steps: ExecutionCount::ZERO,
1376            model_attempts: ExecutionCount::ZERO,
1377            model_turns: ExecutionCount::ZERO,
1378            input_tokens: TokenCount::ZERO,
1379            cached_input_tokens: TokenCount::ZERO,
1380            reasoning_tokens: TokenCount::ZERO,
1381            output_tokens: TokenCount::ZERO,
1382            tool_calls: ExecutionCount::ZERO,
1383            write_calls: ExecutionCount::ZERO,
1384            remote_agent_delegations: ExecutionCount::ZERO,
1385            retries: ExecutionCount::ZERO,
1386            concurrent_branches: ExecutionCount::ZERO,
1387            fan_out: ExecutionCount::ZERO,
1388            input_bytes: ByteCount::ZERO,
1389            output_bytes: ByteCount::ZERO,
1390            event_bytes: ByteCount::ZERO,
1391            checkpoint_bytes: ByteCount::ZERO,
1392            artifact_bytes: ByteCount::ZERO,
1393            known_costs: KnownCosts::empty(),
1394            unpriced_cost_events: ExecutionCount::ZERO,
1395        }
1396    }
1397
1398    fn from_builder(builder: BudgetUsageBuilder) -> Result<Self, BudgetUsageError> {
1399        if builder.cached_input_tokens > builder.input_tokens {
1400            return Err(BudgetUsageError::SubsetExceedsInclusive {
1401                subset: BudgetDimension::CachedInputTokens,
1402                inclusive: BudgetDimension::InputTokens,
1403            });
1404        }
1405        if builder.reasoning_tokens > builder.output_tokens {
1406            return Err(BudgetUsageError::SubsetExceedsInclusive {
1407                subset: BudgetDimension::ReasoningTokens,
1408                inclusive: BudgetDimension::OutputTokens,
1409            });
1410        }
1411        if builder.write_calls > builder.tool_calls {
1412            return Err(BudgetUsageError::SubsetExceedsInclusive {
1413                subset: BudgetDimension::WriteCalls,
1414                inclusive: BudgetDimension::ToolCalls,
1415            });
1416        }
1417        Ok(Self {
1418            graph_depth: builder.graph_depth,
1419            graph_steps: builder.graph_steps,
1420            model_attempts: builder.model_attempts,
1421            model_turns: builder.model_turns,
1422            input_tokens: builder.input_tokens,
1423            cached_input_tokens: builder.cached_input_tokens,
1424            reasoning_tokens: builder.reasoning_tokens,
1425            output_tokens: builder.output_tokens,
1426            tool_calls: builder.tool_calls,
1427            write_calls: builder.write_calls,
1428            remote_agent_delegations: builder.remote_agent_delegations,
1429            retries: builder.retries,
1430            concurrent_branches: builder.concurrent_branches,
1431            fan_out: builder.fan_out,
1432            input_bytes: builder.input_bytes,
1433            output_bytes: builder.output_bytes,
1434            event_bytes: builder.event_bytes,
1435            checkpoint_bytes: builder.checkpoint_bytes,
1436            artifact_bytes: builder.artifact_bytes,
1437            known_costs: builder.known_costs,
1438            unpriced_cost_events: builder.unpriced_cost_events,
1439        })
1440    }
1441
1442    /// Monotonically accumulates a validated usage observation or delta.
1443    ///
1444    /// High-water dimensions take their maximum; cumulative dimensions use
1445    /// checked addition. This pure operation does not replace the durable
1446    /// reservation and commit protocol required for parallel execution.
1447    ///
1448    /// # Errors
1449    ///
1450    /// Returns [`BudgetUsageError`] on integer or monetary overflow, or when
1451    /// the union of cost currencies exceeds the hard ceiling.
1452    pub fn checked_accumulate(&self, other: &Self) -> Result<Self, BudgetUsageError> {
1453        Ok(Self {
1454            graph_depth: self.graph_depth.max(other.graph_depth),
1455            graph_steps: add_execution(
1456                self.graph_steps,
1457                other.graph_steps,
1458                BudgetDimension::GraphSteps,
1459            )?,
1460            model_attempts: add_execution(
1461                self.model_attempts,
1462                other.model_attempts,
1463                BudgetDimension::ModelAttempts,
1464            )?,
1465            model_turns: add_execution(
1466                self.model_turns,
1467                other.model_turns,
1468                BudgetDimension::ModelTurns,
1469            )?,
1470            input_tokens: add_tokens(
1471                self.input_tokens,
1472                other.input_tokens,
1473                BudgetDimension::InputTokens,
1474            )?,
1475            cached_input_tokens: add_tokens(
1476                self.cached_input_tokens,
1477                other.cached_input_tokens,
1478                BudgetDimension::CachedInputTokens,
1479            )?,
1480            reasoning_tokens: add_tokens(
1481                self.reasoning_tokens,
1482                other.reasoning_tokens,
1483                BudgetDimension::ReasoningTokens,
1484            )?,
1485            output_tokens: add_tokens(
1486                self.output_tokens,
1487                other.output_tokens,
1488                BudgetDimension::OutputTokens,
1489            )?,
1490            tool_calls: add_execution(
1491                self.tool_calls,
1492                other.tool_calls,
1493                BudgetDimension::ToolCalls,
1494            )?,
1495            write_calls: add_execution(
1496                self.write_calls,
1497                other.write_calls,
1498                BudgetDimension::WriteCalls,
1499            )?,
1500            remote_agent_delegations: add_execution(
1501                self.remote_agent_delegations,
1502                other.remote_agent_delegations,
1503                BudgetDimension::RemoteAgentDelegations,
1504            )?,
1505            retries: add_execution(self.retries, other.retries, BudgetDimension::Retries)?,
1506            concurrent_branches: self.concurrent_branches.max(other.concurrent_branches),
1507            fan_out: self.fan_out.max(other.fan_out),
1508            input_bytes: add_bytes(
1509                self.input_bytes,
1510                other.input_bytes,
1511                BudgetDimension::InputBytes,
1512            )?,
1513            output_bytes: add_bytes(
1514                self.output_bytes,
1515                other.output_bytes,
1516                BudgetDimension::OutputBytes,
1517            )?,
1518            event_bytes: add_bytes(
1519                self.event_bytes,
1520                other.event_bytes,
1521                BudgetDimension::EventBytes,
1522            )?,
1523            checkpoint_bytes: add_bytes(
1524                self.checkpoint_bytes,
1525                other.checkpoint_bytes,
1526                BudgetDimension::CheckpointBytes,
1527            )?,
1528            artifact_bytes: add_bytes(
1529                self.artifact_bytes,
1530                other.artifact_bytes,
1531                BudgetDimension::ArtifactBytes,
1532            )?,
1533            known_costs: self
1534                .known_costs
1535                .checked_accumulate(&other.known_costs)
1536                .map_err(BudgetUsageError::Costs)?,
1537            unpriced_cost_events: add_execution(
1538                self.unpriced_cost_events,
1539                other.unpriced_cost_events,
1540                BudgetDimension::Costs,
1541            )?,
1542        })
1543    }
1544
1545    define_usage_getters!(
1546        (graph_depth, ExecutionCount),
1547        (graph_steps, ExecutionCount),
1548        (model_attempts, ExecutionCount),
1549        (model_turns, ExecutionCount),
1550        (input_tokens, TokenCount),
1551        (cached_input_tokens, TokenCount),
1552        (reasoning_tokens, TokenCount),
1553        (output_tokens, TokenCount),
1554        (tool_calls, ExecutionCount),
1555        (write_calls, ExecutionCount),
1556        (remote_agent_delegations, ExecutionCount),
1557        (retries, ExecutionCount),
1558        (concurrent_branches, ExecutionCount),
1559        (fan_out, ExecutionCount),
1560        (input_bytes, ByteCount),
1561        (output_bytes, ByteCount),
1562        (event_bytes, ByteCount),
1563        (checkpoint_bytes, ByteCount),
1564        (artifact_bytes, ByteCount),
1565        (unpriced_cost_events, ExecutionCount),
1566    );
1567
1568    /// Returns known accumulated charges by currency.
1569    #[must_use]
1570    pub const fn known_costs(&self) -> &KnownCosts {
1571        &self.known_costs
1572    }
1573}
1574
1575impl<'de> Deserialize<'de> for BudgetUsage {
1576    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1577    where
1578        D: Deserializer<'de>,
1579    {
1580        #[derive(Deserialize)]
1581        #[serde(deny_unknown_fields)]
1582        struct Wire {
1583            graph_depth: ExecutionCount,
1584            graph_steps: ExecutionCount,
1585            model_attempts: ExecutionCount,
1586            model_turns: ExecutionCount,
1587            input_tokens: TokenCount,
1588            cached_input_tokens: TokenCount,
1589            reasoning_tokens: TokenCount,
1590            output_tokens: TokenCount,
1591            tool_calls: ExecutionCount,
1592            write_calls: ExecutionCount,
1593            remote_agent_delegations: ExecutionCount,
1594            retries: ExecutionCount,
1595            concurrent_branches: ExecutionCount,
1596            fan_out: ExecutionCount,
1597            input_bytes: ByteCount,
1598            output_bytes: ByteCount,
1599            event_bytes: ByteCount,
1600            checkpoint_bytes: ByteCount,
1601            artifact_bytes: ByteCount,
1602            known_costs: KnownCosts,
1603            unpriced_cost_events: ExecutionCount,
1604        }
1605
1606        let wire = Wire::deserialize(deserializer)?;
1607        BudgetUsageBuilder {
1608            graph_depth: wire.graph_depth,
1609            graph_steps: wire.graph_steps,
1610            model_attempts: wire.model_attempts,
1611            model_turns: wire.model_turns,
1612            input_tokens: wire.input_tokens,
1613            cached_input_tokens: wire.cached_input_tokens,
1614            reasoning_tokens: wire.reasoning_tokens,
1615            output_tokens: wire.output_tokens,
1616            tool_calls: wire.tool_calls,
1617            write_calls: wire.write_calls,
1618            remote_agent_delegations: wire.remote_agent_delegations,
1619            retries: wire.retries,
1620            concurrent_branches: wire.concurrent_branches,
1621            fan_out: wire.fan_out,
1622            input_bytes: wire.input_bytes,
1623            output_bytes: wire.output_bytes,
1624            event_bytes: wire.event_bytes,
1625            checkpoint_bytes: wire.checkpoint_bytes,
1626            artifact_bytes: wire.artifact_bytes,
1627            known_costs: wire.known_costs,
1628            unpriced_cost_events: wire.unpriced_cost_events,
1629        }
1630        .build()
1631        .map_err(de::Error::custom)
1632    }
1633}
1634
1635fn add_execution(
1636    left: ExecutionCount,
1637    right: ExecutionCount,
1638    dimension: BudgetDimension,
1639) -> Result<ExecutionCount, BudgetUsageError> {
1640    left.checked_add(right)
1641        .ok_or(BudgetUsageError::Overflow { dimension })
1642}
1643
1644fn add_tokens(
1645    left: TokenCount,
1646    right: TokenCount,
1647    dimension: BudgetDimension,
1648) -> Result<TokenCount, BudgetUsageError> {
1649    left.checked_add(right)
1650        .ok_or(BudgetUsageError::Overflow { dimension })
1651}
1652
1653fn add_bytes(
1654    left: ByteCount,
1655    right: ByteCount,
1656    dimension: BudgetDimension,
1657) -> Result<ByteCount, BudgetUsageError> {
1658    left.checked_add(right)
1659        .ok_or(BudgetUsageError::Overflow { dimension })
1660}
1661
1662/// Failure while constructing or monotonically accumulating usage.
1663#[derive(Clone, Debug, Eq, Error, PartialEq)]
1664#[non_exhaustive]
1665pub enum BudgetUsageError {
1666    /// A cumulative observation would erase a previously recorded quantity.
1667    #[error("budget usage regressed dimension {dimension:?}")]
1668    Regression {
1669        /// Regressing dimension, including disappeared known monetary charges.
1670        dimension: BudgetDimension,
1671    },
1672    /// Provider-normalized subset usage exceeded its inclusive total.
1673    #[error("usage subset {subset:?} exceeds inclusive usage {inclusive:?}")]
1674    SubsetExceedsInclusive {
1675        /// Subset dimension.
1676        subset: BudgetDimension,
1677        /// Inclusive parent dimension.
1678        inclusive: BudgetDimension,
1679    },
1680
1681    /// Checked arithmetic overflowed in one dimension.
1682    #[error("budget usage overflowed dimension {dimension:?}")]
1683    Overflow {
1684        /// Overflowed dimension.
1685        dimension: BudgetDimension,
1686    },
1687
1688    /// Known costs could not be accumulated safely.
1689    #[error("invalid known cost usage: {0}")]
1690    Costs(CostCollectionError),
1691}
1692
1693/// Remaining finite capacity after evaluating one usage snapshot.
1694///
1695/// This value can only be constructed by [`ResolvedBudget::remaining`]. A
1696/// successful value therefore proves that every observed dimension is within
1697/// its ceiling and every cost event is priced in a configured currency.
1698#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
1699#[serde(deny_unknown_fields)]
1700pub struct BudgetRemaining {
1701    deadline: Timestamp,
1702    graph_depth: ExecutionCount,
1703    graph_steps: ExecutionCount,
1704    model_attempts: ExecutionCount,
1705    model_turns: ExecutionCount,
1706    input_tokens: TokenCount,
1707    cached_input_tokens: TokenCount,
1708    reasoning_tokens: TokenCount,
1709    output_tokens: TokenCount,
1710    tool_calls: ExecutionCount,
1711    write_calls: ExecutionCount,
1712    remote_agent_delegations: ExecutionCount,
1713    retries: ExecutionCount,
1714    concurrent_branches: ExecutionCount,
1715    fan_out: ExecutionCount,
1716    input_bytes: ByteCount,
1717    output_bytes: ByteCount,
1718    event_bytes: ByteCount,
1719    checkpoint_bytes: ByteCount,
1720    artifact_bytes: ByteCount,
1721    costs: CostLimits,
1722}
1723
1724impl ResolvedBudget {
1725    /// Evaluates usage at an explicitly supplied clock observation.
1726    ///
1727    /// The caller supplies `observed_at` so this pure operation is deterministic
1728    /// and a runtime can durably record the clock value that influenced a
1729    /// decision. Equality with the deadline is expired.
1730    ///
1731    /// # Errors
1732    ///
1733    /// Returns [`BudgetEvaluationError`] for an expired deadline, any exceeded
1734    /// scalar ceiling, an unbudgeted currency, or unpriced provider activity.
1735    pub fn remaining(
1736        &self,
1737        usage: &BudgetUsage,
1738        observed_at: Timestamp,
1739    ) -> Result<BudgetRemaining, BudgetEvaluationError> {
1740        if observed_at >= self.deadline {
1741            return Err(BudgetEvaluationError::DeadlineExceeded {
1742                deadline: self.deadline,
1743                observed_at,
1744            });
1745        }
1746
1747        Ok(BudgetRemaining {
1748            deadline: self.deadline,
1749            graph_depth: remaining_execution(
1750                BudgetDimension::GraphDepth,
1751                self.graph_depth,
1752                usage.graph_depth,
1753            )?,
1754            graph_steps: remaining_execution(
1755                BudgetDimension::GraphSteps,
1756                self.graph_steps,
1757                usage.graph_steps,
1758            )?,
1759            model_attempts: remaining_execution(
1760                BudgetDimension::ModelAttempts,
1761                self.model_attempts,
1762                usage.model_attempts,
1763            )?,
1764            model_turns: remaining_execution(
1765                BudgetDimension::ModelTurns,
1766                self.model_turns,
1767                usage.model_turns,
1768            )?,
1769            input_tokens: remaining_tokens(
1770                BudgetDimension::InputTokens,
1771                self.input_tokens,
1772                usage.input_tokens,
1773            )?,
1774            cached_input_tokens: remaining_tokens(
1775                BudgetDimension::CachedInputTokens,
1776                self.cached_input_tokens,
1777                usage.cached_input_tokens,
1778            )?,
1779            reasoning_tokens: remaining_tokens(
1780                BudgetDimension::ReasoningTokens,
1781                self.reasoning_tokens,
1782                usage.reasoning_tokens,
1783            )?,
1784            output_tokens: remaining_tokens(
1785                BudgetDimension::OutputTokens,
1786                self.output_tokens,
1787                usage.output_tokens,
1788            )?,
1789            tool_calls: remaining_execution(
1790                BudgetDimension::ToolCalls,
1791                self.tool_calls,
1792                usage.tool_calls,
1793            )?,
1794            write_calls: remaining_execution(
1795                BudgetDimension::WriteCalls,
1796                self.write_calls,
1797                usage.write_calls,
1798            )?,
1799            remote_agent_delegations: remaining_execution(
1800                BudgetDimension::RemoteAgentDelegations,
1801                self.remote_agent_delegations,
1802                usage.remote_agent_delegations,
1803            )?,
1804            retries: remaining_execution(BudgetDimension::Retries, self.retries, usage.retries)?,
1805            concurrent_branches: remaining_execution(
1806                BudgetDimension::ConcurrentBranches,
1807                self.concurrent_branches,
1808                usage.concurrent_branches,
1809            )?,
1810            fan_out: remaining_execution(BudgetDimension::FanOut, self.fan_out, usage.fan_out)?,
1811            input_bytes: remaining_bytes(
1812                BudgetDimension::InputBytes,
1813                self.input_bytes,
1814                usage.input_bytes,
1815            )?,
1816            output_bytes: remaining_bytes(
1817                BudgetDimension::OutputBytes,
1818                self.output_bytes,
1819                usage.output_bytes,
1820            )?,
1821            event_bytes: remaining_bytes(
1822                BudgetDimension::EventBytes,
1823                self.event_bytes,
1824                usage.event_bytes,
1825            )?,
1826            checkpoint_bytes: remaining_bytes(
1827                BudgetDimension::CheckpointBytes,
1828                self.checkpoint_bytes,
1829                usage.checkpoint_bytes,
1830            )?,
1831            artifact_bytes: remaining_bytes(
1832                BudgetDimension::ArtifactBytes,
1833                self.artifact_bytes,
1834                usage.artifact_bytes,
1835            )?,
1836            costs: remaining_costs(&self.costs, usage)?,
1837        })
1838    }
1839}
1840
1841macro_rules! define_remaining_getters {
1842    ($(($field:ident, $type:ty)),+ $(,)?) => {
1843        $(
1844            #[doc = concat!("Returns remaining `", stringify!($field), "` capacity.")]
1845            #[must_use]
1846            pub const fn $field(&self) -> $type {
1847                self.$field
1848            }
1849        )+
1850    };
1851}
1852
1853impl BudgetRemaining {
1854    /// Deducts additional verified cumulative charges from this already evaluated capacity.
1855    /// Topology peaks and deadline are unchanged; unknown costs and underflow fail closed.
1856    /// The caller must ensure these charges were not included in the original observation.
1857    pub fn deduct_cumulative(&self, usage: &BudgetUsage) -> Result<Self, BudgetEvaluationError> {
1858        Ok(Self {
1859            graph_steps: remaining_execution(
1860                BudgetDimension::GraphSteps,
1861                self.graph_steps,
1862                usage.graph_steps,
1863            )?,
1864            model_attempts: remaining_execution(
1865                BudgetDimension::ModelAttempts,
1866                self.model_attempts,
1867                usage.model_attempts,
1868            )?,
1869            model_turns: remaining_execution(
1870                BudgetDimension::ModelTurns,
1871                self.model_turns,
1872                usage.model_turns,
1873            )?,
1874            input_tokens: remaining_tokens(
1875                BudgetDimension::InputTokens,
1876                self.input_tokens,
1877                usage.input_tokens,
1878            )?,
1879            cached_input_tokens: remaining_tokens(
1880                BudgetDimension::CachedInputTokens,
1881                self.cached_input_tokens,
1882                usage.cached_input_tokens,
1883            )?,
1884            reasoning_tokens: remaining_tokens(
1885                BudgetDimension::ReasoningTokens,
1886                self.reasoning_tokens,
1887                usage.reasoning_tokens,
1888            )?,
1889            output_tokens: remaining_tokens(
1890                BudgetDimension::OutputTokens,
1891                self.output_tokens,
1892                usage.output_tokens,
1893            )?,
1894            tool_calls: remaining_execution(
1895                BudgetDimension::ToolCalls,
1896                self.tool_calls,
1897                usage.tool_calls,
1898            )?,
1899            write_calls: remaining_execution(
1900                BudgetDimension::WriteCalls,
1901                self.write_calls,
1902                usage.write_calls,
1903            )?,
1904            remote_agent_delegations: remaining_execution(
1905                BudgetDimension::RemoteAgentDelegations,
1906                self.remote_agent_delegations,
1907                usage.remote_agent_delegations,
1908            )?,
1909            retries: remaining_execution(BudgetDimension::Retries, self.retries, usage.retries)?,
1910            input_bytes: remaining_bytes(
1911                BudgetDimension::InputBytes,
1912                self.input_bytes,
1913                usage.input_bytes,
1914            )?,
1915            output_bytes: remaining_bytes(
1916                BudgetDimension::OutputBytes,
1917                self.output_bytes,
1918                usage.output_bytes,
1919            )?,
1920            event_bytes: remaining_bytes(
1921                BudgetDimension::EventBytes,
1922                self.event_bytes,
1923                usage.event_bytes,
1924            )?,
1925            checkpoint_bytes: remaining_bytes(
1926                BudgetDimension::CheckpointBytes,
1927                self.checkpoint_bytes,
1928                usage.checkpoint_bytes,
1929            )?,
1930            artifact_bytes: remaining_bytes(
1931                BudgetDimension::ArtifactBytes,
1932                self.artifact_bytes,
1933                usage.artifact_bytes,
1934            )?,
1935            costs: remaining_costs(&self.costs, usage)?,
1936            ..self.clone()
1937        })
1938    }
1939
1940    /// Returns the absolute deadline used by this remaining-capacity view.
1941    #[must_use]
1942    pub const fn deadline(&self) -> Timestamp {
1943        self.deadline
1944    }
1945
1946    define_remaining_getters!(
1947        (graph_depth, ExecutionCount),
1948        (graph_steps, ExecutionCount),
1949        (model_attempts, ExecutionCount),
1950        (model_turns, ExecutionCount),
1951        (input_tokens, TokenCount),
1952        (cached_input_tokens, TokenCount),
1953        (reasoning_tokens, TokenCount),
1954        (output_tokens, TokenCount),
1955        (tool_calls, ExecutionCount),
1956        (write_calls, ExecutionCount),
1957        (remote_agent_delegations, ExecutionCount),
1958        (retries, ExecutionCount),
1959        (concurrent_branches, ExecutionCount),
1960        (fan_out, ExecutionCount),
1961        (input_bytes, ByteCount),
1962        (output_bytes, ByteCount),
1963        (event_bytes, ByteCount),
1964        (checkpoint_bytes, ByteCount),
1965        (artifact_bytes, ByteCount),
1966    );
1967
1968    /// Returns known remaining monetary capacity by configured currency.
1969    #[must_use]
1970    pub const fn costs(&self) -> &CostLimits {
1971        &self.costs
1972    }
1973}
1974
1975fn remaining_execution(
1976    dimension: BudgetDimension,
1977    limit: ExecutionCount,
1978    actual: ExecutionCount,
1979) -> Result<ExecutionCount, BudgetEvaluationError> {
1980    limit
1981        .checked_sub(actual)
1982        .ok_or(BudgetEvaluationError::ExecutionLimitExceeded {
1983            dimension,
1984            limit,
1985            actual,
1986        })
1987}
1988
1989fn remaining_tokens(
1990    dimension: BudgetDimension,
1991    limit: TokenCount,
1992    actual: TokenCount,
1993) -> Result<TokenCount, BudgetEvaluationError> {
1994    limit
1995        .checked_sub(actual)
1996        .ok_or(BudgetEvaluationError::TokenLimitExceeded {
1997            dimension,
1998            limit,
1999            actual,
2000        })
2001}
2002
2003fn remaining_bytes(
2004    dimension: BudgetDimension,
2005    limit: ByteCount,
2006    actual: ByteCount,
2007) -> Result<ByteCount, BudgetEvaluationError> {
2008    limit
2009        .checked_sub(actual)
2010        .ok_or(BudgetEvaluationError::ByteLimitExceeded {
2011            dimension,
2012            limit,
2013            actual,
2014        })
2015}
2016
2017fn remaining_costs(
2018    limits: &CostLimits,
2019    usage: &BudgetUsage,
2020) -> Result<CostLimits, BudgetEvaluationError> {
2021    for actual in usage.known_costs.iter().copied() {
2022        let limit =
2023            limits
2024                .get(actual.currency())
2025                .ok_or(BudgetEvaluationError::UnbudgetedCurrency {
2026                    currency: actual.currency(),
2027                })?;
2028        if actual.micro_units() > limit.micro_units() {
2029            return Err(BudgetEvaluationError::CostLimitExceeded { limit, actual });
2030        }
2031    }
2032    if usage.unpriced_cost_events != ExecutionCount::ZERO {
2033        return Err(BudgetEvaluationError::UnpricedCost {
2034            events: usage.unpriced_cost_events,
2035        });
2036    }
2037
2038    let remaining = limits
2039        .iter()
2040        .map(|limit| {
2041            let actual = usage
2042                .known_costs
2043                .get(limit.currency())
2044                .map_or(0, Money::micro_units);
2045            Money::new(limit.currency(), limit.micro_units() - actual)
2046        })
2047        .collect::<Vec<_>>()
2048        .into_boxed_slice();
2049    Ok(CostLimits(remaining))
2050}
2051
2052/// Failure while evaluating a complete budget against usage.
2053#[derive(Clone, Debug, Eq, Error, PartialEq)]
2054#[non_exhaustive]
2055pub enum BudgetEvaluationError {
2056    /// The clock reached or passed the absolute deadline.
2057    #[error("budget deadline {deadline} was reached at {observed_at}")]
2058    DeadlineExceeded {
2059        /// Resolved absolute deadline.
2060        deadline: Timestamp,
2061        /// Clock value used for the deterministic decision.
2062        observed_at: Timestamp,
2063    },
2064
2065    /// An execution-count ceiling was exceeded.
2066    #[error("budget dimension {dimension:?} used {actual}; limit is {limit}")]
2067    ExecutionLimitExceeded {
2068        /// Exceeded dimension.
2069        dimension: BudgetDimension,
2070        /// Resolved finite ceiling.
2071        limit: ExecutionCount,
2072        /// Observed usage.
2073        actual: ExecutionCount,
2074    },
2075
2076    /// A token ceiling was exceeded.
2077    #[error("budget dimension {dimension:?} used {actual}; limit is {limit}")]
2078    TokenLimitExceeded {
2079        /// Exceeded dimension.
2080        dimension: BudgetDimension,
2081        /// Resolved finite ceiling.
2082        limit: TokenCount,
2083        /// Observed usage.
2084        actual: TokenCount,
2085    },
2086
2087    /// A byte ceiling was exceeded.
2088    #[error("budget dimension {dimension:?} used {actual}; limit is {limit}")]
2089    ByteLimitExceeded {
2090        /// Exceeded dimension.
2091        dimension: BudgetDimension,
2092        /// Resolved finite ceiling.
2093        limit: ByteCount,
2094        /// Observed usage.
2095        actual: ByteCount,
2096    },
2097
2098    /// Known charge exceeded its same-currency ceiling.
2099    #[error("known cost {actual:?} exceeds budget limit {limit:?}")]
2100    CostLimitExceeded {
2101        /// Resolved same-currency ceiling.
2102        limit: Money,
2103        /// Observed known charge.
2104        actual: Money,
2105    },
2106
2107    /// A known charge used a currency absent from the resolved budget.
2108    #[error("known cost uses unbudgeted currency {currency}")]
2109    UnbudgetedCurrency {
2110        /// Currency not present in the resolved budget.
2111        currency: CurrencyCode,
2112    },
2113
2114    /// At least one cost-bearing event could not be priced.
2115    #[error("remaining monetary budget is indeterminate after {events} unpriced events")]
2116    UnpricedCost {
2117        /// Number of provider or capability events without known cost.
2118        events: ExecutionCount,
2119    },
2120}
2121
2122#[cfg(test)]
2123mod tests {
2124    use super::*;
2125    use proptest::prelude::*;
2126    use serde_json::{Value, from_value, json, to_value};
2127
2128    fn timestamp(value: &str) -> Timestamp {
2129        value.parse().unwrap()
2130    }
2131
2132    fn currency(index: usize) -> CurrencyCode {
2133        let first = u8::try_from(index / (26 * 26)).unwrap();
2134        let second = u8::try_from((index / 26) % 26).unwrap();
2135        let third = u8::try_from(index % 26).unwrap();
2136        CurrencyCode::new([b'A' + first, b'A' + second, b'A' + third]).unwrap()
2137    }
2138
2139    fn usd() -> CurrencyCode {
2140        "USD".parse().unwrap()
2141    }
2142
2143    fn eur() -> CurrencyCode {
2144        "EUR".parse().unwrap()
2145    }
2146
2147    fn full_limits(value: u64) -> BudgetLimits {
2148        let executions = ExecutionCount::new(value);
2149        let tokens = TokenCount::new(value);
2150        let bytes = ByteCount::new(value);
2151        BudgetLimits::empty()
2152            .with_deadline(timestamp("2030-01-01T00:00:00.000000Z"))
2153            .with_graph_depth(executions)
2154            .with_graph_steps(executions)
2155            .with_model_attempts(executions)
2156            .with_model_turns(executions)
2157            .with_input_tokens(tokens)
2158            .with_cached_input_tokens(tokens)
2159            .with_reasoning_tokens(tokens)
2160            .with_output_tokens(tokens)
2161            .with_tool_calls(executions)
2162            .with_write_calls(executions)
2163            .with_remote_agent_delegations(executions)
2164            .with_retries(executions)
2165            .with_concurrent_branches(executions)
2166            .with_fan_out(executions)
2167            .with_input_bytes(bytes)
2168            .with_output_bytes(bytes)
2169            .with_event_bytes(bytes)
2170            .with_checkpoint_bytes(bytes)
2171            .with_artifact_bytes(bytes)
2172            .with_costs(CostLimits::try_new([Money::new(usd(), value)]).unwrap())
2173    }
2174
2175    fn resolved(value: u64) -> ResolvedBudget {
2176        ResolvedBudget::resolve(&[full_limits(value)]).unwrap()
2177    }
2178
2179    #[test]
2180    fn cumulative_deduction_preserves_topology_and_independent_remaining_subsets() {
2181        let direct = BudgetUsage::builder()
2182            .input_tokens(TokenCount::new(80))
2183            .graph_depth(ExecutionCount::new(3))
2184            .build()
2185            .unwrap();
2186        let child = BudgetUsage::builder()
2187            .input_tokens(TokenCount::new(10))
2188            .cached_input_tokens(TokenCount::new(5))
2189            .graph_depth(ExecutionCount::new(99))
2190            .known_costs(KnownCosts::try_new([Money::new(usd(), 7)]).unwrap())
2191            .build()
2192            .unwrap();
2193        let remaining = resolved(100)
2194            .remaining(&direct, timestamp("2029-01-01T00:00:00.000000Z"))
2195            .unwrap();
2196        let deducted = remaining.deduct_cumulative(&child).unwrap();
2197        assert_eq!(deducted.input_tokens(), TokenCount::new(10));
2198        assert_eq!(deducted.cached_input_tokens(), TokenCount::new(95));
2199        assert_eq!(deducted.graph_depth(), remaining.graph_depth());
2200        assert_eq!(deducted.costs().get(usd()).unwrap().micro_units(), 93);
2201        let total = direct.checked_accumulate(&child.cumulative_only()).unwrap();
2202        let recovered = total.checked_subtract_cumulative(&child).unwrap();
2203        assert_eq!(recovered.input_tokens(), direct.input_tokens());
2204        assert_eq!(recovered.graph_depth(), direct.graph_depth());
2205        assert_eq!(recovered.known_costs().get(usd()).unwrap().micro_units(), 0);
2206        assert!(direct.checked_subtract_cumulative(&child).is_err());
2207        assert!(deducted.deduct_cumulative(&direct).is_err());
2208        let unknown = BudgetUsage::builder()
2209            .unpriced_cost_events(ExecutionCount::new(1))
2210            .build()
2211            .unwrap();
2212        assert!(remaining.deduct_cumulative(&unknown).is_err());
2213        let wrong_currency = BudgetUsage::builder()
2214            .known_costs(KnownCosts::try_new([Money::new(eur(), 1)]).unwrap())
2215            .build()
2216            .unwrap();
2217        assert!(remaining.deduct_cumulative(&wrong_currency).is_err());
2218    }
2219
2220    #[test]
2221    fn cumulative_subtraction_refuses_inconsistent_residual_subsets() {
2222        let total = BudgetUsage::builder()
2223            .input_tokens(TokenCount::new(10))
2224            .cached_input_tokens(TokenCount::new(9))
2225            .build()
2226            .unwrap();
2227        let child = BudgetUsage::builder()
2228            .input_tokens(TokenCount::new(5))
2229            .build()
2230            .unwrap();
2231        assert!(matches!(
2232            total.checked_subtract_cumulative(&child),
2233            Err(BudgetUsageError::SubsetExceedsInclusive { .. })
2234        ));
2235    }
2236
2237    #[test]
2238    fn narrowing_checks_every_scalar_without_clamping() {
2239        let parent_wire = to_value(resolved(100)).unwrap();
2240        for field in parent_wire
2241            .as_object()
2242            .unwrap()
2243            .keys()
2244            .filter(|key| *key != "costs")
2245        {
2246            let mut parent = parent_wire.clone();
2247            let mut child = to_value(resolved(50)).unwrap();
2248            let inclusive = match field.as_str() {
2249                "cached_input_tokens" => Some("input_tokens"),
2250                "reasoning_tokens" => Some("output_tokens"),
2251                "write_calls" => Some("tool_calls"),
2252                _ => None,
2253            };
2254            if let Some(inclusive) = inclusive {
2255                parent[inclusive] = json!("200");
2256                child[inclusive] = json!("200");
2257            }
2258            child[field] = if field == "deadline" {
2259                json!("2030-01-01T00:00:00.000001Z")
2260            } else {
2261                json!("101")
2262            };
2263            let child: ResolvedBudget = from_value(child).unwrap();
2264            let parent: ResolvedBudget = from_value(parent).unwrap();
2265            assert_eq!(
2266                child.validate_narrowing(&parent),
2267                Err(BudgetNarrowingError::Widened {
2268                    dimension: from_value(json!(field)).unwrap(),
2269                }),
2270                "{field}"
2271            );
2272        }
2273    }
2274
2275    #[test]
2276    fn narrowing_preserves_equality_zero_and_currency_denial() {
2277        let parent = resolved(100);
2278        assert!(parent.validate_narrowing(&parent).is_ok());
2279        assert!(resolved(0).validate_narrowing(&parent).is_ok());
2280        for amount in [0, 1] {
2281            let child = ResolvedBudget::resolve(&[full_limits(50)
2282                .with_costs(CostLimits::try_new([Money::new(eur(), amount)]).unwrap())])
2283            .unwrap();
2284            assert_eq!(
2285                child.validate_narrowing(&parent),
2286                Err(BudgetNarrowingError::UnbudgetedCurrency { currency: eur() })
2287            );
2288        }
2289        let child = ResolvedBudget::resolve(&[
2290            full_limits(50).with_costs(CostLimits::try_new([Money::new(usd(), 101)]).unwrap())
2291        ])
2292        .unwrap();
2293        assert_eq!(
2294            child.validate_narrowing(&parent),
2295            Err(BudgetNarrowingError::CostWidened { currency: usd() })
2296        );
2297        let child =
2298            ResolvedBudget::resolve(&[full_limits(50).with_costs(CostLimits::default())]).unwrap();
2299        assert!(child.validate_narrowing(&parent).is_ok());
2300    }
2301
2302    #[test]
2303    fn cost_collections_are_sorted_unique_bounded_and_exact() {
2304        let limits = CostLimits::try_new([Money::new(usd(), 20), Money::new(eur(), 10)]).unwrap();
2305        assert_eq!(limits.len(), 2);
2306        assert!(!limits.is_empty());
2307        assert_eq!(limits.get(usd()), Some(Money::new(usd(), 20)));
2308        assert_eq!(limits.get("JPY".parse().unwrap()), None);
2309        assert_eq!(
2310            to_value(&limits).unwrap(),
2311            json!([
2312                {"currency": "EUR", "micro_units": "10"},
2313                {"currency": "USD", "micro_units": "20"}
2314            ])
2315        );
2316        assert_eq!(
2317            from_value::<CostLimits>(to_value(&limits).unwrap()).unwrap(),
2318            limits
2319        );
2320
2321        assert!(CostLimits::try_new([]).unwrap().is_empty());
2322        assert_eq!(KnownCosts::try_new([]).unwrap(), KnownCosts::empty());
2323        assert_eq!(
2324            CostLimits::try_new([Money::new(usd(), 1), Money::new(usd(), 2)]),
2325            Err(CostCollectionError::DuplicateCurrency { currency: usd() })
2326        );
2327        assert!(
2328            from_value::<KnownCosts>(json!([
2329                {"currency": "USD", "micro_units": "1"},
2330                {"currency": "USD", "micro_units": "2"}
2331            ]))
2332            .is_err()
2333        );
2334
2335        let too_many = (0..=MAX_COST_CURRENCIES)
2336            .map(|index| Money::new(currency(index), 1))
2337            .collect::<Vec<_>>();
2338        assert_eq!(
2339            CostLimits::try_new(too_many.clone()),
2340            Err(CostCollectionError::TooMany {
2341                max: MAX_COST_CURRENCIES,
2342                observed: MAX_COST_CURRENCIES + 1,
2343            })
2344        );
2345        assert!(from_value::<KnownCosts>(to_value(too_many).unwrap()).is_err());
2346    }
2347
2348    #[test]
2349    fn cost_intersection_takes_per_currency_minimum_without_conversion() {
2350        let left = CostLimits::try_new([Money::new(usd(), 100), Money::new(eur(), 200)]).unwrap();
2351        let right = CostLimits::try_new([Money::new(usd(), 80)]).unwrap();
2352        let effective = left.most_restrictive(&right);
2353
2354        assert_eq!(effective.get(usd()), Some(Money::new(usd(), 80)));
2355        assert_eq!(effective.get(eur()), None);
2356        assert_eq!(left.most_restrictive(&right), right.most_restrictive(&left));
2357    }
2358
2359    #[test]
2360    fn resolution_requires_every_finite_dimension_and_is_order_independent() {
2361        assert_eq!(
2362            ResolvedBudget::resolve(&[]),
2363            Err(BudgetResolutionError::EmptyLayers)
2364        );
2365        assert_eq!(
2366            ResolvedBudget::resolve(&vec![BudgetLimits::empty(); MAX_BUDGET_LAYERS + 1]),
2367            Err(BudgetResolutionError::TooManyLayers {
2368                max: MAX_BUDGET_LAYERS,
2369                actual: MAX_BUDGET_LAYERS + 1,
2370            })
2371        );
2372
2373        let mut missing = full_limits(100);
2374        missing.artifact_bytes = None;
2375        assert_eq!(
2376            ResolvedBudget::resolve(&[missing]),
2377            Err(BudgetResolutionError::Missing {
2378                dimension: BudgetDimension::ArtifactBytes,
2379            })
2380        );
2381
2382        let system = full_limits(100);
2383        let tenant = BudgetLimits::empty()
2384            .with_deadline(timestamp("2029-01-01T00:00:00.000000Z"))
2385            .with_graph_steps(ExecutionCount::new(60))
2386            .with_input_tokens(TokenCount::new(50))
2387            .with_cached_input_tokens(TokenCount::new(90))
2388            .with_output_tokens(TokenCount::new(40))
2389            .with_reasoning_tokens(TokenCount::new(80))
2390            .with_tool_calls(ExecutionCount::new(20))
2391            .with_write_calls(ExecutionCount::new(30))
2392            .with_costs(CostLimits::try_new([Money::new(usd(), 70)]).unwrap());
2393        let forward = ResolvedBudget::resolve(&[system.clone(), tenant.clone()]).unwrap();
2394        let reverse = ResolvedBudget::resolve(&[tenant, system]).unwrap();
2395
2396        assert_eq!(forward, reverse);
2397        assert_eq!(forward.deadline(), timestamp("2029-01-01T00:00:00.000000Z"));
2398        assert_eq!(forward.graph_steps(), ExecutionCount::new(60));
2399        assert_eq!(forward.input_tokens(), TokenCount::new(50));
2400        assert_eq!(forward.cached_input_tokens(), TokenCount::new(50));
2401        assert_eq!(forward.output_tokens(), TokenCount::new(40));
2402        assert_eq!(forward.reasoning_tokens(), TokenCount::new(40));
2403        assert_eq!(forward.tool_calls(), ExecutionCount::new(20));
2404        assert_eq!(forward.write_calls(), ExecutionCount::new(20));
2405        assert_eq!(forward.costs().get(usd()), Some(Money::new(usd(), 70)));
2406    }
2407
2408    #[test]
2409    fn resolved_budget_wire_rejects_subset_confusion_and_unknown_fields() {
2410        let budget = resolved(100);
2411        let encoded = to_value(&budget).unwrap();
2412        assert_eq!(
2413            from_value::<ResolvedBudget>(encoded.clone()).unwrap(),
2414            budget
2415        );
2416
2417        let mut cached_too_large = encoded.clone();
2418        cached_too_large["input_tokens"] = json!("10");
2419        cached_too_large["cached_input_tokens"] = json!("11");
2420        assert!(from_value::<ResolvedBudget>(cached_too_large).is_err());
2421
2422        let mut reasoning_too_large = encoded.clone();
2423        reasoning_too_large["output_tokens"] = json!("10");
2424        reasoning_too_large["reasoning_tokens"] = json!("11");
2425        assert!(from_value::<ResolvedBudget>(reasoning_too_large).is_err());
2426
2427        let mut writes_too_large = encoded.clone();
2428        writes_too_large["tool_calls"] = json!("10");
2429        writes_too_large["write_calls"] = json!("11");
2430        assert!(from_value::<ResolvedBudget>(writes_too_large).is_err());
2431
2432        let mut unknown = encoded;
2433        unknown["unlimited"] = Value::Bool(true);
2434        assert!(from_value::<ResolvedBudget>(unknown).is_err());
2435    }
2436
2437    #[test]
2438    fn usage_builder_enforces_normalized_subset_relationships() {
2439        assert_eq!(BudgetUsage::zero(), BudgetUsage::builder().build().unwrap());
2440        assert_eq!(
2441            BudgetUsage::builder()
2442                .input_tokens(TokenCount::new(1))
2443                .cached_input_tokens(TokenCount::new(2))
2444                .build(),
2445            Err(BudgetUsageError::SubsetExceedsInclusive {
2446                subset: BudgetDimension::CachedInputTokens,
2447                inclusive: BudgetDimension::InputTokens,
2448            })
2449        );
2450        assert_eq!(
2451            BudgetUsage::builder()
2452                .output_tokens(TokenCount::new(1))
2453                .reasoning_tokens(TokenCount::new(2))
2454                .build(),
2455            Err(BudgetUsageError::SubsetExceedsInclusive {
2456                subset: BudgetDimension::ReasoningTokens,
2457                inclusive: BudgetDimension::OutputTokens,
2458            })
2459        );
2460        assert_eq!(
2461            BudgetUsage::builder()
2462                .tool_calls(ExecutionCount::new(1))
2463                .write_calls(ExecutionCount::new(2))
2464                .build(),
2465            Err(BudgetUsageError::SubsetExceedsInclusive {
2466                subset: BudgetDimension::WriteCalls,
2467                inclusive: BudgetDimension::ToolCalls,
2468            })
2469        );
2470    }
2471
2472    #[test]
2473    fn usage_accumulation_adds_totals_and_merges_high_water_marks() {
2474        let left = BudgetUsage::builder()
2475            .graph_depth(ExecutionCount::new(3))
2476            .graph_steps(ExecutionCount::new(5))
2477            .model_attempts(ExecutionCount::new(1))
2478            .model_turns(ExecutionCount::new(1))
2479            .input_tokens(TokenCount::new(20))
2480            .cached_input_tokens(TokenCount::new(5))
2481            .reasoning_tokens(TokenCount::new(2))
2482            .output_tokens(TokenCount::new(8))
2483            .tool_calls(ExecutionCount::new(2))
2484            .write_calls(ExecutionCount::new(1))
2485            .concurrent_branches(ExecutionCount::new(4))
2486            .fan_out(ExecutionCount::new(3))
2487            .known_costs(KnownCosts::try_new([Money::new(usd(), 10)]).unwrap())
2488            .build()
2489            .unwrap();
2490        let right = BudgetUsage::builder()
2491            .graph_depth(ExecutionCount::new(2))
2492            .graph_steps(ExecutionCount::new(7))
2493            .model_attempts(ExecutionCount::new(2))
2494            .model_turns(ExecutionCount::new(1))
2495            .input_tokens(TokenCount::new(30))
2496            .cached_input_tokens(TokenCount::new(10))
2497            .reasoning_tokens(TokenCount::new(3))
2498            .output_tokens(TokenCount::new(9))
2499            .tool_calls(ExecutionCount::new(3))
2500            .write_calls(ExecutionCount::new(1))
2501            .concurrent_branches(ExecutionCount::new(6))
2502            .fan_out(ExecutionCount::new(2))
2503            .known_costs(
2504                KnownCosts::try_new([Money::new(usd(), 15), Money::new(eur(), 4)]).unwrap(),
2505            )
2506            .unpriced_cost_events(ExecutionCount::new(1))
2507            .build()
2508            .unwrap();
2509        let total = left.checked_accumulate(&right).unwrap();
2510
2511        assert_eq!(total.graph_depth(), ExecutionCount::new(3));
2512        assert_eq!(total.graph_steps(), ExecutionCount::new(12));
2513        assert_eq!(total.model_attempts(), ExecutionCount::new(3));
2514        assert_eq!(total.input_tokens(), TokenCount::new(50));
2515        assert_eq!(total.cached_input_tokens(), TokenCount::new(15));
2516        assert_eq!(total.reasoning_tokens(), TokenCount::new(5));
2517        assert_eq!(total.output_tokens(), TokenCount::new(17));
2518        assert_eq!(total.tool_calls(), ExecutionCount::new(5));
2519        assert_eq!(total.write_calls(), ExecutionCount::new(2));
2520        assert_eq!(total.concurrent_branches(), ExecutionCount::new(6));
2521        assert_eq!(total.fan_out(), ExecutionCount::new(3));
2522        assert_eq!(total.known_costs().get(usd()), Some(Money::new(usd(), 25)));
2523        assert_eq!(total.known_costs().get(eur()), Some(Money::new(eur(), 4)));
2524        assert_eq!(total.unpriced_cost_events(), ExecutionCount::new(1));
2525
2526        let cost_overflow = BudgetUsage::builder()
2527            .known_costs(KnownCosts::try_new([Money::new(usd(), u64::MAX)]).unwrap())
2528            .build()
2529            .unwrap()
2530            .checked_accumulate(
2531                &BudgetUsage::builder()
2532                    .known_costs(KnownCosts::try_new([Money::new(usd(), 1)]).unwrap())
2533                    .build()
2534                    .unwrap(),
2535            );
2536        assert_eq!(
2537            cost_overflow,
2538            Err(BudgetUsageError::Costs(CostCollectionError::Overflow {
2539                currency: usd(),
2540            }))
2541        );
2542
2543        let overflow = BudgetUsage::builder()
2544            .graph_steps(ExecutionCount::MAX)
2545            .build()
2546            .unwrap()
2547            .checked_accumulate(
2548                &BudgetUsage::builder()
2549                    .graph_steps(ExecutionCount::new(1))
2550                    .build()
2551                    .unwrap(),
2552            );
2553        assert_eq!(
2554            overflow,
2555            Err(BudgetUsageError::Overflow {
2556                dimension: BudgetDimension::GraphSteps,
2557            })
2558        );
2559    }
2560
2561    #[test]
2562    fn usage_wire_is_closed_and_revalidates_normalized_totals() {
2563        let usage = BudgetUsage::builder()
2564            .input_tokens(TokenCount::new(10))
2565            .cached_input_tokens(TokenCount::new(4))
2566            .output_tokens(TokenCount::new(8))
2567            .reasoning_tokens(TokenCount::new(3))
2568            .tool_calls(ExecutionCount::new(2))
2569            .write_calls(ExecutionCount::new(1))
2570            .known_costs(KnownCosts::try_new([Money::new(usd(), 5)]).unwrap())
2571            .build()
2572            .unwrap();
2573        let encoded = to_value(&usage).unwrap();
2574        assert_eq!(from_value::<BudgetUsage>(encoded.clone()).unwrap(), usage);
2575
2576        let mut invalid = encoded.clone();
2577        invalid["input_tokens"] = json!("1");
2578        assert!(from_value::<BudgetUsage>(invalid).is_err());
2579
2580        let mut unknown = encoded;
2581        unknown["extra"] = Value::Null;
2582        assert!(from_value::<BudgetUsage>(unknown).is_err());
2583    }
2584
2585    #[test]
2586    fn remaining_is_exact_and_unknown_cost_fails_closed() {
2587        let budget = resolved(100);
2588        let usage = BudgetUsage::builder()
2589            .graph_depth(ExecutionCount::new(4))
2590            .graph_steps(ExecutionCount::new(10))
2591            .model_attempts(ExecutionCount::new(2))
2592            .model_turns(ExecutionCount::new(1))
2593            .input_tokens(TokenCount::new(30))
2594            .cached_input_tokens(TokenCount::new(8))
2595            .reasoning_tokens(TokenCount::new(7))
2596            .output_tokens(TokenCount::new(20))
2597            .tool_calls(ExecutionCount::new(5))
2598            .write_calls(ExecutionCount::new(2))
2599            .input_bytes(ByteCount::new(40))
2600            .known_costs(KnownCosts::try_new([Money::new(usd(), 25)]).unwrap())
2601            .build()
2602            .unwrap();
2603        let remaining = budget
2604            .remaining(&usage, timestamp("2029-01-01T00:00:00.000000Z"))
2605            .unwrap();
2606
2607        assert_eq!(remaining.graph_depth(), ExecutionCount::new(96));
2608        assert_eq!(remaining.graph_steps(), ExecutionCount::new(90));
2609        assert_eq!(remaining.input_tokens(), TokenCount::new(70));
2610        assert_eq!(remaining.cached_input_tokens(), TokenCount::new(92));
2611        assert_eq!(remaining.reasoning_tokens(), TokenCount::new(93));
2612        assert_eq!(remaining.output_tokens(), TokenCount::new(80));
2613        assert_eq!(remaining.tool_calls(), ExecutionCount::new(95));
2614        assert_eq!(remaining.write_calls(), ExecutionCount::new(98));
2615        assert_eq!(remaining.input_bytes(), ByteCount::new(60));
2616        assert_eq!(remaining.costs().get(usd()), Some(Money::new(usd(), 75)));
2617
2618        let unpriced = BudgetUsage::builder()
2619            .unpriced_cost_events(ExecutionCount::new(1))
2620            .build()
2621            .unwrap();
2622        assert_eq!(
2623            budget.remaining(&unpriced, timestamp("2029-01-01T00:00:00.000000Z")),
2624            Err(BudgetEvaluationError::UnpricedCost {
2625                events: ExecutionCount::new(1),
2626            })
2627        );
2628    }
2629
2630    #[test]
2631    fn evaluation_reports_deadline_scalar_and_currency_failures() {
2632        let budget = resolved(10);
2633        assert_eq!(
2634            budget.remaining(
2635                &BudgetUsage::zero(),
2636                timestamp("2030-01-01T00:00:00.000000Z")
2637            ),
2638            Err(BudgetEvaluationError::DeadlineExceeded {
2639                deadline: timestamp("2030-01-01T00:00:00.000000Z"),
2640                observed_at: timestamp("2030-01-01T00:00:00.000000Z"),
2641            })
2642        );
2643
2644        let steps = BudgetUsage::builder()
2645            .graph_steps(ExecutionCount::new(11))
2646            .build()
2647            .unwrap();
2648        assert_eq!(
2649            budget.remaining(&steps, timestamp("2029-01-01T00:00:00.000000Z")),
2650            Err(BudgetEvaluationError::ExecutionLimitExceeded {
2651                dimension: BudgetDimension::GraphSteps,
2652                limit: ExecutionCount::new(10),
2653                actual: ExecutionCount::new(11),
2654            })
2655        );
2656
2657        let tokens = BudgetUsage::builder()
2658            .input_tokens(TokenCount::new(11))
2659            .build()
2660            .unwrap();
2661        assert!(matches!(
2662            budget.remaining(&tokens, timestamp("2029-01-01T00:00:00.000000Z")),
2663            Err(BudgetEvaluationError::TokenLimitExceeded {
2664                dimension: BudgetDimension::InputTokens,
2665                ..
2666            })
2667        ));
2668
2669        let bytes = BudgetUsage::builder()
2670            .input_bytes(ByteCount::new(11))
2671            .build()
2672            .unwrap();
2673        assert!(matches!(
2674            budget.remaining(&bytes, timestamp("2029-01-01T00:00:00.000000Z")),
2675            Err(BudgetEvaluationError::ByteLimitExceeded {
2676                dimension: BudgetDimension::InputBytes,
2677                ..
2678            })
2679        ));
2680
2681        let unbudgeted = BudgetUsage::builder()
2682            .known_costs(KnownCosts::try_new([Money::new(eur(), 1)]).unwrap())
2683            .build()
2684            .unwrap();
2685        assert_eq!(
2686            budget.remaining(&unbudgeted, timestamp("2029-01-01T00:00:00.000000Z")),
2687            Err(BudgetEvaluationError::UnbudgetedCurrency { currency: eur() })
2688        );
2689
2690        let deny_all_costs =
2691            ResolvedBudget::resolve(
2692                &[full_limits(10).with_costs(CostLimits::try_new([]).unwrap())],
2693            )
2694            .unwrap();
2695        assert!(
2696            deny_all_costs
2697                .remaining(
2698                    &BudgetUsage::zero(),
2699                    timestamp("2029-01-01T00:00:00.000000Z")
2700                )
2701                .is_ok()
2702        );
2703        let priced = BudgetUsage::builder()
2704            .known_costs(KnownCosts::try_new([Money::new(usd(), 1)]).unwrap())
2705            .build()
2706            .unwrap();
2707        assert_eq!(
2708            deny_all_costs.remaining(&priced, timestamp("2029-01-01T00:00:00.000000Z")),
2709            Err(BudgetEvaluationError::UnbudgetedCurrency { currency: usd() })
2710        );
2711
2712        let overspent = BudgetUsage::builder()
2713            .known_costs(KnownCosts::try_new([Money::new(usd(), 11)]).unwrap())
2714            .build()
2715            .unwrap();
2716        assert_eq!(
2717            budget.remaining(&overspent, timestamp("2029-01-01T00:00:00.000000Z")),
2718            Err(BudgetEvaluationError::CostLimitExceeded {
2719                limit: Money::new(usd(), 10),
2720                actual: Money::new(usd(), 11),
2721            })
2722        );
2723    }
2724
2725    #[test]
2726    fn budget_schemas_close_objects_and_publish_collection_bounds() {
2727        let limits = to_value(schemars::schema_for!(BudgetLimits)).unwrap();
2728        let resolved = to_value(schemars::schema_for!(ResolvedBudget)).unwrap();
2729        let usage = to_value(schemars::schema_for!(BudgetUsage)).unwrap();
2730        let remaining = to_value(schemars::schema_for!(BudgetRemaining)).unwrap();
2731        let costs = to_value(schemars::schema_for!(CostLimits)).unwrap();
2732        let known = to_value(schemars::schema_for!(KnownCosts)).unwrap();
2733
2734        assert_eq!(limits["additionalProperties"], false);
2735        assert_eq!(resolved["additionalProperties"], false);
2736        assert_eq!(usage["additionalProperties"], false);
2737        assert_eq!(remaining["additionalProperties"], false);
2738        assert!(limits["required"].as_array().is_none_or(Vec::is_empty));
2739        assert_eq!(resolved["required"].as_array().unwrap().len(), 21);
2740        assert_eq!(usage["required"].as_array().unwrap().len(), 21);
2741        assert_eq!(costs["minItems"], 0);
2742        assert_eq!(costs["maxItems"], MAX_COST_CURRENCIES);
2743        assert_eq!(costs["uniqueItems"], true);
2744        assert_eq!(known["maxItems"], MAX_COST_CURRENCIES);
2745        assert_eq!(known["uniqueItems"], true);
2746    }
2747
2748    proptest! {
2749        #[test]
2750        fn scalar_resolution_is_commutative_idempotent_and_never_widens(
2751            left in any::<u64>(),
2752            right in any::<u64>(),
2753        ) {
2754            let left = BudgetLimits::empty().with_graph_steps(ExecutionCount::new(left));
2755            let right = BudgetLimits::empty().with_graph_steps(ExecutionCount::new(right));
2756            let forward = left.most_restrictive(&right);
2757            let reverse = right.most_restrictive(&left);
2758            prop_assert_eq!(&forward, &reverse);
2759            prop_assert_eq!(
2760                forward.graph_steps(),
2761                Some(ExecutionCount::new(left.graph_steps().unwrap().get().min(right.graph_steps().unwrap().get())))
2762            );
2763            prop_assert_eq!(left.most_restrictive(&left), left);
2764        }
2765
2766        #[test]
2767        fn usage_accumulation_matches_checked_counts_and_high_water(
2768            left in any::<u32>(),
2769            right in any::<u32>(),
2770        ) {
2771            let left_usage = BudgetUsage::builder()
2772                .graph_depth(ExecutionCount::new(u64::from(left)))
2773                .graph_steps(ExecutionCount::new(u64::from(left)))
2774                .build()
2775                .unwrap();
2776            let right_usage = BudgetUsage::builder()
2777                .graph_depth(ExecutionCount::new(u64::from(right)))
2778                .graph_steps(ExecutionCount::new(u64::from(right)))
2779                .build()
2780                .unwrap();
2781            let total = left_usage.checked_accumulate(&right_usage).unwrap();
2782            prop_assert_eq!(total.graph_depth().get(), u64::from(left.max(right)));
2783            prop_assert_eq!(total.graph_steps().get(), u64::from(left) + u64::from(right));
2784        }
2785
2786        #[test]
2787        fn remaining_count_is_exact_for_every_in_budget_value(
2788            limit in any::<u32>(),
2789            usage in any::<u32>(),
2790        ) {
2791            let limit = u64::from(limit);
2792            let usage = u64::from(usage).min(limit);
2793            let budget = resolved(limit);
2794            let usage_value = BudgetUsage::builder()
2795                .graph_steps(ExecutionCount::new(usage))
2796                .build()
2797                .unwrap();
2798            let remaining = budget
2799                .remaining(&usage_value, timestamp("2029-01-01T00:00:00.000000Z"))
2800                .unwrap();
2801            prop_assert_eq!(remaining.graph_steps().get(), limit - usage);
2802        }
2803    }
2804}