Skip to main content

agentmux_srv/server/
start_rate.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! How often one sender may start agents (docs/specs/SPEC_ALWAYS_AVAILABLE_AGENTS_2026_10_27.md ยง7,
5//! "wake loops"). A start spends a paid session, and agent A starting stopped agent B, which starts
6//! A again, must not run away: each sender gets [`DEFAULT_PER_MINUTE`] starts in any 60 seconds.
7//!
8//! The sender is whatever the caller names: an agent's id for `Agents start`, `job:<id>` for a Job
9//! or cron fire, so a Job cannot starve the agents and an agent cannot starve a Job. A refusal names
10//! the limit. The count is in memory: a restart gives every sender a fresh minute, which is the
11//! same bound again.
12
13use std::collections::{HashMap, VecDeque};
14use std::sync::{Mutex, OnceLock};
15
16use super::AppState;
17
18/// Starts one sender may make in a minute.
19pub(crate) const DEFAULT_PER_MINUTE: usize = 5;
20/// The setting that changes it; 0 turns the limit off.
21pub(crate) const SETTING_PER_MINUTE: &str = "agents:start_per_minute";
22
23const WINDOW_MS: u64 = 60_000;
24
25type Table = HashMap<String, VecDeque<u64>>;
26
27fn table() -> &'static Mutex<Table> {
28    static T: OnceLock<Mutex<Table>> = OnceLock::new();
29    T.get_or_init(|| Mutex::new(HashMap::new()))
30}
31
32/// The starts a sender may make per minute: the setting, else [`DEFAULT_PER_MINUTE`].
33fn limit_of(state: &AppState) -> usize {
34    state
35        .config_watcher
36        .get_full_config()
37        .settings
38        .extra
39        .get(SETTING_PER_MINUTE)
40        .and_then(|v| v.as_u64())
41        .map_or(DEFAULT_PER_MINUTE, |n| n as usize)
42}
43
44/// Count one start by `sender_key` and say whether it may go ahead. `Err` names the limit and when
45/// the sender may start again; the refused start is not counted.
46pub(crate) fn allow(state: &AppState, sender_key: &str) -> Result<(), String> {
47    allow_at(sender_key, limit_of(state), agentmux_common::time::now_ms_u64())
48}
49
50fn allow_at(sender_key: &str, limit: usize, now_ms: u64) -> Result<(), String> {
51    if limit == 0 {
52        return Ok(());
53    }
54    let mut table = table().lock().unwrap_or_else(|e| e.into_inner());
55    let starts = table.entry(sender_key.to_string()).or_default();
56    while starts.front().is_some_and(|&at| now_ms.saturating_sub(at) >= WINDOW_MS) {
57        starts.pop_front();
58    }
59    if starts.len() >= limit {
60        let retry_in = starts.front().map_or(0, |&at| (at + WINDOW_MS).saturating_sub(now_ms)).div_ceil(1000);
61        return Err(format!(
62            "START_RATE_LIMIT: {sender_key} has started {limit} agents in the last minute (the limit is {limit} per sender per minute); \
63             try again in {retry_in}s"
64        ));
65    }
66    starts.push_back(now_ms);
67    // A sender that went quiet leaves no row behind for long.
68    if table.len() > 256 {
69        table.retain(|_, v| v.back().is_some_and(|&at| now_ms.saturating_sub(at) < WINDOW_MS));
70    }
71    Ok(())
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77
78    #[test]
79    fn a_sender_gets_its_limit_per_minute_and_the_refusal_names_it() {
80        let key = "rate-test-a";
81        for i in 0..5 {
82            assert!(allow_at(key, 5, 1_000 + i).is_ok(), "start {i}");
83        }
84        let e = allow_at(key, 5, 2_000).unwrap_err();
85        assert!(e.starts_with("START_RATE_LIMIT: rate-test-a"), "{e}");
86        assert!(e.contains("5 per sender per minute") && e.contains("try again in 59s"), "{e}");
87    }
88
89    #[test]
90    fn the_minute_slides_and_a_refused_start_is_not_counted() {
91        let key = "rate-test-b";
92        for i in 0..5 {
93            allow_at(key, 5, 10_000 + i * 1_000).unwrap();
94        }
95        assert!(allow_at(key, 5, 20_000).is_err());
96        assert!(allow_at(key, 5, 20_001).is_err(), "still full: the refusals added nothing");
97        // The first start (at 10 s) is a minute old at 70 s: one place frees up, not five.
98        assert!(allow_at(key, 5, 70_000).is_ok());
99        assert!(allow_at(key, 5, 70_001).is_err());
100    }
101
102    #[test]
103    fn senders_are_counted_apart_and_zero_turns_the_limit_off() {
104        for _ in 0..5 {
105            allow_at("rate-test-c", 5, 1).unwrap();
106        }
107        assert!(allow_at("rate-test-c", 5, 2).is_err());
108        assert!(allow_at("job:rate-test-c", 5, 2).is_ok(), "a Job is its own sender");
109        for _ in 0..50 {
110            assert!(allow_at("rate-test-d", 0, 3).is_ok());
111        }
112    }
113
114    #[tokio::test]
115    async fn the_setting_changes_the_limit() {
116        let state = crate::server::tests::test_state();
117        assert_eq!(limit_of(&state), DEFAULT_PER_MINUTE);
118        state.config_watcher.update_settings(serde_json::from_value(serde_json::json!({ SETTING_PER_MINUTE: 2 })).unwrap());
119        assert_eq!(limit_of(&state), 2);
120        state.config_watcher.update_settings(serde_json::from_value(serde_json::json!({ SETTING_PER_MINUTE: 0 })).unwrap());
121        assert_eq!(limit_of(&state), 0, "0 turns the limit off");
122    }
123}