1use std::fmt;
4use std::sync::{Arc, Mutex, PoisonError};
5
6use crate::error::{Error, Result};
7use crate::models::streaming::Usage;
8use crate::types::StopReason;
9
10#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, bon::Builder)]
17pub struct InvokeLimits {
18 pub turns: Option<u64>,
20 pub output_tokens: Option<u64>,
22 pub total_tokens: Option<u64>,
24 pub structured_output_attempts: Option<u64>,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30#[non_exhaustive]
31pub enum LimitKey {
32 Turns,
34 OutputTokens,
36 TotalTokens,
38 StructuredOutputAttempts,
40}
41
42impl LimitKey {
43 #[must_use]
45 pub fn as_str(self) -> &'static str {
46 match self {
47 Self::Turns => "turns",
48 Self::OutputTokens => "outputTokens",
49 Self::TotalTokens => "totalTokens",
50 Self::StructuredOutputAttempts => "structuredOutputAttempts",
51 }
52 }
53}
54
55const LIMIT_KEYS: [LimitKey; 4] = [
56 LimitKey::Turns,
57 LimitKey::OutputTokens,
58 LimitKey::TotalTokens,
59 LimitKey::StructuredOutputAttempts,
60];
61
62impl InvokeLimits {
63 #[must_use]
65 pub fn get(&self, key: LimitKey) -> Option<u64> {
66 match key {
67 LimitKey::Turns => self.turns,
68 LimitKey::OutputTokens => self.output_tokens,
69 LimitKey::TotalTokens => self.total_tokens,
70 LimitKey::StructuredOutputAttempts => self.structured_output_attempts,
71 }
72 }
73
74 pub fn validate(&self) -> Result<()> {
81 let zero = LIMIT_KEYS.into_iter().find(|key| self.get(*key) == Some(0));
82 match zero {
83 Some(key) => Err(Error::other(format!(
84 "limits.{} must be a positive finite number, got 0",
85 key.as_str()
86 ))),
87 None => Ok(()),
88 }
89 }
90}
91
92#[derive(Debug, Clone, Default, PartialEq, Eq)]
95#[non_exhaustive]
96pub struct InvocationContextUsage {
97 pub turns_taken: u64,
99 pub usage: Usage,
101}
102
103#[derive(Default)]
104struct Counters {
105 usage: InvocationContextUsage,
106 structured_output_failures: u64,
107}
108
109struct Inner {
110 limits: Option<InvokeLimits>,
111 parent: Option<InvocationContext>,
112 auxiliary: bool,
113 counters: Mutex<Counters>,
114}
115
116#[derive(Clone)]
123pub struct InvocationContext {
124 inner: Arc<Inner>,
125}
126
127#[cfg_attr(not(test), expect(dead_code, reason = "some helpers are used only by tests"))]
128impl InvocationContext {
129 fn from_parts(limits: Option<InvokeLimits>, parent: Option<Self>, auxiliary: bool) -> Self {
130 Self {
131 inner: Arc::new(Inner {
132 limits,
133 parent,
134 auxiliary,
135 counters: Mutex::default(),
136 }),
137 }
138 }
139
140 pub(crate) fn new(limits: Option<InvokeLimits>) -> Self {
142 Self::from_parts(limits, None, false)
143 }
144
145 pub(crate) fn nested(limits: Option<InvokeLimits>, parent: &Self) -> Self {
147 Self::from_parts(limits, Some(parent.clone()), false)
148 }
149
150 pub(crate) fn resolve(limits: Option<InvokeLimits>, inherited: Option<&Self>) -> Result<Self> {
153 if let Some(limits) = &limits {
154 limits.validate()?;
155 }
156 Ok(match (inherited, limits) {
157 (None, limits) => Self::new(limits),
158 (Some(inherited), None) => inherited.clone(),
159 (Some(inherited), Some(limits)) => Self::nested(Some(limits), inherited),
160 })
161 }
162
163 pub(crate) fn auxiliary(parent: Option<&Self>) -> Option<Self> {
166 parent.map(|parent| Self::from_parts(None, Some(parent.clone()), true))
167 }
168
169 fn counters(&self) -> std::sync::MutexGuard<'_, Counters> {
170 self.inner.counters.lock().unwrap_or_else(PoisonError::into_inner)
171 }
172
173 #[must_use]
175 pub fn usage(&self) -> InvocationContextUsage {
176 self.counters().usage.clone()
177 }
178
179 #[must_use]
181 pub fn limits(&self) -> Option<&InvokeLimits> {
182 self.inner.limits.as_ref()
183 }
184
185 #[must_use]
187 pub(crate) fn structured_output_failures(&self) -> u64 {
188 self.counters().structured_output_failures
189 }
190
191 fn limiting_parent(&self) -> Option<&Self> {
193 if self.inner.auxiliary {
194 return None;
195 }
196 self.inner.parent.as_ref()
197 }
198
199 pub(crate) fn record_usage(&self, usage: &Usage) {
201 self.counters().usage.usage.accumulate(usage);
202 if let Some(parent) = &self.inner.parent {
203 parent.record_usage(usage);
204 }
205 }
206
207 pub(crate) fn record_turn(&self) {
209 let turns = &mut self.counters().usage.turns_taken;
210 *turns = turns.saturating_add(1);
211 if let Some(parent) = self.limiting_parent() {
212 parent.record_turn();
213 }
214 }
215
216 pub(crate) fn record_structured_output_failure(&self) {
218 let failures = &mut self.counters().structured_output_failures;
219 *failures = failures.saturating_add(1);
220 if let Some(parent) = self.limiting_parent() {
221 parent.record_structured_output_failure();
222 }
223 }
224
225 #[must_use]
227 pub(crate) fn has_limit(&self, key: LimitKey) -> bool {
228 let own = self.inner.limits.is_some_and(|limits| limits.get(key).is_some());
229 own || self.limiting_parent().is_some_and(|parent| parent.has_limit(key))
230 }
231
232 #[must_use]
234 pub(crate) fn reached_limit(&self) -> Option<StopReason> {
235 self.reached_own_limit()
236 .or_else(|| self.limiting_parent().and_then(Self::reached_limit))
237 }
238
239 fn reached_own_limit(&self) -> Option<StopReason> {
240 let limits = self.inner.limits?;
241 let counters = self.counters();
242 let usage = &counters.usage;
243 let checks = [
244 (limits.turns, usage.turns_taken, StopReason::LimitTurns),
245 (
246 limits.total_tokens,
247 usage.usage.total_tokens,
248 StopReason::LimitTotalTokens,
249 ),
250 (
251 limits.output_tokens,
252 usage.usage.output_tokens,
253 StopReason::LimitOutputTokens,
254 ),
255 (
256 limits.structured_output_attempts,
257 counters.structured_output_failures,
258 StopReason::LimitStructuredOutputAttempts,
259 ),
260 ];
261 checks
262 .into_iter()
263 .find_map(|(limit, used, reason)| limit.is_some_and(|limit| used >= limit).then_some(reason))
264 }
265
266 #[must_use]
268 pub fn ptr_eq(&self, other: &Self) -> bool {
269 Arc::ptr_eq(&self.inner, &other.inner)
270 }
271}
272
273impl fmt::Debug for InvocationContext {
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275 f.debug_struct("InvocationContext")
276 .field("limits", &self.inner.limits)
277 .field("usage", &self.usage())
278 .finish_non_exhaustive()
279 }
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285
286 fn limits(turns: Option<u64>, structured_output_attempts: Option<u64>) -> Option<InvokeLimits> {
287 Some(InvokeLimits {
288 turns,
289 structured_output_attempts,
290 ..InvokeLimits::default()
291 })
292 }
293
294 #[test]
295 fn counts_toward_limiting_parents_but_not_through_an_auxiliary_call() {
296 let request = InvocationContext::new(limits(None, Some(2)));
297 let nested = InvocationContext::nested(limits(Some(5), None), &request);
298 let auxiliary = InvocationContext::auxiliary(Some(&request)).unwrap();
299
300 nested.record_structured_output_failure();
301 auxiliary.record_structured_output_failure();
302
303 assert_eq!(request.structured_output_failures(), 1);
304 assert_eq!(nested.reached_limit(), None);
305 nested.record_structured_output_failure();
306 assert_eq!(nested.reached_limit(), Some(StopReason::LimitStructuredOutputAttempts));
307 }
308
309 #[test]
310 fn sees_the_limits_of_limiting_parents_only() {
311 let request = InvocationContext::new(limits(None, Some(2)));
312 let auxiliary = InvocationContext::auxiliary(Some(&request)).unwrap();
313
314 assert_eq!(
315 [
316 InvocationContext::nested(limits(Some(5), None), &request)
317 .has_limit(LimitKey::StructuredOutputAttempts),
318 auxiliary.has_limit(LimitKey::StructuredOutputAttempts),
319 InvocationContext::new(limits(Some(5), None)).has_limit(LimitKey::StructuredOutputAttempts),
320 ],
321 [true, false, false]
322 );
323 }
324
325 #[test]
326 fn usage_adds_to_every_parent_and_turns_skip_auxiliary_parents() {
327 let request = InvocationContext::new(None);
328 let auxiliary = InvocationContext::auxiliary(Some(&request)).unwrap();
329 auxiliary.record_usage(&Usage::new(3, 2, 5));
330 auxiliary.record_turn();
331 assert_eq!(request.usage().usage, Usage::new(3, 2, 5));
332 assert_eq!(request.usage().turns_taken, 0);
333 assert_eq!(auxiliary.usage().turns_taken, 1);
334 }
335
336 #[test]
337 fn reached_limit_checks_turns_before_tokens() {
338 let context = InvocationContext::new(Some(InvokeLimits {
339 turns: Some(1),
340 total_tokens: Some(5),
341 ..InvokeLimits::default()
342 }));
343 context.record_usage(&Usage::new(3, 2, 5));
344 assert_eq!(context.reached_limit(), Some(StopReason::LimitTotalTokens));
345 context.record_turn();
346 assert_eq!(context.reached_limit(), Some(StopReason::LimitTurns));
347 }
348
349 #[test]
350 fn resolve_joins_or_nests_and_rejects_zero_limits() {
351 let request = InvocationContext::resolve(None, None).unwrap();
352 assert!(
353 InvocationContext::resolve(None, Some(&request))
354 .unwrap()
355 .ptr_eq(&request)
356 );
357 let nested = InvocationContext::resolve(limits(Some(2), None), Some(&request)).unwrap();
358 assert!(!nested.ptr_eq(&request));
359 assert!(nested.has_limit(LimitKey::Turns));
360 let error = InvocationContext::resolve(limits(Some(0), None), None).unwrap_err();
361 assert_eq!(
362 error.to_string(),
363 "limits.turns must be a positive finite number, got 0"
364 );
365 }
366}