Skip to main content

graphrt_core/
budget.rs

1//! The token and cost budget of a run, and the checkpoints of running nodes.
2//!
3//! A run's budget ([`RunBudget`]) is one pair of counters shared by every
4//! frame and every child run. Model nodes that track their turns
5//! ([`crate::node::Node::tracks_turns`]) charge it after each model response
6//! ([`crate::node::NodeContext::charge`]), with its cost, so an agent loop is
7//! bounded per turn and a failed call is paid for too. The engine charges
8//! every other node the tokens it reports when it completes. The counters and
9//! the limits are in the snapshot and go on after resume.
10//!
11//! A checkpoint ([`NodeProgress`]) is the progress a running node keeps for
12//! its next attempt: a retry after an error or a timeout gets it, and so does
13//! the attempt that runs after the run was preempted and resumed.
14
15use std::sync::Mutex;
16use std::sync::atomic::{AtomicU64, Ordering};
17
18use serde::{Deserialize, Serialize};
19
20use crate::event::Usage;
21use crate::node::NodeError;
22
23/// A run's budget as its snapshot keeps it: what was charged, and the limits
24/// the run started with (a request may have set lower ones than the engine's,
25/// and a resumed run keeps them).
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
27pub struct BudgetState {
28    pub tokens: u64,
29    /// In millionths of the price unit of the providers file.
30    pub cost_micros: u64,
31    pub max_total_tokens: Option<u64>,
32    pub max_cost_micros: Option<u64>,
33}
34
35// Through `serde_json::Value`, whose code every build has already: a derive
36// would add a decoder per input type to every binary that reads snapshots.
37impl Serialize for BudgetState {
38    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
39        let mut json = serde_json::Map::new();
40        json.insert("tokens".into(), self.tokens.into());
41        json.insert("cost_micros".into(), self.cost_micros.into());
42        if let Some(max) = self.max_total_tokens {
43            json.insert("max_total_tokens".into(), max.into());
44        }
45        if let Some(max) = self.max_cost_micros {
46            json.insert("max_cost_micros".into(), max.into());
47        }
48        serde_json::Value::Object(json).serialize(serializer)
49    }
50}
51
52impl<'de> Deserialize<'de> for BudgetState {
53    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
54        let json = serde_json::Value::deserialize(deserializer)?;
55        let number = |key: &str| -> Result<Option<u64>, D::Error> {
56            match json.get(key) {
57                None | Some(serde_json::Value::Null) => Ok(None),
58                Some(value) => value
59                    .as_u64()
60                    .map(Some)
61                    .ok_or_else(|| serde::de::Error::custom(format!("budget `{key}` must be a non-negative integer"))),
62            }
63        };
64        if !json.is_object() {
65            return Err(serde::de::Error::custom("budget must be an object"));
66        }
67        Ok(Self {
68            tokens: number("tokens")?.unwrap_or(0),
69            cost_micros: number("cost_micros")?.unwrap_or(0),
70            max_total_tokens: number("max_total_tokens")?,
71            max_cost_micros: number("max_cost_micros")?,
72        })
73    }
74}
75
76impl BudgetState {
77    pub fn is_empty(&self) -> bool {
78        *self == Self::default()
79    }
80}
81
82/// The budget of one run: limits, and what was charged against them.
83pub struct RunBudget {
84    max_tokens: Option<u64>,
85    max_cost_micros: Option<u64>,
86    tokens: AtomicU64,
87    cost_micros: AtomicU64,
88    /// Called once with the reason when a charge passes a limit (the engine
89    /// stops the run there, as at the step limit).
90    on_exceeded: Box<dyn Fn(String) + Send + Sync>,
91    exceeded: std::sync::atomic::AtomicBool,
92}
93
94impl std::fmt::Debug for RunBudget {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        f.debug_struct("RunBudget")
97            .field("max_tokens", &self.max_tokens)
98            .field("max_cost_micros", &self.max_cost_micros)
99            .field("state", &self.state())
100            .finish_non_exhaustive()
101    }
102}
103
104impl RunBudget {
105    pub(crate) fn new(
106        max_tokens: Option<u64>,
107        max_cost_micros: Option<u64>,
108        used: (u64, u64),
109        on_exceeded: Box<dyn Fn(String) + Send + Sync>,
110    ) -> Self {
111        Self {
112            max_tokens,
113            max_cost_micros,
114            tokens: AtomicU64::new(used.0),
115            cost_micros: AtomicU64::new(used.1),
116            on_exceeded,
117            exceeded: std::sync::atomic::AtomicBool::new(false),
118        }
119    }
120
121    /// A budget without limits that only counts, for node unit tests.
122    pub fn unlimited() -> Self {
123        Self::new(None, None, (0, 0), Box::new(|_| {}))
124    }
125
126    /// A budget with limits whose excess is only reported, for node unit tests.
127    pub fn limited(max_tokens: Option<u64>, max_cost_micros: Option<u64>) -> Self {
128        Self::new(max_tokens, max_cost_micros, (0, 0), Box::new(|_| {}))
129    }
130
131    /// Add `usage` (its total tokens) and `cost_micros`.
132    ///
133    /// @throws NodeError - `limit_exceeded` (fatal) when a limit is passed. The
134    ///   run stops then, so the error ends the node that charged.
135    pub fn charge(&self, usage: &Usage, cost_micros: u64) -> Result<(), NodeError> {
136        let tokens = usage.billable_tokens();
137        let used_tokens = saturating_add(&self.tokens, tokens);
138        let used_cost = saturating_add(&self.cost_micros, cost_micros);
139        let why = match (self.max_tokens, self.max_cost_micros) {
140            (Some(max), _) if used_tokens > max => format!("token budget of {max} exceeded ({used_tokens} used)"),
141            (_, Some(max)) if used_cost > max => {
142                format!("cost budget of {max} micro units exceeded ({used_cost} used)")
143            }
144            _ => return Ok(()),
145        };
146        if !self.exceeded.swap(true, Ordering::AcqRel) {
147            (self.on_exceeded)(why.clone());
148        }
149        Err(NodeError::fatal("limit_exceeded", why))
150    }
151
152    /// Add `usage` and `cost_micros` without checking the limits: what the
153    /// last answer of a node cost when the node chose to answer within the
154    /// budget (it may pass the limit by that one answer, never more).
155    pub fn record(&self, usage: &Usage, cost_micros: u64) {
156        saturating_add(&self.tokens, usage.billable_tokens());
157        saturating_add(&self.cost_micros, cost_micros);
158    }
159
160    /// Stop the run when nothing is left of a limit, as a charge past it does.
161    ///
162    /// @throws NodeError - `limit_exceeded` (fatal) when the budget is spent.
163    pub fn stop_if_spent(&self) -> Result<(), NodeError> {
164        let spent = self.remaining_tokens() == Some(0) || self.remaining_cost_micros() == Some(0);
165        if !spent {
166            return Ok(());
167        }
168        let why = "the run's token or cost budget is spent".to_owned();
169        if !self.exceeded.swap(true, Ordering::AcqRel) {
170            (self.on_exceeded)(why.clone());
171        }
172        Err(NodeError::fatal("limit_exceeded", why))
173    }
174
175    /// Stop the run for `why` (once), as a charge past a limit does: for a
176    /// node that finds the budget cannot afford its next call before making it.
177    pub fn refuse(&self, why: String) -> NodeError {
178        if !self.exceeded.swap(true, Ordering::AcqRel) {
179            (self.on_exceeded)(why.clone());
180        }
181        NodeError::fatal("limit_exceeded", why)
182    }
183
184    /// Tokens left, `None` without a token limit.
185    pub fn remaining_tokens(&self) -> Option<u64> {
186        self.max_tokens.map(|max| max.saturating_sub(self.tokens.load(Ordering::Acquire)))
187    }
188
189    /// Cost left in micro units, `None` without a cost limit.
190    pub fn remaining_cost_micros(&self) -> Option<u64> {
191        self.max_cost_micros.map(|max| max.saturating_sub(self.cost_micros.load(Ordering::Acquire)))
192    }
193
194    /// Whether the run has a token or a cost limit.
195    pub fn is_limited(&self) -> bool {
196        self.max_tokens.is_some() || self.max_cost_micros.is_some()
197    }
198
199    /// What the snapshot keeps: the counters and the limits.
200    pub fn state(&self) -> BudgetState {
201        BudgetState {
202            tokens: self.tokens.load(Ordering::Acquire),
203            cost_micros: self.cost_micros.load(Ordering::Acquire),
204            max_total_tokens: self.max_tokens,
205            max_cost_micros: self.max_cost_micros,
206        }
207    }
208}
209
210/// Add `amount` to `counter` without wrapping. Returns the new value.
211fn saturating_add(counter: &AtomicU64, amount: u64) -> u64 {
212    let mut current = counter.load(Ordering::Acquire);
213    loop {
214        let next = current.saturating_add(amount);
215        match counter.compare_exchange_weak(current, next, Ordering::AcqRel, Ordering::Acquire) {
216            Ok(_) => return next,
217            Err(actual) => current = actual,
218        }
219    }
220}
221
222/// The checkpoint of one execution of a node that tracks its turns
223/// ([`crate::node::Node::tracks_turns`]), shared by its attempts.
224#[derive(Debug, Default)]
225pub struct NodeProgress {
226    checkpoint: Mutex<Option<serde_json::Value>>,
227    /// What the node charged in this execution (every attempt): the run counts
228    /// it when the node fails, as it counts a finished node's own usage.
229    charged: Mutex<Usage>,
230    /// The run has counted this execution (when it ended, or when the run did).
231    settled: std::sync::atomic::AtomicBool,
232}
233
234impl NodeProgress {
235    #[cfg_attr(not(feature = "budgets"), allow(dead_code))]
236    pub(crate) fn with(checkpoint: Option<serde_json::Value>) -> Self {
237        Self { checkpoint: Mutex::new(checkpoint), ..Self::default() }
238    }
239
240    /// Whether the run counted this execution already.
241    #[cfg_attr(not(feature = "budgets"), allow(dead_code))]
242    pub(crate) fn settle_peek(&self) -> bool {
243        self.settled.load(Ordering::Acquire)
244    }
245
246    /// Mark this execution counted. Returns `false` when it already was.
247    #[cfg_attr(not(feature = "budgets"), allow(dead_code))]
248    pub(crate) fn settle(&self) -> bool {
249        !self.settled.swap(true, Ordering::AcqRel)
250    }
251
252    pub(crate) fn add_charged(&self, usage: &Usage) {
253        self.charged.lock().unwrap_or_else(std::sync::PoisonError::into_inner).add(usage);
254    }
255
256    #[cfg_attr(not(feature = "budgets"), allow(dead_code))]
257    pub(crate) fn charged(&self) -> Usage {
258        *self.charged.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
259    }
260
261    pub(crate) fn set(&self, state: serde_json::Value) {
262        *self.checkpoint.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(state);
263    }
264
265    pub(crate) fn get(&self) -> Option<serde_json::Value> {
266        self.checkpoint.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
267    }
268}
269
270#[cfg(test)]
271#[allow(clippy::unwrap_used)]
272mod tests {
273    use super::*;
274
275    fn usage(total: u64) -> Usage {
276        Usage { prompt_tokens: total, completion_tokens: 0, total_tokens: total }
277    }
278
279    #[test]
280    fn a_charge_past_a_limit_reports_once_and_fails() {
281        let seen = std::sync::Arc::new(Mutex::new(Vec::new()));
282        let log = std::sync::Arc::clone(&seen);
283        let budget = RunBudget::new(Some(100), Some(50), (40, 0), Box::new(move |why| log.lock().unwrap().push(why)));
284        budget.charge(&usage(50), 10).unwrap();
285        assert_eq!(budget.remaining_tokens(), Some(10));
286        assert_eq!(budget.remaining_cost_micros(), Some(40));
287        let error = budget.charge(&usage(20), 0).unwrap_err();
288        assert_eq!(error.kind, "limit_exceeded");
289        assert!(!error.retryable);
290        assert!(budget.charge(&usage(1), 0).is_err());
291        assert_eq!(seen.lock().unwrap().len(), 1, "reported once");
292        let state = budget.state();
293        assert_eq!((state.tokens, state.cost_micros, state.max_total_tokens), (111, 10, Some(100)));
294        // Counters never wrap.
295        let huge = RunBudget::limited(Some(u64::MAX), None);
296        huge.charge(&usage(u64::MAX - 1), 0).unwrap();
297        assert!(huge.charge(&usage(10), 0).is_err() || huge.state().tokens == u64::MAX);
298        assert_eq!(huge.state().tokens, u64::MAX);
299        let costly = RunBudget::limited(None, Some(50));
300        costly.charge(&usage(1_000), 50).unwrap();
301        assert!(costly.charge(&usage(0), 1).unwrap_err().message.contains("cost budget of 50"));
302        // Without limits it only counts.
303        let open = RunBudget::unlimited();
304        open.charge(&usage(1_000_000), 1_000_000).unwrap();
305        assert_eq!((open.remaining_tokens(), open.is_limited()), (None, false));
306    }
307
308    #[test]
309    fn progress_keeps_the_last_checkpoint() {
310        let progress = NodeProgress::with(None);
311        assert!(progress.get().is_none());
312        progress.set(serde_json::json!({"turn": 1}));
313        progress.set(serde_json::json!({"turn": 2}));
314        assert_eq!(progress.get(), Some(serde_json::json!({"turn": 2})));
315    }
316}