1use chrono::TimeZone;
19use regex::Regex;
20use std::collections::HashMap;
21use std::collections::HashSet;
22use std::sync::LazyLock;
23use std::sync::MutexGuard;
24use std::sync::{Arc, Mutex, OnceLock};
25use tokio::sync;
26
27use crate::engine::router::config;
28#[cfg(test)]
29use crate::engine::runner::agents::opencode;
30use crate::store::TaskStore;
31
32pub const AGENT_COOLDOWN_SECS: i64 = 30 * 60;
38
39pub const BACKOFF_BASE_SECS: i64 = 5 * 60;
41
42pub const BACKOFF_MAX_SECS: i64 = 4 * 60 * 60;
44
45pub const PERSISTENT_MODEL_BACKOFF_BASE_SECS: i64 = 4 * 60 * 60;
47
48pub const PERSISTENT_MODEL_BACKOFF_MAX_SECS: i64 = 7 * 24 * 60 * 60;
50
51pub const TRANSIENT_MODEL_BACKOFF_BASE_SECS: i64 = 5 * 60;
53
54pub const TRANSIENT_MODEL_BACKOFF_MAX_SECS: i64 = 15 * 60;
56
57pub const CREDIT_BACKOFF_BASE_SECS: i64 = 60 * 60;
59
60pub const ORG_BACKOFF_BASE_SECS: i64 = 2 * 60 * 60;
62
63pub const CREDIT_BACKOFF_MAX_SECS: i64 = 8 * 60 * 60;
66
67pub const BILLING_CYCLE_COOLDOWN_SECS: i64 = 24 * 60 * 60;
75
76pub const BILLING_CYCLE_MAX_SECS: i64 = 7 * 24 * 60 * 60;
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum CreditExhaustionReason {
86 OutOfCredits,
88 OrgLevelDisabled,
90 BillingCycleExhausted,
92}
93
94impl CreditExhaustionReason {
95 pub fn outcome_str(self) -> &'static str {
99 match self {
100 CreditExhaustionReason::OutOfCredits => "credit_exhausted",
101 CreditExhaustionReason::OrgLevelDisabled => "org_level_disabled",
102 CreditExhaustionReason::BillingCycleExhausted => "billing_cycle_exhausted",
103 }
104 }
105}
106
107pub const SILENCE_AGENT_COOLDOWN_SECS: u64 = 120;
114
115pub const SILENCE_COUNT_THRESHOLD: usize = 5;
117
118pub const SILENCE_COUNT_WINDOW_SECS: i64 = 24 * 60 * 60;
120
121pub const SILENCE_EXTENDED_COOLDOWN_SECS: u64 = 4 * 60 * 60;
123
124const KV_PREFIX: &str = "cooldown:";
126
127const SILENCE_COUNT_PREFIX: &str = "silence_count:";
129
130const FAILURE_COUNT_PREFIX: &str = "failure_count:";
132
133const CREDIT_FAILURE_COUNT_PREFIX: &str = "credit_failure_count:";
136
137const PERSISTENT_FAILURE_COUNT_PREFIX: &str = "persistent_failure_count:";
141
142const RATE_LIMITS_CLEARED_AT_PREFIX: &str = "rate_limits_cleared_at:";
144
145fn agent_from_key(key: &str) -> &str {
147 key.split_once(':').map_or(key, |(agent, _)| agent)
148}
149
150struct CooldownEntry {
151 cooldown_until: i64,
153 reason: String,
154}
155
156#[derive(Debug)]
157pub struct SilenceCountResult {
158 pub count: usize,
159 pub extended_cooldown_applied: bool,
160}
161
162fn cooldowns() -> &'static Mutex<HashMap<String, CooldownEntry>> {
171 static COOLDOWNS: OnceLock<Mutex<HashMap<String, CooldownEntry>>> = OnceLock::new();
172 COOLDOWNS.get_or_init(|| Mutex::new(HashMap::new()))
173}
174
175fn cooldown_store() -> &'static sync::Mutex<Option<Arc<TaskStore>>> {
181 static STORE: OnceLock<sync::Mutex<Option<Arc<TaskStore>>>> = OnceLock::new();
182 STORE.get_or_init(|| sync::Mutex::new(None))
183}
184
185fn parse_cooldown_value(value: &str) -> Option<(i64, String)> {
193 if let Ok(serde_json::Value::Object(map)) = serde_json::from_str(value) {
194 let until = map.get("until")?.as_i64()?;
195 let reason = map
196 .get("reason")
197 .and_then(|r| r.as_str())
198 .unwrap_or("persisted")
199 .to_string();
200 return Some((until, reason));
201 }
202 value
203 .parse::<i64>()
204 .ok()
205 .map(|until| (until, "persisted".to_string()))
206}
207
208pub async fn init_cooldown_store(store: Arc<TaskStore>) {
209 match store.kv_list_prefix(KV_PREFIX).await {
210 Ok(rows) => {
211 let now = chrono::Utc::now().timestamp();
212 let mut map = cooldown_lock();
213 let mut loaded = 0;
214 for (key, value) in rows {
215 let cooldown_key = key.trim_start_matches(KV_PREFIX);
216 if let Some((cooldown_until, reason)) = parse_cooldown_value(&value)
217 && now < cooldown_until
218 {
219 map.insert(
220 cooldown_key.to_string(),
221 CooldownEntry {
222 cooldown_until,
223 reason,
224 },
225 );
226 loaded += 1;
227 }
228 }
231 if loaded > 0 {
232 tracing::info!(loaded, "loaded persisted cooldowns from KV store");
233 }
234 }
235 Err(e) => {
236 tracing::warn!(err = %e, "failed to load cooldowns from KV store");
237 }
238 }
239
240 if let Ok(Some(raw)) = store.kv_get("cooldown:github:5xx").await
242 && let Ok(cooldown_until) = raw.parse::<i64>()
243 {
244 let now = chrono::Utc::now().timestamp();
245 if now < cooldown_until {
246 let mut open = github_5xx_circuit_open_lock();
247 *open = Some(cooldown_until);
248 let remaining = cooldown_until - now;
249 tracing::warn!(
250 remaining_secs = remaining,
251 "GitHub 5xx circuit breaker restored from KV (still open)"
252 );
253 }
254 }
255
256 *cooldown_store().lock().await = Some(store);
257}
258
259pub async fn sync_from_kv(store: &Arc<TaskStore>) {
276 let rows = match store.kv_list_prefix(KV_PREFIX).await {
277 Ok(rows) => rows,
278 Err(e) => {
279 tracing::warn!(err = %e, "cooldown sync_from_kv: KV list failed");
280 return;
281 }
282 };
283 let now = chrono::Utc::now().timestamp();
284
285 let mut explicit_kv: HashMap<String, Option<(i64, String)>> =
288 HashMap::with_capacity(rows.len());
289 for (kv_key, value) in &rows {
290 let cooldown_key = kv_key.trim_start_matches(KV_PREFIX);
291 if let Some((ts, reason)) = parse_cooldown_value(value) {
292 let normalized = if ts > now { Some((ts, reason)) } else { None };
293 explicit_kv.insert(cooldown_key.to_string(), normalized);
294 }
295 }
296
297 match explicit_kv.get("github:5xx") {
299 Some(None) => {
300 let mut open = github_5xx_circuit_open_lock();
301 if open.take().is_some() {
302 tracing::info!("GitHub 5xx circuit breaker closed by KV clear");
303 github_5xx_timestamps_lock().clear();
304 }
305 }
306 Some(Some((ts, _))) => {
307 *github_5xx_circuit_open_lock() = Some(*ts);
308 }
309 None => {}
310 }
311
312 let mut map = cooldown_lock();
313 let mut dropped = 0usize;
314 let mut updated = 0usize;
315
316 map.retain(|key, _| {
318 if matches!(explicit_kv.get(key), Some(None)) {
319 dropped += 1;
320 false
321 } else {
322 true
323 }
324 });
325
326 for (key, normalized) in explicit_kv {
328 if let Some((ts, reason)) = normalized {
329 if let Some(entry) = map.get_mut(&key) {
330 if entry.cooldown_until != ts {
331 entry.cooldown_until = ts;
332 updated += 1;
333 }
334 } else {
335 map.insert(
336 key,
337 CooldownEntry {
338 cooldown_until: ts,
339 reason,
340 },
341 );
342 updated += 1;
343 }
344 }
345 }
346
347 if dropped > 0 || updated > 0 {
348 tracing::info!(
349 dropped,
350 updated,
351 "cooldown sync_from_kv: reconciled in-memory map with KV"
352 );
353 }
354}
355
356const EXTENDED_TIER_1_THRESHOLD: u64 = 2;
360
361const EXTENDED_TIER_1_MULTIPLIER: i64 = 6;
363
364const EXTENDED_TIER_2_THRESHOLD: u64 = 5;
368
369const EXTENDED_TIER_2_MULTIPLIER: i64 = 12;
371
372pub fn compute_backoff(count: u64, base: i64, max: i64, allow_extended: bool) -> i64 {
391 if count <= 1 {
392 return base;
393 }
394 let exp = u32::try_from(count.saturating_sub(1)).unwrap_or(u32::MAX);
395 let factor = 3_i64.saturating_pow(exp);
396 let standard = base.saturating_mul(factor).min(max);
397
398 let first_max = if base <= 0 {
407 0
408 } else {
409 let mut accumulated = base;
411 let mut first_max_count = 1u64;
412 while accumulated < max && first_max_count < count {
413 accumulated = accumulated.saturating_mul(3);
414 first_max_count += 1;
415 }
416 first_max_count
417 };
418
419 let times_at_max = count.saturating_sub(first_max);
421
422 if !allow_extended {
423 return standard;
424 }
425
426 if standard == max && times_at_max >= EXTENDED_TIER_2_THRESHOLD {
427 max.saturating_mul(EXTENDED_TIER_2_MULTIPLIER)
428 } else if standard == max && times_at_max >= EXTENDED_TIER_1_THRESHOLD {
429 max.saturating_mul(EXTENDED_TIER_1_MULTIPLIER)
430 } else {
431 standard
432 }
433}
434
435async fn read_and_increment_failure_count(store_opt: Option<&Arc<TaskStore>>, key: &str) -> u64 {
444 read_and_increment_failure_count_with_prefix(store_opt, FAILURE_COUNT_PREFIX, key).await
445}
446
447async fn read_and_increment_failure_count_with_prefix(
452 store_opt: Option<&Arc<TaskStore>>,
453 prefix: &str,
454 key: &str,
455) -> u64 {
456 let kv_key = format!("{prefix}{key}");
457 if let Some(store) = store_opt {
458 match store.kv_increment(&kv_key).await {
459 Ok(n) => n,
460 Err(e) => {
461 tracing::warn!(key = %kv_key, err = %e, "failed to increment failure count — treating as high count for safe backoff");
462 u64::MAX
463 }
464 }
465 } else {
466 1
467 }
468}
469
470struct ModelBackoff {
472 prefix: &'static str,
473 base: i64,
474 max: i64,
475 allow_extended: bool,
476 reason: &'static str,
477}
478
479async fn record_model_backoff(agent_name: &str, model: &str, schedule: &ModelBackoff) {
481 let key = format!("{agent_name}:{model}");
482 let store_opt = cooldown_store().lock().await.clone();
483 let count =
484 read_and_increment_failure_count_with_prefix(store_opt.as_ref(), schedule.prefix, &key)
485 .await;
486 let cooldown_secs =
487 compute_backoff(count, schedule.base, schedule.max, schedule.allow_extended);
488 let cooldown_until = chrono::Utc::now().timestamp() + cooldown_secs;
489 set_cooldown_async(&key, cooldown_until, schedule.reason).await;
490}
491
492pub async fn record_agent_success(agent_name: &str, model: &str) {
498 let store_opt = cooldown_store().lock().await.clone();
499 if let Some(store) = store_opt {
500 let agent_key = format!("{FAILURE_COUNT_PREFIX}{agent_name}");
501 let credit_key = format!("{CREDIT_FAILURE_COUNT_PREFIX}{agent_name}");
502 if let Err(e) = store.kv_set(&agent_key, "0").await {
503 tracing::warn!(key = agent_key, err = %e, "failed to reset failure count");
504 }
505 if !model.is_empty() {
506 let model_key = format!("{FAILURE_COUNT_PREFIX}{agent_name}:{model}");
507 if let Err(e) = store.kv_set(&model_key, "0").await {
508 tracing::warn!(key = model_key, err = %e, "failed to reset failure count");
509 }
510 }
511 if let Err(e) = store.kv_set(&credit_key, "0").await {
512 tracing::warn!(key = credit_key, err = %e, "failed to reset failure count");
513 }
514 }
515}
516
517pub async fn record_agent_failure_with_message(agent_name: &str, error_message: &str) {
523 if let Some(cooldown_until) = parse_retry_at(error_message) {
528 let now = chrono::Utc::now().timestamp();
529 if cooldown_until > now {
530 set_cooldown_async(agent_name, cooldown_until, "agent_error").await;
531 return;
532 }
533 tracing::debug!(
534 agent = agent_name,
535 cooldown_until,
536 "vendor retry_at is in the past — using backoff instead"
537 );
538 }
539
540 let store_opt = cooldown_store().lock().await.clone();
541 let count = read_and_increment_failure_count(store_opt.as_ref(), agent_name).await;
542 let base = config::get_agent_backoff_base(agent_name);
543 let cooldown_until =
544 chrono::Utc::now().timestamp() + compute_backoff(count, base, BACKOFF_MAX_SECS, true);
545 set_cooldown_async(agent_name, cooldown_until, "agent_error").await;
546}
547
548pub fn detect_credit_exhaustion_outcome(error_message: &str) -> Option<&'static str> {
557 detect_credit_exhaustion(error_message).map(CreditExhaustionReason::outcome_str)
558}
559
560pub fn detect_credit_exhaustion(error_message: &str) -> Option<CreditExhaustionReason> {
565 let lower = error_message.to_lowercase();
566
567 let overage_patterns = [
568 "overagedisabledreason",
569 "overage_disabled_reason",
570 "overage disabled reason",
571 ];
572
573 if overage_patterns.iter().any(|p| lower.contains(p)) {
574 if lower.contains("out_of_credits") || lower.contains("outofcredits") {
575 return Some(CreditExhaustionReason::OutOfCredits);
576 }
577 if lower.contains("org_level_disabled") || lower.contains("orgdisabled") {
578 return Some(CreditExhaustionReason::OrgLevelDisabled);
579 }
580 }
581
582 let billing_patterns = [
583 "credit balance too low",
584 "credit balance insufficient",
585 "insufficient credit balance",
586 "billing quota exceeded",
587 "billing limit exceeded",
588 "organization has been disabled",
589 "org disabled",
590 ];
591
592 if billing_patterns.iter().any(|p| lower.contains(p)) {
593 return Some(CreditExhaustionReason::OrgLevelDisabled);
594 }
595
596 let billing_cycle_patterns = [
599 "billing cycle",
600 "quota refreshed next cycle",
601 "monthly quota",
602 "quota will be refreshed",
603 "next billing cycle",
604 "refreshed in the next cycle",
605 "weekly/monthly limit exhausted",
606 "limit will reset at",
607 "upgrade to pro", "upgrade your token plan", "token plan usage limit", "purchase credits for more", ];
612
613 if billing_cycle_patterns.iter().any(|p| lower.contains(p)) {
614 return Some(CreditExhaustionReason::BillingCycleExhausted);
615 }
616
617 if lower.contains("out of credits")
618 || lower.contains("outofcredits")
619 || lower.contains("insufficient funds")
620 || lower.contains("no credits remaining")
621 || lower.contains("insufficient_quota")
622 || lower.contains("quota exceeded")
623 || lower.contains("insufficient balance")
624 || lower.contains("please recharge")
625 || lower.contains("no resource package")
626 || lower.contains("balance exhausted")
627 || lower.contains("402 payment required")
628 {
629 return Some(CreditExhaustionReason::OutOfCredits);
630 }
631
632 None
633}
634
635pub async fn record_credit_exhaustion(agent_name: &str, reason: CreditExhaustionReason) {
648 let reason_str = match reason {
649 CreditExhaustionReason::OutOfCredits => "credit_exhaustion_out_of_credits",
650 CreditExhaustionReason::OrgLevelDisabled => "credit_exhaustion_org_level_disabled",
651 CreditExhaustionReason::BillingCycleExhausted => "billing_cycle_exhausted",
652 };
653
654 if is_in_cooldown_with_reason(agent_name, reason_str) {
656 tracing::debug!(
657 agent = agent_name,
658 reason = reason_str,
659 "credit exhaustion already cooled, not escalating"
660 );
661 return;
662 }
663
664 let store_opt = cooldown_store().lock().await.clone();
665 let count = read_and_increment_failure_count_with_prefix(
670 store_opt.as_ref(),
671 CREDIT_FAILURE_COUNT_PREFIX,
672 agent_name,
673 )
674 .await;
675
676 let (base, max) = match reason {
677 CreditExhaustionReason::OutOfCredits => (CREDIT_BACKOFF_BASE_SECS, CREDIT_BACKOFF_MAX_SECS),
678 CreditExhaustionReason::OrgLevelDisabled => {
679 (ORG_BACKOFF_BASE_SECS, CREDIT_BACKOFF_MAX_SECS)
680 }
681 CreditExhaustionReason::BillingCycleExhausted => {
682 (BILLING_CYCLE_COOLDOWN_SECS, BILLING_CYCLE_MAX_SECS)
683 }
684 };
685 let cooldown_secs = compute_backoff(
686 count,
687 base,
688 max,
689 !matches!(reason, CreditExhaustionReason::BillingCycleExhausted),
690 );
691 let cooldown_until = chrono::Utc::now().timestamp() + cooldown_secs;
692 set_cooldown_async(agent_name, cooldown_until, reason_str).await;
693 tracing::warn!(
694 agent = agent_name,
695 reason = reason_str,
696 attempt = count,
697 cooldown_secs,
698 "credit exhaustion detected: applying exponential agent-wide cooldown"
699 );
700}
701
702pub async fn record_credit_exhaustion_from_message(
704 agent_name: &str,
705 model: Option<&str>,
706 message: &str,
707) -> bool {
708 let Some(reason) = detect_credit_exhaustion(message) else {
709 return false;
710 };
711 match (reason, model) {
712 (CreditExhaustionReason::BillingCycleExhausted, Some(model)) => {
713 record_persistent_model_failure(agent_name, model).await;
714 }
715 _ => record_credit_exhaustion(agent_name, reason).await,
716 }
717 true
718}
719
720pub async fn record_model_failure(agent_name: &str, model: &str) {
724 let base = config::get_agent_backoff_base(agent_name);
725 let schedule = ModelBackoff {
726 prefix: FAILURE_COUNT_PREFIX,
727 base,
728 max: BACKOFF_MAX_SECS,
729 allow_extended: true,
730 reason: "model_error",
731 };
732 record_model_backoff(agent_name, model, &schedule).await;
733}
734
735pub async fn record_rate_limit(agent_name: &str, model: Option<&str>, error_message: &str) {
743 if let Some(window_secs) = parse_relative_usage_window(error_message)
744 && let Some(m) = model
745 {
746 let cooldown_until = chrono::Utc::now()
747 .timestamp()
748 .saturating_add(i64::try_from(window_secs).unwrap_or(i64::MAX));
749 set_model_cooldown(agent_name, m, window_secs, "rate_limit_usage_window").await;
750 tracing::info!(
751 agent = agent_name,
752 model = m,
753 window_secs,
754 cooldown_until,
755 "relative usage window detected: applying model-specific cooldown"
756 );
757 return;
758 }
759
760 record_agent_failure_with_message(agent_name, error_message).await;
761 if let Some(m) = model {
762 record_model_failure(agent_name, m).await;
763 }
764}
765
766pub async fn record_persistent_model_failure(agent_name: &str, model: &str) {
778 let schedule = ModelBackoff {
779 prefix: PERSISTENT_FAILURE_COUNT_PREFIX,
780 base: PERSISTENT_MODEL_BACKOFF_BASE_SECS,
781 max: PERSISTENT_MODEL_BACKOFF_MAX_SECS,
782 allow_extended: false,
783 reason: "persistent_model_error",
784 };
785 record_model_backoff(agent_name, model, &schedule).await;
786}
787
788pub async fn record_model_unavailable(agent_name: &str, model: &str, message: &str) {
793 if is_model_permanently_gone(message) {
794 record_persistent_model_failure(agent_name, model).await;
795 } else {
796 record_model_failure(agent_name, model).await;
797 }
798}
799
800fn is_model_permanently_gone(message: &str) -> bool {
801 let lower = message.to_lowercase();
802 lower.contains("not found")
803 || lower.contains("not supported")
804 || lower.contains("not available in your country")
805 || lower.contains("not available in your region")
806}
807
808pub async fn record_transient_model_failure(agent_name: &str, model: &str) {
814 let schedule = ModelBackoff {
815 prefix: FAILURE_COUNT_PREFIX,
816 base: TRANSIENT_MODEL_BACKOFF_BASE_SECS,
817 max: TRANSIENT_MODEL_BACKOFF_MAX_SECS,
818 allow_extended: false,
819 reason: "transient_model_error",
820 };
821 record_model_backoff(agent_name, model, &schedule).await;
822}
823
824pub async fn set_model_cooldown(agent_name: &str, model: &str, duration_secs: u64, reason: &str) {
831 let key = format!("{agent_name}:{model}");
832 let cooldown_until = chrono::Utc::now()
833 .timestamp()
834 .saturating_add(i64::try_from(duration_secs).unwrap_or(i64::MAX));
835 set_cooldown_async(&key, cooldown_until, reason).await;
836}
837
838pub async fn set_model_cooldown_until(agent_name: &str, model: &str, until: i64) {
840 let key = format!("{agent_name}:{model}");
841 set_cooldown_async(&key, until, "vendor_reset_at").await;
842}
843
844pub async fn set_agent_cooldown(agent_name: &str, duration_secs: u64) {
851 let cooldown_until = chrono::Utc::now()
852 .timestamp()
853 .saturating_add(i64::try_from(duration_secs).unwrap_or(i64::MAX));
854 set_cooldown_async(agent_name, cooldown_until, "silence_agent_cooldown").await;
855}
856
857pub const RATE_WINDOW_KV_PREFIX: &str = "rate_window:";
859
860#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
862pub struct RateLimitWindow {
863 pub status: String,
864 pub window_type: String,
865 pub utilization: Option<f64>,
866 pub resets_at: Option<i64>,
867}
868
869pub async fn record_rate_limit_window(agent_name: &str, window: &RateLimitWindow) {
871 let store_opt = cooldown_store().lock().await.clone();
872 if let Some(store) = store_opt
873 && let Ok(value) = serde_json::to_string(window)
874 && let Err(e) = store
875 .kv_set(
876 &format!("{RATE_WINDOW_KV_PREFIX}{agent_name}:{}", window.window_type),
877 &value,
878 )
879 .await
880 {
881 tracing::warn!(agent = agent_name, err = %e, "failed to persist rate limit window");
882 }
883
884 let now = chrono::Utc::now().timestamp();
885 if window.status == "rejected"
886 && let Some(reset) = window.resets_at
887 && reset > now
888 {
889 let until = reset.min(now + PERSISTENT_MODEL_BACKOFF_MAX_SECS);
890 set_cooldown_async(agent_name, until, "rate_limit_window").await;
891 tracing::info!(
892 agent = agent_name,
893 window = %window.window_type,
894 cooldown_until = until,
895 "rate limit window rejected: cooling agent until vendor reset"
896 );
897 }
898}
899
900pub async fn list_rate_limit_windows(store: &Arc<TaskStore>) -> Vec<(String, RateLimitWindow)> {
902 let rows = store
903 .kv_list_prefix(RATE_WINDOW_KV_PREFIX)
904 .await
905 .unwrap_or_default();
906 let mut windows: Vec<(String, RateLimitWindow)> = rows
907 .into_iter()
908 .filter_map(|(key, value)| {
909 let (agent, _) = key.strip_prefix(RATE_WINDOW_KV_PREFIX)?.rsplit_once(':')?;
910 let window = serde_json::from_str(&value).ok()?;
911 Some((agent.to_string(), window))
912 })
913 .collect();
914 windows.sort_by(|a, b| (&a.0, &a.1.window_type).cmp(&(&b.0, &b.1.window_type)));
915 windows
916}
917
918pub async fn record_silence_detection(agent_name: &str, model: &str) -> Option<SilenceCountResult> {
921 let store_opt = cooldown_store().lock().await.clone();
922 let Some(store) = store_opt else {
923 tracing::debug!(
924 agent = agent_name,
925 model,
926 "skipping silence count record (no KV store)"
927 );
928 return None;
929 };
930
931 let key = format!("{SILENCE_COUNT_PREFIX}{agent_name}:{model}");
932 let now = chrono::Utc::now().timestamp();
933 let window_start = now - SILENCE_COUNT_WINDOW_SECS;
934
935 let mut timestamps = match store.kv_get(&key).await {
936 Ok(Some(raw)) => match serde_json::from_str::<Vec<i64>>(&raw) {
937 Ok(ts) => ts,
938 Err(e) => {
939 tracing::warn!(
940 kv_key = %key,
941 err = %e,
942 "failed to parse silence timestamps from KV — resetting window"
943 );
944 Vec::new()
945 }
946 },
947 Ok(None) => Vec::new(),
948 Err(err) => {
949 tracing::warn!(
950 kv_key = %key,
951 err = %err,
952 "failed to load silence count from KV"
953 );
954 Vec::new()
955 }
956 };
957
958 timestamps.retain(|ts| *ts >= window_start);
959 timestamps.push(now);
960
961 let count = timestamps.len();
962 let mut extended_cooldown_applied = false;
963 if count >= SILENCE_COUNT_THRESHOLD {
964 set_model_cooldown(
965 agent_name,
966 model,
967 SILENCE_EXTENDED_COOLDOWN_SECS,
968 "silence_detected",
969 )
970 .await;
971 extended_cooldown_applied = true;
972 timestamps.clear();
973 }
974
975 let value = serde_json::to_string(×tamps).unwrap_or_else(|_| "[]".to_string());
976 if let Err(err) = store.kv_set(&key, &value).await {
977 tracing::warn!(kv_key = key, err = %err, "failed to persist silence count");
978 }
979
980 Some(SilenceCountResult {
981 count,
982 extended_cooldown_applied,
983 })
984}
985
986pub fn is_model_in_cooldown(agent_name: &str, model: &str) -> bool {
988 let key = format!("{agent_name}:{model}");
989 is_in_cooldown(&key)
990}
991
992pub fn is_agent_in_cooldown(agent_name: &str) -> bool {
994 is_in_cooldown(agent_name)
995}
996
997pub fn cooldown_until(key: &str) -> Option<i64> {
999 let map = cooldown_lock();
1000 map.get(key).and_then(|entry| {
1001 let now = chrono::Utc::now().timestamp();
1002 if now < entry.cooldown_until {
1003 Some(entry.cooldown_until)
1004 } else {
1005 None
1006 }
1007 })
1008}
1009
1010pub fn cooldown_reason(key: &str) -> Option<String> {
1012 let map = cooldown_lock();
1013 map.get(key).and_then(|entry| {
1014 let now = chrono::Utc::now().timestamp();
1015 if now < entry.cooldown_until {
1016 Some(entry.reason.clone())
1017 } else {
1018 None
1019 }
1020 })
1021}
1022
1023pub async fn list_persisted_cooldowns(store: &TaskStore) -> Vec<(String, i64, String)> {
1026 let now = chrono::Utc::now().timestamp();
1027 let mut out: Vec<(String, i64, String)> = store
1028 .kv_list_prefix(KV_PREFIX)
1029 .await
1030 .unwrap_or_default()
1031 .into_iter()
1032 .filter_map(|(key, value)| {
1033 let (until, reason) = parse_cooldown_value(&value)?;
1034 (now < until).then(|| (key.trim_start_matches(KV_PREFIX).to_string(), until, reason))
1035 })
1036 .collect();
1037 out.sort_by(|a, b| a.0.cmp(&b.0));
1038 out
1039}
1040
1041pub fn list_all_cooldowns() -> Vec<(String, i64, String)> {
1046 let now = chrono::Utc::now().timestamp();
1047 let map = cooldown_lock();
1048 let mut result: Vec<(String, i64, String)> = map
1049 .iter()
1050 .filter(|(_, entry)| now < entry.cooldown_until)
1051 .map(|(key, entry)| (key.clone(), entry.cooldown_until, entry.reason.clone()))
1052 .collect();
1053 result.sort_by(|a, b| a.0.cmp(&b.0));
1054 result
1055}
1056
1057pub async fn mark_rate_limits_cleared(store: &Arc<TaskStore>, agents: &[String]) {
1060 let now = chrono::Utc::now().timestamp().to_string();
1061 let mut seen = HashSet::new();
1062 for key in agents {
1063 let agent = agent_from_key(key);
1064 if agent.is_empty() || !seen.insert(agent.to_string()) {
1065 continue;
1066 }
1067 let kv_key = format!("{RATE_LIMITS_CLEARED_AT_PREFIX}{agent}");
1068 if let Err(e) = store.kv_set(&kv_key, &now).await {
1069 tracing::warn!(agent, err = %e, "failed to mark rate limits cleared");
1070 }
1071 }
1072}
1073
1074pub async fn clear_cooldown(key: &str, store: &Arc<TaskStore>) {
1081 let mut agents_to_mark: Vec<String> = Vec::new();
1082 if key == "*" {
1083 let keys: Vec<String> = {
1084 let mut map = cooldown_lock();
1085 let keys: Vec<String> = map.keys().cloned().collect();
1086 map.clear();
1087 keys
1088 };
1089 for k in &keys {
1090 let kv_key = format!("{KV_PREFIX}{k}");
1091 if let Err(e) = store.kv_set(&kv_key, "0").await {
1092 tracing::warn!(key = kv_key, err = %e, "failed to clear cooldown");
1093 }
1094 let fc_key = format!("{FAILURE_COUNT_PREFIX}{k}");
1096 if let Err(e) = store.kv_set(&fc_key, "0").await {
1097 tracing::warn!(key = fc_key, err = %e, "failed to reset failure count");
1098 }
1099 let credit_fc_key = format!("{CREDIT_FAILURE_COUNT_PREFIX}{k}");
1101 if let Err(e) = store.kv_set(&credit_fc_key, "0").await {
1102 tracing::warn!(key = credit_fc_key, err = %e, "failed to reset credit failure count");
1103 }
1104 let persistent_fc_key = format!("{PERSISTENT_FAILURE_COUNT_PREFIX}{k}");
1106 if let Err(e) = store.kv_set(&persistent_fc_key, "0").await {
1107 tracing::warn!(key = persistent_fc_key, err = %e, "failed to reset persistent failure count");
1108 }
1109 }
1110 if let Ok(fc_entries) = store.kv_list_prefix(FAILURE_COUNT_PREFIX).await {
1114 for (fc_key, _) in fc_entries {
1115 if let Err(e) = store.kv_set(&fc_key, "0").await {
1116 tracing::warn!(key = fc_key, err = %e, "failed to reset failure count");
1117 }
1118 }
1119 }
1120 if let Ok(cfc_entries) = store.kv_list_prefix(CREDIT_FAILURE_COUNT_PREFIX).await {
1121 for (cfc_key, _) in cfc_entries {
1122 if let Err(e) = store.kv_set(&cfc_key, "0").await {
1123 tracing::warn!(key = cfc_key, err = %e, "failed to reset credit failure count");
1124 }
1125 }
1126 }
1127 if let Ok(pfc_entries) = store.kv_list_prefix(PERSISTENT_FAILURE_COUNT_PREFIX).await {
1128 for (pfc_key, _) in pfc_entries {
1129 if let Err(e) = store.kv_set(&pfc_key, "0").await {
1130 tracing::warn!(key = pfc_key, err = %e, "failed to reset persistent failure count");
1131 }
1132 }
1133 }
1134 tracing::info!(
1135 count = keys.len(),
1136 "cleared all cooldowns and failure counts"
1137 );
1138 agents_to_mark.extend(keys.iter().map(|k| agent_from_key(k).to_string()));
1139 match store.rate_limit_agents().await {
1140 Ok(rl_agents) => agents_to_mark.extend(rl_agents),
1141 Err(e) => tracing::warn!(err = %e, "failed to list rate_limits agents while clearing"),
1142 }
1143 match store.kv_list_prefix(RATE_LIMITS_CLEARED_AT_PREFIX).await {
1144 Ok(marks) => {
1145 for (k, _) in marks {
1146 let agent = k.trim_start_matches(RATE_LIMITS_CLEARED_AT_PREFIX);
1147 if !agent.is_empty() {
1148 agents_to_mark.push(agent.to_string());
1149 }
1150 }
1151 }
1152 Err(e) => tracing::warn!(err = %e, "failed to list rate_limits_cleared_at keys"),
1153 }
1154 } else {
1155 {
1156 let mut map = cooldown_lock();
1157 map.remove(key);
1158 }
1159 let kv_key = format!("{KV_PREFIX}{key}");
1160 if let Err(e) = store.kv_set(&kv_key, "0").await {
1161 tracing::warn!(key = kv_key, err = %e, "failed to clear cooldown");
1162 }
1163 let fc_key = format!("{FAILURE_COUNT_PREFIX}{key}");
1165 if let Err(e) = store.kv_set(&fc_key, "0").await {
1166 tracing::warn!(key = fc_key, err = %e, "failed to reset failure count");
1167 }
1168 let credit_fc_key = format!("{CREDIT_FAILURE_COUNT_PREFIX}{key}");
1170 if let Err(e) = store.kv_set(&credit_fc_key, "0").await {
1171 tracing::warn!(key = credit_fc_key, err = %e, "failed to reset credit failure count");
1172 }
1173 let persistent_fc_key = format!("{PERSISTENT_FAILURE_COUNT_PREFIX}{key}");
1175 if let Err(e) = store.kv_set(&persistent_fc_key, "0").await {
1176 tracing::warn!(key = persistent_fc_key, err = %e, "failed to reset persistent failure count");
1177 }
1178 tracing::info!(key, "cleared cooldown and failure count");
1179 agents_to_mark.push(agent_from_key(key).to_string());
1180 }
1181 mark_rate_limits_cleared(store, &agents_to_mark).await;
1182}
1183
1184fn set_cooldown_in_memory(key: &str, cooldown_until: i64, reason: &str) -> bool {
1193 let mut map = cooldown_lock();
1194 if let Some(existing) = map.get(key) {
1195 if existing.cooldown_until >= cooldown_until {
1199 return false;
1200 }
1201 }
1202 map.insert(
1203 key.to_string(),
1204 CooldownEntry {
1205 cooldown_until,
1206 reason: reason.to_string(),
1207 },
1208 );
1209 true
1210}
1211
1212async fn set_cooldown_async(key: &str, cooldown_until: i64, reason: &str) -> bool {
1222 if !set_cooldown_in_memory(key, cooldown_until, reason) {
1223 return false;
1224 }
1225 let store_opt = cooldown_store().lock().await.clone();
1226 if let Some(store) = store_opt {
1227 let kv_key = format!("{KV_PREFIX}{key}");
1228 let value = serde_json::json!({"until": cooldown_until, "reason": reason}).to_string();
1229 if let Err(e) = store.kv_set(&kv_key, &value).await {
1230 tracing::warn!(
1231 kv_key,
1232 err = %e,
1233 "failed to persist cooldown to KV store — rolling back in-memory entry"
1234 );
1235 let mut map = cooldown_lock();
1236 if map.get(key).map(|e| e.cooldown_until) == Some(cooldown_until) {
1240 map.remove(key);
1241 }
1242 return false;
1243 }
1244 }
1245 true
1246}
1247
1248fn cooldown_lock() -> MutexGuard<'static, HashMap<String, CooldownEntry>> {
1250 cooldowns().lock().unwrap_or_else(|e| {
1251 tracing::error!("cooldown map lock poisoned — recovering with partial state; backoff and degraded-agent decisions may be incorrect");
1252 e.into_inner()
1253 })
1254}
1255
1256fn degraded_agents_lock() -> MutexGuard<'static, HashMap<String, String>> {
1258 degraded_agents().lock().unwrap_or_else(|e| {
1259 tracing::error!("degraded agents lock poisoned — recovering with partial state; health check decisions may be incorrect");
1260 e.into_inner()
1261 })
1262}
1263
1264fn github_5xx_timestamps_lock() -> MutexGuard<'static, Vec<i64>> {
1266 github_5xx_timestamps().lock().unwrap_or_else(|e| {
1267 tracing::error!("github 5xx timestamps lock poisoned — recovering with partial state; circuit breaker may operate incorrectly");
1268 e.into_inner()
1269 })
1270}
1271
1272fn github_5xx_circuit_open_lock() -> MutexGuard<'static, Option<i64>> {
1274 github_5xx_circuit_open().lock().unwrap_or_else(|e| {
1275 tracing::error!("github 5xx circuit open lock poisoned — recovering with partial state; circuit breaker may operate incorrectly");
1276 e.into_inner()
1277 })
1278}
1279
1280fn is_in_cooldown_with_reason(key: &str, reason: &str) -> bool {
1282 let map = cooldown_lock();
1283 map.get(key).is_some_and(|entry| {
1284 entry.reason == reason && chrono::Utc::now().timestamp() < entry.cooldown_until
1285 })
1286}
1287
1288fn is_in_cooldown(key: &str) -> bool {
1290 let map = cooldown_lock();
1291 if let Some(entry) = map.get(key) {
1292 let now = chrono::Utc::now().timestamp();
1293 return now < entry.cooldown_until;
1294 }
1295 false
1296}
1297
1298pub const DEFAULT_HEALTH_CHECK_WINDOW_HOURS: u32 = 6;
1304
1305pub const DEFAULT_DEGRADED_RATE_LIMIT_THRESHOLD: i64 = 3;
1309
1310fn degraded_agents() -> &'static Mutex<HashMap<String, String>> {
1313 static DEGRADED: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();
1314 DEGRADED.get_or_init(|| Mutex::new(HashMap::new()))
1315}
1316
1317pub fn is_agent_degraded(agent: &str) -> bool {
1322 let set = degraded_agents_lock();
1323 set.contains_key(agent)
1324}
1325
1326pub fn agent_degraded_reason(agent: &str) -> Option<String> {
1328 degraded_agents_lock().get(agent).cloned()
1329}
1330
1331pub fn list_degraded_agents() -> Vec<(String, String)> {
1333 let mut entries: Vec<(String, String)> = degraded_agents_lock()
1334 .iter()
1335 .map(|(agent, reason)| (agent.clone(), reason.clone()))
1336 .collect();
1337 entries.sort_by(|a, b| a.0.cmp(&b.0));
1338 entries
1339}
1340
1341pub fn mark_agent_degraded(agent: &str) {
1343 mark_agent_degraded_with_reason(agent, "degraded");
1344}
1345
1346fn mark_agent_degraded_with_reason(agent: &str, reason: &str) {
1347 let mut set = degraded_agents_lock();
1348 set.insert(agent.to_string(), reason.to_string());
1349}
1350
1351pub fn clear_agent_degraded(agent: &str) {
1353 let mut set = degraded_agents_lock();
1354 set.remove(agent);
1355}
1356
1357pub async fn refresh_degraded_agents(
1371 store: &Arc<TaskStore>,
1372 available_agents: &[String],
1373 model_checker: &(dyn Fn(&str) -> bool + Send + Sync),
1374 window_hours: u32,
1375 threshold: i64,
1376) {
1377 clear_expired_cooldowns();
1381
1382 let start = chrono::Utc::now();
1385 let counts = match store.recent_rate_limit_counts(window_hours).await {
1386 Ok(c) => {
1387 let dur_ms = (chrono::Utc::now() - start).num_milliseconds();
1388 tracing::info!(
1389 duration_ms = dur_ms,
1390 window_hours,
1391 "recent_rate_limit_counts query completed"
1392 );
1393 c
1394 }
1395 Err(e) => {
1396 let dur_ms = (chrono::Utc::now() - start).num_milliseconds();
1397 tracing::warn!(
1398 err = %e,
1399 duration_ms = dur_ms,
1400 "failed to query recent rate limit counts for health check"
1401 );
1402 return;
1403 }
1404 };
1405
1406 for agent in available_agents {
1407 let in_cooldown = is_agent_in_cooldown(agent);
1408 let no_models = !model_checker(agent);
1409 let rate_limit_count = counts.get(agent.as_str()).copied().unwrap_or(0);
1410 let over_threshold = rate_limit_count >= threshold;
1411
1412 let degraded = in_cooldown || no_models || over_threshold;
1413
1414 if degraded {
1415 let reason = if in_cooldown {
1416 "agent in cooldown"
1417 } else if no_models {
1418 "all models cooled"
1419 } else {
1420 "rate limit threshold exceeded"
1421 };
1422 let previous = agent_degraded_reason(agent);
1423 match previous.as_deref() {
1424 None => tracing::warn!(
1425 agent,
1426 reason,
1427 rate_limit_count,
1428 window_hours,
1429 threshold,
1430 "pre-emptive health check: marking agent as degraded"
1431 ),
1432 Some(prev) if prev != reason => tracing::warn!(
1433 agent,
1434 reason,
1435 previous = prev,
1436 rate_limit_count,
1437 window_hours,
1438 threshold,
1439 "pre-emptive health check: degraded reason changed"
1440 ),
1441 Some(_) => {}
1442 }
1443 mark_agent_degraded_with_reason(agent, reason);
1444 } else {
1445 if is_agent_degraded(agent) {
1446 tracing::info!(
1447 agent,
1448 rate_limit_count,
1449 "pre-emptive health check: agent recovered, clearing degraded flag"
1450 );
1451 }
1452 clear_agent_degraded(agent);
1453 }
1454 }
1455}
1456
1457pub fn clear_expired_cooldowns() {
1459 let mut map = cooldown_lock();
1460 let now = chrono::Utc::now().timestamp();
1461 map.retain(|_key, entry| now < entry.cooldown_until);
1462}
1463
1464const GITHUB_5XX_WINDOW_SECS: i64 = 120;
1470
1471const GITHUB_5XX_THRESHOLD: usize = 5;
1473
1474const GITHUB_5XX_COOLDOWN_SECS: i64 = 180;
1476
1477fn github_5xx_timestamps() -> &'static Mutex<Vec<i64>> {
1479 static TS: OnceLock<Mutex<Vec<i64>>> = OnceLock::new();
1480 TS.get_or_init(|| Mutex::new(Vec::new()))
1481}
1482
1483fn github_5xx_circuit_open() -> &'static Mutex<Option<i64>> {
1485 static OPEN: OnceLock<Mutex<Option<i64>>> = OnceLock::new();
1486 OPEN.get_or_init(|| Mutex::new(None))
1487}
1488
1489pub async fn record_github_5xx() {
1494 let now = chrono::Utc::now().timestamp();
1495 let window_start = now - GITHUB_5XX_WINDOW_SECS;
1496
1497 let should_trip = {
1498 let mut ts = github_5xx_timestamps_lock();
1499 ts.retain(|t| *t >= window_start);
1500 ts.push(now);
1501 ts.len() >= GITHUB_5XX_THRESHOLD
1502 };
1503
1504 if should_trip {
1505 let cooldown_until = {
1506 let mut open = github_5xx_circuit_open_lock();
1507 if open.is_none() {
1508 let cd = now + GITHUB_5XX_COOLDOWN_SECS;
1509 *open = Some(cd);
1510 tracing::warn!(
1511 errors_in_window = GITHUB_5XX_THRESHOLD,
1512 window_secs = GITHUB_5XX_WINDOW_SECS,
1513 cooldown_secs = GITHUB_5XX_COOLDOWN_SECS,
1514 "GitHub 5xx circuit breaker OPEN — throttling non-critical work"
1515 );
1516 Some(cd)
1517 } else {
1518 None
1519 }
1520 };
1521 if let Some(cd) = cooldown_until {
1523 let store_opt = cooldown_store().lock().await.clone();
1524 if let Some(store) = store_opt {
1525 let _ = store.kv_set("cooldown:github:5xx", &cd.to_string()).await;
1526 }
1527 set_agent_cooldown("github:5xx", GITHUB_5XX_COOLDOWN_SECS as u64).await;
1531 }
1532 let mut ts = github_5xx_timestamps_lock();
1534 ts.clear();
1535 }
1536}
1537
1538pub fn is_github_circuit_open() -> bool {
1546 {
1549 let mut open = github_5xx_circuit_open_lock();
1550 if let Some(until) = *open {
1551 let now = chrono::Utc::now().timestamp();
1552 if now >= until {
1553 *open = None;
1554 tracing::info!("GitHub 5xx circuit breaker CLOSED — resuming normal operations");
1555 return false;
1556 }
1557 return true;
1558 }
1559 }
1560
1561 if let Some(until) = cooldown_until("github:5xx") {
1565 let mut open = github_5xx_circuit_open_lock();
1568 if open.is_none() {
1569 *open = Some(until);
1570 let now = chrono::Utc::now().timestamp();
1571 if now < until {
1572 let remaining = until - now;
1573 tracing::warn!(
1574 remaining_secs = remaining,
1575 "GitHub 5xx circuit breaker OPEN (discovered via generic cooldown) — throttling non-critical work"
1576 );
1577 }
1578 }
1579 return true;
1580 }
1581
1582 false
1583}
1584
1585pub fn github_circuit_remaining_secs() -> u64 {
1588 {
1590 let open = github_5xx_circuit_open_lock();
1591 if let Some(until) = *open {
1592 let now = chrono::Utc::now().timestamp();
1593 if now < until {
1594 return u64::try_from(until - now).unwrap_or(0);
1595 }
1596 return 0;
1597 }
1598 }
1599
1600 if let Some(until) = cooldown_until("github:5xx") {
1602 let now = chrono::Utc::now().timestamp();
1603 if now < until {
1604 return u64::try_from(until - now).unwrap_or(0);
1605 }
1606 }
1607 0
1608}
1609
1610pub(crate) fn parse_retry_at(error_message: &str) -> Option<i64> {
1614 if error_message.is_empty() {
1615 return None;
1616 }
1617
1618 let lower = error_message.to_lowercase();
1619 for retry_marker in [
1623 "try again at ",
1624 "reset at ",
1625 "resets at ",
1626 "resets ",
1627 "reset ",
1628 ] {
1629 if let Some(idx) = lower.find(retry_marker) {
1630 let date_str = &lower[idx + retry_marker.len()..];
1631 let date_str = date_str
1633 .split(['.', '\n'])
1634 .next()
1635 .unwrap_or(date_str)
1636 .trim();
1637
1638 let cleaned = date_str
1641 .replace("st,", ",")
1642 .replace("nd,", ",")
1643 .replace("rd,", ",")
1644 .replace("th,", ",");
1645
1646 for fmt in &[
1647 "%b %d, %Y %I:%M %p", "%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", ] {
1654 if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(&cleaned, fmt) {
1655 let utc = match chrono::Local.from_local_datetime(&dt) {
1658 chrono::LocalResult::Single(local_dt) => {
1659 local_dt.with_timezone(&chrono::Utc)
1660 }
1661 chrono::LocalResult::Ambiguous(earliest, _) => {
1662 earliest.with_timezone(&chrono::Utc)
1664 }
1665 chrono::LocalResult::None => {
1666 dt.and_utc()
1668 }
1669 };
1670 tracing::info!(
1671 retry_at = %utc,
1672 raw = date_str,
1673 marker = retry_marker,
1674 "parsed rate limit retry-at date"
1675 );
1676 return Some(utc.timestamp());
1677 }
1678 }
1679 tracing::debug!(
1680 raw = date_str,
1681 marker = retry_marker,
1682 "could not parse retry-at date"
1683 );
1684
1685 let time_only = date_str.split_once('(').map_or(date_str, |(t, _)| t).trim();
1690 let mut compact = time_only.replace(" am", "am").replace(" pm", "pm");
1692 let split = compact.rfind(' ').map_or(0, |i| i + 1);
1693 let last = &compact[split..];
1694 if !last.contains(':')
1695 && (last.ends_with("am") || last.ends_with("pm"))
1696 && last.len() > 2
1697 {
1698 let at = split + last.len() - 2;
1699 compact.insert_str(at, ":00");
1700 }
1701 let md = compact.replace(" at ", " ");
1703 let now_local = chrono::Local::now();
1704 let this_year = chrono::Datelike::year(&now_local);
1705 for year in [this_year, this_year + 1] {
1706 let with_year = format!("{year} {md}");
1707 if let Ok(dt) =
1708 chrono::NaiveDateTime::parse_from_str(&with_year, "%Y %b %d %I:%M%p")
1709 && let Some(local_dt) = chrono::Local.from_local_datetime(&dt).earliest()
1710 && local_dt > now_local
1711 {
1712 return Some(local_dt.timestamp());
1713 }
1714 }
1715 let time_only = compact.as_str();
1716 for tf in &["%I:%M %p", "%I:%M%p", "%I %p", "%H:%M"] {
1717 if let Ok(t) = chrono::NaiveTime::parse_from_str(time_only, tf) {
1718 let local_now = chrono::Local::now();
1721 let today = local_now.date_naive();
1722 let candidate = chrono::NaiveDateTime::new(today, t);
1723 let candidate_local: chrono::DateTime<chrono::Local> =
1726 match chrono::Local.from_local_datetime(&candidate) {
1727 chrono::LocalResult::Single(dt) => dt,
1728 chrono::LocalResult::Ambiguous(earliest, _) => earliest,
1729 chrono::LocalResult::None => {
1730 let utc_dt = candidate.and_utc();
1732 return Some(utc_dt.timestamp());
1733 }
1734 };
1735 let chosen = if candidate_local <= local_now {
1736 let tomorrow = today.succ_opt().unwrap_or(today);
1738 let ndt = chrono::NaiveDateTime::new(tomorrow, t);
1739 match chrono::Local.from_local_datetime(&ndt) {
1740 chrono::LocalResult::Single(dt) => dt.with_timezone(&chrono::Utc),
1741 chrono::LocalResult::Ambiguous(earliest, _) => {
1742 earliest.with_timezone(&chrono::Utc)
1743 }
1744 chrono::LocalResult::None => ndt.and_utc(),
1745 }
1746 } else {
1747 candidate_local.with_timezone(&chrono::Utc)
1748 };
1749 tracing::info!(
1750 retry_at = %chosen,
1751 raw = date_str,
1752 marker = retry_marker,
1753 "parsed rate limit retry-at time-only; interpreted as next occurrence"
1754 );
1755 return Some(chosen.timestamp());
1756 }
1757 }
1758 }
1759 }
1760
1761 None
1765}
1766
1767pub(crate) fn parse_relative_usage_window(error_message: &str) -> Option<u64> {
1778 static WINDOW_RE: LazyLock<Regex> = LazyLock::new(|| {
1779 Regex::new(
1780 r"(?i)(?:^|\s|[\(\)\.,;:!?])(?:(\d+)\s*-?\s*(hour|hours|hr|hrs|minute|minutes|min|mins|day|days)|(hourly|daily|weekly|monthly))(?:$|\s|[\(\)\.,;:!?])"
1781 )
1782 .expect("usage window regex is valid")
1783 });
1784
1785 if error_message.is_empty() {
1786 return None;
1787 }
1788
1789 let lower = error_message.to_lowercase();
1790 let has_context = lower.contains("usage limit")
1791 || lower.contains("quota")
1792 || lower.contains("window")
1793 || lower.contains("limit");
1794 if !has_context {
1795 return None;
1796 }
1797
1798 let mut max_secs: Option<u64> = None;
1799 for caps in WINDOW_RE.captures_iter(&lower) {
1800 let secs = if let Some(num) = caps.get(1) {
1801 let n: u64 = num.as_str().parse().ok()?;
1802 let unit = caps.get(2)?.as_str().to_lowercase();
1803 let multiplier = match unit.as_str() {
1804 "hour" | "hours" | "hr" | "hrs" => 3600,
1805 "minute" | "minutes" | "min" | "mins" => 60,
1806 "day" | "days" => 86400,
1807 _ => return None,
1808 };
1809 n.checked_mul(multiplier)?
1810 } else if let Some(word) = caps.get(3) {
1811 match word.as_str().to_lowercase().as_str() {
1812 "hourly" => 3600,
1813 "daily" => 86400,
1814 "weekly" => 604_800,
1815 "monthly" => 2_592_000,
1816 _ => return None,
1817 }
1818 } else {
1819 continue;
1820 };
1821 max_secs = Some(max_secs.map_or(secs, |m| m.max(secs)));
1822 }
1823
1824 max_secs
1825}
1826
1827#[cfg(test)]
1828pub(crate) async fn reset_global_state() {
1829 cooldowns().lock().unwrap().clear();
1830 *cooldown_store().lock().await = None;
1831 github_5xx_timestamps().lock().unwrap().clear();
1832 *github_5xx_circuit_open().lock().unwrap() = None;
1833 degraded_agents().lock().unwrap().clear();
1834 opencode::reset_model_caches_for_test();
1835}
1836
1837#[cfg(test)]
1838mod tests;
1839
1840#[cfg(test)]
1841mod classify_tests;