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::config;
28use crate::store::TaskStore;
29
30pub const AGENT_COOLDOWN_SECS: i64 = 30 * 60;
36
37pub const BACKOFF_BASE_SECS: i64 = 5 * 60;
39
40pub const BACKOFF_MAX_SECS: i64 = 4 * 60 * 60;
42
43pub const PERSISTENT_MODEL_BACKOFF_BASE_SECS: i64 = 4 * 60 * 60;
45
46pub const PERSISTENT_MODEL_BACKOFF_MAX_SECS: i64 = 7 * 24 * 60 * 60;
48
49pub const TRANSIENT_MODEL_BACKOFF_BASE_SECS: i64 = 5 * 60;
51
52pub const TRANSIENT_MODEL_BACKOFF_MAX_SECS: i64 = 15 * 60;
54
55pub const CREDIT_BACKOFF_BASE_SECS: i64 = 60 * 60;
57
58pub const ORG_BACKOFF_BASE_SECS: i64 = 2 * 60 * 60;
60
61pub const CREDIT_BACKOFF_MAX_SECS: i64 = 8 * 60 * 60;
64
65pub const BILLING_CYCLE_COOLDOWN_SECS: i64 = 24 * 60 * 60;
73
74pub const BILLING_CYCLE_MAX_SECS: i64 = 7 * 24 * 60 * 60;
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum CreditExhaustionReason {
84 OutOfCredits,
86 OrgLevelDisabled,
88 BillingCycleExhausted,
90}
91
92impl CreditExhaustionReason {
93 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
105pub const SILENCE_AGENT_COOLDOWN_SECS: u64 = 120;
112
113pub const SILENCE_COUNT_THRESHOLD: usize = 5;
115
116pub const SILENCE_COUNT_WINDOW_SECS: i64 = 24 * 60 * 60;
118
119pub const SILENCE_EXTENDED_COOLDOWN_SECS: u64 = 4 * 60 * 60;
121
122const KV_PREFIX: &str = "cooldown:";
124
125const SILENCE_COUNT_PREFIX: &str = "silence_count:";
127
128const FAILURE_COUNT_PREFIX: &str = "failure_count:";
130
131const CREDIT_FAILURE_COUNT_PREFIX: &str = "credit_failure_count:";
134
135const PERSISTENT_FAILURE_COUNT_PREFIX: &str = "persistent_failure_count:";
139
140const RATE_LIMITS_CLEARED_AT_PREFIX: &str = "rate_limits_cleared_at:";
142
143fn agent_from_key(key: &str) -> &str {
145 key.split_once(':').map_or(key, |(agent, _)| agent)
146}
147
148struct CooldownEntry {
149 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
160fn 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
173fn 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
183fn 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 }
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 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
257pub 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 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 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 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 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
354const EXTENDED_TIER_1_THRESHOLD: u64 = 2;
358
359const EXTENDED_TIER_1_MULTIPLIER: i64 = 6;
361
362const EXTENDED_TIER_2_THRESHOLD: u64 = 5;
366
367const EXTENDED_TIER_2_MULTIPLIER: i64 = 12;
369
370pub 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 let first_max = if base <= 0 {
405 0
406 } else {
407 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 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
433async 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
445async 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
468struct ModelBackoff {
470 prefix: &'static str,
471 base: i64,
472 max: i64,
473 allow_extended: bool,
474 reason: &'static str,
475}
476
477async 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
490pub 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
515pub async fn record_agent_failure_with_message(agent_name: &str, error_message: &str) {
521 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
546pub fn detect_credit_exhaustion_outcome(error_message: &str) -> Option<&'static str> {
555 detect_credit_exhaustion(error_message).map(CreditExhaustionReason::outcome_str)
556}
557
558pub 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 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", "upgrade your token plan", "token plan usage limit", "purchase credits for more", ];
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
633pub 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 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 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
700pub 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
718pub 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
733pub 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
764pub 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
786pub 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
806pub 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
822pub 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
836pub 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
842pub 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
855pub const RATE_WINDOW_KV_PREFIX: &str = "rate_window:";
857
858#[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
867pub 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
898pub 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
916pub 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(×tamps).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
984pub 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
990pub fn is_agent_in_cooldown(agent_name: &str) -> bool {
992 is_in_cooldown(agent_name)
993}
994
995pub 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
1008pub 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
1021pub 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
1039pub 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
1055pub 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
1072pub 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 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 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 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 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 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 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 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
1182fn 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 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
1210async 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 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
1246fn 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
1254fn 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
1262fn 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
1270fn 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
1278fn 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
1286fn 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
1296pub const DEFAULT_HEALTH_CHECK_WINDOW_HOURS: u32 = 6;
1302
1303pub const DEFAULT_DEGRADED_RATE_LIMIT_THRESHOLD: i64 = 3;
1307
1308fn 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
1315pub fn is_agent_degraded(agent: &str) -> bool {
1320 let set = degraded_agents_lock();
1321 set.contains_key(agent)
1322}
1323
1324pub fn agent_degraded_reason(agent: &str) -> Option<String> {
1326 degraded_agents_lock().get(agent).cloned()
1327}
1328
1329pub 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
1339pub 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
1349pub fn clear_agent_degraded(agent: &str) {
1351 let mut set = degraded_agents_lock();
1352 set.remove(agent);
1353}
1354
1355pub 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();
1379
1380 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
1455pub 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
1462const GITHUB_5XX_WINDOW_SECS: i64 = 120;
1468
1469const GITHUB_5XX_THRESHOLD: usize = 5;
1471
1472const GITHUB_5XX_COOLDOWN_SECS: i64 = 180;
1474
1475fn 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
1481fn 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
1487pub 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 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 set_agent_cooldown("github:5xx", GITHUB_5XX_COOLDOWN_SECS as u64).await;
1529 }
1530 let mut ts = github_5xx_timestamps_lock();
1532 ts.clear();
1533 }
1534}
1535
1536pub fn is_github_circuit_open() -> bool {
1544 {
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 let Some(until) = cooldown_until("github:5xx") {
1563 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
1583pub fn github_circuit_remaining_secs() -> u64 {
1586 {
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 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
1608pub(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 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 let date_str = date_str
1631 .split(['.', '\n'])
1632 .next()
1633 .unwrap_or(date_str)
1634 .trim();
1635
1636 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", "%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", ] {
1652 if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(&cleaned, fmt) {
1653 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 earliest.with_timezone(&chrono::Utc)
1662 }
1663 chrono::LocalResult::None => {
1664 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 let time_only = date_str.split_once('(').map_or(date_str, |(t, _)| t).trim();
1688 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 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 let local_now = chrono::Local::now();
1719 let today = local_now.date_naive();
1720 let candidate = chrono::NaiveDateTime::new(today, t);
1721 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 let utc_dt = candidate.and_utc();
1730 return Some(utc_dt.timestamp());
1731 }
1732 };
1733 let chosen = if candidate_local <= local_now {
1734 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 None
1763}
1764
1765pub(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
1825pub 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;