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> {
166 let spent = self.exceeded.load(Ordering::Acquire)
167 || self.remaining_tokens() == Some(0)
168 || self.remaining_cost_micros() == Some(0);
169 if !spent {
170 return Ok(());
171 }
172 let why = "the run's token or cost budget is spent".to_owned();
173 if !self.exceeded.swap(true, Ordering::AcqRel) {
174 (self.on_exceeded)(why.clone());
175 }
176 Err(NodeError::fatal("limit_exceeded", why))
177 }
178
179 pub fn refuse(&self, why: String) -> NodeError {
182 if !self.exceeded.swap(true, Ordering::AcqRel) {
183 (self.on_exceeded)(why.clone());
184 }
185 NodeError::fatal("limit_exceeded", why)
186 }
187
188 pub fn remaining_tokens(&self) -> Option<u64> {
190 self.max_tokens.map(|max| max.saturating_sub(self.tokens.load(Ordering::Acquire)))
191 }
192
193 pub fn remaining_cost_micros(&self) -> Option<u64> {
195 self.max_cost_micros.map(|max| max.saturating_sub(self.cost_micros.load(Ordering::Acquire)))
196 }
197
198 pub fn is_limited(&self) -> bool {
200 self.max_tokens.is_some() || self.max_cost_micros.is_some()
201 }
202
203 pub fn state(&self) -> BudgetState {
205 BudgetState {
206 tokens: self.tokens.load(Ordering::Acquire),
207 cost_micros: self.cost_micros.load(Ordering::Acquire),
208 max_total_tokens: self.max_tokens,
209 max_cost_micros: self.max_cost_micros,
210 }
211 }
212}
213
214fn saturating_add(counter: &AtomicU64, amount: u64) -> u64 {
216 let mut current = counter.load(Ordering::Acquire);
217 loop {
218 let next = current.saturating_add(amount);
219 match counter.compare_exchange_weak(current, next, Ordering::AcqRel, Ordering::Acquire) {
220 Ok(_) => return next,
221 Err(actual) => current = actual,
222 }
223 }
224}
225
226#[derive(Debug, Default)]
229pub struct NodeProgress {
230 checkpoint: Mutex<Option<serde_json::Value>>,
231 charged: Mutex<Usage>,
234 settled: std::sync::atomic::AtomicBool,
236}
237
238impl NodeProgress {
239 #[cfg_attr(not(feature = "budgets"), allow(dead_code))]
240 pub(crate) fn with(checkpoint: Option<serde_json::Value>) -> Self {
241 Self { checkpoint: Mutex::new(checkpoint), ..Self::default() }
242 }
243
244 #[cfg_attr(not(feature = "budgets"), allow(dead_code))]
246 pub(crate) fn settle_peek(&self) -> bool {
247 self.settled.load(Ordering::Acquire)
248 }
249
250 #[cfg_attr(not(feature = "budgets"), allow(dead_code))]
252 pub(crate) fn settle(&self) -> bool {
253 !self.settled.swap(true, Ordering::AcqRel)
254 }
255
256 pub(crate) fn add_charged(&self, usage: &Usage) {
257 self.charged.lock().unwrap_or_else(std::sync::PoisonError::into_inner).add(usage);
258 }
259
260 #[cfg_attr(not(feature = "budgets"), allow(dead_code))]
261 pub(crate) fn charged(&self) -> Usage {
262 *self.charged.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
263 }
264
265 pub(crate) fn set(&self, state: serde_json::Value) {
266 *self.checkpoint.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(state);
267 }
268
269 pub(crate) fn get(&self) -> Option<serde_json::Value> {
270 self.checkpoint.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
271 }
272}
273
274#[cfg(test)]
275#[allow(clippy::unwrap_used)]
276mod tests {
277 use super::*;
278
279 fn usage(total: u64) -> Usage {
280 Usage { prompt_tokens: total, completion_tokens: 0, total_tokens: total, cost_micros: 0 }
281 }
282
283 #[test]
284 fn a_charge_past_a_limit_reports_once_and_fails() {
285 let seen = std::sync::Arc::new(Mutex::new(Vec::new()));
286 let log = std::sync::Arc::clone(&seen);
287 let budget = RunBudget::new(Some(100), Some(50), (40, 0), Box::new(move |why| log.lock().unwrap().push(why)));
288 budget.charge(&usage(50), 10).unwrap();
289 assert_eq!(budget.remaining_tokens(), Some(10));
290 assert_eq!(budget.remaining_cost_micros(), Some(40));
291 let error = budget.charge(&usage(20), 0).unwrap_err();
292 assert_eq!(error.kind, "limit_exceeded");
293 assert!(!error.retryable);
294 assert!(budget.charge(&usage(1), 0).is_err());
295 assert_eq!(seen.lock().unwrap().len(), 1, "reported once");
296 let state = budget.state();
297 assert_eq!((state.tokens, state.cost_micros, state.max_total_tokens), (111, 10, Some(100)));
298 let huge = RunBudget::limited(Some(u64::MAX), None);
300 huge.charge(&usage(u64::MAX - 1), 0).unwrap();
301 assert!(huge.charge(&usage(10), 0).is_err() || huge.state().tokens == u64::MAX);
302 assert_eq!(huge.state().tokens, u64::MAX);
303 let costly = RunBudget::limited(None, Some(50));
304 costly.charge(&usage(1_000), 50).unwrap();
305 assert!(costly.charge(&usage(0), 1).unwrap_err().message.contains("cost budget of 50"));
306 let open = RunBudget::unlimited();
308 open.charge(&usage(1_000_000), 1_000_000).unwrap();
309 assert_eq!((open.remaining_tokens(), open.is_limited()), (None, false));
310 }
311
312 #[test]
313 fn progress_keeps_the_last_checkpoint() {
314 let progress = NodeProgress::with(None);
315 assert!(progress.get().is_none());
316 progress.set(serde_json::json!({"turn": 1}));
317 progress.set(serde_json::json!({"turn": 2}));
318 assert_eq!(progress.get(), Some(serde_json::json!({"turn": 2})));
319 }
320}