Skip to main content

orch/engine/cooldown/
mod.rs

1//! Per-agent and per-model cooldown tracking.
2//!
3//! Shared by `engine::runner::response` (recording failures) and
4//! `engine::router::config` (avoiding cooled models during pool selection).
5//!
6//! # Persistence
7//!
8//! All cooldowns are persisted to the KV store in SQLite so they survive
9//! service restarts. Call [`init_cooldown_store`] once at startup (after
10//! the `TaskStore` is open) to register the store and pre-load unexpired
11//! cooldowns.
12//!
13//! When a rate limit includes a "try again at {date}" message, the cooldown
14//! is set to that specific timestamp instead of the default duration.
15//! Relative usage windows (e.g. "5-hour usage limit") are also detected and
16//! used to set a model-specific cooldown matching the advertised window.
17
18use chrono::TimeZone;
19use regex::Regex;
20use std::collections::HashMap;
21use std::collections::HashSet;
22use std::sync::LazyLock;
23use std::sync::MutexGuard;
24use std::sync::{Arc, Mutex, OnceLock};
25use tokio::sync;
26
27use crate::engine::router::config;
28#[cfg(test)]
29use crate::engine::runner::agents::opencode;
30use crate::store::TaskStore;
31
32/// Default fallback cooldown for agents when no store is available: 30 minutes.
33///
34/// Used in contexts that need a concrete duration and cannot compute exponential
35/// backoff (e.g. computing how long to wait before retrying when a cooldown
36/// expiry timestamp is unknown). New code should use [`BACKOFF_BASE_SECS`] instead.
37pub const AGENT_COOLDOWN_SECS: i64 = 30 * 60;
38
39/// Base backoff for generic agent/model failures: 5 minutes.
40pub const BACKOFF_BASE_SECS: i64 = 5 * 60;
41
42/// Maximum backoff for generic agent/model failures: 4 hours.
43pub const BACKOFF_MAX_SECS: i64 = 4 * 60 * 60;
44
45/// Base backoff for persistent model failures (silent exit/provider errors): 4 hours.
46pub const PERSISTENT_MODEL_BACKOFF_BASE_SECS: i64 = 4 * 60 * 60;
47
48/// Maximum backoff for persistent model failures: 7 days.
49pub const PERSISTENT_MODEL_BACKOFF_MAX_SECS: i64 = 7 * 24 * 60 * 60;
50
51/// Base backoff for a one-off model failure that does not mean the model is gone: 5 minutes.
52pub const TRANSIENT_MODEL_BACKOFF_BASE_SECS: i64 = 5 * 60;
53
54/// Maximum backoff for a one-off model failure: 15 minutes.
55pub const TRANSIENT_MODEL_BACKOFF_MAX_SECS: i64 = 15 * 60;
56
57/// Base backoff for credit exhaustion (out_of_credits): 1 hour.
58pub const CREDIT_BACKOFF_BASE_SECS: i64 = 60 * 60;
59
60/// Base backoff for org-level disabling: 2 hours.
61pub const ORG_BACKOFF_BASE_SECS: i64 = 2 * 60 * 60;
62
63/// Standard cap for credit exhaustion and org-level disabling: 8 hours.
64/// Repeated failures at the cap move to the extended tiers (48h, then 96h)
65pub const CREDIT_BACKOFF_MAX_SECS: i64 = 8 * 60 * 60;
66
67/// Base cooldown for billing cycle exhaustion: 24 hours.
68///
69/// Unlike per-request rate limits, billing cycle exhaustion is a calendar event
70/// that won't self-resolve for days or weeks. The first failure starts at 24h;
71/// subsequent failures escalate via `compute_backoff()` up to
72/// `BILLING_CYCLE_MAX_SECS` (7 days). This prevents daily retry-and-fail cycles
73/// when a monthly billing quota is exhausted.
74pub const BILLING_CYCLE_COOLDOWN_SECS: i64 = 24 * 60 * 60;
75
76/// Maximum cooldown for billing cycle exhaustion: 7 days.
77///
78/// Monthly billing cycles typically reset on a fixed date. 7 days is a
79/// reasonable cap — the cooldown will expire before the next monthly reset
80/// in most cases, allowing a single probe to re-check availability.
81pub const BILLING_CYCLE_MAX_SECS: i64 = 7 * 24 * 60 * 60;
82
83/// Credit exhaustion reason detected from error message.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum CreditExhaustionReason {
86    /// Per-model credit exhaustion (out_of_credits).
87    OutOfCredits,
88    /// Organization-level disabling (org_level_disabled).
89    OrgLevelDisabled,
90    /// Monthly billing cycle exhaustion — escalating cooldown (24h base, 7d cap).
91    BillingCycleExhausted,
92}
93
94impl CreditExhaustionReason {
95    /// Stable string for `task_runs.outcome`, distinct from the cooldown reason
96    /// string used by `record_credit_exhaustion`. Lets callers persist the actual
97    /// failure mode instead of collapsing it into a generic "rate_limit"/"failed".
98    pub fn outcome_str(self) -> &'static str {
99        match self {
100            CreditExhaustionReason::OutOfCredits => "credit_exhausted",
101            CreditExhaustionReason::OrgLevelDisabled => "org_level_disabled",
102            CreditExhaustionReason::BillingCycleExhausted => "billing_cycle_exhausted",
103        }
104    }
105}
106
107/// Short agent cooldown applied on silence detection (120 seconds).
108///
109/// Forces the router to pick a different agent immediately on re-route,
110/// without long-term blocking. The model cooldown (exponential, starting at
111/// 5 min) keeps the dead model out while this short cooldown just breaks
112/// the same-agent loop.
113pub const SILENCE_AGENT_COOLDOWN_SECS: u64 = 120;
114
115/// Silence detections before applying an extended cooldown (rolling window).
116pub const SILENCE_COUNT_THRESHOLD: usize = 5;
117
118/// Rolling window for silence detections (24 hours).
119pub const SILENCE_COUNT_WINDOW_SECS: i64 = 24 * 60 * 60;
120
121/// Extended cooldown applied after repeated silence detections (4 hours).
122pub const SILENCE_EXTENDED_COOLDOWN_SECS: u64 = 4 * 60 * 60;
123
124/// KV key prefix for persisted cooldowns (both agent and model).
125const KV_PREFIX: &str = "cooldown:";
126
127/// KV key prefix for rolling silence counters.
128const SILENCE_COUNT_PREFIX: &str = "silence_count:";
129
130/// KV key prefix for per-agent and per-agent:model failure counts (drives exponential backoff).
131const FAILURE_COUNT_PREFIX: &str = "failure_count:";
132
133/// KV key prefix for credit-exhaustion failure counts (separate from generic failures to prevent
134/// cross-contamination of backoff escalation — credit exhaustion uses different base/max durations).
135const CREDIT_FAILURE_COUNT_PREFIX: &str = "credit_failure_count:";
136
137/// KV key prefix for persistent model failure counts (separate from [`FAILURE_COUNT_PREFIX`] so
138/// `record_agent_success()` resetting the generic counter on an intervening success doesn't erase
139/// escalation progress for structurally unreliable models — see `record_persistent_model_failure`).
140const PERSISTENT_FAILURE_COUNT_PREFIX: &str = "persistent_failure_count:";
141
142/// KV key prefix for the unix timestamp after which `rate_limits` rows count toward degraded
143const RATE_LIMITS_CLEARED_AT_PREFIX: &str = "rate_limits_cleared_at:";
144
145/// Agent name from a cooldown key (`claude:sonnet` -> `claude`)
146fn agent_from_key(key: &str) -> &str {
147    key.split_once(':').map_or(key, |(agent, _)| agent)
148}
149
150struct CooldownEntry {
151    /// Unix timestamp when the cooldown expires.
152    cooldown_until: i64,
153    reason: String,
154}
155
156#[derive(Debug)]
157pub struct SilenceCountResult {
158    pub count: usize,
159    pub extended_cooldown_applied: bool,
160}
161
162/// Global in-memory cooldown map, protected by a Mutex.
163///
164/// Uses `std::sync::Mutex` because this map is also read from sync helper
165/// functions (`is_in_cooldown`, `is_model_in_cooldown`, etc.).  All lock
166/// holders perform only in-memory HashMap operations — **no `.await` is ever
167/// called while a guard is held**.  This invariant must be preserved: if a
168/// future caller needs to await while holding this lock, switch to
169/// `tokio::sync::Mutex` and make the helpers async.
170fn cooldowns() -> &'static Mutex<HashMap<String, CooldownEntry>> {
171    static COOLDOWNS: OnceLock<Mutex<HashMap<String, CooldownEntry>>> = OnceLock::new();
172    COOLDOWNS.get_or_init(|| Mutex::new(HashMap::new()))
173}
174
175/// Global store reference used for background KV writes.
176///
177/// Uses `tokio::sync::Mutex` because this value is only ever accessed from
178/// async functions. A `tokio::sync::Mutex` yields the Tokio task instead of
179/// blocking the worker thread if the lock is contended.
180fn cooldown_store() -> &'static sync::Mutex<Option<Arc<TaskStore>>> {
181    static STORE: OnceLock<sync::Mutex<Option<Arc<TaskStore>>>> = OnceLock::new();
182    STORE.get_or_init(|| sync::Mutex::new(None))
183}
184
185/// Initialise persistent cooldowns.
186///
187/// Must be called once at engine startup, after the `TaskStore` is opened.
188/// Loads unexpired cooldowns from KV and registers the store for future writes.
189/* Parses the `{"until": N, "reason": "..."}` cooldown KV format, falling back
190to the legacy bare-integer format (reason unknown) so existing rows keep
191working across the upgrade without a migration. */
192fn parse_cooldown_value(value: &str) -> Option<(i64, String)> {
193    if let Ok(serde_json::Value::Object(map)) = serde_json::from_str(value) {
194        let until = map.get("until")?.as_i64()?;
195        let reason = map
196            .get("reason")
197            .and_then(|r| r.as_str())
198            .unwrap_or("persisted")
199            .to_string();
200        return Some((until, reason));
201    }
202    value
203        .parse::<i64>()
204        .ok()
205        .map(|until| (until, "persisted".to_string()))
206}
207
208pub async fn init_cooldown_store(store: Arc<TaskStore>) {
209    match store.kv_list_prefix(KV_PREFIX).await {
210        Ok(rows) => {
211            let now = chrono::Utc::now().timestamp();
212            let mut map = cooldown_lock();
213            let mut loaded = 0;
214            for (key, value) in rows {
215                let cooldown_key = key.trim_start_matches(KV_PREFIX);
216                if let Some((cooldown_until, reason)) = parse_cooldown_value(&value)
217                    && now < cooldown_until
218                {
219                    map.insert(
220                        cooldown_key.to_string(),
221                        CooldownEntry {
222                            cooldown_until,
223                            reason,
224                        },
225                    );
226                    loaded += 1;
227                }
228                // Expired entries are simply not loaded — they'll be overwritten
229                // on the next failure or cleaned up by future writes.
230            }
231            if loaded > 0 {
232                tracing::info!(loaded, "loaded persisted cooldowns from KV store");
233            }
234        }
235        Err(e) => {
236            tracing::warn!(err = %e, "failed to load cooldowns from KV store");
237        }
238    }
239
240    // Load GitHub 5xx circuit breaker state if it was persisted before restart.
241    if let Ok(Some(raw)) = store.kv_get("cooldown:github:5xx").await
242        && let Ok(cooldown_until) = raw.parse::<i64>()
243    {
244        let now = chrono::Utc::now().timestamp();
245        if now < cooldown_until {
246            let mut open = github_5xx_circuit_open_lock();
247            *open = Some(cooldown_until);
248            let remaining = cooldown_until - now;
249            tracing::warn!(
250                remaining_secs = remaining,
251                "GitHub 5xx circuit breaker restored from KV (still open)"
252            );
253        }
254    }
255
256    *cooldown_store().lock().await = Some(store);
257}
258
259/// Reconcile the in-memory cooldown map with the persisted KV state.
260///
261/// KV is the source of truth. This is called once per tick by
262/// `router.refresh_health` so the running service notices state mutated by a
263/// separate process (e.g. `orch cooldown clear`). Without this sync, the CLI
264/// clears KV but the engine's in-memory map keeps the stale entries until they
265/// expire on their own, producing the "all agents cooled" + "No active
266/// cooldowns" inconsistency.
267///
268/// Reconciliation rules (KV authoritative for every key it has):
269/// - KV row missing for an in-memory key: leave memory alone — likely a
270///   `set_cooldown_async` race where memory was written but the KV row isn't
271///   yet visible. The next tick will catch up.
272/// - KV row present with `cooldown_until <= now` (including the "0" tombstone
273///   written by `clear_cooldown`): drop from memory.
274/// - KV row present with `cooldown_until > now`: insert/update memory to match.
275pub async fn sync_from_kv(store: &Arc<TaskStore>) {
276    let rows = match store.kv_list_prefix(KV_PREFIX).await {
277        Ok(rows) => rows,
278        Err(e) => {
279            tracing::warn!(err = %e, "cooldown sync_from_kv: KV list failed");
280            return;
281        }
282    };
283    let now = chrono::Utc::now().timestamp();
284
285    // Some((ts, reason)) for active cooldowns, None for cleared/expired rows.
286    // Missing key means no KV row at all, left alone below.
287    let mut explicit_kv: HashMap<String, Option<(i64, String)>> =
288        HashMap::with_capacity(rows.len());
289    for (kv_key, value) in &rows {
290        let cooldown_key = kv_key.trim_start_matches(KV_PREFIX);
291        if let Some((ts, reason)) = parse_cooldown_value(value) {
292            let normalized = if ts > now { Some((ts, reason)) } else { None };
293            explicit_kv.insert(cooldown_key.to_string(), normalized);
294        }
295    }
296
297    // The 5xx circuit breaker lives in its own statics, so mirror its KV row there
298    match explicit_kv.get("github:5xx") {
299        Some(None) => {
300            let mut open = github_5xx_circuit_open_lock();
301            if open.take().is_some() {
302                tracing::info!("GitHub 5xx circuit breaker closed by KV clear");
303                github_5xx_timestamps_lock().clear();
304            }
305        }
306        Some(Some((ts, _))) => {
307            *github_5xx_circuit_open_lock() = Some(*ts);
308        }
309        None => {}
310    }
311
312    let mut map = cooldown_lock();
313    let mut dropped = 0usize;
314    let mut updated = 0usize;
315
316    // Drop in-memory entries that KV explicitly marks cleared/expired.
317    map.retain(|key, _| {
318        if matches!(explicit_kv.get(key), Some(None)) {
319            dropped += 1;
320            false
321        } else {
322            true
323        }
324    });
325
326    // Adopt KV's authoritative timestamp for active cooldowns.
327    for (key, normalized) in explicit_kv {
328        if let Some((ts, reason)) = normalized {
329            if let Some(entry) = map.get_mut(&key) {
330                if entry.cooldown_until != ts {
331                    entry.cooldown_until = ts;
332                    updated += 1;
333                }
334            } else {
335                map.insert(
336                    key,
337                    CooldownEntry {
338                        cooldown_until: ts,
339                        reason,
340                    },
341                );
342                updated += 1;
343            }
344        }
345    }
346
347    if dropped > 0 || updated > 0 {
348        tracing::info!(
349            dropped,
350            updated,
351            "cooldown sync_from_kv: reconciled in-memory map with KV"
352        );
353    }
354}
355
356/// Failure count threshold (times at max backoff) for first extended tier (24h).
357///
358/// After a model has been at the max cap this many times, apply a 6x multiplier.
359const EXTENDED_TIER_1_THRESHOLD: u64 = 2;
360
361/// Multiplier for first extended tier (6x = 24h when max=4h).
362const EXTENDED_TIER_1_MULTIPLIER: i64 = 6;
363
364/// Failure count threshold (times at max backoff) for second extended tier (48h).
365///
366/// After a model has been at the max cap this many times, apply a 12x multiplier.
367const EXTENDED_TIER_2_THRESHOLD: u64 = 5;
368
369/// Multiplier for second extended tier (12x = 48h when max=4h).
370const EXTENDED_TIER_2_MULTIPLIER: i64 = 12;
371
372/// Compute exponential backoff duration using base-3 growth.
373///
374/// Returns `min(base * 3^(count-1), max)` for count >= 1.
375/// For count == 0 or 1 (first failure), returns `base`.
376///
377/// | count | base=300s | result |
378/// |-------|-----------|--------|
379/// | 0     | 300       | 300    |
380/// | 1     | 300       | 300    |
381/// | 2     | 300       | 900    |
382/// | 3     | 300       | 2700   |
383/// | 4     | 300       | 8100   |
384/// | 5-6   | 14400     | 14400 (max, not yet extended) |
385/// | 7-9   | 86400     | 86400 (24h extended tier) |
386/// | 10+   | 172800    | 172800 (48h extended tier) |
387///
388/// The extended tier applies when the model has hit the max cap multiple times,
389/// indicating a persistently broken model that won't self-resolve quickly.
390pub fn compute_backoff(count: u64, base: i64, max: i64, allow_extended: bool) -> i64 {
391    if count <= 1 {
392        return base;
393    }
394    let exp = u32::try_from(count.saturating_sub(1)).unwrap_or(u32::MAX);
395    let factor = 3_i64.saturating_pow(exp);
396    let standard = base.saturating_mul(factor).min(max);
397
398    // Extended tier: after N failures at max backoff, apply longer window
399    // to reduce noise from persistently broken models.
400    //
401    // First find the count at which exponential growth first hits max:
402    // solve: base * 3^(first_max-1) >= max
403    // => 3^(first_max-1) >= max / base
404    // => first_max-1 >= log_3(max / base)
405    // => first_max >= 1 + log_3(max / base)
406    let first_max = if base <= 0 {
407        0
408    } else {
409        // Use integer approximation: count where base * 3^(count-1) would first exceed max
410        let mut accumulated = base;
411        let mut first_max_count = 1u64;
412        while accumulated < max && first_max_count < count {
413            accumulated = accumulated.saturating_mul(3);
414            first_max_count += 1;
415        }
416        first_max_count
417    };
418
419    // Times we've been at the max cap (excluding the first time we hit it)
420    let times_at_max = count.saturating_sub(first_max);
421
422    if !allow_extended {
423        return standard;
424    }
425
426    if standard == max && times_at_max >= EXTENDED_TIER_2_THRESHOLD {
427        max.saturating_mul(EXTENDED_TIER_2_MULTIPLIER)
428    } else if standard == max && times_at_max >= EXTENDED_TIER_1_THRESHOLD {
429        max.saturating_mul(EXTENDED_TIER_1_MULTIPLIER)
430    } else {
431        standard
432    }
433}
434
435/// Read the failure count for a key from KV, increment it, write it back, and return the new count.
436///
437/// Always increments — the backoff formula's `max` parameter prevents the
438/// cooldown duration from growing beyond the cap, so unbounded counts are safe.
439///
440/// Returns 1 when no store is configured (unit-test contexts without a store).
441/// Returns `u64::MAX` on store errors (e.g. lock contention) so backoff applies the cap duration
442/// instead of resetting to the base, preventing rapid re-dispatch during store outages.
443async fn read_and_increment_failure_count(store_opt: Option<&Arc<TaskStore>>, key: &str) -> u64 {
444    read_and_increment_failure_count_with_prefix(store_opt, FAILURE_COUNT_PREFIX, key).await
445}
446
447/// Like [`read_and_increment_failure_count`] but with an explicit KV prefix.
448///
449/// Credit exhaustion uses [`CREDIT_FAILURE_COUNT_PREFIX`] so its backoff escalation
450/// is independent of generic agent failures (which use [`FAILURE_COUNT_PREFIX`]).
451async fn read_and_increment_failure_count_with_prefix(
452    store_opt: Option<&Arc<TaskStore>>,
453    prefix: &str,
454    key: &str,
455) -> u64 {
456    let kv_key = format!("{prefix}{key}");
457    if let Some(store) = store_opt {
458        match store.kv_increment(&kv_key).await {
459            Ok(n) => n,
460            Err(e) => {
461                tracing::warn!(key = %kv_key, err = %e, "failed to increment failure count — treating as high count for safe backoff");
462                u64::MAX
463            }
464        }
465    } else {
466        1
467    }
468}
469
470/// Backoff schedule for one kind of per-model failure.
471struct ModelBackoff {
472    prefix: &'static str,
473    base: i64,
474    max: i64,
475    allow_extended: bool,
476    reason: &'static str,
477}
478
479/// Bump the failure counter for `agent:model` and cool the model for the backoff it maps to.
480async fn record_model_backoff(agent_name: &str, model: &str, schedule: &ModelBackoff) {
481    let key = format!("{agent_name}:{model}");
482    let store_opt = cooldown_store().lock().await.clone();
483    let count =
484        read_and_increment_failure_count_with_prefix(store_opt.as_ref(), schedule.prefix, &key)
485            .await;
486    let cooldown_secs =
487        compute_backoff(count, schedule.base, schedule.max, schedule.allow_extended);
488    let cooldown_until = chrono::Utc::now().timestamp() + cooldown_secs;
489    set_cooldown_async(&key, cooldown_until, schedule.reason).await;
490}
491
492/// Reset failure counts for an agent and agent:model combo after a successful run.
493///
494/// Call this from the runner's success path so that the next failure starts
495/// backoff from the base duration again, not from wherever it left off.
496/// Resets both generic and credit-exhaustion failure counters.
497pub async fn record_agent_success(agent_name: &str, model: &str) {
498    let store_opt = cooldown_store().lock().await.clone();
499    if let Some(store) = store_opt {
500        let agent_key = format!("{FAILURE_COUNT_PREFIX}{agent_name}");
501        let credit_key = format!("{CREDIT_FAILURE_COUNT_PREFIX}{agent_name}");
502        if let Err(e) = store.kv_set(&agent_key, "0").await {
503            tracing::warn!(key = agent_key, err = %e, "failed to reset failure count");
504        }
505        if !model.is_empty() {
506            let model_key = format!("{FAILURE_COUNT_PREFIX}{agent_name}:{model}");
507            if let Err(e) = store.kv_set(&model_key, "0").await {
508                tracing::warn!(key = model_key, err = %e, "failed to reset failure count");
509            }
510        }
511        if let Err(e) = store.kv_set(&credit_key, "0").await {
512            tracing::warn!(key = credit_key, err = %e, "failed to reset failure count");
513        }
514    }
515}
516
517/// Record that an agent has failed and should be temporarily avoided.
518///
519/// Applies exponential backoff based on the agent's failure count in KV.
520/// If `error_message` contains "try again at {date}", that vendor date is used
521/// instead of the computed backoff (vendor dates are always authoritative).
522pub async fn record_agent_failure_with_message(agent_name: &str, error_message: &str) {
523    // Vendor-specified retry date takes priority over backoff — but only
524    // if it is in the present or future. If the parsed timestamp is in the
525    // past (stale vendor message), fall through to the exponential backoff
526    // path instead of returning early and bypassing backoff entirely.
527    if let Some(cooldown_until) = parse_retry_at(error_message) {
528        let now = chrono::Utc::now().timestamp();
529        if cooldown_until > now {
530            set_cooldown_async(agent_name, cooldown_until, "agent_error").await;
531            return;
532        }
533        tracing::debug!(
534            agent = agent_name,
535            cooldown_until,
536            "vendor retry_at is in the past — using backoff instead"
537        );
538    }
539
540    let store_opt = cooldown_store().lock().await.clone();
541    let count = read_and_increment_failure_count(store_opt.as_ref(), agent_name).await;
542    let base = config::get_agent_backoff_base(agent_name);
543    let cooldown_until =
544        chrono::Utc::now().timestamp() + compute_backoff(count, base, BACKOFF_MAX_SECS, true);
545    set_cooldown_async(agent_name, cooldown_until, "agent_error").await;
546}
547
548/// Detect credit exhaustion from an error message and return the stable
549/// `task_runs.outcome` string for it (see `CreditExhaustionReason::outcome_str`).
550///
551/// Callers that classify `AgentError::RateLimit`/`AgentError::Auth` into an
552/// outcome string should consult this first — generic rate-limit patterns like
553/// "usage limit" also match billing-cycle exhaustion messages (e.g. Kimi's
554/// "You've reached your usage limit for this billing cycle"), which would
555/// otherwise be stored as a plain "rate_limit" outcome.
556pub fn detect_credit_exhaustion_outcome(error_message: &str) -> Option<&'static str> {
557    detect_credit_exhaustion(error_message).map(CreditExhaustionReason::outcome_str)
558}
559
560/// Detect credit exhaustion reasons from error message.
561///
562/// Returns `Some(CreditExhaustionReason)` if the error indicates
563/// out_of_credits or org_level_disabled, which require longer agent-wide cooldowns.
564pub fn detect_credit_exhaustion(error_message: &str) -> Option<CreditExhaustionReason> {
565    let lower = error_message.to_lowercase();
566
567    let overage_patterns = [
568        "overagedisabledreason",
569        "overage_disabled_reason",
570        "overage disabled reason",
571    ];
572
573    if overage_patterns.iter().any(|p| lower.contains(p)) {
574        if lower.contains("out_of_credits") || lower.contains("outofcredits") {
575            return Some(CreditExhaustionReason::OutOfCredits);
576        }
577        if lower.contains("org_level_disabled") || lower.contains("orgdisabled") {
578            return Some(CreditExhaustionReason::OrgLevelDisabled);
579        }
580    }
581
582    let billing_patterns = [
583        "credit balance too low",
584        "credit balance insufficient",
585        "insufficient credit balance",
586        "billing quota exceeded",
587        "billing limit exceeded",
588        "organization has been disabled",
589        "org disabled",
590    ];
591
592    if billing_patterns.iter().any(|p| lower.contains(p)) {
593        return Some(CreditExhaustionReason::OrgLevelDisabled);
594    }
595
596    // Billing cycle exhaustion: monthly quota reset — check before generic quota
597    // patterns because "monthly quota exceeded" would otherwise match "quota exceeded".
598    let billing_cycle_patterns = [
599        "billing cycle",
600        "quota refreshed next cycle",
601        "monthly quota",
602        "quota will be refreshed",
603        "next billing cycle",
604        "refreshed in the next cycle",
605        "weekly/monthly limit exhausted",
606        "limit will reset at",
607        "upgrade to pro", // codex/chatgpt plan usage cap: requires billing upgrade
608        "upgrade your token plan", // minimax: Token Plan usage limit reached
609        "token plan usage limit", // minimax: Token Plan usage limit reached
610        "purchase credits for more", // minimax: ...purchase Credits for more usage
611    ];
612
613    if billing_cycle_patterns.iter().any(|p| lower.contains(p)) {
614        return Some(CreditExhaustionReason::BillingCycleExhausted);
615    }
616
617    if lower.contains("out of credits")
618        || lower.contains("outofcredits")
619        || lower.contains("insufficient funds")
620        || lower.contains("no credits remaining")
621        || lower.contains("insufficient_quota")
622        || lower.contains("quota exceeded")
623        || lower.contains("insufficient balance")
624        || lower.contains("please recharge")
625        || lower.contains("no resource package")
626        || lower.contains("balance exhausted")
627        || lower.contains("402 payment required")
628    {
629        return Some(CreditExhaustionReason::OutOfCredits);
630    }
631
632    None
633}
634
635/// Record an agent-level cooldown for credit exhaustion.
636///
637/// Applies exponential backoff based on the agent's failure count.
638/// All variants use escalating backoff:
639/// - `OutOfCredits`: 1h, 3h, then 8h (credits can be refilled any time), 48h from the 5th failure, 96h from the 8th
640/// - `OrgLevelDisabled`: 2h, 6h, then 8h, 48h from the 5th failure, 96h from the 8th
641/// - `BillingCycleExhausted`: starts at 24h, caps at 7 days (monthly event)
642///
643/// Billing cycle exhaustion was previously a flat 24h, but this caused daily
644/// retry-and-fail cycles when a monthly quota was exhausted (the 24h cooldown
645/// would expire, kimi would be retried, fail immediately, and get another 24h).
646/// Now each recurrence escalates: 24h → 72h → 7d (capped).
647pub async fn record_credit_exhaustion(agent_name: &str, reason: CreditExhaustionReason) {
648    let reason_str = match reason {
649        CreditExhaustionReason::OutOfCredits => "credit_exhaustion_out_of_credits",
650        CreditExhaustionReason::OrgLevelDisabled => "credit_exhaustion_org_level_disabled",
651        CreditExhaustionReason::BillingCycleExhausted => "billing_cycle_exhausted",
652    };
653
654    // A failure from a run that started before the cooldown is the same event
655    if is_in_cooldown_with_reason(agent_name, reason_str) {
656        tracing::debug!(
657            agent = agent_name,
658            reason = reason_str,
659            "credit exhaustion already cooled, not escalating"
660        );
661        return;
662    }
663
664    let store_opt = cooldown_store().lock().await.clone();
665    // Use a distinct failure counter (CREDIT_FAILURE_COUNT_PREFIX) so credit-
666    // exhaustion backoff escalation is independent of generic agent failures.
667    // Previously both paths shared FAILURE_COUNT_PREFIX, causing generic failures
668    // to inflate credit-exhaustion backoff (and vice versa).
669    let count = read_and_increment_failure_count_with_prefix(
670        store_opt.as_ref(),
671        CREDIT_FAILURE_COUNT_PREFIX,
672        agent_name,
673    )
674    .await;
675
676    let (base, max) = match reason {
677        CreditExhaustionReason::OutOfCredits => (CREDIT_BACKOFF_BASE_SECS, CREDIT_BACKOFF_MAX_SECS),
678        CreditExhaustionReason::OrgLevelDisabled => {
679            (ORG_BACKOFF_BASE_SECS, CREDIT_BACKOFF_MAX_SECS)
680        }
681        CreditExhaustionReason::BillingCycleExhausted => {
682            (BILLING_CYCLE_COOLDOWN_SECS, BILLING_CYCLE_MAX_SECS)
683        }
684    };
685    let cooldown_secs = compute_backoff(
686        count,
687        base,
688        max,
689        !matches!(reason, CreditExhaustionReason::BillingCycleExhausted),
690    );
691    let cooldown_until = chrono::Utc::now().timestamp() + cooldown_secs;
692    set_cooldown_async(agent_name, cooldown_until, reason_str).await;
693    tracing::warn!(
694        agent = agent_name,
695        reason = reason_str,
696        attempt = count,
697        cooldown_secs,
698        "credit exhaustion detected: applying exponential agent-wide cooldown"
699    );
700}
701
702// Returns false when the message is no credit exhaustion. Model-scoped billing cycle cools the model only
703pub async fn record_credit_exhaustion_from_message(
704    agent_name: &str,
705    model: Option<&str>,
706    message: &str,
707) -> bool {
708    let Some(reason) = detect_credit_exhaustion(message) else {
709        return false;
710    };
711    match (reason, model) {
712        (CreditExhaustionReason::BillingCycleExhausted, Some(model)) => {
713            record_persistent_model_failure(agent_name, model).await;
714        }
715        _ => record_credit_exhaustion(agent_name, reason).await,
716    }
717    true
718}
719
720/// Record that a specific agent+model combo has failed.
721///
722/// Applies exponential backoff based on the model's failure count in KV.
723pub async fn record_model_failure(agent_name: &str, model: &str) {
724    let base = config::get_agent_backoff_base(agent_name);
725    let schedule = ModelBackoff {
726        prefix: FAILURE_COUNT_PREFIX,
727        base,
728        max: BACKOFF_MAX_SECS,
729        allow_extended: true,
730        reason: "model_error",
731    };
732    record_model_backoff(agent_name, model, &schedule).await;
733}
734
735/// Record a rate-limit event for an agent+model.
736///
737/// If the error message advertises a relative usage window (e.g.
738/// "5-hour usage limit"), the cooldown is applied to the specific model for
739/// that window length. The quota is model-scoped, so the whole agent is not
740/// cooled. If no window is detected, fall back to the generic agent+model
741/// exponential backoff path.
742pub async fn record_rate_limit(agent_name: &str, model: Option<&str>, error_message: &str) {
743    if let Some(window_secs) = parse_relative_usage_window(error_message)
744        && let Some(m) = model
745    {
746        let cooldown_until = chrono::Utc::now()
747            .timestamp()
748            .saturating_add(i64::try_from(window_secs).unwrap_or(i64::MAX));
749        set_model_cooldown(agent_name, m, window_secs, "rate_limit_usage_window").await;
750        tracing::info!(
751            agent = agent_name,
752            model = m,
753            window_secs,
754            cooldown_until,
755            "relative usage window detected: applying model-specific cooldown"
756        );
757        return;
758    }
759
760    record_agent_failure_with_message(agent_name, error_message).await;
761    if let Some(m) = model {
762        record_model_failure(agent_name, m).await;
763    }
764}
765
766/// Record a persistent model-specific failure and apply longer exponential backoff.
767///
768/// Used for failure modes that are commonly broken for long periods (for example
769/// silent exit-0 or opaque provider errors). Starts at 4h and escalates with
770/// the generic backoff formula up to 7 days.
771///
772/// Uses [`PERSISTENT_FAILURE_COUNT_PREFIX`], a counter independent of the generic
773/// `failure_count:` key that `record_agent_success()` resets on every successful
774/// run. Otherwise a single intervening success between persistent failures would
775/// reset escalation back to the 4h base, letting structurally unreliable models
776/// (intermittent parse errors, truncated runs) stay in rotation indefinitely.
777pub async fn record_persistent_model_failure(agent_name: &str, model: &str) {
778    let schedule = ModelBackoff {
779        prefix: PERSISTENT_FAILURE_COUNT_PREFIX,
780        base: PERSISTENT_MODEL_BACKOFF_BASE_SECS,
781        max: PERSISTENT_MODEL_BACKOFF_MAX_SECS,
782        allow_extended: false,
783        reason: "persistent_model_error",
784    };
785    record_model_backoff(agent_name, model, &schedule).await;
786}
787
788/// Record a `ModelUnavailable` failure for an agent+model.
789///
790/// "Not found", "not supported" and region blocks never lift on their own, so they get the
791/// persistent backoff (4h base, 7d max). Any other message gets [`record_model_failure`]
792pub async fn record_model_unavailable(agent_name: &str, model: &str, message: &str) {
793    if is_model_permanently_gone(message) {
794        record_persistent_model_failure(agent_name, model).await;
795    } else {
796        record_model_failure(agent_name, model).await;
797    }
798}
799
800fn is_model_permanently_gone(message: &str) -> bool {
801    let lower = message.to_lowercase();
802    lower.contains("not found")
803        || lower.contains("not supported")
804        || lower.contains("not available in your country")
805        || lower.contains("not available in your region")
806}
807
808/// Record a run that failed without showing the model is gone: empty or cut off output, an
809/// unparseable review, an opaque provider error.
810///
811/// A stopped session or one odd answer causes these, so the backoff is 5 then 15 minutes. Billing
812/// exhaustion and "model not found" keep [`record_persistent_model_failure`]
813pub async fn record_transient_model_failure(agent_name: &str, model: &str) {
814    let schedule = ModelBackoff {
815        prefix: FAILURE_COUNT_PREFIX,
816        base: TRANSIENT_MODEL_BACKOFF_BASE_SECS,
817        max: TRANSIENT_MODEL_BACKOFF_MAX_SECS,
818        allow_extended: false,
819        reason: "transient_model_error",
820    };
821    record_model_backoff(agent_name, model, &schedule).await;
822}
823
824/// Set a model cooldown with a custom duration (in seconds) and reason.
825///
826/// Generic model-cooldown setter shared by silence detection and the
827/// rate-limit relative-usage-window path. The reason is persisted with
828/// the cooldown (KV + in-memory entry) so operators can tell the two
829/// apart in `orch cooldown list`.
830pub async fn set_model_cooldown(agent_name: &str, model: &str, duration_secs: u64, reason: &str) {
831    let key = format!("{agent_name}:{model}");
832    let cooldown_until = chrono::Utc::now()
833        .timestamp()
834        .saturating_add(i64::try_from(duration_secs).unwrap_or(i64::MAX));
835    set_cooldown_async(&key, cooldown_until, reason).await;
836}
837
838/// Set a model cooldown that ends at a vendor-provided Unix timestamp.
839pub async fn set_model_cooldown_until(agent_name: &str, model: &str, until: i64) {
840    let key = format!("{agent_name}:{model}");
841    set_cooldown_async(&key, until, "vendor_reset_at").await;
842}
843
844/// Set a short agent-level cooldown (in seconds).
845///
846/// Used by silence detection to temporarily block the whole agent so the
847/// router picks a different one on re-route. Unlike `record_agent_failure`
848/// (exponential backoff), this uses a short duration (typically 120s) —
849/// just enough to force one re-route cycle to a different agent.
850pub async fn set_agent_cooldown(agent_name: &str, duration_secs: u64) {
851    let cooldown_until = chrono::Utc::now()
852        .timestamp()
853        .saturating_add(i64::try_from(duration_secs).unwrap_or(i64::MAX));
854    set_cooldown_async(agent_name, cooldown_until, "silence_agent_cooldown").await;
855}
856
857/// KV prefix for the latest quota window of each type an agent reported: `rate_window:{agent}:{type}`
858pub const RATE_WINDOW_KV_PREFIX: &str = "rate_window:";
859
860/// One quota window from a vendor `rate_limit_event`, with the vendor window type kept as sent
861#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
862pub struct RateLimitWindow {
863    pub status: String,
864    pub window_type: String,
865    pub utilization: Option<f64>,
866    pub resets_at: Option<i64>,
867}
868
869/// Store the latest window for an agent. A rejected window cools the agent until its reset time
870pub async fn record_rate_limit_window(agent_name: &str, window: &RateLimitWindow) {
871    let store_opt = cooldown_store().lock().await.clone();
872    if let Some(store) = store_opt
873        && let Ok(value) = serde_json::to_string(window)
874        && let Err(e) = store
875            .kv_set(
876                &format!("{RATE_WINDOW_KV_PREFIX}{agent_name}:{}", window.window_type),
877                &value,
878            )
879            .await
880    {
881        tracing::warn!(agent = agent_name, err = %e, "failed to persist rate limit window");
882    }
883
884    let now = chrono::Utc::now().timestamp();
885    if window.status == "rejected"
886        && let Some(reset) = window.resets_at
887        && reset > now
888    {
889        let until = reset.min(now + PERSISTENT_MODEL_BACKOFF_MAX_SECS);
890        set_cooldown_async(agent_name, until, "rate_limit_window").await;
891        tracing::info!(
892            agent = agent_name,
893            window = %window.window_type,
894            cooldown_until = until,
895            "rate limit window rejected: cooling agent until vendor reset"
896        );
897    }
898}
899
900/// Latest stored quota window per agent, sorted by agent name
901pub async fn list_rate_limit_windows(store: &Arc<TaskStore>) -> Vec<(String, RateLimitWindow)> {
902    let rows = store
903        .kv_list_prefix(RATE_WINDOW_KV_PREFIX)
904        .await
905        .unwrap_or_default();
906    let mut windows: Vec<(String, RateLimitWindow)> = rows
907        .into_iter()
908        .filter_map(|(key, value)| {
909            let (agent, _) = key.strip_prefix(RATE_WINDOW_KV_PREFIX)?.rsplit_once(':')?;
910            let window = serde_json::from_str(&value).ok()?;
911            Some((agent.to_string(), window))
912        })
913        .collect();
914    windows.sort_by(|a, b| (&a.0, &a.1.window_type).cmp(&(&b.0, &b.1.window_type)));
915    windows
916}
917
918/// Record a silence detection for an agent+model and apply extended cooldowns
919/// when repeated silences exceed the threshold within the rolling window.
920pub async fn record_silence_detection(agent_name: &str, model: &str) -> Option<SilenceCountResult> {
921    let store_opt = cooldown_store().lock().await.clone();
922    let Some(store) = store_opt else {
923        tracing::debug!(
924            agent = agent_name,
925            model,
926            "skipping silence count record (no KV store)"
927        );
928        return None;
929    };
930
931    let key = format!("{SILENCE_COUNT_PREFIX}{agent_name}:{model}");
932    let now = chrono::Utc::now().timestamp();
933    let window_start = now - SILENCE_COUNT_WINDOW_SECS;
934
935    let mut timestamps = match store.kv_get(&key).await {
936        Ok(Some(raw)) => match serde_json::from_str::<Vec<i64>>(&raw) {
937            Ok(ts) => ts,
938            Err(e) => {
939                tracing::warn!(
940                    kv_key = %key,
941                    err = %e,
942                    "failed to parse silence timestamps from KV — resetting window"
943                );
944                Vec::new()
945            }
946        },
947        Ok(None) => Vec::new(),
948        Err(err) => {
949            tracing::warn!(
950                kv_key = %key,
951                err = %err,
952                "failed to load silence count from KV"
953            );
954            Vec::new()
955        }
956    };
957
958    timestamps.retain(|ts| *ts >= window_start);
959    timestamps.push(now);
960
961    let count = timestamps.len();
962    let mut extended_cooldown_applied = false;
963    if count >= SILENCE_COUNT_THRESHOLD {
964        set_model_cooldown(
965            agent_name,
966            model,
967            SILENCE_EXTENDED_COOLDOWN_SECS,
968            "silence_detected",
969        )
970        .await;
971        extended_cooldown_applied = true;
972        timestamps.clear();
973    }
974
975    let value = serde_json::to_string(&timestamps).unwrap_or_else(|_| "[]".to_string());
976    if let Err(err) = store.kv_set(&key, &value).await {
977        tracing::warn!(kv_key = key, err = %err, "failed to persist silence count");
978    }
979
980    Some(SilenceCountResult {
981        count,
982        extended_cooldown_applied,
983    })
984}
985
986/// Check if a specific agent+model combo is in cooldown.
987pub fn is_model_in_cooldown(agent_name: &str, model: &str) -> bool {
988    let key = format!("{agent_name}:{model}");
989    is_in_cooldown(&key)
990}
991
992/// Check if an agent is currently in cooldown period.
993pub fn is_agent_in_cooldown(agent_name: &str) -> bool {
994    is_in_cooldown(agent_name)
995}
996
997/// Return the cooldown expiry timestamp for a key (agent or agent:model), if active.
998pub fn cooldown_until(key: &str) -> Option<i64> {
999    let map = cooldown_lock();
1000    map.get(key).and_then(|entry| {
1001        let now = chrono::Utc::now().timestamp();
1002        if now < entry.cooldown_until {
1003            Some(entry.cooldown_until)
1004        } else {
1005            None
1006        }
1007    })
1008}
1009
1010/// Return the reason string recorded when a cooldown was set, if the cooldown is still active.
1011pub fn cooldown_reason(key: &str) -> Option<String> {
1012    let map = cooldown_lock();
1013    map.get(key).and_then(|entry| {
1014        let now = chrono::Utc::now().timestamp();
1015        if now < entry.cooldown_until {
1016            Some(entry.reason.clone())
1017        } else {
1018            None
1019        }
1020    })
1021}
1022
1023/// Active cooldowns as `(key, cooldown_until_unix, reason)` from the store, so a process other
1024/// than the daemon sees the same list as `orch cooldown list`
1025pub async fn list_persisted_cooldowns(store: &TaskStore) -> Vec<(String, i64, String)> {
1026    let now = chrono::Utc::now().timestamp();
1027    let mut out: Vec<(String, i64, String)> = store
1028        .kv_list_prefix(KV_PREFIX)
1029        .await
1030        .unwrap_or_default()
1031        .into_iter()
1032        .filter_map(|(key, value)| {
1033            let (until, reason) = parse_cooldown_value(&value)?;
1034            (now < until).then(|| (key.trim_start_matches(KV_PREFIX).to_string(), until, reason))
1035        })
1036        .collect();
1037    out.sort_by(|a, b| a.0.cmp(&b.0));
1038    out
1039}
1040
1041/// Return all currently active cooldowns as `(key, cooldown_until_unix, reason)`.
1042///
1043/// Reads from the in-memory map only — always fast, no async needed.
1044/// Expired entries are filtered out. Used by `orch cooldown list`.
1045pub fn list_all_cooldowns() -> Vec<(String, i64, String)> {
1046    let now = chrono::Utc::now().timestamp();
1047    let map = cooldown_lock();
1048    let mut result: Vec<(String, i64, String)> = map
1049        .iter()
1050        .filter(|(_, entry)| now < entry.cooldown_until)
1051        .map(|(key, entry)| (key.clone(), entry.cooldown_until, entry.reason.clone()))
1052        .collect();
1053    result.sort_by(|a, b| a.0.cmp(&b.0));
1054    result
1055}
1056
1057/// Write `rate_limits_cleared_at:{agent}` = now so the next health check
1058/// ignores older `rate_limits` rows. Rows stay in the table for metrics
1059pub async fn mark_rate_limits_cleared(store: &Arc<TaskStore>, agents: &[String]) {
1060    let now = chrono::Utc::now().timestamp().to_string();
1061    let mut seen = HashSet::new();
1062    for key in agents {
1063        let agent = agent_from_key(key);
1064        if agent.is_empty() || !seen.insert(agent.to_string()) {
1065            continue;
1066        }
1067        let kv_key = format!("{RATE_LIMITS_CLEARED_AT_PREFIX}{agent}");
1068        if let Err(e) = store.kv_set(&kv_key, &now).await {
1069            tracing::warn!(agent, err = %e, "failed to mark rate limits cleared");
1070        }
1071    }
1072}
1073
1074/// Clear a specific cooldown by key, or all cooldowns when `key == "*"`.
1075///
1076/// Removes from the in-memory map, writes a past timestamp to KV, and resets
1077/// the corresponding `failure_count:` entries so the next failure starts
1078/// backoff from the base duration. Also writes `rate_limits_cleared_at:{agent}`
1079/// so a degraded agent held only by rate rows recovers on the next health check
1080pub async fn clear_cooldown(key: &str, store: &Arc<TaskStore>) {
1081    let mut agents_to_mark: Vec<String> = Vec::new();
1082    if key == "*" {
1083        let keys: Vec<String> = {
1084            let mut map = cooldown_lock();
1085            let keys: Vec<String> = map.keys().cloned().collect();
1086            map.clear();
1087            keys
1088        };
1089        for k in &keys {
1090            let kv_key = format!("{KV_PREFIX}{k}");
1091            if let Err(e) = store.kv_set(&kv_key, "0").await {
1092                tracing::warn!(key = kv_key, err = %e, "failed to clear cooldown");
1093            }
1094            // Reset failure count so backoff restarts from base.
1095            let fc_key = format!("{FAILURE_COUNT_PREFIX}{k}");
1096            if let Err(e) = store.kv_set(&fc_key, "0").await {
1097                tracing::warn!(key = fc_key, err = %e, "failed to reset failure count");
1098            }
1099            // Also reset credit-specific failure count.
1100            let credit_fc_key = format!("{CREDIT_FAILURE_COUNT_PREFIX}{k}");
1101            if let Err(e) = store.kv_set(&credit_fc_key, "0").await {
1102                tracing::warn!(key = credit_fc_key, err = %e, "failed to reset credit failure count");
1103            }
1104            // Also reset the persistent-model-failure counter.
1105            let persistent_fc_key = format!("{PERSISTENT_FAILURE_COUNT_PREFIX}{k}");
1106            if let Err(e) = store.kv_set(&persistent_fc_key, "0").await {
1107                tracing::warn!(key = persistent_fc_key, err = %e, "failed to reset persistent failure count");
1108            }
1109        }
1110        // Also reset any persisted failure_count keys that are not in the
1111        // in-memory map (e.g. survived a restart or were set without a
1112        // corresponding in-memory cooldown entry).
1113        if let Ok(fc_entries) = store.kv_list_prefix(FAILURE_COUNT_PREFIX).await {
1114            for (fc_key, _) in fc_entries {
1115                if let Err(e) = store.kv_set(&fc_key, "0").await {
1116                    tracing::warn!(key = fc_key, err = %e, "failed to reset failure count");
1117                }
1118            }
1119        }
1120        if let Ok(cfc_entries) = store.kv_list_prefix(CREDIT_FAILURE_COUNT_PREFIX).await {
1121            for (cfc_key, _) in cfc_entries {
1122                if let Err(e) = store.kv_set(&cfc_key, "0").await {
1123                    tracing::warn!(key = cfc_key, err = %e, "failed to reset credit failure count");
1124                }
1125            }
1126        }
1127        if let Ok(pfc_entries) = store.kv_list_prefix(PERSISTENT_FAILURE_COUNT_PREFIX).await {
1128            for (pfc_key, _) in pfc_entries {
1129                if let Err(e) = store.kv_set(&pfc_key, "0").await {
1130                    tracing::warn!(key = pfc_key, err = %e, "failed to reset persistent failure count");
1131                }
1132            }
1133        }
1134        tracing::info!(
1135            count = keys.len(),
1136            "cleared all cooldowns and failure counts"
1137        );
1138        agents_to_mark.extend(keys.iter().map(|k| agent_from_key(k).to_string()));
1139        match store.rate_limit_agents().await {
1140            Ok(rl_agents) => agents_to_mark.extend(rl_agents),
1141            Err(e) => tracing::warn!(err = %e, "failed to list rate_limits agents while clearing"),
1142        }
1143        match store.kv_list_prefix(RATE_LIMITS_CLEARED_AT_PREFIX).await {
1144            Ok(marks) => {
1145                for (k, _) in marks {
1146                    let agent = k.trim_start_matches(RATE_LIMITS_CLEARED_AT_PREFIX);
1147                    if !agent.is_empty() {
1148                        agents_to_mark.push(agent.to_string());
1149                    }
1150                }
1151            }
1152            Err(e) => tracing::warn!(err = %e, "failed to list rate_limits_cleared_at keys"),
1153        }
1154    } else {
1155        {
1156            let mut map = cooldown_lock();
1157            map.remove(key);
1158        }
1159        let kv_key = format!("{KV_PREFIX}{key}");
1160        if let Err(e) = store.kv_set(&kv_key, "0").await {
1161            tracing::warn!(key = kv_key, err = %e, "failed to clear cooldown");
1162        }
1163        // Reset failure count so backoff restarts from base.
1164        let fc_key = format!("{FAILURE_COUNT_PREFIX}{key}");
1165        if let Err(e) = store.kv_set(&fc_key, "0").await {
1166            tracing::warn!(key = fc_key, err = %e, "failed to reset failure count");
1167        }
1168        // Also reset credit-specific failure count.
1169        let credit_fc_key = format!("{CREDIT_FAILURE_COUNT_PREFIX}{key}");
1170        if let Err(e) = store.kv_set(&credit_fc_key, "0").await {
1171            tracing::warn!(key = credit_fc_key, err = %e, "failed to reset credit failure count");
1172        }
1173        // Also reset the persistent-model-failure counter.
1174        let persistent_fc_key = format!("{PERSISTENT_FAILURE_COUNT_PREFIX}{key}");
1175        if let Err(e) = store.kv_set(&persistent_fc_key, "0").await {
1176            tracing::warn!(key = persistent_fc_key, err = %e, "failed to reset persistent failure count");
1177        }
1178        tracing::info!(key, "cleared cooldown and failure count");
1179        agents_to_mark.push(agent_from_key(key).to_string());
1180    }
1181    mark_rate_limits_cleared(store, &agents_to_mark).await;
1182}
1183
1184/// Set a cooldown with a specific expiry timestamp. Updates in-memory state only.
1185///
1186/// Returns `true` if the cooldown was applied, `false` if an existing longer
1187/// cooldown prevented the update (never-shorten rule).
1188///
1189/// **Callers are responsible for persisting to KV.** Use [`set_cooldown_async`]
1190/// for critical cooldowns that must survive a crash, or this function combined
1191/// with a fire-and-forget `tokio::spawn` for non-critical short cooldowns.
1192fn set_cooldown_in_memory(key: &str, cooldown_until: i64, reason: &str) -> bool {
1193    let mut map = cooldown_lock();
1194    if let Some(existing) = map.get(key) {
1195        // Never shorten an existing cooldown. This prevents a short
1196        // retry window (e.g., generic rate limit) from overriding a longer
1197        // billing-cycle cooldown.
1198        if existing.cooldown_until >= cooldown_until {
1199            return false;
1200        }
1201    }
1202    map.insert(
1203        key.to_string(),
1204        CooldownEntry {
1205            cooldown_until,
1206            reason: reason.to_string(),
1207        },
1208    );
1209    true
1210}
1211
1212/// Set a cooldown with a specific expiry timestamp and persist to KV inline.
1213///
1214/// This is the preferred function for critical cooldowns (credit exhaustion,
1215/// billing cycle, agent/model failures) that must survive a service crash.
1216/// The KV write is awaited before returning, so the caller can be confident
1217/// the cooldown is durable once this function returns `true`.
1218///
1219/// Returns `true` if the cooldown was applied, `false` if an existing longer
1220/// cooldown prevented the update (never-shorten rule).
1221async fn set_cooldown_async(key: &str, cooldown_until: i64, reason: &str) -> bool {
1222    if !set_cooldown_in_memory(key, cooldown_until, reason) {
1223        return false;
1224    }
1225    let store_opt = cooldown_store().lock().await.clone();
1226    if let Some(store) = store_opt {
1227        let kv_key = format!("{KV_PREFIX}{key}");
1228        let value = serde_json::json!({"until": cooldown_until, "reason": reason}).to_string();
1229        if let Err(e) = store.kv_set(&kv_key, &value).await {
1230            tracing::warn!(
1231                kv_key,
1232                err = %e,
1233                "failed to persist cooldown to KV store — rolling back in-memory entry"
1234            );
1235            let mut map = cooldown_lock();
1236            // Only roll back if nothing has superseded our write.
1237            // A racing thread may have set a longer cooldown in the meantime;
1238            // removing unconditionally would erase that valid entry.
1239            if map.get(key).map(|e| e.cooldown_until) == Some(cooldown_until) {
1240                map.remove(key);
1241            }
1242            return false;
1243        }
1244    }
1245    true
1246}
1247
1248/// Helper to acquire the cooldown map lock, logging and recovering on poison.
1249fn cooldown_lock() -> MutexGuard<'static, HashMap<String, CooldownEntry>> {
1250    cooldowns().lock().unwrap_or_else(|e| {
1251        tracing::error!("cooldown map lock poisoned — recovering with partial state; backoff and degraded-agent decisions may be incorrect");
1252        e.into_inner()
1253    })
1254}
1255
1256/// Helper to acquire the degraded agents lock, logging and recovering on poison.
1257fn degraded_agents_lock() -> MutexGuard<'static, HashMap<String, String>> {
1258    degraded_agents().lock().unwrap_or_else(|e| {
1259        tracing::error!("degraded agents lock poisoned — recovering with partial state; health check decisions may be incorrect");
1260        e.into_inner()
1261    })
1262}
1263
1264/// Helper to acquire the GitHub 5xx timestamps lock, logging and recovering on poison.
1265fn github_5xx_timestamps_lock() -> MutexGuard<'static, Vec<i64>> {
1266    github_5xx_timestamps().lock().unwrap_or_else(|e| {
1267        tracing::error!("github 5xx timestamps lock poisoned — recovering with partial state; circuit breaker may operate incorrectly");
1268        e.into_inner()
1269    })
1270}
1271
1272/// Helper to acquire the GitHub 5xx circuit open lock, logging and recovering on poison.
1273fn github_5xx_circuit_open_lock() -> MutexGuard<'static, Option<i64>> {
1274    github_5xx_circuit_open().lock().unwrap_or_else(|e| {
1275        tracing::error!("github 5xx circuit open lock poisoned — recovering with partial state; circuit breaker may operate incorrectly");
1276        e.into_inner()
1277    })
1278}
1279
1280/// Check if a key is in cooldown with the given reason.
1281fn is_in_cooldown_with_reason(key: &str, reason: &str) -> bool {
1282    let map = cooldown_lock();
1283    map.get(key).is_some_and(|entry| {
1284        entry.reason == reason && chrono::Utc::now().timestamp() < entry.cooldown_until
1285    })
1286}
1287
1288/// Check if a key is currently in cooldown.
1289fn is_in_cooldown(key: &str) -> bool {
1290    let map = cooldown_lock();
1291    if let Some(entry) = map.get(key) {
1292        let now = chrono::Utc::now().timestamp();
1293        return now < entry.cooldown_until;
1294    }
1295    false
1296}
1297
1298// ---------------------------------------------------------------------------
1299// Degraded-agent tracking (pre-emptive health check)
1300// ---------------------------------------------------------------------------
1301
1302/// Default health check window for recent rate-limit events (hours).
1303pub const DEFAULT_HEALTH_CHECK_WINDOW_HOURS: u32 = 6;
1304
1305/// Default threshold: minimum rate-limit events within the window to consider
1306/// an agent degraded.  A single transient 429 shouldn't mark an agent; we need
1307/// a pattern of repeated failures.
1308pub const DEFAULT_DEGRADED_RATE_LIMIT_THRESHOLD: i64 = 3;
1309
1310/// In-memory map of agents currently flagged as degraded, keyed by agent
1311/// with the reason that holds now
1312fn degraded_agents() -> &'static Mutex<HashMap<String, String>> {
1313    static DEGRADED: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();
1314    DEGRADED.get_or_init(|| Mutex::new(HashMap::new()))
1315}
1316
1317/// Check if an agent is currently flagged as degraded by the health check.
1318///
1319/// Degraded means: all configured models are cooled **or** the agent has
1320/// exceeded the rate-limit threshold within the configured lookback window.
1321pub fn is_agent_degraded(agent: &str) -> bool {
1322    let set = degraded_agents_lock();
1323    set.contains_key(agent)
1324}
1325
1326/// Reason the agent is currently degraded, if it is
1327pub fn agent_degraded_reason(agent: &str) -> Option<String> {
1328    degraded_agents_lock().get(agent).cloned()
1329}
1330
1331/// Active degraded agents as `(agent, reason)`, sorted by agent name
1332pub fn list_degraded_agents() -> Vec<(String, String)> {
1333    let mut entries: Vec<(String, String)> = degraded_agents_lock()
1334        .iter()
1335        .map(|(agent, reason)| (agent.clone(), reason.clone()))
1336        .collect();
1337    entries.sort_by(|a, b| a.0.cmp(&b.0));
1338    entries
1339}
1340
1341/// Mark an agent as degraded (called by [`refresh_degraded_agents`]).
1342pub fn mark_agent_degraded(agent: &str) {
1343    mark_agent_degraded_with_reason(agent, "degraded");
1344}
1345
1346fn mark_agent_degraded_with_reason(agent: &str, reason: &str) {
1347    let mut set = degraded_agents_lock();
1348    set.insert(agent.to_string(), reason.to_string());
1349}
1350
1351/// Clear the degraded flag for an agent.
1352pub fn clear_agent_degraded(agent: &str) {
1353    let mut set = degraded_agents_lock();
1354    set.remove(agent);
1355}
1356
1357/// Refresh the degraded-agent set from the rate_limits table and cooldown state.
1358///
1359/// An agent is marked degraded when:
1360/// 1. It is in agent-level cooldown (explicit cooldown KV key exists and hasn't expired), **or**
1361/// 2. All its configured models are in cooldown, **or**
1362/// 3. It has >= `threshold` `limit_type = 'rate'` events within `window_hours`.
1363///
1364/// Failures keep their own cooldowns and do not count toward the threshold
1365/// Agents that no longer meet these criteria are cleared.
1366///
1367/// Note: This function calls `clear_expired_cooldowns()` first to ensure the
1368/// in-memory cooldown map reflects current state. An agent should NOT be marked
1369/// degraded simply because an expired cooldown entry hasn't been cleaned up yet.
1370pub async fn refresh_degraded_agents(
1371    store: &Arc<TaskStore>,
1372    available_agents: &[String],
1373    model_checker: &(dyn Fn(&str) -> bool + Send + Sync),
1374    window_hours: u32,
1375    threshold: i64,
1376) {
1377    // Clear expired cooldowns from in-memory map before evaluating agent state.
1378    // This ensures we don't incorrectly mark agents as degraded due to stale
1379    // in-memory entries that should have expired but weren't cleaned up.
1380    clear_expired_cooldowns();
1381
1382    // Time the DB query to surface slow health-checks that can dominate the
1383    // engine tick latency. If the query fails, log and return early.
1384    let start = chrono::Utc::now();
1385    let counts = match store.recent_rate_limit_counts(window_hours).await {
1386        Ok(c) => {
1387            let dur_ms = (chrono::Utc::now() - start).num_milliseconds();
1388            tracing::info!(
1389                duration_ms = dur_ms,
1390                window_hours,
1391                "recent_rate_limit_counts query completed"
1392            );
1393            c
1394        }
1395        Err(e) => {
1396            let dur_ms = (chrono::Utc::now() - start).num_milliseconds();
1397            tracing::warn!(
1398                err = %e,
1399                duration_ms = dur_ms,
1400                "failed to query recent rate limit counts for health check"
1401            );
1402            return;
1403        }
1404    };
1405
1406    for agent in available_agents {
1407        let in_cooldown = is_agent_in_cooldown(agent);
1408        let no_models = !model_checker(agent);
1409        let rate_limit_count = counts.get(agent.as_str()).copied().unwrap_or(0);
1410        let over_threshold = rate_limit_count >= threshold;
1411
1412        let degraded = in_cooldown || no_models || over_threshold;
1413
1414        if degraded {
1415            let reason = if in_cooldown {
1416                "agent in cooldown"
1417            } else if no_models {
1418                "all models cooled"
1419            } else {
1420                "rate limit threshold exceeded"
1421            };
1422            let previous = agent_degraded_reason(agent);
1423            match previous.as_deref() {
1424                None => tracing::warn!(
1425                    agent,
1426                    reason,
1427                    rate_limit_count,
1428                    window_hours,
1429                    threshold,
1430                    "pre-emptive health check: marking agent as degraded"
1431                ),
1432                Some(prev) if prev != reason => tracing::warn!(
1433                    agent,
1434                    reason,
1435                    previous = prev,
1436                    rate_limit_count,
1437                    window_hours,
1438                    threshold,
1439                    "pre-emptive health check: degraded reason changed"
1440                ),
1441                Some(_) => {}
1442            }
1443            mark_agent_degraded_with_reason(agent, reason);
1444        } else {
1445            if is_agent_degraded(agent) {
1446                tracing::info!(
1447                    agent,
1448                    rate_limit_count,
1449                    "pre-emptive health check: agent recovered, clearing degraded flag"
1450                );
1451            }
1452            clear_agent_degraded(agent);
1453        }
1454    }
1455}
1456
1457/// Clear expired cooldowns from the in-memory map.
1458pub fn clear_expired_cooldowns() {
1459    let mut map = cooldown_lock();
1460    let now = chrono::Utc::now().timestamp();
1461    map.retain(|_key, entry| now < entry.cooldown_until);
1462}
1463
1464// ---------------------------------------------------------------------------
1465// GitHub 5xx circuit breaker
1466// ---------------------------------------------------------------------------
1467
1468/// Sliding window for counting GitHub 5xx errors (seconds).
1469const GITHUB_5XX_WINDOW_SECS: i64 = 120;
1470
1471/// Number of 5xx errors within the window to trip the circuit breaker.
1472const GITHUB_5XX_THRESHOLD: usize = 5;
1473
1474/// Duration the circuit breaker stays open after tripping (seconds).
1475const GITHUB_5XX_COOLDOWN_SECS: i64 = 180;
1476
1477/// Global sliding window of 5xx error timestamps.
1478fn github_5xx_timestamps() -> &'static Mutex<Vec<i64>> {
1479    static TS: OnceLock<Mutex<Vec<i64>>> = OnceLock::new();
1480    TS.get_or_init(|| Mutex::new(Vec::new()))
1481}
1482
1483/// Whether the GitHub 5xx circuit breaker is currently open (tripped).
1484fn github_5xx_circuit_open() -> &'static Mutex<Option<i64>> {
1485    static OPEN: OnceLock<Mutex<Option<i64>>> = OnceLock::new();
1486    OPEN.get_or_init(|| Mutex::new(None))
1487}
1488
1489/// Record a GitHub 5xx server error and trip the circuit breaker if the
1490/// sliding window threshold is exceeded.
1491///
1492/// Emits a single high-level log entry when the circuit transitions to open.
1493pub async fn record_github_5xx() {
1494    let now = chrono::Utc::now().timestamp();
1495    let window_start = now - GITHUB_5XX_WINDOW_SECS;
1496
1497    let should_trip = {
1498        let mut ts = github_5xx_timestamps_lock();
1499        ts.retain(|t| *t >= window_start);
1500        ts.push(now);
1501        ts.len() >= GITHUB_5XX_THRESHOLD
1502    };
1503
1504    if should_trip {
1505        let cooldown_until = {
1506            let mut open = github_5xx_circuit_open_lock();
1507            if open.is_none() {
1508                let cd = now + GITHUB_5XX_COOLDOWN_SECS;
1509                *open = Some(cd);
1510                tracing::warn!(
1511                    errors_in_window = GITHUB_5XX_THRESHOLD,
1512                    window_secs = GITHUB_5XX_WINDOW_SECS,
1513                    cooldown_secs = GITHUB_5XX_COOLDOWN_SECS,
1514                    "GitHub 5xx circuit breaker OPEN — throttling non-critical work"
1515                );
1516                Some(cd)
1517            } else {
1518                None
1519            }
1520        };
1521        // Persist to KV (outside the mutex lock so the future is Send).
1522        if let Some(cd) = cooldown_until {
1523            let store_opt = cooldown_store().lock().await.clone();
1524            if let Some(store) = store_opt {
1525                let _ = store.kv_set("cooldown:github:5xx", &cd.to_string()).await;
1526            }
1527            // Also set the generic cooldown so is_agent_in_cooldown("github:5xx")
1528            // returns true immediately, avoiding a race window where concurrent
1529            // requests bypass the circuit breaker.
1530            set_agent_cooldown("github:5xx", GITHUB_5XX_COOLDOWN_SECS as u64).await;
1531        }
1532        // Clear the sliding window after tripping so we don't re-trip immediately
1533        let mut ts = github_5xx_timestamps_lock();
1534        ts.clear();
1535    }
1536}
1537
1538/// Check if the GitHub 5xx circuit breaker is currently open.
1539///
1540/// When open, non-critical background work (cleanup, polling, mention scans)
1541/// should be skipped. Critical operations (PR creation) should still attempt
1542/// with their existing exponential backoff.
1543///
1544/// Automatically recovers (logs a recovery message) when the cooldown expires.
1545pub fn is_github_circuit_open() -> bool {
1546    // Check the dedicated in-memory circuit flag first. If present, honour it
1547    // and perform auto-recovery when it expires (logging once on close).
1548    {
1549        let mut open = github_5xx_circuit_open_lock();
1550        if let Some(until) = *open {
1551            let now = chrono::Utc::now().timestamp();
1552            if now >= until {
1553                *open = None;
1554                tracing::info!("GitHub 5xx circuit breaker CLOSED — resuming normal operations");
1555                return false;
1556            }
1557            return true;
1558        }
1559    }
1560
1561    // If the dedicated flag is not set, consult the generic cooldown map so
1562    // callers see a consistent view regardless of which code path set the
1563    // persisted cooldown (e.g. send_with_retries -> set_agent_cooldown).
1564    if let Some(until) = cooldown_until("github:5xx") {
1565        // Populate the dedicated in-memory flag so future checks and the
1566        // auto-recovery path go through the same code and logging.
1567        let mut open = github_5xx_circuit_open_lock();
1568        if open.is_none() {
1569            *open = Some(until);
1570            let now = chrono::Utc::now().timestamp();
1571            if now < until {
1572                let remaining = until - now;
1573                tracing::warn!(
1574                    remaining_secs = remaining,
1575                    "GitHub 5xx circuit breaker OPEN (discovered via generic cooldown) — throttling non-critical work"
1576                );
1577            }
1578        }
1579        return true;
1580    }
1581
1582    false
1583}
1584
1585/// Returns the remaining seconds of the GitHub 5xx circuit breaker cooldown,
1586/// or 0 if the circuit is closed.
1587pub fn github_circuit_remaining_secs() -> u64 {
1588    // Prefer the dedicated in-memory value when present.
1589    {
1590        let open = github_5xx_circuit_open_lock();
1591        if let Some(until) = *open {
1592            let now = chrono::Utc::now().timestamp();
1593            if now < until {
1594                return u64::try_from(until - now).unwrap_or(0);
1595            }
1596            return 0;
1597        }
1598    }
1599
1600    // Fall back to the generic cooldown map if the dedicated flag isn't set.
1601    if let Some(until) = cooldown_until("github:5xx") {
1602        let now = chrono::Utc::now().timestamp();
1603        if now < until {
1604            return u64::try_from(until - now).unwrap_or(0);
1605        }
1606    }
1607    0
1608}
1609
1610/// Parse a "try again at {date}" or "reset at {date}" from an error message.
1611///
1612/// Returns a Unix timestamp if a retry-at date is found.
1613pub(crate) fn parse_retry_at(error_message: &str) -> Option<i64> {
1614    if error_message.is_empty() {
1615        return None;
1616    }
1617
1618    let lower = error_message.to_lowercase();
1619    // Accept a wider set of vendor-provided markers. Claude commonly uses
1620    // variations like "resets 10:30am" (no explicit "at"), so include
1621    // both "resets" and the older "reset at"/"try again at" markers.
1622    for retry_marker in [
1623        "try again at ",
1624        "reset at ",
1625        "resets at ",
1626        "resets ",
1627        "reset ",
1628    ] {
1629        if let Some(idx) = lower.find(retry_marker) {
1630            let date_str = &lower[idx + retry_marker.len()..];
1631            // Take until period, newline, or end
1632            let date_str = date_str
1633                .split(['.', '\n'])
1634                .next()
1635                .unwrap_or(date_str)
1636                .trim();
1637
1638            // Try common date formats
1639            // "Mar 26th, 2026 5:55 AM" → strip ordinal suffixes
1640            let cleaned = date_str
1641                .replace("st,", ",")
1642                .replace("nd,", ",")
1643                .replace("rd,", ",")
1644                .replace("th,", ",");
1645
1646            for fmt in &[
1647                "%b %d, %Y %I:%M %p", // Mar 26, 2026 5:55 AM
1648                "%b %d, %Y %I:%M%p",  // Mar 26, 2026 5:55AM
1649                "%B %d, %Y %I:%M %p", // March 26, 2026 5:55 AM
1650                "%Y-%m-%dT%H:%M:%S",  // 2026-03-26T05:55:00
1651                "%Y-%m-%d %H:%M:%S",  // 2026-03-26 05:55:00
1652                "%Y-%m-%d %H:%M",     // 2026-03-26 05:55
1653            ] {
1654                if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(&cleaned, fmt) {
1655                    // Vendor messages (e.g. Codex/GLM) emit times in the machine's
1656                    // local timezone, not UTC. Interpret naive datetime as local time.
1657                    let utc = match chrono::Local.from_local_datetime(&dt) {
1658                        chrono::LocalResult::Single(local_dt) => {
1659                            local_dt.with_timezone(&chrono::Utc)
1660                        }
1661                        chrono::LocalResult::Ambiguous(earliest, _) => {
1662                            // DST fold: pick the earlier (conservative) interpretation
1663                            earliest.with_timezone(&chrono::Utc)
1664                        }
1665                        chrono::LocalResult::None => {
1666                            // DST gap: fall back to treating as UTC to avoid panic
1667                            dt.and_utc()
1668                        }
1669                    };
1670                    tracing::info!(
1671                        retry_at = %utc,
1672                        raw = date_str,
1673                        marker = retry_marker,
1674                        "parsed rate limit retry-at date"
1675                    );
1676                    return Some(utc.timestamp());
1677                }
1678            }
1679            tracing::debug!(
1680                raw = date_str,
1681                marker = retry_marker,
1682                "could not parse retry-at date"
1683            );
1684
1685            // If the vendor provided only a time (e.g. "resets 10:30am"),
1686            // attempt to parse a time-only and interpret it as the next
1687            // occurrence of that time in the local timezone.
1688            // Strip parenthesised timezone hints like "(America/Sao_Paulo)".
1689            let time_only = date_str.split_once('(').map_or(date_str, |(t, _)| t).trim();
1690            // Hour-only values like "8am" have no minute field, which chrono needs, so insert ":00"
1691            let mut compact = time_only.replace(" am", "am").replace(" pm", "pm");
1692            let split = compact.rfind(' ').map_or(0, |i| i + 1);
1693            let last = &compact[split..];
1694            if !last.contains(':')
1695                && (last.ends_with("am") || last.ends_with("pm"))
1696                && last.len() > 2
1697            {
1698                let at = split + last.len() - 2;
1699                compact.insert_str(at, ":00");
1700            }
1701            // "Jun 9 at 1am" has no year, so take the next future occurrence
1702            let md = compact.replace(" at ", " ");
1703            let now_local = chrono::Local::now();
1704            let this_year = chrono::Datelike::year(&now_local);
1705            for year in [this_year, this_year + 1] {
1706                let with_year = format!("{year} {md}");
1707                if let Ok(dt) =
1708                    chrono::NaiveDateTime::parse_from_str(&with_year, "%Y %b %d %I:%M%p")
1709                    && let Some(local_dt) = chrono::Local.from_local_datetime(&dt).earliest()
1710                    && local_dt > now_local
1711                {
1712                    return Some(local_dt.timestamp());
1713                }
1714            }
1715            let time_only = compact.as_str();
1716            for tf in &["%I:%M %p", "%I:%M%p", "%I %p", "%H:%M"] {
1717                if let Ok(t) = chrono::NaiveTime::parse_from_str(time_only, tf) {
1718                    // Build a NaiveDateTime for today at that time, then choose
1719                    // today or tomorrow depending on whether the time has passed.
1720                    let local_now = chrono::Local::now();
1721                    let today = local_now.date_naive();
1722                    let candidate = chrono::NaiveDateTime::new(today, t);
1723                    // Use the TimeZone trait methods; annotate types so the
1724                    // compiler can infer the concrete DateTime types.
1725                    let candidate_local: chrono::DateTime<chrono::Local> =
1726                        match chrono::Local.from_local_datetime(&candidate) {
1727                            chrono::LocalResult::Single(dt) => dt,
1728                            chrono::LocalResult::Ambiguous(earliest, _) => earliest,
1729                            chrono::LocalResult::None => {
1730                                // DST gap — fall back to UTC interpretation
1731                                let utc_dt = candidate.and_utc();
1732                                return Some(utc_dt.timestamp());
1733                            }
1734                        };
1735                    let chosen = if candidate_local <= local_now {
1736                        // Use tomorrow
1737                        let tomorrow = today.succ_opt().unwrap_or(today);
1738                        let ndt = chrono::NaiveDateTime::new(tomorrow, t);
1739                        match chrono::Local.from_local_datetime(&ndt) {
1740                            chrono::LocalResult::Single(dt) => dt.with_timezone(&chrono::Utc),
1741                            chrono::LocalResult::Ambiguous(earliest, _) => {
1742                                earliest.with_timezone(&chrono::Utc)
1743                            }
1744                            chrono::LocalResult::None => ndt.and_utc(),
1745                        }
1746                    } else {
1747                        candidate_local.with_timezone(&chrono::Utc)
1748                    };
1749                    tracing::info!(
1750                        retry_at = %chosen,
1751                        raw = date_str,
1752                        marker = retry_marker,
1753                        "parsed rate limit retry-at time-only; interpreted as next occurrence"
1754                    );
1755                    return Some(chosen.timestamp());
1756                }
1757            }
1758        }
1759    }
1760
1761    // Without a specific retry/reset date, return None and let the caller use
1762    // its default cooldown (exponential backoff). A blanket long fallback here
1763    // would cause false billing-cycle cooldowns on agents without those limits.
1764    None
1765}
1766
1767/// Parse a relative usage window (e.g. "5-hour usage limit") from an error
1768/// message.
1769///
1770/// Returns the window length in seconds. Only matches in usage/quota/limit
1771/// contexts ("usage limit", "quota", "window", "limit") to avoid interpreting
1772/// unrelated numbers as cooldown durations.
1773///
1774/// `pub(crate)` so `engine::runner::fallback::handle_error()` can apply the
1775/// same window-detection the `needs_review` call site
1776/// (`record_rate_limit()`, below) already uses — see issue #3580.
1777pub(crate) fn parse_relative_usage_window(error_message: &str) -> Option<u64> {
1778    static WINDOW_RE: LazyLock<Regex> = LazyLock::new(|| {
1779        Regex::new(
1780            r"(?i)(?:^|\s|[\(\)\.,;:!?])(?:(\d+)\s*-?\s*(hour|hours|hr|hrs|minute|minutes|min|mins|day|days)|(hourly|daily|weekly|monthly))(?:$|\s|[\(\)\.,;:!?])"
1781        )
1782        .expect("usage window regex is valid")
1783    });
1784
1785    if error_message.is_empty() {
1786        return None;
1787    }
1788
1789    let lower = error_message.to_lowercase();
1790    let has_context = lower.contains("usage limit")
1791        || lower.contains("quota")
1792        || lower.contains("window")
1793        || lower.contains("limit");
1794    if !has_context {
1795        return None;
1796    }
1797
1798    let mut max_secs: Option<u64> = None;
1799    for caps in WINDOW_RE.captures_iter(&lower) {
1800        let secs = if let Some(num) = caps.get(1) {
1801            let n: u64 = num.as_str().parse().ok()?;
1802            let unit = caps.get(2)?.as_str().to_lowercase();
1803            let multiplier = match unit.as_str() {
1804                "hour" | "hours" | "hr" | "hrs" => 3600,
1805                "minute" | "minutes" | "min" | "mins" => 60,
1806                "day" | "days" => 86400,
1807                _ => return None,
1808            };
1809            n.checked_mul(multiplier)?
1810        } else if let Some(word) = caps.get(3) {
1811            match word.as_str().to_lowercase().as_str() {
1812                "hourly" => 3600,
1813                "daily" => 86400,
1814                "weekly" => 604_800,
1815                "monthly" => 2_592_000,
1816                _ => return None,
1817            }
1818        } else {
1819            continue;
1820        };
1821        max_secs = Some(max_secs.map_or(secs, |m| m.max(secs)));
1822    }
1823
1824    max_secs
1825}
1826
1827#[cfg(test)]
1828pub(crate) async fn reset_global_state() {
1829    cooldowns().lock().unwrap().clear();
1830    *cooldown_store().lock().await = None;
1831    github_5xx_timestamps().lock().unwrap().clear();
1832    *github_5xx_circuit_open().lock().unwrap() = None;
1833    degraded_agents().lock().unwrap().clear();
1834    opencode::reset_model_caches_for_test();
1835}
1836
1837#[cfg(test)]
1838mod tests;
1839
1840#[cfg(test)]
1841mod classify_tests;