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    /// Record a rate limit event — decay the weight.
84    /// Note: Jitter is set at the AgentWeights level using the agent name.
85    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    /// Record a successful completion — bump weight back toward base_weight.
92    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    /// Tick recovery: if enough time has passed since the last limit (plus jitter), gradually restore.
98    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    /// Is this agent currently rate-limited (weight below its base weight)?
113    pub fn is_limited(&self) -> bool {
114        self.weight < self.base_weight
115    }
116}
117
118/// Tracks per-agent weights for weighted round-robin routing.
119#[derive(Debug, Clone, Default)]
120pub struct AgentWeights {
121    pub states: HashMap<String, RateLimitState>,
122    /// Configured base weights per agent (from config.yml).
123    /// Used as the recovery ceiling instead of DEFAULT_WEIGHT.
124    pub base_weights: HashMap<String, f64>,
125}
126
127impl AgentWeights {
128    /// Ensure all available agents have an entry, using configured base weights.
129    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    /// Ensure all available agents have an entry, applying configured base weights.
136    ///
137    /// Agents with an explicit weight in `config.yml` use that as their base.
138    /// Agents without a configured weight default to the minimum of the
139    /// explicitly configured weights (see `default_missing_weight`), so an
140    /// omission never outranks an agent the operator actually configured.
141    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            // Update base weight if agent was already initialized (e.g. after config reload)
161            // but only if the agent isn't currently rate-limited (don't override decay)
162            if !state.is_limited() {
163                state.weight = base;
164            }
165        }
166    }
167
168    /// Record a rate limit event for an agent.
169    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        // Generate jitter to stagger recovery times across agents
173        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    /// Record a successful task completion for an agent.
184    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    /// Tick recovery for all agents.
192    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    /// Select an agent by weighted probability from the given list.
203    ///
204    /// Uses a simple weighted random selection: each agent's probability is
205    /// proportional to its weight. If all weights are zero (shouldn't happen
206    /// due to MIN_WEIGHT), falls back to uniform selection.
207    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            // Safety fallback: uniform random
230            let idx = simple_hash_index_for(agents.len(), task_id);
231            return Some(agents[idx].clone());
232        }
233
234        // Deterministic-ish selection using a hash of the current time
235        // to avoid requiring rand crate. Good enough for load distribution.
236        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        // Rounding edge case — return last agent (agents is guaranteed non-empty by caller)
246        debug_assert!(!agents.is_empty(), "agents must not be empty");
247        Some(agents[agents.len() - 1].clone())
248    }
249
250    /// Get the current weight for an agent.
251    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    /// Get a snapshot of all agent weights (for logging/debugging).
264    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        // Weight should be DEFAULT_WEIGHT * RATE_LIMIT_DECAY
317        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        // Hit many times
327        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        // Decay first
341        state.record_rate_limit();
342        state.record_rate_limit();
343        let after_decay = state.weight;
344
345        // Record success
346        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        // Already at full weight, success shouldn't exceed it
357        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        // Reduce claude's weight
381        weights.record_rate_limit("claude");
382        let claude_weight = weights.get_weight("claude");
383        assert!(claude_weight < DEFAULT_WEIGHT);
384
385        // Ensure agents again — claude's weight should be preserved
386        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        // minimax omitted from router.weights — must not silently outrank
406        // every explicitly configured agent (issue #3596).
407        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        // minimax was omitted from router.weights but must not get the old
436        // DEFAULT_WEIGHT of 1.0, which would outrank every configured agent.
437        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        // Snapshot is sorted alphabetically
477        assert_eq!(snap[0].0, "claude");
478        assert!(snap[0].1 < DEFAULT_WEIGHT);
479        assert_eq!(snap[0].2, 1); // 1 hit
480
481        assert_eq!(snap[1].0, "codex");
482        assert_eq!(snap[1].1, DEFAULT_WEIGHT);
483        assert_eq!(snap[1].2, 0); // 0 hits
484    }
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        // Heavily penalize claude
494        for _ in 0..10 {
495            weights.record_rate_limit("claude");
496        }
497
498        // Run many selections and count
499        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        // Codex should get significantly more selections
510        // (claude weight is near MIN_WEIGHT, codex is at 1.0)
511        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        // Regression test: when routing a batch of tasks in the same tick,
528        // different task IDs should not all select the same agent.
529        let mut weights = AgentWeights::default();
530        let agents = vec!["claude".to_string(), "codex".to_string()];
531        weights.ensure_agents(&agents);
532
533        // Simulate batch routing: 20 different task IDs called in rapid succession
534        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        // With 20 tasks and 2 agents of equal weight, we should see both agents selected.
541        // The probability of all 20 selecting the same agent by chance is (0.5)^19 < 1e-6.
542        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        // Set up a rate limit that looks like it happened long ago
568        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        // Set weight just below full with an old limit
591        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}