Skip to main content

stateknot_core/
budget_reservation.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Pure cumulative-capacity arithmetic, separate from durable reservation.
5
6use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
7use serde::{Deserialize, Deserializer, Serialize, de};
8use thiserror::Error;
9
10use crate::{
11    BudgetDimension, BudgetEvaluationError, BudgetRemaining, BudgetUsage, BudgetUsageError,
12    CostCollectionError, ExecutionCount, KnownCosts, ResolvedBudget, Timestamp,
13};
14
15/// An immutable ceiling reserved for cumulative work, not observed usage.
16///
17/// All cumulative dimensions, inclusive token/call subsets, and configured
18/// currencies are reserved. High-water dimensions (`graph_depth`,
19/// `concurrent_branches`, `fan_out`) are deliberately absent (zero in the
20/// underlying amount); topology and live concurrency require their own
21/// admission checks. Unknown price is never a zero-cost reservation.
22///
23/// This value does not reserve database capacity. A durable caller must bind
24/// it to one ownership key and atomically check the complete set of current
25/// reservations and accounted usage while serializing competing admissions
26/// and direct-work budget consumption. Never persist the projected capacity
27/// from [`Self::check_capacity`] as actual usage.
28#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
29#[serde(deny_unknown_fields)]
30pub struct CumulativeBudgetReservation {
31    #[schemars(schema_with = "amount_schema")]
32    amount: BudgetUsage,
33}
34
35fn amount_schema(generator: &mut SchemaGenerator) -> Schema {
36    json_schema!({
37        "allOf": [
38            generator.subschema_for::<BudgetUsage>(),
39            {"properties": {
40                "graph_depth": {"const": "0"},
41                "concurrent_branches": {"const": "0"},
42                "fan_out": {"const": "0"},
43                "unpriced_cost_events": {"const": "0"}
44            }}
45        ]
46    })
47}
48
49impl CumulativeBudgetReservation {
50    /// Maximum reservation count accepted by one bounded capacity check.
51    ///
52    /// This is an arithmetic work bound, not an implemented child fan-out limit.
53    pub const MAX_RESERVATIONS: usize = 256;
54
55    /// Constructs a reservation from explicit cumulative ceilings.
56    ///
57    /// Rejects high-water dimensions and unpriced activity. Subset and integer
58    /// validation is inherited from [`BudgetUsage`]. Zero denies further
59    /// cumulative work; it does not mean unlimited capacity.
60    pub fn new(amount: BudgetUsage) -> Result<Self, CumulativeBudgetReservationError> {
61        for (dimension, count) in [
62            (BudgetDimension::GraphDepth, amount.graph_depth()),
63            (
64                BudgetDimension::ConcurrentBranches,
65                amount.concurrent_branches(),
66            ),
67            (BudgetDimension::FanOut, amount.fan_out()),
68        ] {
69            if count != ExecutionCount::ZERO {
70                return Err(CumulativeBudgetReservationError::HighWaterDimension { dimension });
71            }
72        }
73        if amount.unpriced_cost_events() != ExecutionCount::ZERO {
74            return Err(CumulativeBudgetReservationError::UnpricedCost);
75        }
76        Ok(Self { amount })
77    }
78
79    /// Reserves every cumulative ceiling from an already finite budget.
80    ///
81    /// Does not copy the deadline or high-water limits. Child deadline,
82    /// authority, ancestry, and concurrency narrowing must be checked apart
83    /// from this arithmetic projection.
84    pub fn from_budget(budget: &ResolvedBudget) -> Result<Self, CumulativeBudgetReservationError> {
85        Self::new(
86            BudgetUsage::builder()
87                .graph_steps(budget.graph_steps())
88                .model_attempts(budget.model_attempts())
89                .model_turns(budget.model_turns())
90                .input_tokens(budget.input_tokens())
91                .cached_input_tokens(budget.cached_input_tokens())
92                .reasoning_tokens(budget.reasoning_tokens())
93                .output_tokens(budget.output_tokens())
94                .tool_calls(budget.tool_calls())
95                .write_calls(budget.write_calls())
96                .remote_agent_delegations(budget.remote_agent_delegations())
97                .retries(budget.retries())
98                .input_bytes(budget.input_bytes())
99                .output_bytes(budget.output_bytes())
100                .event_bytes(budget.event_bytes())
101                .checkpoint_bytes(budget.checkpoint_bytes())
102                .artifact_bytes(budget.artifact_bytes())
103                .known_costs(KnownCosts::try_new(budget.costs().iter().copied())?)
104                .build()?,
105        )
106    }
107
108    /// Returns reserved ceilings encoded using the validated usage dimensions.
109    ///
110    /// These amounts are not evidence of spent tokens, calls, bytes, or money.
111    #[must_use]
112    pub const fn amount(&self) -> &BudgetUsage {
113        &self.amount
114    }
115
116    /// Checks accounted usage plus all outstanding reservations, including any
117    /// proposed new reservation, against the parent budget at a supplied clock.
118    ///
119    /// `accounted` must include direct usage and settled child usage exactly
120    /// once, but exclude these outstanding reservations. Uses checked addition
121    /// and rejects unknown price, unsupported currencies, excess limits, and
122    /// expired deadlines. Existing high-water usage is checked, not decremented
123    /// per child. Duplicate entries are charged twice, never silently deduped.
124    ///
125    /// This pure check neither owns a lock nor proves a durable snapshot is
126    /// complete. Commit-time atomicity is the storage adapter's responsibility.
127    pub fn check_capacity(
128        parent: &ResolvedBudget,
129        accounted: &BudgetUsage,
130        outstanding: &[Self],
131        observed_at: Timestamp,
132    ) -> Result<BudgetRemaining, CumulativeBudgetReservationError> {
133        if outstanding.len() > Self::MAX_RESERVATIONS {
134            return Err(CumulativeBudgetReservationError::TooManyReservations);
135        }
136        let mut projected = accounted.clone();
137        for reservation in outstanding {
138            projected = projected.checked_accumulate(&reservation.amount)?;
139        }
140        Ok(parent.remaining(&projected, observed_at)?)
141    }
142}
143
144impl<'de> Deserialize<'de> for CumulativeBudgetReservation {
145    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
146    where
147        D: Deserializer<'de>,
148    {
149        #[derive(Deserialize)]
150        #[serde(deny_unknown_fields)]
151        struct Wire {
152            amount: BudgetUsage,
153        }
154        Self::new(Wire::deserialize(deserializer)?.amount).map_err(de::Error::custom)
155    }
156}
157
158/// Invalid cumulative reservation or insufficient projected budget capacity.
159#[derive(Clone, Debug, Eq, Error, PartialEq)]
160#[non_exhaustive]
161pub enum CumulativeBudgetReservationError {
162    /// A peak topology count cannot be reserved as cumulative expenditure.
163    #[error("cannot cumulatively reserve high-water dimension {dimension:?}")]
164    HighWaterDimension {
165        /// The rejected non-cumulative dimension.
166        dimension: BudgetDimension,
167    },
168    /// Unknown external price cannot be treated as a finite known reservation.
169    #[error("cannot reserve unpriced activity as known cumulative cost")]
170    UnpricedCost,
171    /// One check exceeded its bounded amount of arithmetic work.
172    #[error("too many outstanding cumulative budget reservations")]
173    TooManyReservations,
174    /// Checked scalar addition, currency union, or subset validation failed.
175    #[error(transparent)]
176    Usage(#[from] BudgetUsageError),
177    /// A currency-specific reservation was invalid.
178    #[error(transparent)]
179    Costs(#[from] CostCollectionError),
180    /// The projected capacity exceeds a ceiling or cannot be evaluated safely.
181    #[error(transparent)]
182    Capacity(#[from] BudgetEvaluationError),
183}
184
185#[cfg(test)]
186#[path = "budget_reservation_tests.rs"]
187mod tests;