Skip to main content

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