use chrono::TimeZone;
use regex::Regex;
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::LazyLock;
use std::sync::MutexGuard;
use std::sync::{Arc, Mutex, OnceLock};
use tokio::sync;
use crate::engine::router::config;
#[cfg(test)]
use crate::engine::runner::agents::opencode;
use crate::store::TaskStore;
pub const AGENT_COOLDOWN_SECS: i64 = 30 * 60;
pub const BACKOFF_BASE_SECS: i64 = 5 * 60;
pub const BACKOFF_MAX_SECS: i64 = 4 * 60 * 60;
pub const PERSISTENT_MODEL_BACKOFF_BASE_SECS: i64 = 4 * 60 * 60;
pub const PERSISTENT_MODEL_BACKOFF_MAX_SECS: i64 = 7 * 24 * 60 * 60;
pub const TRANSIENT_MODEL_BACKOFF_BASE_SECS: i64 = 5 * 60;
pub const TRANSIENT_MODEL_BACKOFF_MAX_SECS: i64 = 15 * 60;
pub const CREDIT_BACKOFF_BASE_SECS: i64 = 60 * 60;
pub const ORG_BACKOFF_BASE_SECS: i64 = 2 * 60 * 60;
pub const CREDIT_BACKOFF_MAX_SECS: i64 = 8 * 60 * 60;
pub const BILLING_CYCLE_COOLDOWN_SECS: i64 = 24 * 60 * 60;
pub const BILLING_CYCLE_MAX_SECS: i64 = 7 * 24 * 60 * 60;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CreditExhaustionReason {
OutOfCredits,
OrgLevelDisabled,
BillingCycleExhausted,
}
impl CreditExhaustionReason {
pub fn outcome_str(self) -> &'static str {
match self {
CreditExhaustionReason::OutOfCredits => "credit_exhausted",
CreditExhaustionReason::OrgLevelDisabled => "org_level_disabled",
CreditExhaustionReason::BillingCycleExhausted => "billing_cycle_exhausted",
}
}
}
pub const SILENCE_AGENT_COOLDOWN_SECS: u64 = 120;
pub const SILENCE_COUNT_THRESHOLD: usize = 5;
pub const SILENCE_COUNT_WINDOW_SECS: i64 = 24 * 60 * 60;
pub const SILENCE_EXTENDED_COOLDOWN_SECS: u64 = 4 * 60 * 60;
const KV_PREFIX: &str = "cooldown:";
const SILENCE_COUNT_PREFIX: &str = "silence_count:";
const FAILURE_COUNT_PREFIX: &str = "failure_count:";
const CREDIT_FAILURE_COUNT_PREFIX: &str = "credit_failure_count:";
const PERSISTENT_FAILURE_COUNT_PREFIX: &str = "persistent_failure_count:";
const RATE_LIMITS_CLEARED_AT_PREFIX: &str = "rate_limits_cleared_at:";
fn agent_from_key(key: &str) -> &str {
key.split_once(':').map_or(key, |(agent, _)| agent)
}
struct CooldownEntry {
cooldown_until: i64,
reason: String,
}
#[derive(Debug)]
pub struct SilenceCountResult {
pub count: usize,
pub extended_cooldown_applied: bool,
}
fn cooldowns() -> &'static Mutex<HashMap<String, CooldownEntry>> {
static COOLDOWNS: OnceLock<Mutex<HashMap<String, CooldownEntry>>> = OnceLock::new();
COOLDOWNS.get_or_init(|| Mutex::new(HashMap::new()))
}
fn cooldown_store() -> &'static sync::Mutex<Option<Arc<TaskStore>>> {
static STORE: OnceLock<sync::Mutex<Option<Arc<TaskStore>>>> = OnceLock::new();
STORE.get_or_init(|| sync::Mutex::new(None))
}
fn parse_cooldown_value(value: &str) -> Option<(i64, String)> {
if let Ok(serde_json::Value::Object(map)) = serde_json::from_str(value) {
let until = map.get("until")?.as_i64()?;
let reason = map
.get("reason")
.and_then(|r| r.as_str())
.unwrap_or("persisted")
.to_string();
return Some((until, reason));
}
value
.parse::<i64>()
.ok()
.map(|until| (until, "persisted".to_string()))
}
pub async fn init_cooldown_store(store: Arc<TaskStore>) {
match store.kv_list_prefix(KV_PREFIX).await {
Ok(rows) => {
let now = chrono::Utc::now().timestamp();
let mut map = cooldown_lock();
let mut loaded = 0;
for (key, value) in rows {
let cooldown_key = key.trim_start_matches(KV_PREFIX);
if let Some((cooldown_until, reason)) = parse_cooldown_value(&value)
&& now < cooldown_until
{
map.insert(
cooldown_key.to_string(),
CooldownEntry {
cooldown_until,
reason,
},
);
loaded += 1;
}
}
if loaded > 0 {
tracing::info!(loaded, "loaded persisted cooldowns from KV store");
}
}
Err(e) => {
tracing::warn!(err = %e, "failed to load cooldowns from KV store");
}
}
if let Ok(Some(raw)) = store.kv_get("cooldown:github:5xx").await
&& let Ok(cooldown_until) = raw.parse::<i64>()
{
let now = chrono::Utc::now().timestamp();
if now < cooldown_until {
let mut open = github_5xx_circuit_open_lock();
*open = Some(cooldown_until);
let remaining = cooldown_until - now;
tracing::warn!(
remaining_secs = remaining,
"GitHub 5xx circuit breaker restored from KV (still open)"
);
}
}
*cooldown_store().lock().await = Some(store);
}
pub async fn sync_from_kv(store: &Arc<TaskStore>) {
let rows = match store.kv_list_prefix(KV_PREFIX).await {
Ok(rows) => rows,
Err(e) => {
tracing::warn!(err = %e, "cooldown sync_from_kv: KV list failed");
return;
}
};
let now = chrono::Utc::now().timestamp();
let mut explicit_kv: HashMap<String, Option<(i64, String)>> =
HashMap::with_capacity(rows.len());
for (kv_key, value) in &rows {
let cooldown_key = kv_key.trim_start_matches(KV_PREFIX);
if let Some((ts, reason)) = parse_cooldown_value(value) {
let normalized = if ts > now { Some((ts, reason)) } else { None };
explicit_kv.insert(cooldown_key.to_string(), normalized);
}
}
match explicit_kv.get("github:5xx") {
Some(None) => {
let mut open = github_5xx_circuit_open_lock();
if open.take().is_some() {
tracing::info!("GitHub 5xx circuit breaker closed by KV clear");
github_5xx_timestamps_lock().clear();
}
}
Some(Some((ts, _))) => {
*github_5xx_circuit_open_lock() = Some(*ts);
}
None => {}
}
let mut map = cooldown_lock();
let mut dropped = 0usize;
let mut updated = 0usize;
map.retain(|key, _| {
if matches!(explicit_kv.get(key), Some(None)) {
dropped += 1;
false
} else {
true
}
});
for (key, normalized) in explicit_kv {
if let Some((ts, reason)) = normalized {
if let Some(entry) = map.get_mut(&key) {
if entry.cooldown_until != ts {
entry.cooldown_until = ts;
updated += 1;
}
} else {
map.insert(
key,
CooldownEntry {
cooldown_until: ts,
reason,
},
);
updated += 1;
}
}
}
if dropped > 0 || updated > 0 {
tracing::info!(
dropped,
updated,
"cooldown sync_from_kv: reconciled in-memory map with KV"
);
}
}
const EXTENDED_TIER_1_THRESHOLD: u64 = 2;
const EXTENDED_TIER_1_MULTIPLIER: i64 = 6;
const EXTENDED_TIER_2_THRESHOLD: u64 = 5;
const EXTENDED_TIER_2_MULTIPLIER: i64 = 12;
pub fn compute_backoff(count: u64, base: i64, max: i64, allow_extended: bool) -> i64 {
if count <= 1 {
return base;
}
let exp = u32::try_from(count.saturating_sub(1)).unwrap_or(u32::MAX);
let factor = 3_i64.saturating_pow(exp);
let standard = base.saturating_mul(factor).min(max);
let first_max = if base <= 0 {
0
} else {
let mut accumulated = base;
let mut first_max_count = 1u64;
while accumulated < max && first_max_count < count {
accumulated = accumulated.saturating_mul(3);
first_max_count += 1;
}
first_max_count
};
let times_at_max = count.saturating_sub(first_max);
if !allow_extended {
return standard;
}
if standard == max && times_at_max >= EXTENDED_TIER_2_THRESHOLD {
max.saturating_mul(EXTENDED_TIER_2_MULTIPLIER)
} else if standard == max && times_at_max >= EXTENDED_TIER_1_THRESHOLD {
max.saturating_mul(EXTENDED_TIER_1_MULTIPLIER)
} else {
standard
}
}
async fn read_and_increment_failure_count(store_opt: Option<&Arc<TaskStore>>, key: &str) -> u64 {
read_and_increment_failure_count_with_prefix(store_opt, FAILURE_COUNT_PREFIX, key).await
}
async fn read_and_increment_failure_count_with_prefix(
store_opt: Option<&Arc<TaskStore>>,
prefix: &str,
key: &str,
) -> u64 {
let kv_key = format!("{prefix}{key}");
if let Some(store) = store_opt {
match store.kv_increment(&kv_key).await {
Ok(n) => n,
Err(e) => {
tracing::warn!(key = %kv_key, err = %e, "failed to increment failure count — treating as high count for safe backoff");
u64::MAX
}
}
} else {
1
}
}
struct ModelBackoff {
prefix: &'static str,
base: i64,
max: i64,
allow_extended: bool,
reason: &'static str,
}
async fn record_model_backoff(agent_name: &str, model: &str, schedule: &ModelBackoff) {
let key = format!("{agent_name}:{model}");
let store_opt = cooldown_store().lock().await.clone();
let count =
read_and_increment_failure_count_with_prefix(store_opt.as_ref(), schedule.prefix, &key)
.await;
let cooldown_secs =
compute_backoff(count, schedule.base, schedule.max, schedule.allow_extended);
let cooldown_until = chrono::Utc::now().timestamp() + cooldown_secs;
set_cooldown_async(&key, cooldown_until, schedule.reason).await;
}
pub async fn record_agent_success(agent_name: &str, model: &str) {
let store_opt = cooldown_store().lock().await.clone();
if let Some(store) = store_opt {
let agent_key = format!("{FAILURE_COUNT_PREFIX}{agent_name}");
let credit_key = format!("{CREDIT_FAILURE_COUNT_PREFIX}{agent_name}");
if let Err(e) = store.kv_set(&agent_key, "0").await {
tracing::warn!(key = agent_key, err = %e, "failed to reset failure count");
}
if !model.is_empty() {
let model_key = format!("{FAILURE_COUNT_PREFIX}{agent_name}:{model}");
if let Err(e) = store.kv_set(&model_key, "0").await {
tracing::warn!(key = model_key, err = %e, "failed to reset failure count");
}
}
if let Err(e) = store.kv_set(&credit_key, "0").await {
tracing::warn!(key = credit_key, err = %e, "failed to reset failure count");
}
}
}
pub async fn record_agent_failure_with_message(agent_name: &str, error_message: &str) {
if let Some(cooldown_until) = parse_retry_at(error_message) {
let now = chrono::Utc::now().timestamp();
if cooldown_until > now {
set_cooldown_async(agent_name, cooldown_until, "agent_error").await;
return;
}
tracing::debug!(
agent = agent_name,
cooldown_until,
"vendor retry_at is in the past — using backoff instead"
);
}
let store_opt = cooldown_store().lock().await.clone();
let count = read_and_increment_failure_count(store_opt.as_ref(), agent_name).await;
let base = config::get_agent_backoff_base(agent_name);
let cooldown_until =
chrono::Utc::now().timestamp() + compute_backoff(count, base, BACKOFF_MAX_SECS, true);
set_cooldown_async(agent_name, cooldown_until, "agent_error").await;
}
pub fn detect_credit_exhaustion_outcome(error_message: &str) -> Option<&'static str> {
detect_credit_exhaustion(error_message).map(CreditExhaustionReason::outcome_str)
}
pub fn detect_credit_exhaustion(error_message: &str) -> Option<CreditExhaustionReason> {
let lower = error_message.to_lowercase();
let overage_patterns = [
"overagedisabledreason",
"overage_disabled_reason",
"overage disabled reason",
];
if overage_patterns.iter().any(|p| lower.contains(p)) {
if lower.contains("out_of_credits") || lower.contains("outofcredits") {
return Some(CreditExhaustionReason::OutOfCredits);
}
if lower.contains("org_level_disabled") || lower.contains("orgdisabled") {
return Some(CreditExhaustionReason::OrgLevelDisabled);
}
}
let billing_patterns = [
"credit balance too low",
"credit balance insufficient",
"insufficient credit balance",
"billing quota exceeded",
"billing limit exceeded",
"organization has been disabled",
"org disabled",
];
if billing_patterns.iter().any(|p| lower.contains(p)) {
return Some(CreditExhaustionReason::OrgLevelDisabled);
}
let billing_cycle_patterns = [
"billing cycle",
"quota refreshed next cycle",
"monthly quota",
"quota will be refreshed",
"next billing cycle",
"refreshed in the next cycle",
"weekly/monthly limit exhausted",
"limit will reset at",
"upgrade to pro", "upgrade your token plan", "token plan usage limit", "purchase credits for more", ];
if billing_cycle_patterns.iter().any(|p| lower.contains(p)) {
return Some(CreditExhaustionReason::BillingCycleExhausted);
}
if lower.contains("out of credits")
|| lower.contains("outofcredits")
|| lower.contains("insufficient funds")
|| lower.contains("no credits remaining")
|| lower.contains("insufficient_quota")
|| lower.contains("quota exceeded")
|| lower.contains("insufficient balance")
|| lower.contains("please recharge")
|| lower.contains("no resource package")
|| lower.contains("balance exhausted")
|| lower.contains("402 payment required")
{
return Some(CreditExhaustionReason::OutOfCredits);
}
None
}
pub async fn record_credit_exhaustion(agent_name: &str, reason: CreditExhaustionReason) {
let reason_str = match reason {
CreditExhaustionReason::OutOfCredits => "credit_exhaustion_out_of_credits",
CreditExhaustionReason::OrgLevelDisabled => "credit_exhaustion_org_level_disabled",
CreditExhaustionReason::BillingCycleExhausted => "billing_cycle_exhausted",
};
if is_in_cooldown_with_reason(agent_name, reason_str) {
tracing::debug!(
agent = agent_name,
reason = reason_str,
"credit exhaustion already cooled, not escalating"
);
return;
}
let store_opt = cooldown_store().lock().await.clone();
let count = read_and_increment_failure_count_with_prefix(
store_opt.as_ref(),
CREDIT_FAILURE_COUNT_PREFIX,
agent_name,
)
.await;
let (base, max) = match reason {
CreditExhaustionReason::OutOfCredits => (CREDIT_BACKOFF_BASE_SECS, CREDIT_BACKOFF_MAX_SECS),
CreditExhaustionReason::OrgLevelDisabled => {
(ORG_BACKOFF_BASE_SECS, CREDIT_BACKOFF_MAX_SECS)
}
CreditExhaustionReason::BillingCycleExhausted => {
(BILLING_CYCLE_COOLDOWN_SECS, BILLING_CYCLE_MAX_SECS)
}
};
let cooldown_secs = compute_backoff(
count,
base,
max,
!matches!(reason, CreditExhaustionReason::BillingCycleExhausted),
);
let cooldown_until = chrono::Utc::now().timestamp() + cooldown_secs;
set_cooldown_async(agent_name, cooldown_until, reason_str).await;
tracing::warn!(
agent = agent_name,
reason = reason_str,
attempt = count,
cooldown_secs,
"credit exhaustion detected: applying exponential agent-wide cooldown"
);
}
pub async fn record_credit_exhaustion_from_message(
agent_name: &str,
model: Option<&str>,
message: &str,
) -> bool {
let Some(reason) = detect_credit_exhaustion(message) else {
return false;
};
match (reason, model) {
(CreditExhaustionReason::BillingCycleExhausted, Some(model)) => {
record_persistent_model_failure(agent_name, model).await;
}
_ => record_credit_exhaustion(agent_name, reason).await,
}
true
}
pub async fn record_model_failure(agent_name: &str, model: &str) {
let base = config::get_agent_backoff_base(agent_name);
let schedule = ModelBackoff {
prefix: FAILURE_COUNT_PREFIX,
base,
max: BACKOFF_MAX_SECS,
allow_extended: true,
reason: "model_error",
};
record_model_backoff(agent_name, model, &schedule).await;
}
pub async fn record_rate_limit(agent_name: &str, model: Option<&str>, error_message: &str) {
if let Some(window_secs) = parse_relative_usage_window(error_message)
&& let Some(m) = model
{
let cooldown_until = chrono::Utc::now()
.timestamp()
.saturating_add(i64::try_from(window_secs).unwrap_or(i64::MAX));
set_model_cooldown(agent_name, m, window_secs, "rate_limit_usage_window").await;
tracing::info!(
agent = agent_name,
model = m,
window_secs,
cooldown_until,
"relative usage window detected: applying model-specific cooldown"
);
return;
}
record_agent_failure_with_message(agent_name, error_message).await;
if let Some(m) = model {
record_model_failure(agent_name, m).await;
}
}
pub async fn record_persistent_model_failure(agent_name: &str, model: &str) {
let schedule = ModelBackoff {
prefix: PERSISTENT_FAILURE_COUNT_PREFIX,
base: PERSISTENT_MODEL_BACKOFF_BASE_SECS,
max: PERSISTENT_MODEL_BACKOFF_MAX_SECS,
allow_extended: false,
reason: "persistent_model_error",
};
record_model_backoff(agent_name, model, &schedule).await;
}
pub async fn record_model_unavailable(agent_name: &str, model: &str, message: &str) {
if is_model_permanently_gone(message) {
record_persistent_model_failure(agent_name, model).await;
} else {
record_model_failure(agent_name, model).await;
}
}
fn is_model_permanently_gone(message: &str) -> bool {
let lower = message.to_lowercase();
lower.contains("not found")
|| lower.contains("not supported")
|| lower.contains("not available in your country")
|| lower.contains("not available in your region")
}
pub async fn record_transient_model_failure(agent_name: &str, model: &str) {
let schedule = ModelBackoff {
prefix: FAILURE_COUNT_PREFIX,
base: TRANSIENT_MODEL_BACKOFF_BASE_SECS,
max: TRANSIENT_MODEL_BACKOFF_MAX_SECS,
allow_extended: false,
reason: "transient_model_error",
};
record_model_backoff(agent_name, model, &schedule).await;
}
pub async fn set_model_cooldown(agent_name: &str, model: &str, duration_secs: u64, reason: &str) {
let key = format!("{agent_name}:{model}");
let cooldown_until = chrono::Utc::now()
.timestamp()
.saturating_add(i64::try_from(duration_secs).unwrap_or(i64::MAX));
set_cooldown_async(&key, cooldown_until, reason).await;
}
pub async fn set_model_cooldown_until(agent_name: &str, model: &str, until: i64) {
let key = format!("{agent_name}:{model}");
set_cooldown_async(&key, until, "vendor_reset_at").await;
}
pub async fn set_agent_cooldown(agent_name: &str, duration_secs: u64) {
let cooldown_until = chrono::Utc::now()
.timestamp()
.saturating_add(i64::try_from(duration_secs).unwrap_or(i64::MAX));
set_cooldown_async(agent_name, cooldown_until, "silence_agent_cooldown").await;
}
pub const RATE_WINDOW_KV_PREFIX: &str = "rate_window:";
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct RateLimitWindow {
pub status: String,
pub window_type: String,
pub utilization: Option<f64>,
pub resets_at: Option<i64>,
}
pub async fn record_rate_limit_window(agent_name: &str, window: &RateLimitWindow) {
let store_opt = cooldown_store().lock().await.clone();
if let Some(store) = store_opt
&& let Ok(value) = serde_json::to_string(window)
&& let Err(e) = store
.kv_set(
&format!("{RATE_WINDOW_KV_PREFIX}{agent_name}:{}", window.window_type),
&value,
)
.await
{
tracing::warn!(agent = agent_name, err = %e, "failed to persist rate limit window");
}
let now = chrono::Utc::now().timestamp();
if window.status == "rejected"
&& let Some(reset) = window.resets_at
&& reset > now
{
let until = reset.min(now + PERSISTENT_MODEL_BACKOFF_MAX_SECS);
set_cooldown_async(agent_name, until, "rate_limit_window").await;
tracing::info!(
agent = agent_name,
window = %window.window_type,
cooldown_until = until,
"rate limit window rejected: cooling agent until vendor reset"
);
}
}
pub async fn list_rate_limit_windows(store: &Arc<TaskStore>) -> Vec<(String, RateLimitWindow)> {
let rows = store
.kv_list_prefix(RATE_WINDOW_KV_PREFIX)
.await
.unwrap_or_default();
let mut windows: Vec<(String, RateLimitWindow)> = rows
.into_iter()
.filter_map(|(key, value)| {
let (agent, _) = key.strip_prefix(RATE_WINDOW_KV_PREFIX)?.rsplit_once(':')?;
let window = serde_json::from_str(&value).ok()?;
Some((agent.to_string(), window))
})
.collect();
windows.sort_by(|a, b| (&a.0, &a.1.window_type).cmp(&(&b.0, &b.1.window_type)));
windows
}
pub async fn record_silence_detection(agent_name: &str, model: &str) -> Option<SilenceCountResult> {
let store_opt = cooldown_store().lock().await.clone();
let Some(store) = store_opt else {
tracing::debug!(
agent = agent_name,
model,
"skipping silence count record (no KV store)"
);
return None;
};
let key = format!("{SILENCE_COUNT_PREFIX}{agent_name}:{model}");
let now = chrono::Utc::now().timestamp();
let window_start = now - SILENCE_COUNT_WINDOW_SECS;
let mut timestamps = match store.kv_get(&key).await {
Ok(Some(raw)) => match serde_json::from_str::<Vec<i64>>(&raw) {
Ok(ts) => ts,
Err(e) => {
tracing::warn!(
kv_key = %key,
err = %e,
"failed to parse silence timestamps from KV — resetting window"
);
Vec::new()
}
},
Ok(None) => Vec::new(),
Err(err) => {
tracing::warn!(
kv_key = %key,
err = %err,
"failed to load silence count from KV"
);
Vec::new()
}
};
timestamps.retain(|ts| *ts >= window_start);
timestamps.push(now);
let count = timestamps.len();
let mut extended_cooldown_applied = false;
if count >= SILENCE_COUNT_THRESHOLD {
set_model_cooldown(
agent_name,
model,
SILENCE_EXTENDED_COOLDOWN_SECS,
"silence_detected",
)
.await;
extended_cooldown_applied = true;
timestamps.clear();
}
let value = serde_json::to_string(×tamps).unwrap_or_else(|_| "[]".to_string());
if let Err(err) = store.kv_set(&key, &value).await {
tracing::warn!(kv_key = key, err = %err, "failed to persist silence count");
}
Some(SilenceCountResult {
count,
extended_cooldown_applied,
})
}
pub fn is_model_in_cooldown(agent_name: &str, model: &str) -> bool {
let key = format!("{agent_name}:{model}");
is_in_cooldown(&key)
}
pub fn is_agent_in_cooldown(agent_name: &str) -> bool {
is_in_cooldown(agent_name)
}
pub fn cooldown_until(key: &str) -> Option<i64> {
let map = cooldown_lock();
map.get(key).and_then(|entry| {
let now = chrono::Utc::now().timestamp();
if now < entry.cooldown_until {
Some(entry.cooldown_until)
} else {
None
}
})
}
pub fn cooldown_reason(key: &str) -> Option<String> {
let map = cooldown_lock();
map.get(key).and_then(|entry| {
let now = chrono::Utc::now().timestamp();
if now < entry.cooldown_until {
Some(entry.reason.clone())
} else {
None
}
})
}
pub async fn list_persisted_cooldowns(store: &TaskStore) -> Vec<(String, i64, String)> {
let now = chrono::Utc::now().timestamp();
let mut out: Vec<(String, i64, String)> = store
.kv_list_prefix(KV_PREFIX)
.await
.unwrap_or_default()
.into_iter()
.filter_map(|(key, value)| {
let (until, reason) = parse_cooldown_value(&value)?;
(now < until).then(|| (key.trim_start_matches(KV_PREFIX).to_string(), until, reason))
})
.collect();
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
pub fn list_all_cooldowns() -> Vec<(String, i64, String)> {
let now = chrono::Utc::now().timestamp();
let map = cooldown_lock();
let mut result: Vec<(String, i64, String)> = map
.iter()
.filter(|(_, entry)| now < entry.cooldown_until)
.map(|(key, entry)| (key.clone(), entry.cooldown_until, entry.reason.clone()))
.collect();
result.sort_by(|a, b| a.0.cmp(&b.0));
result
}
pub async fn mark_rate_limits_cleared(store: &Arc<TaskStore>, agents: &[String]) {
let now = chrono::Utc::now().timestamp().to_string();
let mut seen = HashSet::new();
for key in agents {
let agent = agent_from_key(key);
if agent.is_empty() || !seen.insert(agent.to_string()) {
continue;
}
let kv_key = format!("{RATE_LIMITS_CLEARED_AT_PREFIX}{agent}");
if let Err(e) = store.kv_set(&kv_key, &now).await {
tracing::warn!(agent, err = %e, "failed to mark rate limits cleared");
}
}
}
pub async fn clear_cooldown(key: &str, store: &Arc<TaskStore>) {
let mut agents_to_mark: Vec<String> = Vec::new();
if key == "*" {
let keys: Vec<String> = {
let mut map = cooldown_lock();
let keys: Vec<String> = map.keys().cloned().collect();
map.clear();
keys
};
for k in &keys {
let kv_key = format!("{KV_PREFIX}{k}");
if let Err(e) = store.kv_set(&kv_key, "0").await {
tracing::warn!(key = kv_key, err = %e, "failed to clear cooldown");
}
let fc_key = format!("{FAILURE_COUNT_PREFIX}{k}");
if let Err(e) = store.kv_set(&fc_key, "0").await {
tracing::warn!(key = fc_key, err = %e, "failed to reset failure count");
}
let credit_fc_key = format!("{CREDIT_FAILURE_COUNT_PREFIX}{k}");
if let Err(e) = store.kv_set(&credit_fc_key, "0").await {
tracing::warn!(key = credit_fc_key, err = %e, "failed to reset credit failure count");
}
let persistent_fc_key = format!("{PERSISTENT_FAILURE_COUNT_PREFIX}{k}");
if let Err(e) = store.kv_set(&persistent_fc_key, "0").await {
tracing::warn!(key = persistent_fc_key, err = %e, "failed to reset persistent failure count");
}
}
if let Ok(fc_entries) = store.kv_list_prefix(FAILURE_COUNT_PREFIX).await {
for (fc_key, _) in fc_entries {
if let Err(e) = store.kv_set(&fc_key, "0").await {
tracing::warn!(key = fc_key, err = %e, "failed to reset failure count");
}
}
}
if let Ok(cfc_entries) = store.kv_list_prefix(CREDIT_FAILURE_COUNT_PREFIX).await {
for (cfc_key, _) in cfc_entries {
if let Err(e) = store.kv_set(&cfc_key, "0").await {
tracing::warn!(key = cfc_key, err = %e, "failed to reset credit failure count");
}
}
}
if let Ok(pfc_entries) = store.kv_list_prefix(PERSISTENT_FAILURE_COUNT_PREFIX).await {
for (pfc_key, _) in pfc_entries {
if let Err(e) = store.kv_set(&pfc_key, "0").await {
tracing::warn!(key = pfc_key, err = %e, "failed to reset persistent failure count");
}
}
}
tracing::info!(
count = keys.len(),
"cleared all cooldowns and failure counts"
);
agents_to_mark.extend(keys.iter().map(|k| agent_from_key(k).to_string()));
match store.rate_limit_agents().await {
Ok(rl_agents) => agents_to_mark.extend(rl_agents),
Err(e) => tracing::warn!(err = %e, "failed to list rate_limits agents while clearing"),
}
match store.kv_list_prefix(RATE_LIMITS_CLEARED_AT_PREFIX).await {
Ok(marks) => {
for (k, _) in marks {
let agent = k.trim_start_matches(RATE_LIMITS_CLEARED_AT_PREFIX);
if !agent.is_empty() {
agents_to_mark.push(agent.to_string());
}
}
}
Err(e) => tracing::warn!(err = %e, "failed to list rate_limits_cleared_at keys"),
}
} else {
{
let mut map = cooldown_lock();
map.remove(key);
}
let kv_key = format!("{KV_PREFIX}{key}");
if let Err(e) = store.kv_set(&kv_key, "0").await {
tracing::warn!(key = kv_key, err = %e, "failed to clear cooldown");
}
let fc_key = format!("{FAILURE_COUNT_PREFIX}{key}");
if let Err(e) = store.kv_set(&fc_key, "0").await {
tracing::warn!(key = fc_key, err = %e, "failed to reset failure count");
}
let credit_fc_key = format!("{CREDIT_FAILURE_COUNT_PREFIX}{key}");
if let Err(e) = store.kv_set(&credit_fc_key, "0").await {
tracing::warn!(key = credit_fc_key, err = %e, "failed to reset credit failure count");
}
let persistent_fc_key = format!("{PERSISTENT_FAILURE_COUNT_PREFIX}{key}");
if let Err(e) = store.kv_set(&persistent_fc_key, "0").await {
tracing::warn!(key = persistent_fc_key, err = %e, "failed to reset persistent failure count");
}
tracing::info!(key, "cleared cooldown and failure count");
agents_to_mark.push(agent_from_key(key).to_string());
}
mark_rate_limits_cleared(store, &agents_to_mark).await;
}
fn set_cooldown_in_memory(key: &str, cooldown_until: i64, reason: &str) -> bool {
let mut map = cooldown_lock();
if let Some(existing) = map.get(key) {
if existing.cooldown_until >= cooldown_until {
return false;
}
}
map.insert(
key.to_string(),
CooldownEntry {
cooldown_until,
reason: reason.to_string(),
},
);
true
}
async fn set_cooldown_async(key: &str, cooldown_until: i64, reason: &str) -> bool {
if !set_cooldown_in_memory(key, cooldown_until, reason) {
return false;
}
let store_opt = cooldown_store().lock().await.clone();
if let Some(store) = store_opt {
let kv_key = format!("{KV_PREFIX}{key}");
let value = serde_json::json!({"until": cooldown_until, "reason": reason}).to_string();
if let Err(e) = store.kv_set(&kv_key, &value).await {
tracing::warn!(
kv_key,
err = %e,
"failed to persist cooldown to KV store — rolling back in-memory entry"
);
let mut map = cooldown_lock();
if map.get(key).map(|e| e.cooldown_until) == Some(cooldown_until) {
map.remove(key);
}
return false;
}
}
true
}
fn cooldown_lock() -> MutexGuard<'static, HashMap<String, CooldownEntry>> {
cooldowns().lock().unwrap_or_else(|e| {
tracing::error!("cooldown map lock poisoned — recovering with partial state; backoff and degraded-agent decisions may be incorrect");
e.into_inner()
})
}
fn degraded_agents_lock() -> MutexGuard<'static, HashMap<String, String>> {
degraded_agents().lock().unwrap_or_else(|e| {
tracing::error!("degraded agents lock poisoned — recovering with partial state; health check decisions may be incorrect");
e.into_inner()
})
}
fn github_5xx_timestamps_lock() -> MutexGuard<'static, Vec<i64>> {
github_5xx_timestamps().lock().unwrap_or_else(|e| {
tracing::error!("github 5xx timestamps lock poisoned — recovering with partial state; circuit breaker may operate incorrectly");
e.into_inner()
})
}
fn github_5xx_circuit_open_lock() -> MutexGuard<'static, Option<i64>> {
github_5xx_circuit_open().lock().unwrap_or_else(|e| {
tracing::error!("github 5xx circuit open lock poisoned — recovering with partial state; circuit breaker may operate incorrectly");
e.into_inner()
})
}
fn is_in_cooldown_with_reason(key: &str, reason: &str) -> bool {
let map = cooldown_lock();
map.get(key).is_some_and(|entry| {
entry.reason == reason && chrono::Utc::now().timestamp() < entry.cooldown_until
})
}
fn is_in_cooldown(key: &str) -> bool {
let map = cooldown_lock();
if let Some(entry) = map.get(key) {
let now = chrono::Utc::now().timestamp();
return now < entry.cooldown_until;
}
false
}
pub const DEFAULT_HEALTH_CHECK_WINDOW_HOURS: u32 = 6;
pub const DEFAULT_DEGRADED_RATE_LIMIT_THRESHOLD: i64 = 3;
fn degraded_agents() -> &'static Mutex<HashMap<String, String>> {
static DEGRADED: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();
DEGRADED.get_or_init(|| Mutex::new(HashMap::new()))
}
pub fn is_agent_degraded(agent: &str) -> bool {
let set = degraded_agents_lock();
set.contains_key(agent)
}
pub fn agent_degraded_reason(agent: &str) -> Option<String> {
degraded_agents_lock().get(agent).cloned()
}
pub fn list_degraded_agents() -> Vec<(String, String)> {
let mut entries: Vec<(String, String)> = degraded_agents_lock()
.iter()
.map(|(agent, reason)| (agent.clone(), reason.clone()))
.collect();
entries.sort_by(|a, b| a.0.cmp(&b.0));
entries
}
pub fn mark_agent_degraded(agent: &str) {
mark_agent_degraded_with_reason(agent, "degraded");
}
fn mark_agent_degraded_with_reason(agent: &str, reason: &str) {
let mut set = degraded_agents_lock();
set.insert(agent.to_string(), reason.to_string());
}
pub fn clear_agent_degraded(agent: &str) {
let mut set = degraded_agents_lock();
set.remove(agent);
}
pub async fn refresh_degraded_agents(
store: &Arc<TaskStore>,
available_agents: &[String],
model_checker: &(dyn Fn(&str) -> bool + Send + Sync),
window_hours: u32,
threshold: i64,
) {
clear_expired_cooldowns();
let start = chrono::Utc::now();
let counts = match store.recent_rate_limit_counts(window_hours).await {
Ok(c) => {
let dur_ms = (chrono::Utc::now() - start).num_milliseconds();
tracing::info!(
duration_ms = dur_ms,
window_hours,
"recent_rate_limit_counts query completed"
);
c
}
Err(e) => {
let dur_ms = (chrono::Utc::now() - start).num_milliseconds();
tracing::warn!(
err = %e,
duration_ms = dur_ms,
"failed to query recent rate limit counts for health check"
);
return;
}
};
for agent in available_agents {
let in_cooldown = is_agent_in_cooldown(agent);
let no_models = !model_checker(agent);
let rate_limit_count = counts.get(agent.as_str()).copied().unwrap_or(0);
let over_threshold = rate_limit_count >= threshold;
let degraded = in_cooldown || no_models || over_threshold;
if degraded {
let reason = if in_cooldown {
"agent in cooldown"
} else if no_models {
"all models cooled"
} else {
"rate limit threshold exceeded"
};
let previous = agent_degraded_reason(agent);
match previous.as_deref() {
None => tracing::warn!(
agent,
reason,
rate_limit_count,
window_hours,
threshold,
"pre-emptive health check: marking agent as degraded"
),
Some(prev) if prev != reason => tracing::warn!(
agent,
reason,
previous = prev,
rate_limit_count,
window_hours,
threshold,
"pre-emptive health check: degraded reason changed"
),
Some(_) => {}
}
mark_agent_degraded_with_reason(agent, reason);
} else {
if is_agent_degraded(agent) {
tracing::info!(
agent,
rate_limit_count,
"pre-emptive health check: agent recovered, clearing degraded flag"
);
}
clear_agent_degraded(agent);
}
}
}
pub fn clear_expired_cooldowns() {
let mut map = cooldown_lock();
let now = chrono::Utc::now().timestamp();
map.retain(|_key, entry| now < entry.cooldown_until);
}
const GITHUB_5XX_WINDOW_SECS: i64 = 120;
const GITHUB_5XX_THRESHOLD: usize = 5;
const GITHUB_5XX_COOLDOWN_SECS: i64 = 180;
fn github_5xx_timestamps() -> &'static Mutex<Vec<i64>> {
static TS: OnceLock<Mutex<Vec<i64>>> = OnceLock::new();
TS.get_or_init(|| Mutex::new(Vec::new()))
}
fn github_5xx_circuit_open() -> &'static Mutex<Option<i64>> {
static OPEN: OnceLock<Mutex<Option<i64>>> = OnceLock::new();
OPEN.get_or_init(|| Mutex::new(None))
}
pub async fn record_github_5xx() {
let now = chrono::Utc::now().timestamp();
let window_start = now - GITHUB_5XX_WINDOW_SECS;
let should_trip = {
let mut ts = github_5xx_timestamps_lock();
ts.retain(|t| *t >= window_start);
ts.push(now);
ts.len() >= GITHUB_5XX_THRESHOLD
};
if should_trip {
let cooldown_until = {
let mut open = github_5xx_circuit_open_lock();
if open.is_none() {
let cd = now + GITHUB_5XX_COOLDOWN_SECS;
*open = Some(cd);
tracing::warn!(
errors_in_window = GITHUB_5XX_THRESHOLD,
window_secs = GITHUB_5XX_WINDOW_SECS,
cooldown_secs = GITHUB_5XX_COOLDOWN_SECS,
"GitHub 5xx circuit breaker OPEN — throttling non-critical work"
);
Some(cd)
} else {
None
}
};
if let Some(cd) = cooldown_until {
let store_opt = cooldown_store().lock().await.clone();
if let Some(store) = store_opt {
let _ = store.kv_set("cooldown:github:5xx", &cd.to_string()).await;
}
set_agent_cooldown("github:5xx", GITHUB_5XX_COOLDOWN_SECS as u64).await;
}
let mut ts = github_5xx_timestamps_lock();
ts.clear();
}
}
pub fn is_github_circuit_open() -> bool {
{
let mut open = github_5xx_circuit_open_lock();
if let Some(until) = *open {
let now = chrono::Utc::now().timestamp();
if now >= until {
*open = None;
tracing::info!("GitHub 5xx circuit breaker CLOSED — resuming normal operations");
return false;
}
return true;
}
}
if let Some(until) = cooldown_until("github:5xx") {
let mut open = github_5xx_circuit_open_lock();
if open.is_none() {
*open = Some(until);
let now = chrono::Utc::now().timestamp();
if now < until {
let remaining = until - now;
tracing::warn!(
remaining_secs = remaining,
"GitHub 5xx circuit breaker OPEN (discovered via generic cooldown) — throttling non-critical work"
);
}
}
return true;
}
false
}
pub fn github_circuit_remaining_secs() -> u64 {
{
let open = github_5xx_circuit_open_lock();
if let Some(until) = *open {
let now = chrono::Utc::now().timestamp();
if now < until {
return u64::try_from(until - now).unwrap_or(0);
}
return 0;
}
}
if let Some(until) = cooldown_until("github:5xx") {
let now = chrono::Utc::now().timestamp();
if now < until {
return u64::try_from(until - now).unwrap_or(0);
}
}
0
}
pub(crate) fn parse_retry_at(error_message: &str) -> Option<i64> {
if error_message.is_empty() {
return None;
}
let lower = error_message.to_lowercase();
for retry_marker in [
"try again at ",
"reset at ",
"resets at ",
"resets ",
"reset ",
] {
if let Some(idx) = lower.find(retry_marker) {
let date_str = &lower[idx + retry_marker.len()..];
let date_str = date_str
.split(['.', '\n'])
.next()
.unwrap_or(date_str)
.trim();
let cleaned = date_str
.replace("st,", ",")
.replace("nd,", ",")
.replace("rd,", ",")
.replace("th,", ",");
for fmt in &[
"%b %d, %Y %I:%M %p", "%b %d, %Y %I:%M%p", "%B %d, %Y %I:%M %p", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", ] {
if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(&cleaned, fmt) {
let utc = match chrono::Local.from_local_datetime(&dt) {
chrono::LocalResult::Single(local_dt) => {
local_dt.with_timezone(&chrono::Utc)
}
chrono::LocalResult::Ambiguous(earliest, _) => {
earliest.with_timezone(&chrono::Utc)
}
chrono::LocalResult::None => {
dt.and_utc()
}
};
tracing::info!(
retry_at = %utc,
raw = date_str,
marker = retry_marker,
"parsed rate limit retry-at date"
);
return Some(utc.timestamp());
}
}
tracing::debug!(
raw = date_str,
marker = retry_marker,
"could not parse retry-at date"
);
let time_only = date_str.split_once('(').map_or(date_str, |(t, _)| t).trim();
let mut compact = time_only.replace(" am", "am").replace(" pm", "pm");
let split = compact.rfind(' ').map_or(0, |i| i + 1);
let last = &compact[split..];
if !last.contains(':')
&& (last.ends_with("am") || last.ends_with("pm"))
&& last.len() > 2
{
let at = split + last.len() - 2;
compact.insert_str(at, ":00");
}
let md = compact.replace(" at ", " ");
let now_local = chrono::Local::now();
let this_year = chrono::Datelike::year(&now_local);
for year in [this_year, this_year + 1] {
let with_year = format!("{year} {md}");
if let Ok(dt) =
chrono::NaiveDateTime::parse_from_str(&with_year, "%Y %b %d %I:%M%p")
&& let Some(local_dt) = chrono::Local.from_local_datetime(&dt).earliest()
&& local_dt > now_local
{
return Some(local_dt.timestamp());
}
}
let time_only = compact.as_str();
for tf in &["%I:%M %p", "%I:%M%p", "%I %p", "%H:%M"] {
if let Ok(t) = chrono::NaiveTime::parse_from_str(time_only, tf) {
let local_now = chrono::Local::now();
let today = local_now.date_naive();
let candidate = chrono::NaiveDateTime::new(today, t);
let candidate_local: chrono::DateTime<chrono::Local> =
match chrono::Local.from_local_datetime(&candidate) {
chrono::LocalResult::Single(dt) => dt,
chrono::LocalResult::Ambiguous(earliest, _) => earliest,
chrono::LocalResult::None => {
let utc_dt = candidate.and_utc();
return Some(utc_dt.timestamp());
}
};
let chosen = if candidate_local <= local_now {
let tomorrow = today.succ_opt().unwrap_or(today);
let ndt = chrono::NaiveDateTime::new(tomorrow, t);
match chrono::Local.from_local_datetime(&ndt) {
chrono::LocalResult::Single(dt) => dt.with_timezone(&chrono::Utc),
chrono::LocalResult::Ambiguous(earliest, _) => {
earliest.with_timezone(&chrono::Utc)
}
chrono::LocalResult::None => ndt.and_utc(),
}
} else {
candidate_local.with_timezone(&chrono::Utc)
};
tracing::info!(
retry_at = %chosen,
raw = date_str,
marker = retry_marker,
"parsed rate limit retry-at time-only; interpreted as next occurrence"
);
return Some(chosen.timestamp());
}
}
}
}
None
}
pub(crate) fn parse_relative_usage_window(error_message: &str) -> Option<u64> {
static WINDOW_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(
r"(?i)(?:^|\s|[\(\)\.,;:!?])(?:(\d+)\s*-?\s*(hour|hours|hr|hrs|minute|minutes|min|mins|day|days)|(hourly|daily|weekly|monthly))(?:$|\s|[\(\)\.,;:!?])"
)
.expect("usage window regex is valid")
});
if error_message.is_empty() {
return None;
}
let lower = error_message.to_lowercase();
let has_context = lower.contains("usage limit")
|| lower.contains("quota")
|| lower.contains("window")
|| lower.contains("limit");
if !has_context {
return None;
}
let mut max_secs: Option<u64> = None;
for caps in WINDOW_RE.captures_iter(&lower) {
let secs = if let Some(num) = caps.get(1) {
let n: u64 = num.as_str().parse().ok()?;
let unit = caps.get(2)?.as_str().to_lowercase();
let multiplier = match unit.as_str() {
"hour" | "hours" | "hr" | "hrs" => 3600,
"minute" | "minutes" | "min" | "mins" => 60,
"day" | "days" => 86400,
_ => return None,
};
n.checked_mul(multiplier)?
} else if let Some(word) = caps.get(3) {
match word.as_str().to_lowercase().as_str() {
"hourly" => 3600,
"daily" => 86400,
"weekly" => 604_800,
"monthly" => 2_592_000,
_ => return None,
}
} else {
continue;
};
max_secs = Some(max_secs.map_or(secs, |m| m.max(secs)));
}
max_secs
}
#[cfg(test)]
pub(crate) async fn reset_global_state() {
cooldowns().lock().unwrap().clear();
*cooldown_store().lock().await = None;
github_5xx_timestamps().lock().unwrap().clear();
*github_5xx_circuit_open().lock().unwrap() = None;
degraded_agents().lock().unwrap().clear();
opencode::reset_model_caches_for_test();
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod classify_tests;