Skip to main content

ag_contracts/
provider_call_budget.rs

1//! Shared accounting for provider turns, including transport and protocol
2//! retries.
3
4use std::fmt;
5use std::sync::Arc;
6use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
7
8use crate::OneShotError;
9
10/// Observes every change to one shared provider-call pool, so a host can
11/// persist spending across process restarts.
12///
13/// A charge is reported after a call leaves the pool, including the initial
14/// call held by a reservation. A refund is reported before an unused
15/// reservation returns its call, so a returned call is never charged again
16/// ahead of its refund. Charges minus refunds therefore never exceed the
17/// calls spent, and equal them once accounting is idle.
18/// Implementations must not block; they run inside budget accounting.
19pub trait ProviderCallLedger: Send + Sync {
20    /// One call left the shared pool.
21    fn charged(&self);
22
23    /// One unused reserved call returned to the shared pool.
24    fn refunded(&self);
25}
26
27/// A shared limit on underlying provider turns across cloned requests.
28///
29/// Transports must consume one slot immediately before each provider attempt,
30/// including repairs and restart retries. Failed attempts also consume a slot.
31/// An in-process harness run is one attempt however many model requests it
32/// sends, so one slot means the same on every backend.
33#[derive(Clone, Debug)]
34pub struct ProviderCallBudget {
35    ceiling: Option<Box<ProviderCallBudget>>,
36    pool: Arc<SharedPool>,
37    reservation: Option<Arc<ReservedCall>>,
38}
39
40impl ProviderCallBudget {
41    /// Creates a budget shared by all clones.
42    pub fn new(limit: usize) -> Self {
43        Self::from_pool(SharedPool {
44            calls: AtomicUsize::new(limit),
45            ledger: None,
46        })
47    }
48
49    /// Creates a budget whose shared pool reports each charge and refund to
50    /// `ledger`. `remaining` is the credit still available, for example after
51    /// restoring spending recorded before a restart.
52    pub fn with_ledger(remaining: usize, ledger: Arc<dyn ProviderCallLedger>) -> Self {
53        Self::from_pool(SharedPool {
54            calls: AtomicUsize::new(remaining),
55            ledger: Some(ledger),
56        })
57    }
58
59    /// Returns available shared calls plus this budget's reserved initial call.
60    /// Calls reserved by other budgets are unavailable to this budget.
61    pub fn remaining(&self) -> usize {
62        let remaining = self
63            .pool
64            .calls
65            .load(Ordering::Relaxed)
66            .saturating_add(usize::from(
67                self.reservation
68                    .as_ref()
69                    .is_some_and(|call| call.available.load(Ordering::Relaxed)),
70            ));
71
72        self.ceiling
73            .as_ref()
74            .map_or(remaining, |ceiling| remaining.min(ceiling.remaining()))
75    }
76
77    /// Adds `calls` to this budget's shared pool, for every clone and
78    /// reservation that draws from it. Enclosing ceilings keep their own
79    /// limits. The ledger is not told: a grant raises the limit the host
80    /// recorded, and no call is spent or refunded.
81    pub fn extend(&self, calls: usize) {
82        // Saturate instead of wrapping, like `remaining`.
83        let _ = self
84            .pool
85            .calls
86            .try_update(Ordering::Relaxed, Ordering::Relaxed, |available| {
87                Some(available.saturating_add(calls))
88            });
89    }
90
91    /// Adds an enclosing workflow ceiling while preserving the caller's own
92    /// limit. Each distinct shared counter charges every provider attempt once.
93    #[must_use]
94    pub fn with_ceiling(mut self, ceiling: Self) -> Self {
95        let mut next = Some(ceiling);
96        while let Some(mut counter) = next {
97            next = counter.ceiling.take().map(|ceiling| *ceiling);
98            self.merge_counter(counter);
99        }
100
101        self
102    }
103
104    /// Atomically reserves one initial attempt in a child budget.
105    ///
106    /// The returned budget and its clones redeem that call once through
107    /// `consume`; subsequent attempts charge the shared pool normally.
108    /// Dropping all child clones before redemption refunds the reservation
109    /// to its source. Admission must retain the child through worker delivery.
110    ///
111    /// # Errors
112    /// Returns the same exhaustion error as `consume` when no call is
113    /// available.
114    pub fn reserve(&self) -> Result<Self, OneShotError> {
115        let source = self.take_call()?;
116
117        let mut reserved = Self {
118            ceiling: None,
119            pool: self.pool.clone(),
120            reservation: Some(Arc::new(ReservedCall {
121                available: AtomicBool::new(true),
122                source,
123            })),
124        };
125        reserved.ceiling = self
126            .ceiling
127            .as_ref()
128            .map(|ceiling| ceiling.reserve().map(Box::new))
129            .transpose()?;
130
131        Ok(reserved)
132    }
133
134    /// Checks for exhaustion without charging a turn at an outer boundary.
135    ///
136    /// # Errors
137    /// Returns an input-size reduction error when no slots remain.
138    pub fn ensure_available(&self) -> Result<(), OneShotError> {
139        if self.remaining() == 0 {
140            return Err(Self::exhausted());
141        }
142
143        Ok(())
144    }
145
146    /// Charges one underlying provider attempt atomically.
147    /// Redeems a reserved initial call before charging the shared pool.
148    ///
149    /// # Errors
150    /// Returns an input-size reduction error before execution when exhausted.
151    /// Failed consumption refunds every debit, including reserved credit.
152    pub fn consume(&self) -> Result<(), OneShotError> {
153        // Reservation rolls back earlier counters if a later ceiling loses a
154        // race. Redeem only after every counter has supplied its credit.
155        let reservation = self.reserve()?;
156        let mut counter = Some(&reservation);
157        while let Some(reserved) = counter {
158            reserved.take_call()?;
159            counter = reserved.ceiling.as_deref();
160        }
161
162        Ok(())
163    }
164
165    fn from_pool(pool: SharedPool) -> Self {
166        Self {
167            ceiling: None,
168            pool: Arc::new(pool),
169            reservation: None,
170        }
171    }
172
173    /// Incoming chains are flattened before merging so overlapping tails cannot
174    /// charge a counter twice. Retain available reserved credit when present.
175    fn merge_counter(&mut self, counter: Self) {
176        let mut current = self;
177        loop {
178            if Arc::ptr_eq(&current.pool, &counter.pool) {
179                if let Some(reservation) = counter.reservation
180                    && reservation.available.load(Ordering::Relaxed)
181                    && !current
182                        .reservation
183                        .as_ref()
184                        .is_some_and(|call| call.available.load(Ordering::Relaxed))
185                {
186                    current.reservation = Some(reservation);
187                }
188
189                return;
190            }
191            if let Some(ref mut ceiling) = current.ceiling {
192                current = ceiling;
193            } else {
194                current.ceiling = Some(Box::new(counter));
195
196                return;
197            }
198        }
199    }
200
201    fn take_call(&self) -> Result<CallSource, OneShotError> {
202        if let Some(call) = &self.reservation
203            && call.available.swap(false, Ordering::Relaxed)
204        {
205            return Ok(CallSource::Reserved(call.clone()));
206        }
207
208        self.pool.take()?;
209
210        Ok(CallSource::Shared(self.pool.clone()))
211    }
212
213    /// Keep exhaustion terminal for commit assistance as well as transport
214    /// retries.
215    fn exhausted() -> OneShotError {
216        OneShotError::new(
217            "Input exceeds the maximum length reduction budget: provider call limit reached; \
218             changes are preserved",
219        )
220    }
221}
222
223/// One counter shared by every clone, reservation, and ceiling merge.
224struct SharedPool {
225    calls: AtomicUsize,
226    ledger: Option<Arc<dyn ProviderCallLedger>>,
227}
228
229impl SharedPool {
230    /// Debits one call and reports it only after the debit succeeded.
231    fn take(&self) -> Result<(), OneShotError> {
232        self.calls
233            .try_update(Ordering::Relaxed, Ordering::Relaxed, |calls| {
234                calls.checked_sub(1)
235            })
236            .map_err(|_| ProviderCallBudget::exhausted())?;
237        if let Some(ledger) = &self.ledger {
238            ledger.charged();
239        }
240
241        Ok(())
242    }
243
244    /// Reports the refund before the call returns. Crediting first would let
245    /// another owner charge the returned call ahead of its refund, and a
246    /// ledger capped at the limit would then drop that charge.
247    fn refund(&self) {
248        if let Some(ledger) = &self.ledger {
249            ledger.refunded();
250        }
251        self.calls.fetch_add(1, Ordering::Relaxed);
252    }
253}
254
255impl fmt::Debug for SharedPool {
256    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
257        formatter
258            .debug_struct("SharedPool")
259            .field("calls", &self.calls)
260            .field("has_ledger", &self.ledger.is_some())
261            .finish()
262    }
263}
264
265/// Clones share one redeemable call; only its last owner can refund it.
266#[derive(Debug)]
267struct ReservedCall {
268    available: AtomicBool,
269    source: CallSource,
270}
271
272impl Drop for ReservedCall {
273    fn drop(&mut self) {
274        if self.available.load(Ordering::Relaxed) {
275            match &self.source {
276                CallSource::Reserved(parent) => parent.available.store(true, Ordering::Relaxed),
277                CallSource::Shared(pool) => pool.refund(),
278            }
279        }
280    }
281}
282
283/// Nested reservations return unused credit to their original owner.
284#[derive(Debug)]
285enum CallSource {
286    Reserved(Arc<ReservedCall>),
287    Shared(Arc<SharedPool>),
288}
289
290#[cfg(test)]
291#[path = "provider_call_budget_test.rs"]
292mod tests;