Skip to main content

aidaemon_core/
quota.rs

1//! [`QuotaGuard`]: remembers that an account cannot answer for a while.
2
3use std::collections::HashMap;
4use std::sync::{Arc, Mutex};
5use std::time::{Duration, SystemTime};
6
7use async_trait::async_trait;
8use futures::stream::{self, BoxStream, StreamExt};
9
10use crate::provider::{ModelRequest, ModelResponse, Provider, ProviderError, StreamEvent};
11
12/// How long a used-up quota is remembered when the provider does not say
13/// when it resets.
14const QUOTA_UNKNOWN_RESET: Duration = Duration::from_secs(15 * 60);
15/// Longest a stated reset is trusted (a weekly plan window, with room).
16const QUOTA_MAX_COOLDOWN: Duration = Duration::from_secs(8 * 24 * 60 * 60);
17/// How long an account that cannot pay is remembered (credits may be added).
18const BILLING_COOLDOWN: Duration = Duration::from_secs(10 * 60);
19/// How long a rejected credential is remembered: long enough that the other
20/// models of one call are not each sent, short enough to notice a fix.
21const AUTH_COOLDOWN: Duration = Duration::from_secs(60);
22
23/// An account (or one model of it) that will not answer until `until`.
24#[derive(Debug, Clone, PartialEq)]
25pub struct Cooldown {
26    /// The model the cooldown covers, or `None` for the whole account.
27    pub model: Option<String>,
28    pub until: SystemTime,
29    /// The error that started it, returned for every call it blocks.
30    pub error: ProviderError,
31}
32
33/// A provider wrapper for one account. After a failure that no other model
34/// of the account can avoid (a used-up quota, an account that cannot pay, a
35/// rejected credential) it answers every call with that error, without
36/// sending it, until the cooldown ends: until the quota's stated reset, or
37/// for a fixed time when there is none.
38///
39/// Wrap each configured account once and share the guard (it is cheap to
40/// clone through an `Arc`): every caller then learns from the first
41/// failure, and a [`crate::Failover`] chain moves past the account's other
42/// models at once instead of retrying each.
43pub struct QuotaGuard {
44    inner: Arc<dyn Provider>,
45    cooldowns: Mutex<HashMap<Option<String>, Cooldown>>,
46}
47
48impl QuotaGuard {
49    pub fn new(inner: impl Provider + 'static) -> Self {
50        Self::from_arc(Arc::new(inner))
51    }
52
53    pub fn from_arc(inner: Arc<dyn Provider>) -> Self {
54        Self {
55            inner,
56            cooldowns: Mutex::new(HashMap::new()),
57        }
58    }
59
60    /// The cooldowns in force now.
61    pub fn active(&self) -> Vec<Cooldown> {
62        let now = SystemTime::now();
63        let mut cooldowns = self.lock();
64        cooldowns.retain(|_, cooldown| cooldown.until > now);
65        cooldowns.values().cloned().collect()
66    }
67
68    /// Forget every cooldown (say, after the owner changed the credential).
69    pub fn clear(&self) {
70        self.lock().clear();
71    }
72
73    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<Option<String>, Cooldown>> {
74        self.cooldowns
75            .lock()
76            .unwrap_or_else(std::sync::PoisonError::into_inner)
77    }
78
79    /// The error blocking `model` now, if any.
80    fn blocked(&self, model: &str) -> Option<ProviderError> {
81        let now = SystemTime::now();
82        let mut cooldowns = self.lock();
83        cooldowns.retain(|_, cooldown| cooldown.until > now);
84        cooldowns
85            .get(&None)
86            .or_else(|| cooldowns.get(&Some(model.to_string())))
87            .map(|cooldown| cooldown.error.clone())
88    }
89
90    /// Start a cooldown if `error` says waiting is the only cure.
91    fn record(&self, model: &str, error: &ProviderError) {
92        let now = SystemTime::now();
93        let (key, lasts) = match error {
94            ProviderError::QuotaExhausted {
95                resets_at,
96                per_model,
97                ..
98            } => {
99                let lasts = match resets_at {
100                    Some(at) => match at.duration_since(now) {
101                        Ok(left) => left.min(QUOTA_MAX_COOLDOWN),
102                        // Already past: the clock or the provider is off.
103                        // Remember it briefly rather than not at all.
104                        Err(_) => AUTH_COOLDOWN,
105                    },
106                    None => QUOTA_UNKNOWN_RESET,
107                };
108                (per_model.then(|| model.to_string()), lasts)
109            }
110            // A stated affordable output means a smaller request may pass.
111            ProviderError::Billing {
112                affordable_tokens: None,
113                ..
114            } => (None, BILLING_COOLDOWN),
115            ProviderError::Auth(_) => (None, AUTH_COOLDOWN),
116            _ => return,
117        };
118        // Every call the cooldown blocks is refused here, before it is
119        // sent, whatever the original answer was.
120        let mut refusal = error.clone();
121        if let ProviderError::QuotaExhausted { in_stream, .. } = &mut refusal {
122            *in_stream = false;
123        }
124        self.lock().insert(
125            key.clone(),
126            Cooldown {
127                model: key,
128                until: now + lasts,
129                error: refusal,
130            },
131        );
132    }
133}
134
135#[async_trait]
136impl Provider for QuotaGuard {
137    fn name(&self) -> &str {
138        self.inner.name()
139    }
140
141    fn default_model(&self) -> Option<&str> {
142        self.inner.default_model()
143    }
144
145    async fn complete(&self, request: &ModelRequest) -> Result<ModelResponse, ProviderError> {
146        if let Some(error) = self.blocked(&request.model) {
147            return Err(error);
148        }
149        let result = self.inner.complete(request).await;
150        if let Err(error) = &result {
151            self.record(&request.model, error);
152        }
153        result
154    }
155
156    fn unavailable_until(&self, model: &str) -> Option<SystemTime> {
157        let now = SystemTime::now();
158        let mut cooldowns = self.lock();
159        cooldowns.retain(|_, cooldown| cooldown.until > now);
160        [
161            cooldowns.get(&None),
162            cooldowns.get(&Some(model.to_string())),
163        ]
164        .into_iter()
165        .flatten()
166        .map(|cooldown| cooldown.until)
167        .max()
168    }
169
170    fn stream<'a>(
171        &'a self,
172        request: &'a ModelRequest,
173    ) -> BoxStream<'a, Result<StreamEvent, ProviderError>> {
174        if let Some(error) = self.blocked(&request.model) {
175            return stream::iter([Err(error)]).boxed();
176        }
177        self.inner
178            .stream(request)
179            .inspect(move |event| {
180                if let Err(error) = event {
181                    self.record(&request.model, error);
182                }
183            })
184            .boxed()
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191    use crate::testing::{ScriptedProvider, text};
192    use crate::{Failover, FailoverStep};
193
194    fn request(model: &str) -> ModelRequest {
195        ModelRequest {
196            model: model.into(),
197            messages: vec![crate::Message::user("hello")],
198            ..Default::default()
199        }
200    }
201
202    fn capped(resets_at: Option<SystemTime>, per_model: bool) -> ProviderError {
203        ProviderError::QuotaExhausted {
204            message: "plan cap".into(),
205            resets_at,
206            per_model,
207            in_stream: false,
208        }
209    }
210
211    /// Behind an `Arc<dyn Provider>` (how every backend is held) the guard
212    /// still says when a used-up model can answer again.
213    #[tokio::test]
214    async fn a_shared_guard_reports_its_cooldown() {
215        let reset = SystemTime::now() + Duration::from_secs(3600);
216        let shared: Arc<dyn Provider> = Arc::new(QuotaGuard::new(ScriptedProvider::with_results(
217            vec![Err(capped(Some(reset), false))],
218        )));
219        assert_eq!(shared.unavailable_until("model-a"), None);
220        let _ = shared.complete(&request("model-a")).await;
221        let until = shared.unavailable_until("model-b").expect("known out");
222        assert!(until > SystemTime::now() + Duration::from_secs(3500));
223    }
224
225    /// A plan cap on the first model blocks the account's other models
226    /// without sending them, until the stated reset.
227    #[tokio::test]
228    async fn an_account_cap_blocks_every_model_without_sending() {
229        let reset = SystemTime::now() + Duration::from_secs(3600);
230        let inner = Arc::new(ScriptedProvider::with_results(vec![
231            Err(capped(Some(reset), false)),
232            Ok(text("never sent")),
233        ]));
234        let guard = QuotaGuard::from_arc(inner.clone());
235
236        assert_eq!(
237            guard.complete(&request("model-a")).await,
238            Err(capped(Some(reset), false))
239        );
240        assert_eq!(
241            guard.complete(&request("model-b")).await,
242            Err(capped(Some(reset), false))
243        );
244        assert_eq!(inner.requests().len(), 1);
245        let active = guard.active();
246        assert_eq!(active.len(), 1);
247        assert_eq!(active[0].model, None);
248        assert!(active[0].until >= reset - Duration::from_secs(1));
249    }
250
251    /// A per-model quota (a daily allowance of one model) leaves the
252    /// account's other models alone.
253    #[tokio::test]
254    async fn a_per_model_cap_blocks_only_that_model() {
255        let inner = Arc::new(ScriptedProvider::with_results(vec![
256            Err(capped(None, true)),
257            Ok(text("other model answers")),
258        ]));
259        let guard = QuotaGuard::from_arc(inner.clone());
260
261        assert!(guard.complete(&request("model-a")).await.is_err());
262        assert_eq!(
263            guard.stream(&request("model-a")).collect::<Vec<_>>().await,
264            vec![Err(capped(None, true))]
265        );
266        let other = guard.complete(&request("model-b")).await.unwrap();
267        assert_eq!(other.text, "other model answers");
268        assert_eq!(inner.requests().len(), 2);
269    }
270
271    /// Throttling, outages and a billing error that names a smaller
272    /// affordable request are not remembered.
273    #[tokio::test]
274    async fn retryable_and_affordable_errors_start_no_cooldown() {
275        let inner = Arc::new(ScriptedProvider::with_results(vec![
276            Err(ProviderError::RateLimited { retry_after: None }),
277            Err(ProviderError::Transient("blip".into())),
278            Err(ProviderError::Billing {
279                message: "402".into(),
280                affordable_tokens: Some(600),
281            }),
282            Ok(text("answered")),
283        ]));
284        let guard = QuotaGuard::from_arc(inner.clone());
285        for _ in 0..3 {
286            assert!(guard.complete(&request("model-a")).await.is_err());
287        }
288        assert!(guard.active().is_empty());
289        assert_eq!(
290            guard.complete(&request("model-a")).await.unwrap().text,
291            "answered"
292        );
293    }
294
295    #[tokio::test]
296    async fn an_unpayable_account_and_a_rejected_key_are_remembered() {
297        let broke = QuotaGuard::new(ScriptedProvider::with_results(vec![Err(
298            ProviderError::Billing {
299                message: "no credits".into(),
300                affordable_tokens: None,
301            },
302        )]));
303        assert!(broke.complete(&request("m")).await.is_err());
304        assert!(matches!(
305            broke.complete(&request("other")).await,
306            Err(ProviderError::Billing { .. })
307        ));
308
309        let rejected = QuotaGuard::new(ScriptedProvider::with_results(vec![Err(
310            ProviderError::Auth("revoked".into()),
311        )]));
312        assert!(
313            rejected
314                .stream(&request("m"))
315                .next()
316                .await
317                .unwrap()
318                .is_err()
319        );
320        assert_eq!(rejected.active().len(), 1);
321        rejected.clear();
322        assert!(rejected.active().is_empty());
323    }
324
325    /// In a chain, a capped account's remaining models fail at once and the
326    /// next account answers: no backoff is spent on models that share the
327    /// cap.
328    #[tokio::test(start_paused = true)]
329    async fn a_failover_chain_moves_past_a_capped_account_at_once() {
330        let account = Arc::new(QuotaGuard::new(ScriptedProvider::with_results(vec![Err(
331            capped(None, false),
332        )])));
333        let other = ScriptedProvider::new(vec![text("from the other provider")]);
334        let chain = Failover::new(vec![
335            FailoverStep::from_arc(account.clone())
336                .model("plan-a")
337                .attempts(3),
338            FailoverStep::from_arc(account.clone())
339                .model("plan-b")
340                .attempts(3),
341            FailoverStep::new(other).model("other-model"),
342        ]);
343        let started = tokio::time::Instant::now();
344        let response = chain.complete(&request("plan-a")).await.unwrap();
345        assert_eq!(response.text, "from the other provider");
346        assert_eq!(started.elapsed(), Duration::ZERO);
347    }
348
349    /// A used-up account says until when every model of it cannot answer;
350    /// one that has not failed may answer now.
351    #[tokio::test]
352    async fn a_cooldown_says_until_when_the_model_cannot_answer() {
353        let reset = SystemTime::now() + Duration::from_secs(3_600);
354        let guard = QuotaGuard::new(ScriptedProvider::with_results(vec![Err(
355            ProviderError::QuotaExhausted {
356                message: "limit".into(),
357                resets_at: Some(reset),
358                per_model: false,
359                in_stream: true,
360            },
361        )]));
362        assert_eq!(guard.unavailable_until("any-model"), None);
363        let _ = guard.complete(&request("model-a")).await;
364        let until = guard
365            .unavailable_until("model-b")
366            .expect("account cooldown");
367        assert!(until >= reset - Duration::from_secs(1) && until <= reset);
368        // A blocked call is refused before it is sent: provably unspent.
369        let refusal = guard.complete(&request("model-b")).await.unwrap_err();
370        assert!(refusal.proves_nothing_spent(), "{refusal:?}");
371    }
372}