1use 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
27pub struct BudgetState {
28 pub tokens: u64,
29 pub cost_micros: u64,
31 pub max_total_tokens: Option<u64>,
32 pub max_cost_micros: Option<u64>,
33}
34
35impl 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
82pub struct RunBudget {
84 max_tokens: Option<u64>,
85 max_cost_micros: Option<u64>,
86 tokens: AtomicU64,
87 cost_micros: AtomicU64,
88 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 pub fn unlimited() -> Self {
123 Self::new(None, None, (0, 0), Box::new(|_| {}))
124 }
125
126 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 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 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 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 pub fn remaining_tokens(&self) -> Option<u64> {
177 self.max_tokens.map(|max| max.saturating_sub(self.tokens.load(Ordering::Acquire)))
178 }
179
180 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 pub fn is_limited(&self) -> bool {
187 self.max_tokens.is_some() || self.max_cost_micros.is_some()
188 }
189
190 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
201fn 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#[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 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 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}