1use std::collections::HashMap;
10use std::time::{Duration, Instant};
11
12use super::selection::{hash_task_id, simple_hash_fraction_for, simple_hash_index_for};
13
14pub(super) const DEFAULT_WEIGHT: f64 = 1.0;
16
17pub(super) const MIN_WEIGHT: f64 = 0.05;
19
20pub(super) const RATE_LIMIT_DECAY: f64 = 0.3;
22
23pub(super) fn default_missing_weight(configured_weights: &HashMap<String, f64>) -> f64 {
30 configured_weights
31 .values()
32 .copied()
33 .fold(None, |min, w| Some(min.map_or(w, |m: f64| m.min(w))))
34 .unwrap_or(DEFAULT_WEIGHT)
35}
36
37fn generate_recovery_jitter(agent: &str) -> Duration {
40 let max_secs = RECOVERY_JITTER_MAX.as_secs();
41 let jitter_secs = hash_task_id(agent) % max_secs;
42 Duration::from_secs(jitter_secs)
43}
44
45pub(super) const RECOVERY_DELAY: Duration = Duration::from_secs(60);
47
48pub(super) const RECOVERY_JITTER_MAX: Duration = Duration::from_secs(30);
51
52pub(super) const RECOVERY_RATE: f64 = 0.1;
54
55#[derive(Debug, Clone)]
57pub struct RateLimitState {
58 pub weight: f64,
60 pub last_limited_at: Option<Instant>,
62 pub recovery_jitter: Duration,
64 pub consecutive_hits: u32,
66 pub base_weight: f64,
68}
69
70impl Default for RateLimitState {
71 fn default() -> Self {
72 Self {
73 weight: DEFAULT_WEIGHT,
74 last_limited_at: None,
75 recovery_jitter: Duration::ZERO,
76 consecutive_hits: 0,
77 base_weight: DEFAULT_WEIGHT,
78 }
79 }
80}
81
82impl RateLimitState {
83 fn with_base(base: f64) -> Self {
84 Self {
85 weight: base,
86 base_weight: base,
87 ..Default::default()
88 }
89 }
90
91 fn set_base(&mut self, base: f64) {
93 self.base_weight = base;
94 if !self.is_limited() {
95 self.weight = base;
96 }
97 }
98
99 fn stagger_recovery(&mut self, agent: &str) -> Duration {
101 self.recovery_jitter = generate_recovery_jitter(agent);
102 self.recovery_jitter
103 }
104
105 pub fn record_rate_limit(&mut self) {
108 self.consecutive_hits += 1;
109 self.weight = (self.weight * RATE_LIMIT_DECAY).max(MIN_WEIGHT);
110 self.last_limited_at = Some(Instant::now());
111 }
112
113 pub fn record_success(&mut self) {
115 self.consecutive_hits = 0;
116 self.weight = (self.weight + RECOVERY_RATE).min(self.base_weight);
117 }
118
119 pub fn maybe_recover(&mut self) {
121 if let Some(last) = self.last_limited_at {
122 let recovery_threshold = RECOVERY_DELAY + self.recovery_jitter;
123 if last.elapsed() >= recovery_threshold {
124 self.weight = (self.weight + RECOVERY_RATE).min(self.base_weight);
125 if self.weight >= self.base_weight {
126 self.last_limited_at = None;
127 self.recovery_jitter = Duration::ZERO;
128 self.consecutive_hits = 0;
129 }
130 }
131 }
132 }
133
134 pub fn is_limited(&self) -> bool {
136 self.weight < self.base_weight
137 }
138}
139
140#[derive(Debug, Clone, Default)]
142pub struct AgentWeights {
143 pub states: HashMap<String, RateLimitState>,
144 pub base_weights: HashMap<String, f64>,
147}
148
149impl AgentWeights {
150 pub fn ensure_agents(&mut self, agents: &[String]) {
152 for agent in agents {
153 self.states.entry(agent.clone()).or_default();
154 }
155 }
156
157 pub fn ensure_agents_with_weights(
164 &mut self,
165 agents: &[String],
166 configured_weights: &HashMap<String, f64>,
167 ) {
168 for agent in agents {
169 let base = configured_weights
170 .get(agent)
171 .copied()
172 .unwrap_or_else(|| default_missing_weight(configured_weights));
173 self.states
174 .entry(agent.clone())
175 .or_insert_with(|| RateLimitState::with_base(base))
176 .set_base(base);
177 }
178 }
179
180 pub fn record_rate_limit(&mut self, agent: &str) {
182 let state = self.states.entry(agent.to_string()).or_default();
183 state.record_rate_limit();
184 let jitter = state.stagger_recovery(agent);
185 tracing::info!(
186 agent,
187 weight = state.weight,
188 hits = state.consecutive_hits,
189 jitter_secs = jitter.as_secs(),
190 "agent weight reduced (rate limit)"
191 );
192 }
193
194 pub fn record_success(&mut self, agent: &str) {
196 self.states
197 .entry(agent.to_string())
198 .or_default()
199 .record_success();
200 }
201
202 pub fn tick_recovery(&mut self) {
204 for (agent, state) in &mut self.states {
205 let was_limited = state.is_limited();
206 state.maybe_recover();
207 if was_limited && !state.is_limited() {
208 tracing::info!(agent, "agent weight fully recovered");
209 }
210 }
211 }
212
213 pub fn weighted_select(&self, agents: &[String], task_id: &str) -> Option<String> {
219 if agents.is_empty() {
220 return None;
221 }
222
223 let weights: Vec<f64> = agents
224 .iter()
225 .map(|a| {
226 self.states.get(a).map_or_else(
227 || {
228 self.base_weights
229 .get(a)
230 .copied()
231 .unwrap_or_else(|| default_missing_weight(&self.base_weights))
232 },
233 |s| s.weight,
234 )
235 })
236 .collect();
237
238 let total: f64 = weights.iter().sum();
239 if total <= 0.0 {
240 let idx = simple_hash_index_for(agents.len(), task_id);
242 return Some(agents[idx].clone());
243 }
244
245 let pick = simple_hash_fraction_for(task_id) * total;
248 let mut cumulative = 0.0;
249 for (i, w) in weights.iter().enumerate() {
250 cumulative += w;
251 if pick < cumulative {
252 return Some(agents[i].clone());
253 }
254 }
255
256 debug_assert!(!agents.is_empty(), "agents must not be empty");
258 Some(agents[agents.len() - 1].clone())
259 }
260
261 pub fn get_weight(&self, agent: &str) -> f64 {
263 self.states.get(agent).map_or_else(
264 || {
265 self.base_weights
266 .get(agent)
267 .copied()
268 .unwrap_or_else(|| default_missing_weight(&self.base_weights))
269 },
270 |s| s.weight,
271 )
272 }
273
274 pub fn snapshot(&self) -> Vec<(String, f64, u32)> {
276 let mut snap: Vec<_> = self
277 .states
278 .iter()
279 .map(|(a, s)| (a.clone(), s.weight, s.consecutive_hits))
280 .collect();
281 snap.sort_by(|a, b| a.0.cmp(&b.0));
282 snap
283 }
284}
285
286#[cfg(test)]
287#[expect(
288 clippy::float_cmp,
289 reason = "the weights are stored constants, so they compare exactly"
290)]
291mod tests {
292 use super::*;
293 use serial_test::serial;
294
295 #[test]
296 fn recovery_jitter_is_the_byte_hash_modulo_the_cap() {
297 assert_eq!(generate_recovery_jitter(""), Duration::from_secs(0));
298 assert_eq!(generate_recovery_jitter("a"), Duration::from_secs(7));
299 assert_eq!(
300 generate_recovery_jitter("claude"),
301 generate_recovery_jitter("claude")
302 );
303 assert!(generate_recovery_jitter("claude") < RECOVERY_JITTER_MAX);
304 }
305
306 #[serial(cooldown_state)]
307 #[test]
308 fn rate_limit_state_defaults_to_full_weight() {
309 let state = RateLimitState::default();
310 assert_eq!(state.weight, DEFAULT_WEIGHT);
311 assert_eq!(state.consecutive_hits, 0);
312 assert!(state.last_limited_at.is_none());
313 assert!(!state.is_limited());
314 }
315
316 #[serial(cooldown_state)]
317 #[test]
318 fn rate_limit_state_decays_on_hit() {
319 let mut state = RateLimitState::default();
320 state.record_rate_limit();
321
322 assert!(state.weight < DEFAULT_WEIGHT);
323 assert_eq!(state.consecutive_hits, 1);
324 assert!(state.last_limited_at.is_some());
325 assert!(state.is_limited());
326
327 let expected = DEFAULT_WEIGHT * RATE_LIMIT_DECAY;
329 assert!((state.weight - expected).abs() < 1e-10);
330 }
331
332 #[serial(cooldown_state)]
333 #[test]
334 fn rate_limit_state_never_drops_below_min() {
335 let mut state = RateLimitState::default();
336
337 for _ in 0..100 {
339 state.record_rate_limit();
340 }
341
342 assert!(state.weight >= MIN_WEIGHT);
343 assert_eq!(state.consecutive_hits, 100);
344 }
345
346 #[serial(cooldown_state)]
347 #[test]
348 fn rate_limit_state_recovers_on_success() {
349 let mut state = RateLimitState::default();
350
351 state.record_rate_limit();
353 state.record_rate_limit();
354 let after_decay = state.weight;
355
356 state.record_success();
358 assert!(state.weight > after_decay);
359 assert_eq!(state.consecutive_hits, 0);
360 }
361
362 #[serial(cooldown_state)]
363 #[test]
364 fn rate_limit_state_success_caps_at_default() {
365 let mut state = RateLimitState::default();
366
367 state.record_success();
369 assert_eq!(state.weight, DEFAULT_WEIGHT);
370 }
371
372 #[serial(cooldown_state)]
373 #[test]
374 fn agent_weights_ensure_agents() {
375 let mut weights = AgentWeights::default();
376 let agents = vec!["claude".to_string(), "codex".to_string()];
377 weights.ensure_agents(&agents);
378
379 assert_eq!(weights.states.len(), 2);
380 assert_eq!(weights.get_weight("claude"), DEFAULT_WEIGHT);
381 assert_eq!(weights.get_weight("codex"), DEFAULT_WEIGHT);
382 }
383
384 #[serial(cooldown_state)]
385 #[test]
386 fn agent_weights_ensure_agents_preserves_existing() {
387 let mut weights = AgentWeights::default();
388 let agents = vec!["claude".to_string(), "codex".to_string()];
389 weights.ensure_agents(&agents);
390
391 weights.record_rate_limit("claude");
393 let claude_weight = weights.get_weight("claude");
394 assert!(claude_weight < DEFAULT_WEIGHT);
395
396 let agents2 = vec![
398 "claude".to_string(),
399 "codex".to_string(),
400 "opencode".to_string(),
401 ];
402 weights.ensure_agents(&agents2);
403
404 assert_eq!(weights.get_weight("claude"), claude_weight);
405 assert_eq!(weights.get_weight("opencode"), DEFAULT_WEIGHT);
406 }
407
408 #[test]
409 fn default_missing_weight_uses_minimum_of_configured() {
410 let mut configured = HashMap::new();
411 configured.insert("claude".to_string(), 0.2);
412 configured.insert("codex".to_string(), 0.2);
413 configured.insert("opencode".to_string(), 0.2);
414 configured.insert("kimi".to_string(), 0.2);
415
416 assert_eq!(default_missing_weight(&configured), 0.2);
419 }
420
421 #[test]
422 fn default_missing_weight_falls_back_when_none_configured() {
423 let configured = HashMap::new();
424 assert_eq!(default_missing_weight(&configured), DEFAULT_WEIGHT);
425 }
426
427 #[serial(cooldown_state)]
428 #[test]
429 fn ensure_agents_with_weights_missing_agent_does_not_outrank_configured() {
430 let mut weights = AgentWeights::default();
431 let mut configured = HashMap::new();
432 configured.insert("claude".to_string(), 0.2);
433 configured.insert("codex".to_string(), 0.2);
434 configured.insert("opencode".to_string(), 0.2);
435 configured.insert("kimi".to_string(), 0.2);
436
437 let agents = vec![
438 "claude".to_string(),
439 "codex".to_string(),
440 "opencode".to_string(),
441 "kimi".to_string(),
442 "minimax".to_string(),
443 ];
444 weights.ensure_agents_with_weights(&agents, &configured);
445
446 assert_eq!(weights.get_weight("minimax"), 0.2);
449 assert_eq!(weights.get_weight("claude"), 0.2);
450 }
451
452 #[serial(cooldown_state)]
453 #[test]
454 fn agent_weights_record_rate_limit() {
455 let mut weights = AgentWeights::default();
456 weights.ensure_agents(&["claude".to_string(), "codex".to_string()]);
457
458 weights.record_rate_limit("claude");
459
460 assert!(weights.get_weight("claude") < DEFAULT_WEIGHT);
461 assert_eq!(weights.get_weight("codex"), DEFAULT_WEIGHT);
462 }
463
464 #[serial(cooldown_state)]
465 #[test]
466 fn agent_weights_record_success() {
467 let mut weights = AgentWeights::default();
468 weights.ensure_agents(&["claude".to_string()]);
469
470 weights.record_rate_limit("claude");
471 let after_limit = weights.get_weight("claude");
472
473 weights.record_success("claude");
474 assert!(weights.get_weight("claude") > after_limit);
475 }
476
477 #[serial(cooldown_state)]
478 #[test]
479 fn agent_weights_snapshot() {
480 let mut weights = AgentWeights::default();
481 weights.ensure_agents(&["claude".to_string(), "codex".to_string()]);
482 weights.record_rate_limit("claude");
483
484 let snap = weights.snapshot();
485 assert_eq!(snap.len(), 2);
486
487 assert_eq!(snap[0].0, "claude");
489 assert!(snap[0].1 < DEFAULT_WEIGHT);
490 assert_eq!(snap[0].2, 1); assert_eq!(snap[1].0, "codex");
493 assert_eq!(snap[1].1, DEFAULT_WEIGHT);
494 assert_eq!(snap[1].2, 0); }
496
497 #[serial(cooldown_state)]
498 #[test]
499 fn agent_weights_weighted_select_favors_higher_weight() {
500 let mut weights = AgentWeights::default();
501 let agents = vec!["claude".to_string(), "codex".to_string()];
502 weights.ensure_agents(&agents);
503
504 for _ in 0..10 {
506 weights.record_rate_limit("claude");
507 }
508
509 let mut claude_count = 0;
511 let mut codex_count = 0;
512 for _ in 0..100 {
513 match weights.weighted_select(&agents, "task-1") {
514 Some(ref a) if a == "claude" => claude_count += 1,
515 Some(ref a) if a == "codex" => codex_count += 1,
516 _ => {}
517 }
518 }
519
520 assert!(
523 codex_count > claude_count,
524 "codex ({codex_count}) should get more selections than claude ({claude_count})"
525 );
526 }
527
528 #[serial(cooldown_state)]
529 #[test]
530 fn agent_weights_weighted_select_empty_returns_none() {
531 let weights = AgentWeights::default();
532 assert!(weights.weighted_select(&[], "task-1").is_none());
533 }
534
535 #[serial(cooldown_state)]
536 #[test]
537 fn agent_weights_batch_routing_produces_varied_selections() {
538 let mut weights = AgentWeights::default();
541 let agents = vec!["claude".to_string(), "codex".to_string()];
542 weights.ensure_agents(&agents);
543
544 let task_ids: Vec<String> = (1..=20).map(|i| format!("task-{i}")).collect();
546 let selections: Vec<String> = task_ids
547 .iter()
548 .filter_map(|id| weights.weighted_select(&agents, id))
549 .collect();
550
551 let claude_count = selections.iter().filter(|a| a.as_str() == "claude").count();
554 let codex_count = selections.iter().filter(|a| a.as_str() == "codex").count();
555 assert!(
556 claude_count > 0 && codex_count > 0,
557 "batch routing should distribute across agents; got claude={claude_count} codex={codex_count}"
558 );
559 }
560
561 #[serial(cooldown_state)]
562 #[test]
563 fn agent_weights_weighted_select_single_agent() {
564 let mut weights = AgentWeights::default();
565 let agents = vec!["claude".to_string()];
566 weights.ensure_agents(&agents);
567
568 let selected = weights.weighted_select(&agents, "task-1");
569 assert_eq!(selected, Some("claude".to_string()));
570 }
571
572 #[serial(cooldown_state)]
573 #[test]
574 fn agent_weights_tick_recovery_restores_weight() {
575 let mut weights = AgentWeights::default();
576 weights.ensure_agents(&["claude".to_string()]);
577
578 let state = weights.states.get_mut("claude").unwrap();
580 state.weight = 0.5;
581 state.last_limited_at = Some(
582 Instant::now()
583 .checked_sub(RECOVERY_DELAY + Duration::from_secs(1))
584 .expect("the clock is past the recovery delay"),
585 );
586 state.consecutive_hits = 2;
587
588 let before = weights.get_weight("claude");
589 weights.tick_recovery();
590 let after = weights.get_weight("claude");
591
592 assert!(after > before, "weight should increase after recovery tick");
593 }
594
595 #[serial(cooldown_state)]
596 #[test]
597 fn agent_weights_tick_recovery_clears_on_full_restore() {
598 let mut weights = AgentWeights::default();
599 weights.ensure_agents(&["claude".to_string()]);
600
601 let state = weights.states.get_mut("claude").unwrap();
603 state.weight = DEFAULT_WEIGHT - 0.01;
604 state.last_limited_at = Some(
605 Instant::now()
606 .checked_sub(RECOVERY_DELAY + Duration::from_secs(1))
607 .expect("the clock is past the recovery delay"),
608 );
609 state.consecutive_hits = 1;
610
611 weights.tick_recovery();
612
613 let state = weights.states.get("claude").unwrap();
614 assert_eq!(state.weight, DEFAULT_WEIGHT);
615 assert!(state.last_limited_at.is_none());
616 assert_eq!(state.consecutive_hits, 0);
617 }
618}