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 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 pub fn remaining_tokens(&self) -> Option<u64> {
186 self.max_tokens.map(|max| max.saturating_sub(self.tokens.load(Ordering::Acquire)))
187 }
188
189 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 pub fn is_limited(&self) -> bool {
196 self.max_tokens.is_some() || self.max_cost_micros.is_some()
197 }
198
199 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
210fn 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#[derive(Debug, Default)]
225pub struct NodeProgress {
226 checkpoint: Mutex<Option<serde_json::Value>>,
227 charged: Mutex<Usage>,
230 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 #[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 #[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 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 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}