Skip to main content

orch/engine/router/
weights.rs

1//! Per-agent routing weights and rate-limit recovery.
2//!
3//! `RateLimitState` tracks a single agent's current routing weight and
4//! recovers it over time after rate-limit events.
5//!
6//! `AgentWeights` aggregates per-agent states and provides weighted
7//! probabilistic selection via `weighted_select`.
8
9use std::collections::HashMap;
10use std::time::{Duration, Instant};
11
12use super::selection::{hash_task_id, simple_hash_fraction_for, simple_hash_index_for};
13
14/// Default weight for agents with full capacity.
15pub(super) const DEFAULT_WEIGHT: f64 = 1.0;
16
17/// Minimum weight — an agent never drops below this (still gets occasional tasks).
18pub(super) const MIN_WEIGHT: f64 = 0.05;
19
20/// How much to reduce weight on each rate limit hit (multiplicative decay).
21pub(super) const RATE_LIMIT_DECAY: f64 = 0.3;
22
23/// Weight to use for an agent that is absent from a configured `router.weights`
24/// map. Rather than the constant `DEFAULT_WEIGHT` (1.0) — which would silently
25/// outrank every agent the operator *did* configure — an omitted agent falls
26/// back to the minimum of the explicitly configured weights. An empty map
27/// means no weights are configured at all, so `DEFAULT_WEIGHT` applies to
28/// everyone equally.
29pub(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
37/// Generate jitter duration for recovery delay based on agent name.
38/// Uses a simple hash to create deterministic but varied jitter per agent.
39fn 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
45/// Duration after which a rate-limited agent starts recovering weight.
46pub(super) const RECOVERY_DELAY: Duration = Duration::from_secs(60);
47
48/// Maximum jitter added to recovery delay to stagger agent recoveries.
49/// This prevents thundering herd where all agents recover simultaneously.
50pub(super) const RECOVERY_JITTER_MAX: Duration = Duration::from_secs(30);
51
52/// Per-tick weight recovery amount (additive, applied each routing call).
53pub(super) const RECOVERY_RATE: f64 = 0.1;
54
55/// Rate limit state for a single agent.
56#[derive(Debug, Clone)]
57pub struct RateLimitState {
58    /// Current routing weight (0.0..=1.0). Higher = more tasks.
59    pub weight: f64,
60    /// When the last rate limit error was recorded.
61    pub last_limited_at: Option<Instant>,
62    /// Jitter added to recovery delay to stagger recoveries (avoid thundering herd).
63    pub recovery_jitter: Duration,
64    /// How many consecutive rate limit hits.
65    pub consecutive_hits: u32,
66    /// The configured base weight this agent should recover toward.
67    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    /// Take a new base weight, after a config reload. A rate-limited agent keeps its decayed weight
92    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    /// Spread recovery times across agents with a jitter derived from the agent name
100    fn stagger_recovery(&mut self, agent: &str) -> Duration {
101        self.recovery_jitter = generate_recovery_jitter(agent);
102        self.recovery_jitter
103    }
104
105    /// Record a rate limit event — decay the weight.
106    /// Note: Jitter is set at the AgentWeights level using the agent name.
107    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    /// Record a successful completion — bump weight back toward base_weight.
114    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    /// Tick recovery: if enough time has passed since the last limit (plus jitter), gradually restore.
120    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    /// Is this agent currently rate-limited (weight below its base weight)?
135    pub fn is_limited(&self) -> bool {
136        self.weight < self.base_weight
137    }
138}
139
140/// Tracks per-agent weights for weighted round-robin routing.
141#[derive(Debug, Clone, Default)]
142pub struct AgentWeights {
143    pub states: HashMap<String, RateLimitState>,
144    /// Configured base weights per agent (from config.yml).
145    /// Used as the recovery ceiling instead of DEFAULT_WEIGHT.
146    pub base_weights: HashMap<String, f64>,
147}
148
149impl AgentWeights {
150    /// Ensure all available agents have an entry, using configured base weights.
151    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    /// Ensure all available agents have an entry, applying configured base weights.
158    ///
159    /// Agents with an explicit weight in `config.yml` use that as their base.
160    /// Agents without a configured weight default to the minimum of the
161    /// explicitly configured weights (see `default_missing_weight`), so an
162    /// omission never outranks an agent the operator actually configured.
163    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    /// Record a rate limit event for an agent.
181    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    /// Record a successful task completion for an agent.
195    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    /// Tick recovery for all agents.
203    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    /// Select an agent by weighted probability from the given list.
214    ///
215    /// Uses a simple weighted random selection: each agent's probability is
216    /// proportional to its weight. If all weights are zero (shouldn't happen
217    /// due to MIN_WEIGHT), falls back to uniform selection.
218    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            // Safety fallback: uniform random
241            let idx = simple_hash_index_for(agents.len(), task_id);
242            return Some(agents[idx].clone());
243        }
244
245        // Deterministic-ish selection using a hash of the current time
246        // to avoid requiring rand crate. Good enough for load distribution.
247        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        // Rounding edge case — return last agent (agents is guaranteed non-empty by caller)
257        debug_assert!(!agents.is_empty(), "agents must not be empty");
258        Some(agents[agents.len() - 1].clone())
259    }
260
261    /// Get the current weight for an agent.
262    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    /// Get a snapshot of all agent weights (for logging/debugging).
275    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        // Weight should be DEFAULT_WEIGHT * RATE_LIMIT_DECAY
328        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        // Hit many times
338        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        // Decay first
352        state.record_rate_limit();
353        state.record_rate_limit();
354        let after_decay = state.weight;
355
356        // Record success
357        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        // Already at full weight, success shouldn't exceed it
368        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        // Reduce claude's weight
392        weights.record_rate_limit("claude");
393        let claude_weight = weights.get_weight("claude");
394        assert!(claude_weight < DEFAULT_WEIGHT);
395
396        // Ensure agents again — claude's weight should be preserved
397        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        // minimax omitted from router.weights — must not silently outrank
417        // every explicitly configured agent (issue #3596).
418        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        // minimax was omitted from router.weights but must not get the old
447        // DEFAULT_WEIGHT of 1.0, which would outrank every configured agent.
448        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        // Snapshot is sorted alphabetically
488        assert_eq!(snap[0].0, "claude");
489        assert!(snap[0].1 < DEFAULT_WEIGHT);
490        assert_eq!(snap[0].2, 1); // 1 hit
491
492        assert_eq!(snap[1].0, "codex");
493        assert_eq!(snap[1].1, DEFAULT_WEIGHT);
494        assert_eq!(snap[1].2, 0); // 0 hits
495    }
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        // Heavily penalize claude
505        for _ in 0..10 {
506            weights.record_rate_limit("claude");
507        }
508
509        // Run many selections and count
510        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        // Codex should get significantly more selections
521        // (claude weight is near MIN_WEIGHT, codex is at 1.0)
522        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        // Regression test: when routing a batch of tasks in the same tick,
539        // different task IDs should not all select the same agent.
540        let mut weights = AgentWeights::default();
541        let agents = vec!["claude".to_string(), "codex".to_string()];
542        weights.ensure_agents(&agents);
543
544        // Simulate batch routing: 20 different task IDs called in rapid succession
545        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        // With 20 tasks and 2 agents of equal weight, we should see both agents selected.
552        // The probability of all 20 selecting the same agent by chance is (0.5)^19 < 1e-6.
553        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        // Set up a rate limit that looks like it happened long ago
579        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        // Set weight just below full with an old limit
602        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}