Skip to main content

lean_ctx_cloud/
throttle.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Quota and policy throttles (Release B, Cloud API §7.2 and §8.1).
3//!
4//! When Cloud answers `429 quota_exceeded` (monthly transfer or bus
5//! messages), `409 quota_exceeded` for a cooling-down Personal engine slot, or
6//! `403 policy_denied`, the engine records a throttle in
7//! `<data_dir>/throttles.json` and every path it applies to waits instead
8//! of asking again: sync and pushes, bus publishes, task claims, connect.
9//! The local work stays where it is (the replica's pending events, the bus
10//! queue, the outbox) and goes once the throttle ends.
11//!
12//! Backoff rules (deterministic, never a busy loop):
13//! - monthly quota (429): until `now + retry_after_s` (the body's value, or
14//!   the `Retry-After` header), else `reset_at`, else the start of the next
15//!   calendar month (UTC), the reset the contract names; at least
16//!   [`MIN_WAIT_S`], at most [`MAX_WAIT_S`];
17//! - Personal slot cool-down (409 `registered_instances`, `cooldown_days`): until
18//!   `reset_at` (the web recovery frees it sooner, P7);
19//! - policy refusal (403) of a bus publish or a task claim:
20//!   [`POLICY_HOLD_S`] per member and path, then one try (an admin may have
21//!   changed the policy meanwhile), and at once when a newer policy is
22//!   installed ([`policy_changed`]); a sync refusal holds only its draft
23//!   (outbox, same wait, also ended by a newer policy) or its vault sync,
24//!   never the other vaults;
25//! - the subscription models gateway (mz6, [`Scope::Models`]): `429
26//!   quota_exceeded` for `model_credit_usd_micros` holds like a monthly
27//!   quota; `402 plan_required` (key `plan:models`, ended by a plan change)
28//!   and `403 policy_denied` hold [`POLICY_HOLD_S`]; the proxy's `leanctx`
29//!   provider answers locally meanwhile ([`models_hold_kind`]);
30//! - other counted quotas (409 `private_vaults`, a slot without
31//!   cool-down): no throttle; the refusal is shown and nothing retries it
32//!   by itself;
33//! - token mint rate limit (429 `rate_limited` at `/instances/{id}/token`):
34//!   one hold for every process of this machine (they all mint with the
35//!   same instance key, on the same server budget). It grows exponentially
36//!   with each 429 in a row, from [`RATE_FIRST_S`] up to [`RATE_MAX_WAIT_S`],
37//!   and never ends before the server's `Retry-After` (the floor, also
38//!   above the cap). No caller passes it, a person's manual sync neither:
39//!   the server counts refused attempts too. A minted token ends it.
40//!
41//! `lean-ctx cloud status` lists the active throttles ([`status_lines`]).
42
43use std::collections::BTreeMap;
44
45use lean_ctx_time::{OffsetDateTime, UtcDateTime};
46use serde::{Deserialize, Serialize};
47
48use super::CloudError;
49use super::state::{CloudStore, load_or_quarantine, lock_state, write_private};
50
51pub(crate) const THROTTLE_FILE: &str = "throttles.json";
52/// The shortest wait of a throttle: one tick of a loop is never a retry.
53pub const MIN_WAIT_S: i64 = 60;
54/// The longest wait (a reset further out is shortened to this).
55pub const MAX_WAIT_S: i64 = 32 * 86_400;
56/// How long a policy refusal holds its path.
57pub const POLICY_HOLD_S: i64 = 15 * 60;
58/// A quota throttle lets one call through this often before it ends, so a
59/// quota that was raised or lowered in Cloud is noticed (E2E-FINAL: sync
60/// waited for the month's end after usage was lowered).
61pub const QUOTA_PROBE_S: i64 = 3600;
62/// The key of the token mint rate limit.
63const TOKEN_KEY: &str = "rate:token";
64/// The scope name the token mint hold shows in `cloud status`.
65pub const TOKEN_SCOPE: &str = "token";
66/// The first wait after a token mint 429 (a longer `Retry-After` wins).
67pub const RATE_FIRST_S: i64 = 60;
68/// The longest computed token mint wait; a longer `Retry-After` still wins.
69pub const RATE_MAX_WAIT_S: i64 = 3600;
70/// The longest server `Retry-After` the token mint hold honours (a day).
71pub const RATE_FLOOR_MAX_S: i64 = 86_400;
72/// How long an ended token mint hold is remembered, so that the next 429
73/// within it doubles the wait instead of starting again at the first.
74pub const RATE_MEMORY_S: i64 = 6 * 3600;
75
76/// The engine paths a throttle can hold.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
78pub enum Scope {
79    /// Knowledge sync, event tail and push, snapshots (transfer).
80    Sync,
81    /// Bus publishes (bus messages).
82    Bus,
83    /// Task claims, renewals and results.
84    Tasks,
85    /// A new engine registration (`cloud connect`).
86    Connect,
87    /// The `leanctx` provider's requests to the Cloud models gateway (mz6).
88    Models,
89}
90
91impl Scope {
92    pub fn as_str(self) -> &'static str {
93        match self {
94            Self::Sync => "sync",
95            Self::Bus => "bus",
96            Self::Tasks => "tasks",
97            Self::Connect => "connect",
98            Self::Models => "models",
99        }
100    }
101}
102
103/// The paths a quota resource holds besides the one that met it.
104fn resource_scopes(resource: &str) -> &'static [Scope] {
105    match resource {
106        // API §8.1: transfer counts the engine data routes (event push and
107        // tail, snapshots and segments, knowledge, graphs, bus history).
108        "transfer_bytes" => &[Scope::Sync],
109        "bus_messages" => &[Scope::Bus],
110        "registered_instances" => &[Scope::Connect],
111        // mz6: the month's model credit, counted by the models gateway.
112        "model_credit_usd_micros" => &[Scope::Models],
113        _ => &[],
114    }
115}
116
117/// One recorded throttle.
118#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
119pub struct Throttle {
120    /// Sorted scope names it holds.
121    pub scopes: Vec<String>,
122    /// When it ends, second precision `Z`.
123    pub until: String,
124    /// The refusal, as `CloudError` shows it.
125    pub line: String,
126    /// A quota throttle's next probe ([`QUOTA_PROBE_S`]): from then one
127    /// call may pass, and its success ends the throttle ([`passed`]).
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub probe_at: Option<String>,
130    /// The token mint hold's 429s in a row (its backoff step); 0 elsewhere.
131    #[serde(default, skip_serializing_if = "is_zero")]
132    pub strikes: u32,
133}
134
135#[allow(clippy::trivially_copy_pass_by_ref)] // serde passes a reference
136fn is_zero(n: &u32) -> bool {
137    *n == 0
138}
139
140impl Throttle {
141    fn holds(&self, scope: Scope) -> bool {
142        self.scopes.iter().any(|s| s == scope.as_str())
143    }
144
145    fn active_at(&self, now: UtcDateTime) -> bool {
146        OffsetDateTime::parse_from_rfc3339(&self.until).is_ok_and(|until| until > now)
147    }
148
149    /// Whether it is kept at `now`: while active, and a token mint hold
150    /// also [`RATE_MEMORY_S`] after it ended (its backoff step counts on).
151    /// A stale token mint hold ([`Self::token_stale`]) is not kept.
152    fn kept_at(&self, key: &str, now: UtcDateTime) -> bool {
153        if key == TOKEN_KEY {
154            return !self.token_stale(now)
155                && OffsetDateTime::parse_from_rfc3339(&self.until).is_ok_and(|until| {
156                    until.to_utc() + lean_ctx_time::Duration::seconds(RATE_MEMORY_S) > now
157                });
158        }
159        self.active_at(now)
160    }
161
162    /// Whether this token mint hold ends more than [`RATE_FLOOR_MAX_S`]
163    /// after `now`: longer than any hold is written for, so it was written
164    /// under another clock (a clock set back, or one that ran ahead when it
165    /// was written) and holds nothing. Otherwise it would block every cloud
166    /// call for as long as the clock jumped, and no mint could clear it.
167    fn token_stale(&self, now: UtcDateTime) -> bool {
168        OffsetDateTime::parse_from_rfc3339(&self.until)
169            .is_ok_and(|until| (until.to_utc() - now).num_seconds() > RATE_FLOOR_MAX_S)
170    }
171
172    /// The error a held path answers instead of calling Cloud.
173    #[must_use]
174    pub fn refusal(&self) -> CloudError {
175        CloudError::Refused(format!(
176            "waiting for the Cloud until {}: {}",
177            self.until, self.line
178        ))
179    }
180}
181
182#[derive(Debug, Clone, Default, Serialize, Deserialize)]
183struct Throttles {
184    /// Key (`quota:<resource>` or `policy:<member>:<scope>`) → throttle.
185    #[serde(default)]
186    items: BTreeMap<String, Throttle>,
187}
188
189fn stamp(at: UtcDateTime) -> String {
190    at.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
191}
192
193/// 00:00 UTC on the first day of the month after `now`'s.
194fn next_month(now: UtcDateTime) -> UtcDateTime {
195    let (year, month) = if now.month() == 12 {
196        (now.year() + 1, 1)
197    } else {
198        (now.year(), now.month() + 1)
199    };
200    UtcDateTime::with_ymd_and_hms(year, month, 1, 0, 0, 0)
201        .unwrap_or(now + lean_ctx_time::Duration::days(31))
202}
203
204/// `until` itself when it is [`MIN_WAIT_S`]..=[`MAX_WAIT_S`] away (so a
205/// `reset_at` is kept to the second), else the nearer bound.
206fn clamp(now: UtcDateTime, until: UtcDateTime) -> UtcDateTime {
207    let wait = (until - now).num_seconds();
208    if (MIN_WAIT_S..=MAX_WAIT_S).contains(&wait) {
209        until
210    } else {
211        now + lean_ctx_time::Duration::seconds(wait.clamp(MIN_WAIT_S, MAX_WAIT_S))
212    }
213}
214
215/// The throttle `error` sets at `now`, if it sets one: on the paths its
216/// quota resource holds plus `scope`, the path that met it (`None`: an
217/// HTTP call of unknown path, so only the resource's paths; a policy
218/// refusal then sets nothing).
219#[must_use]
220pub fn of_error(
221    scope: Option<Scope>,
222    error: &CloudError,
223    now: UtcDateTime,
224) -> Option<(String, Throttle)> {
225    let (key, scopes, until) = match error {
226        CloudError::QuotaExceeded(q) if q.waits() => {
227            let until = match error.retry_after_at(now) {
228                // Clamped before the arithmetic: a huge `retry_after_s`
229                // (up to u64::MAX) must not overflow the time type (a panic).
230                Some(seconds) => {
231                    let wait = i64::try_from(seconds)
232                        .unwrap_or(MAX_WAIT_S)
233                        .clamp(MIN_WAIT_S, MAX_WAIT_S);
234                    now + lean_ctx_time::Duration::seconds(wait)
235                }
236                None => next_month(now),
237            };
238            (
239                format!("quota:{}", q.resource),
240                resource_scopes(&q.resource),
241                clamp(now, until),
242            )
243        }
244        CloudError::QuotaExceeded(q) if q.cooling_slot() => {
245            let reset = OffsetDateTime::parse_from_rfc3339(q.reset_at.as_deref()?)
246                .ok()?
247                .to_utc();
248            (
249                format!("quota:{}", q.resource),
250                resource_scopes(&q.resource),
251                clamp(now, reset),
252            )
253        }
254        CloudError::PolicyDenied(d) => (
255            format!(
256                "policy:{}:{}",
257                d.member.as_deref().unwrap_or("unknown"),
258                scope?.as_str()
259            ),
260            &[][..],
261            now + lean_ctx_time::Duration::seconds(POLICY_HOLD_S),
262        ),
263        // A gateway `402 plan_required` (the plan lost the subscription
264        // models): the models path waits like a policy hold; a newer lease
265        // ends it at once ([`plan_changed`]). Elsewhere a 402 sets nothing.
266        CloudError::PlanRequired(_) if scope == Some(Scope::Models) => (
267            "plan:models".to_string(),
268            &[][..],
269            now + lean_ctx_time::Duration::seconds(POLICY_HOLD_S),
270        ),
271        _ => return None,
272    };
273    let mut names: Vec<String> = scope
274        .into_iter()
275        .chain(scopes.iter().copied())
276        .map(|s| s.as_str().to_string())
277        .collect();
278    names.sort();
279    names.dedup();
280    if names.is_empty() {
281        return None;
282    }
283    let probe = now + lean_ctx_time::Duration::seconds(QUOTA_PROBE_S);
284    let probe_at = (key.starts_with("quota:") && until > probe).then(|| stamp(probe));
285    Some((
286        key,
287        Throttle {
288            scopes: names,
289            until: stamp(until),
290            line: error.to_string(),
291            probe_at,
292            strikes: 0,
293        },
294    ))
295}
296
297fn read(store: &CloudStore) -> Throttles {
298    load_or_quarantine(&store.data_dir().join(THROTTLE_FILE), |_: &Throttles| true)
299        .ok()
300        .flatten()
301        .unwrap_or_default()
302}
303
304fn change(store: &CloudStore, edit: impl FnOnce(&mut Throttles)) -> Result<(), CloudError> {
305    let dir = store.data_dir();
306    let _lock = lock_state(dir, THROTTLE_FILE)?;
307    let mut throttles = read(store);
308    edit(&mut throttles);
309    let bytes = serde_json::to_vec(&throttles).map_err(|e| CloudError::Local(e.to_string()))?;
310    write_private(dir, THROTTLE_FILE, &bytes)
311}
312
313/// Record the throttle `error` sets on `scope` (expired ones are dropped
314/// on the way) and pass the error on unchanged.
315pub fn note(store: &CloudStore, scope: Scope, error: CloudError, now: UtcDateTime) -> CloudError {
316    note_on(store, Some(scope), error, now)
317}
318
319/// [`note`] for an answer of any engine route: a quota holds the paths its
320/// resource names (every authenticated call passes here, `Session`).
321pub fn note_on(
322    store: &CloudStore,
323    scope: Option<Scope>,
324    error: CloudError,
325    now: UtcDateTime,
326) -> CloudError {
327    if let Some((key, throttle)) = of_error(scope, &error, now)
328        && let Err(e) = change(store, |t| {
329            t.items.retain(|k, v| v.kept_at(k, now));
330            t.items.insert(key, throttle);
331        })
332    {
333        tracing::warn!("cloud: could not record a throttle: {e}");
334    }
335    error
336}
337
338/// The token mint wait after the `strikes`-th 429 in a row (`strikes >= 1`)
339/// with the server's `Retry-After` `floor`: doubling from [`RATE_FIRST_S`]
340/// up to [`RATE_MAX_WAIT_S`], never shorter than the floor (which is kept
341/// above the cap too, up to [`RATE_FLOOR_MAX_S`]: a broken or hostile
342/// answer cannot stop every call for weeks).
343#[must_use]
344pub fn rate_wait(strikes: u32, floor: Option<u64>) -> i64 {
345    let backoff = RATE_FIRST_S
346        .saturating_mul(1i64 << strikes.saturating_sub(1).min(16))
347        .min(RATE_MAX_WAIT_S);
348    let floor = floor.map_or(0, |s| {
349        i64::try_from(s)
350            .unwrap_or(RATE_FLOOR_MAX_S)
351            .min(RATE_FLOOR_MAX_S)
352    });
353    backoff.max(floor).max(1)
354}
355
356/// Record a `429 rate_limited` of the token mint: every process of this
357/// machine waits [`rate_wait`] before it mints again. Any other error is
358/// left alone. Returns the error unchanged.
359pub fn note_token_limit(store: &CloudStore, error: CloudError, now: UtcDateTime) -> CloudError {
360    let CloudError::RateLimited { retry_after } = &error else {
361        return error;
362    };
363    let floor = *retry_after;
364    let line = error.to_string();
365    if let Err(e) = change(store, |t| {
366        let strikes = t
367            .items
368            .get(TOKEN_KEY)
369            .filter(|prev| prev.kept_at(TOKEN_KEY, now))
370            .map_or(0, |prev| prev.strikes)
371            .saturating_add(1);
372        let until = now + lean_ctx_time::Duration::seconds(rate_wait(strikes, floor));
373        t.items.retain(|k, v| v.kept_at(k, now));
374        t.items.insert(
375            TOKEN_KEY.to_string(),
376            Throttle {
377                scopes: vec![TOKEN_SCOPE.to_string()],
378                until: stamp(until),
379                line,
380                probe_at: None,
381                strikes,
382            },
383        );
384    }) {
385        tracing::warn!("cloud: could not record the token rate limit: {e}");
386    }
387    error
388}
389
390/// While the token mint is held at `now`: the `429 rate_limited` a mint
391/// answers instead of calling the cloud, with the seconds left as `retry_after`
392/// (so every caller's backoff waits at least as long). A stale hold (more
393/// than [`RATE_FLOOR_MAX_S`] left) holds nothing; the next change drops it.
394#[must_use]
395pub fn token_hold(store: &CloudStore, now: UtcDateTime) -> Option<CloudError> {
396    let held = read(store).items.remove(TOKEN_KEY)?;
397    let until = OffsetDateTime::parse_from_rfc3339(&held.until).ok()?;
398    let left = (until.to_utc() - now).num_seconds();
399    (left > 0 && left <= RATE_FLOOR_MAX_S).then(|| CloudError::RateLimited {
400        retry_after: u64::try_from(left).ok(),
401    })
402}
403
404/// A token was minted: the token mint hold and its backoff step end.
405pub fn token_minted(store: &CloudStore) {
406    if read(store).items.contains_key(TOKEN_KEY) {
407        let _ = change(store, |t| {
408            t.items.remove(TOKEN_KEY);
409        });
410    }
411}
412
413/// The active throttle holding `scope` at `now` (the one ending last).
414#[must_use]
415pub fn holding(store: &CloudStore, scope: Scope, now: UtcDateTime) -> Option<Throttle> {
416    read(store)
417        .items
418        .into_values()
419        .filter(|t| t.holds(scope) && t.active_at(now))
420        .max_by(|a, b| a.until.cmp(&b.until))
421}
422
423/// `Err` with the throttle's refusal while `scope` is held. When only
424/// quota throttles hold it and their probe is due, one call passes (the
425/// next probe is an hour later): a success ends them ([`passed`]), a new
426/// refusal records them again.
427pub fn check(store: &CloudStore, scope: Scope, now: UtcDateTime) -> Result<(), CloudError> {
428    let Some(held) = holding(store, scope, now) else {
429        return Ok(());
430    };
431    let due = |t: &Throttle| {
432        t.probe_at
433            .as_deref()
434            .and_then(|p| OffsetDateTime::parse_from_rfc3339(p).ok())
435            .is_some_and(|p| p <= now)
436    };
437    let throttles = read(store);
438    let active: Vec<(&String, &Throttle)> = throttles
439        .items
440        .iter()
441        .filter(|(_, t)| t.holds(scope) && t.active_at(now))
442        .collect();
443    if !active
444        .iter()
445        .all(|(k, t)| k.starts_with("quota:") && due(t))
446    {
447        return Err(held.refusal());
448    }
449    let next = stamp(now + lean_ctx_time::Duration::seconds(QUOTA_PROBE_S));
450    let keys: Vec<String> = active.iter().map(|(k, _)| (*k).clone()).collect();
451    let _ = change(store, |t| {
452        for k in &keys {
453            if let Some(v) = t.items.get_mut(k) {
454                v.probe_at = Some(next.clone());
455            }
456        }
457    });
458    Ok(())
459}
460
461/// Whether a quota throttle (not only a policy hold) holds `scope` now.
462#[must_use]
463pub fn quota_holds(store: &CloudStore, scope: Scope, now: UtcDateTime) -> bool {
464    read(store)
465        .items
466        .iter()
467        .any(|(k, t)| k.starts_with("quota:") && t.holds(scope) && t.active_at(now))
468}
469
470/// What holds the models path (mz6), for the local answer's status.
471#[derive(Debug, Clone, Copy, PartialEq, Eq)]
472pub enum HoldKind {
473    Quota,
474    Plan,
475    Policy,
476}
477
478/// The kind of the throttle ending last among those holding
479/// [`Scope::Models`] at `now` (a policy hold when none is a quota or plan).
480#[must_use]
481pub fn models_hold_kind(store: &CloudStore, now: UtcDateTime) -> HoldKind {
482    read(store)
483        .items
484        .iter()
485        .filter(|(_, t)| t.holds(Scope::Models) && t.active_at(now))
486        .max_by(|a, b| a.1.until.cmp(&b.1.until))
487        .map_or(HoldKind::Policy, |(k, _)| {
488            if k.starts_with("quota:") {
489                HoldKind::Quota
490            } else if k.starts_with("plan:") {
491                HoldKind::Plan
492            } else {
493                HoldKind::Policy
494            }
495        })
496}
497
498/// The quota is back (a successful call, or an answer that shows it):
499/// every quota throttle holding `scope` ends.
500pub fn quota_lifted(store: &CloudStore, scope: Scope) {
501    if read(store)
502        .items
503        .iter()
504        .any(|(k, t)| k.starts_with("quota:") && t.holds(scope))
505    {
506        let _ = change(store, |t| {
507            t.items
508                .retain(|k, v| !(k.starts_with("quota:") && v.holds(scope)));
509        });
510    }
511}
512
513/// A successful call on `scope`: its policy holds and quota throttles are
514/// over (a probe that passed, or a quota raised in Cloud meanwhile).
515pub fn passed(store: &CloudStore, scope: Scope) {
516    let suffix = format!(":{}", scope.as_str());
517    if read(store)
518        .items
519        .keys()
520        .any(|k| k.starts_with("policy:") && k.ends_with(&suffix))
521    {
522        let _ = change(store, |t| {
523            t.items
524                .retain(|k, _| !(k.starts_with("policy:") && k.ends_with(&suffix)));
525        });
526    }
527    quota_lifted(store, scope);
528}
529
530/// The workspace's plan changed (a newer lease): every quota throttle was
531/// the old plan's answer and ends, and so does a plan hold of the models
532/// path; policy holds stay.
533pub fn plan_changed(store: &CloudStore) {
534    let old_plan = |k: &str| k.starts_with("quota:") || k.starts_with("plan:");
535    if read(store).items.keys().any(|k| old_plan(k)) {
536        let _ = change(store, |t| t.items.retain(|k, _| !old_plan(k)));
537    }
538}
539
540/// A newer policy is in force: every policy hold is over, on every path
541/// (each was the old policy's answer), and so is every outbox item's
542/// policy wait (a refused knowledge draft); quota throttles stay.
543pub fn policy_changed(store: &CloudStore) {
544    if read(store).items.keys().any(|k| k.starts_with("policy:")) {
545        let _ = change(store, |t| t.items.retain(|k, _| !k.starts_with("policy:")));
546    }
547    super::outbox::Outbox::at(store.data_dir()).release_policy_holds();
548}
549
550/// A new enrolment starts without the old connect throttle.
551pub fn clear_connect(store: &CloudStore) {
552    let _ = change(store, |t| {
553        t.items.retain(|_, v| !v.holds(Scope::Connect));
554    });
555}
556
557/// `cloud status` lines of every active throttle, sorted by key (stable).
558#[must_use]
559pub fn status_lines(store: &CloudStore, now: UtcDateTime) -> Vec<String> {
560    read(store)
561        .items
562        .iter()
563        .filter(|(key, t)| t.active_at(now) && !(key.as_str() == TOKEN_KEY && t.token_stale(now)))
564        .map(|(_, t)| {
565            format!(
566                "Throttled:    {} until {}: {}",
567                t.scopes.join(", "),
568                t.until,
569                t.line
570            )
571        })
572        .collect()
573}
574
575#[cfg(test)]
576#[path = "throttle_tests.rs"]
577mod tests;