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 pub fn record_rate_limit(&mut self) {
86 self.consecutive_hits += 1;
87 self.weight = (self.weight * RATE_LIMIT_DECAY).max(MIN_WEIGHT);
88 self.last_limited_at = Some(Instant::now());
89 }
90
91 pub fn record_success(&mut self) {
93 self.consecutive_hits = 0;
94 self.weight = (self.weight + RECOVERY_RATE).min(self.base_weight);
95 }
96
97 pub fn maybe_recover(&mut self) {
99 if let Some(last) = self.last_limited_at {
100 let recovery_threshold = RECOVERY_DELAY + self.recovery_jitter;
101 if last.elapsed() >= recovery_threshold {
102 self.weight = (self.weight + RECOVERY_RATE).min(self.base_weight);
103 if self.weight >= self.base_weight {
104 self.last_limited_at = None;
105 self.recovery_jitter = Duration::ZERO;
106 self.consecutive_hits = 0;
107 }
108 }
109 }
110 }
111
112 pub fn is_limited(&self) -> bool {
114 self.weight < self.base_weight
115 }
116}
117
118#[derive(Debug, Clone, Default)]
120pub struct AgentWeights {
121 pub states: HashMap<String, RateLimitState>,
122 pub base_weights: HashMap<String, f64>,
125}
126
127impl AgentWeights {
128 pub fn ensure_agents(&mut self, agents: &[String]) {
130 for agent in agents {
131 self.states.entry(agent.clone()).or_default();
132 }
133 }
134
135 pub fn ensure_agents_with_weights(
142 &mut self,
143 agents: &[String],
144 configured_weights: &HashMap<String, f64>,
145 ) {
146 for agent in agents {
147 let base = configured_weights
148 .get(agent)
149 .copied()
150 .unwrap_or_else(|| default_missing_weight(configured_weights));
151 let state = self
152 .states
153 .entry(agent.clone())
154 .or_insert_with(|| RateLimitState {
155 weight: base,
156 base_weight: base,
157 ..Default::default()
158 });
159 state.base_weight = base;
160 if !state.is_limited() {
163 state.weight = base;
164 }
165 }
166 }
167
168 pub fn record_rate_limit(&mut self, agent: &str) {
170 let state = self.states.entry(agent.to_string()).or_default();
171 state.record_rate_limit();
172 state.recovery_jitter = generate_recovery_jitter(agent);
174 tracing::info!(
175 agent,
176 weight = state.weight,
177 hits = state.consecutive_hits,
178 jitter_secs = state.recovery_jitter.as_secs(),
179 "agent weight reduced (rate limit)"
180 );
181 }
182
183 pub fn record_success(&mut self, agent: &str) {
185 self.states
186 .entry(agent.to_string())
187 .or_default()
188 .record_success();
189 }
190
191 pub fn tick_recovery(&mut self) {
193 for (agent, state) in &mut self.states {
194 let was_limited = state.is_limited();
195 state.maybe_recover();
196 if was_limited && !state.is_limited() {
197 tracing::info!(agent, "agent weight fully recovered");
198 }
199 }
200 }
201
202 pub fn weighted_select(&self, agents: &[String], task_id: &str) -> Option<String> {
208 if agents.is_empty() {
209 return None;
210 }
211
212 let weights: Vec<f64> = agents
213 .iter()
214 .map(|a| {
215 self.states.get(a).map_or_else(
216 || {
217 self.base_weights
218 .get(a)
219 .copied()
220 .unwrap_or_else(|| default_missing_weight(&self.base_weights))
221 },
222 |s| s.weight,
223 )
224 })
225 .collect();
226
227 let total: f64 = weights.iter().sum();
228 if total <= 0.0 {
229 let idx = simple_hash_index_for(agents.len(), task_id);
231 return Some(agents[idx].clone());
232 }
233
234 let pick = simple_hash_fraction_for(task_id) * total;
237 let mut cumulative = 0.0;
238 for (i, w) in weights.iter().enumerate() {
239 cumulative += w;
240 if pick < cumulative {
241 return Some(agents[i].clone());
242 }
243 }
244
245 debug_assert!(!agents.is_empty(), "agents must not be empty");
247 Some(agents[agents.len() - 1].clone())
248 }
249
250 pub fn get_weight(&self, agent: &str) -> f64 {
252 self.states.get(agent).map_or_else(
253 || {
254 self.base_weights
255 .get(agent)
256 .copied()
257 .unwrap_or_else(|| default_missing_weight(&self.base_weights))
258 },
259 |s| s.weight,
260 )
261 }
262
263 pub fn snapshot(&self) -> Vec<(String, f64, u32)> {
265 let mut snap: Vec<_> = self
266 .states
267 .iter()
268 .map(|(a, s)| (a.clone(), s.weight, s.consecutive_hits))
269 .collect();
270 snap.sort_by(|a, b| a.0.cmp(&b.0));
271 snap
272 }
273}
274
275#[cfg(test)]
276#[expect(
277 clippy::float_cmp,
278 reason = "the weights are stored constants, so they compare exactly"
279)]
280mod tests {
281 use super::*;
282 use serial_test::serial;
283
284 #[test]
285 fn recovery_jitter_is_the_byte_hash_modulo_the_cap() {
286 assert_eq!(generate_recovery_jitter(""), Duration::from_secs(0));
287 assert_eq!(generate_recovery_jitter("a"), Duration::from_secs(7));
288 assert_eq!(
289 generate_recovery_jitter("claude"),
290 generate_recovery_jitter("claude")
291 );
292 assert!(generate_recovery_jitter("claude") < RECOVERY_JITTER_MAX);
293 }
294
295 #[serial(cooldown_state)]
296 #[test]
297 fn rate_limit_state_defaults_to_full_weight() {
298 let state = RateLimitState::default();
299 assert_eq!(state.weight, DEFAULT_WEIGHT);
300 assert_eq!(state.consecutive_hits, 0);
301 assert!(state.last_limited_at.is_none());
302 assert!(!state.is_limited());
303 }
304
305 #[serial(cooldown_state)]
306 #[test]
307 fn rate_limit_state_decays_on_hit() {
308 let mut state = RateLimitState::default();
309 state.record_rate_limit();
310
311 assert!(state.weight < DEFAULT_WEIGHT);
312 assert_eq!(state.consecutive_hits, 1);
313 assert!(state.last_limited_at.is_some());
314 assert!(state.is_limited());
315
316 let expected = DEFAULT_WEIGHT * RATE_LIMIT_DECAY;
318 assert!((state.weight - expected).abs() < 1e-10);
319 }
320
321 #[serial(cooldown_state)]
322 #[test]
323 fn rate_limit_state_never_drops_below_min() {
324 let mut state = RateLimitState::default();
325
326 for _ in 0..100 {
328 state.record_rate_limit();
329 }
330
331 assert!(state.weight >= MIN_WEIGHT);
332 assert_eq!(state.consecutive_hits, 100);
333 }
334
335 #[serial(cooldown_state)]
336 #[test]
337 fn rate_limit_state_recovers_on_success() {
338 let mut state = RateLimitState::default();
339
340 state.record_rate_limit();
342 state.record_rate_limit();
343 let after_decay = state.weight;
344
345 state.record_success();
347 assert!(state.weight > after_decay);
348 assert_eq!(state.consecutive_hits, 0);
349 }
350
351 #[serial(cooldown_state)]
352 #[test]
353 fn rate_limit_state_success_caps_at_default() {
354 let mut state = RateLimitState::default();
355
356 state.record_success();
358 assert_eq!(state.weight, DEFAULT_WEIGHT);
359 }
360
361 #[serial(cooldown_state)]
362 #[test]
363 fn agent_weights_ensure_agents() {
364 let mut weights = AgentWeights::default();
365 let agents = vec!["claude".to_string(), "codex".to_string()];
366 weights.ensure_agents(&agents);
367
368 assert_eq!(weights.states.len(), 2);
369 assert_eq!(weights.get_weight("claude"), DEFAULT_WEIGHT);
370 assert_eq!(weights.get_weight("codex"), DEFAULT_WEIGHT);
371 }
372
373 #[serial(cooldown_state)]
374 #[test]
375 fn agent_weights_ensure_agents_preserves_existing() {
376 let mut weights = AgentWeights::default();
377 let agents = vec!["claude".to_string(), "codex".to_string()];
378 weights.ensure_agents(&agents);
379
380 weights.record_rate_limit("claude");
382 let claude_weight = weights.get_weight("claude");
383 assert!(claude_weight < DEFAULT_WEIGHT);
384
385 let agents2 = vec![
387 "claude".to_string(),
388 "codex".to_string(),
389 "opencode".to_string(),
390 ];
391 weights.ensure_agents(&agents2);
392
393 assert_eq!(weights.get_weight("claude"), claude_weight);
394 assert_eq!(weights.get_weight("opencode"), DEFAULT_WEIGHT);
395 }
396
397 #[test]
398 fn default_missing_weight_uses_minimum_of_configured() {
399 let mut configured = HashMap::new();
400 configured.insert("claude".to_string(), 0.2);
401 configured.insert("codex".to_string(), 0.2);
402 configured.insert("opencode".to_string(), 0.2);
403 configured.insert("kimi".to_string(), 0.2);
404
405 assert_eq!(default_missing_weight(&configured), 0.2);
408 }
409
410 #[test]
411 fn default_missing_weight_falls_back_when_none_configured() {
412 let configured = HashMap::new();
413 assert_eq!(default_missing_weight(&configured), DEFAULT_WEIGHT);
414 }
415
416 #[serial(cooldown_state)]
417 #[test]
418 fn ensure_agents_with_weights_missing_agent_does_not_outrank_configured() {
419 let mut weights = AgentWeights::default();
420 let mut configured = HashMap::new();
421 configured.insert("claude".to_string(), 0.2);
422 configured.insert("codex".to_string(), 0.2);
423 configured.insert("opencode".to_string(), 0.2);
424 configured.insert("kimi".to_string(), 0.2);
425
426 let agents = vec![
427 "claude".to_string(),
428 "codex".to_string(),
429 "opencode".to_string(),
430 "kimi".to_string(),
431 "minimax".to_string(),
432 ];
433 weights.ensure_agents_with_weights(&agents, &configured);
434
435 assert_eq!(weights.get_weight("minimax"), 0.2);
438 assert_eq!(weights.get_weight("claude"), 0.2);
439 }
440
441 #[serial(cooldown_state)]
442 #[test]
443 fn agent_weights_record_rate_limit() {
444 let mut weights = AgentWeights::default();
445 weights.ensure_agents(&["claude".to_string(), "codex".to_string()]);
446
447 weights.record_rate_limit("claude");
448
449 assert!(weights.get_weight("claude") < DEFAULT_WEIGHT);
450 assert_eq!(weights.get_weight("codex"), DEFAULT_WEIGHT);
451 }
452
453 #[serial(cooldown_state)]
454 #[test]
455 fn agent_weights_record_success() {
456 let mut weights = AgentWeights::default();
457 weights.ensure_agents(&["claude".to_string()]);
458
459 weights.record_rate_limit("claude");
460 let after_limit = weights.get_weight("claude");
461
462 weights.record_success("claude");
463 assert!(weights.get_weight("claude") > after_limit);
464 }
465
466 #[serial(cooldown_state)]
467 #[test]
468 fn agent_weights_snapshot() {
469 let mut weights = AgentWeights::default();
470 weights.ensure_agents(&["claude".to_string(), "codex".to_string()]);
471 weights.record_rate_limit("claude");
472
473 let snap = weights.snapshot();
474 assert_eq!(snap.len(), 2);
475
476 assert_eq!(snap[0].0, "claude");
478 assert!(snap[0].1 < DEFAULT_WEIGHT);
479 assert_eq!(snap[0].2, 1); assert_eq!(snap[1].0, "codex");
482 assert_eq!(snap[1].1, DEFAULT_WEIGHT);
483 assert_eq!(snap[1].2, 0); }
485
486 #[serial(cooldown_state)]
487 #[test]
488 fn agent_weights_weighted_select_favors_higher_weight() {
489 let mut weights = AgentWeights::default();
490 let agents = vec!["claude".to_string(), "codex".to_string()];
491 weights.ensure_agents(&agents);
492
493 for _ in 0..10 {
495 weights.record_rate_limit("claude");
496 }
497
498 let mut claude_count = 0;
500 let mut codex_count = 0;
501 for _ in 0..100 {
502 match weights.weighted_select(&agents, "task-1") {
503 Some(ref a) if a == "claude" => claude_count += 1,
504 Some(ref a) if a == "codex" => codex_count += 1,
505 _ => {}
506 }
507 }
508
509 assert!(
512 codex_count > claude_count,
513 "codex ({codex_count}) should get more selections than claude ({claude_count})"
514 );
515 }
516
517 #[serial(cooldown_state)]
518 #[test]
519 fn agent_weights_weighted_select_empty_returns_none() {
520 let weights = AgentWeights::default();
521 assert!(weights.weighted_select(&[], "task-1").is_none());
522 }
523
524 #[serial(cooldown_state)]
525 #[test]
526 fn agent_weights_batch_routing_produces_varied_selections() {
527 let mut weights = AgentWeights::default();
530 let agents = vec!["claude".to_string(), "codex".to_string()];
531 weights.ensure_agents(&agents);
532
533 let task_ids: Vec<String> = (1..=20).map(|i| format!("task-{i}")).collect();
535 let selections: Vec<String> = task_ids
536 .iter()
537 .filter_map(|id| weights.weighted_select(&agents, id))
538 .collect();
539
540 let claude_count = selections.iter().filter(|a| a.as_str() == "claude").count();
543 let codex_count = selections.iter().filter(|a| a.as_str() == "codex").count();
544 assert!(
545 claude_count > 0 && codex_count > 0,
546 "batch routing should distribute across agents; got claude={claude_count} codex={codex_count}"
547 );
548 }
549
550 #[serial(cooldown_state)]
551 #[test]
552 fn agent_weights_weighted_select_single_agent() {
553 let mut weights = AgentWeights::default();
554 let agents = vec!["claude".to_string()];
555 weights.ensure_agents(&agents);
556
557 let selected = weights.weighted_select(&agents, "task-1");
558 assert_eq!(selected, Some("claude".to_string()));
559 }
560
561 #[serial(cooldown_state)]
562 #[test]
563 fn agent_weights_tick_recovery_restores_weight() {
564 let mut weights = AgentWeights::default();
565 weights.ensure_agents(&["claude".to_string()]);
566
567 let state = weights.states.get_mut("claude").unwrap();
569 state.weight = 0.5;
570 state.last_limited_at = Some(
571 Instant::now()
572 .checked_sub(RECOVERY_DELAY + Duration::from_secs(1))
573 .expect("the clock is past the recovery delay"),
574 );
575 state.consecutive_hits = 2;
576
577 let before = weights.get_weight("claude");
578 weights.tick_recovery();
579 let after = weights.get_weight("claude");
580
581 assert!(after > before, "weight should increase after recovery tick");
582 }
583
584 #[serial(cooldown_state)]
585 #[test]
586 fn agent_weights_tick_recovery_clears_on_full_restore() {
587 let mut weights = AgentWeights::default();
588 weights.ensure_agents(&["claude".to_string()]);
589
590 let state = weights.states.get_mut("claude").unwrap();
592 state.weight = DEFAULT_WEIGHT - 0.01;
593 state.last_limited_at = Some(
594 Instant::now()
595 .checked_sub(RECOVERY_DELAY + Duration::from_secs(1))
596 .expect("the clock is past the recovery delay"),
597 );
598 state.consecutive_hits = 1;
599
600 weights.tick_recovery();
601
602 let state = weights.states.get("claude").unwrap();
603 assert_eq!(state.weight, DEFAULT_WEIGHT);
604 assert!(state.last_limited_at.is_none());
605 assert_eq!(state.consecutive_hits, 0);
606 }
607}