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    /// Tokens left, `None` without a token limit.
176    pub fn remaining_tokens(&self) -> Option<u64> {
177        self.max_tokens.map(|max| max.saturating_sub(self.tokens.load(Ordering::Acquire)))
178    }
179
180    /// Cost left in micro units, `None` without a cost limit.
181    pub fn remaining_cost_micros(&self) -> Option<u64> {
182        self.max_cost_micros.map(|max| max.saturating_sub(self.cost_micros.load(Ordering::Acquire)))
183    }
184
185    /// Whether the run has a token or a cost limit.
186    pub fn is_limited(&self) -> bool {
187        self.max_tokens.is_some() || self.max_cost_micros.is_some()
188    }
189
190    /// What the snapshot keeps: the counters and the limits.
191    pub fn state(&self) -> BudgetState {
192        BudgetState {
193            tokens: self.tokens.load(Ordering::Acquire),
194            cost_micros: self.cost_micros.load(Ordering::Acquire),
195            max_total_tokens: self.max_tokens,
196            max_cost_micros: self.max_cost_micros,
197        }
198    }
199}
200
201/// Add `amount` to `counter` without wrapping. Returns the new value.
202fn saturating_add(counter: &AtomicU64, amount: u64) -> u64 {
203    let mut current = counter.load(Ordering::Acquire);
204    loop {
205        let next = current.saturating_add(amount);
206        match counter.compare_exchange_weak(current, next, Ordering::AcqRel, Ordering::Acquire) {
207            Ok(_) => return next,
208            Err(actual) => current = actual,
209        }
210    }
211}
212
213/// The checkpoint of one execution of a node that tracks its turns
214/// ([`crate::node::Node::tracks_turns`]), shared by its attempts.
215#[derive(Debug, Default)]
216pub struct NodeProgress {
217    checkpoint: Mutex<Option<serde_json::Value>>,
218}
219
220impl NodeProgress {
221    #[cfg_attr(not(feature = "budgets"), allow(dead_code))]
222    pub(crate) fn with(checkpoint: Option<serde_json::Value>) -> Self {
223        Self { checkpoint: Mutex::new(checkpoint) }
224    }
225
226    pub(crate) fn set(&self, state: serde_json::Value) {
227        *self.checkpoint.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(state);
228    }
229
230    pub(crate) fn get(&self) -> Option<serde_json::Value> {
231        self.checkpoint.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
232    }
233}
234
235#[cfg(test)]
236#[allow(clippy::unwrap_used)]
237mod tests {
238    use super::*;
239
240    fn usage(total: u64) -> Usage {
241        Usage { prompt_tokens: total, completion_tokens: 0, total_tokens: total }
242    }
243
244    #[test]
245    fn a_charge_past_a_limit_reports_once_and_fails() {
246        let seen = std::sync::Arc::new(Mutex::new(Vec::new()));
247        let log = std::sync::Arc::clone(&seen);
248        let budget = RunBudget::new(Some(100), Some(50), (40, 0), Box::new(move |why| log.lock().unwrap().push(why)));
249        budget.charge(&usage(50), 10).unwrap();
250        assert_eq!(budget.remaining_tokens(), Some(10));
251        assert_eq!(budget.remaining_cost_micros(), Some(40));
252        let error = budget.charge(&usage(20), 0).unwrap_err();
253        assert_eq!(error.kind, "limit_exceeded");
254        assert!(!error.retryable);
255        assert!(budget.charge(&usage(1), 0).is_err());
256        assert_eq!(seen.lock().unwrap().len(), 1, "reported once");
257        let state = budget.state();
258        assert_eq!((state.tokens, state.cost_micros, state.max_total_tokens), (111, 10, Some(100)));
259        // Counters never wrap.
260        let huge = RunBudget::limited(Some(u64::MAX), None);
261        huge.charge(&usage(u64::MAX - 1), 0).unwrap();
262        assert!(huge.charge(&usage(10), 0).is_err() || huge.state().tokens == u64::MAX);
263        assert_eq!(huge.state().tokens, u64::MAX);
264        let costly = RunBudget::limited(None, Some(50));
265        costly.charge(&usage(1_000), 50).unwrap();
266        assert!(costly.charge(&usage(0), 1).unwrap_err().message.contains("cost budget of 50"));
267        // Without limits it only counts.
268        let open = RunBudget::unlimited();
269        open.charge(&usage(1_000_000), 1_000_000).unwrap();
270        assert_eq!((open.remaining_tokens(), open.is_limited()), (None, false));
271    }
272
273    #[test]
274    fn progress_keeps_the_last_checkpoint() {
275        let progress = NodeProgress::with(None);
276        assert!(progress.get().is_none());
277        progress.set(serde_json::json!({"turn": 1}));
278        progress.set(serde_json::json!({"turn": 2}));
279        assert_eq!(progress.get(), Some(serde_json::json!({"turn": 2})));
280    }
281}