Skip to main content

agentmux_srv/server/
limit_probe.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Finding out that a limited agent can work again when nothing else will say
5//! so. A stored usage limit ends at its reset, a clean turn, a sign-in or an
6//! account move; if the account was changed out of band (the plan was raised,
7//! the limit was lifted by hand) none of those happens, and every message to
8//! the agent stays held. So a message that must not wait (urgent, or naming a
9//! task that waits on the agent) is still held, and in addition one small
10//! turn is started on the pane. A clean turn clears the failure and wakes the
11//! replay, which then sends what was held; a turn that fails again leaves the
12//! agent limited and the message held. The message itself never rides the
13//! probe, so a failed turn loses nothing. Spec:
14//! `docs/specs/SPEC_AGENT_AVAILABILITY_ONE_STATE_2026_10_26.md`.
15
16use std::collections::HashMap;
17use std::sync::{LazyLock, Mutex};
18
19use crate::agents::failure::FailureClass;
20use crate::backend::agent_state::{failure_of_block, AgentState, Unavailable};
21use crate::backend::obj::Block;
22use crate::backend::storage::store::Store;
23use crate::backend::reactive::InjectionRequest;
24
25use super::AppState;
26
27/// The least time between two probes of one agent.
28pub(super) const PROBE_EVERY_MS: u64 = 15 * 60 * 1000;
29
30/// What the agent is asked; any reply is a clean turn.
31pub(super) const PROBE_NOTE: &str =
32    "[AgentMux] A message for you is waiting while your account was out of quota. Reply with the single word: ok";
33
34/// How long after it started a probe's turn is taken to still be running.
35const PROBE_WINDOW_MS: u64 = 10 * 60 * 1000;
36
37static LAST_PROBE: LazyLock<Mutex<HashMap<String, u64>>> = LazyLock::new(Default::default);
38/// The panes with a probe turn in flight, and when it began.
39static PROBING: LazyLock<Mutex<HashMap<String, u64>>> = LazyLock::new(Default::default);
40
41/// Whether a held message to this agent warrants a probe: the agent is out of
42/// quota until a known reset (without one, messages are delivered and a turn
43/// finds out), and the message cannot wait.
44pub(super) fn wants_probe(unavailable: &Unavailable, cannot_wait: bool) -> bool {
45    cannot_wait && unavailable.state == AgentState::Limited && unavailable.resets_at_ms.is_some()
46}
47
48/// Takes the probe slot of `key` if its last probe is at least
49/// [`PROBE_EVERY_MS`] ago; `false` leaves it as it was.
50pub(super) fn take_slot(key: &str, now_ms: u64) -> bool {
51    let mut last = LAST_PROBE.lock().unwrap_or_else(|e| e.into_inner());
52    if last.get(key).is_some_and(|at| now_ms.saturating_sub(*at) < PROBE_EVERY_MS) {
53        return false;
54    }
55    last.insert(key.to_string(), now_ms);
56    true
57}
58
59/// The limit of the agent on `block_id` while its probe turn runs. A turn in
60/// flight makes the pane `working`, so the usual check would let a replay pass
61/// release held messages into the probe, and a probe that fails would lose
62/// them. The hold lasts until the probe clears the stored failure (a clean
63/// turn) or [`PROBE_WINDOW_MS`] has passed. BLOCKING.
64pub(super) fn unavailable_while_probing(mstore: &Store, block_id: &str, now_ms: u64) -> Option<Unavailable> {
65    {
66        let mut probing = PROBING.lock().unwrap_or_else(|e| e.into_inner());
67        let started = *probing.get(block_id)?;
68        if now_ms.saturating_sub(started) >= PROBE_WINDOW_MS {
69            probing.remove(block_id);
70            return None;
71        }
72    }
73    let failure = failure_of_block(&mstore.get::<Block>(block_id).ok()??)?;
74    let resets_at_ms = failure.resets_at_ms.filter(|r| *r > now_ms)?;
75    (failure.code == FailureClass::UsageLimit).then(|| Unavailable {
76        state: AgentState::Limited,
77        code: failure.code,
78        title: failure.title,
79        resets_at_ms: Some(resets_at_ms),
80        since_ms: failure.at_ms.unwrap_or(now_ms).min(now_ms),
81        account_id: None,
82    })
83}
84
85/// After `req` was held for a limited agent: start a probe turn if it
86/// warrants one and the agent's slot is free.
87pub(super) async fn maybe_probe(state: &AppState, req: &InjectionRequest, unavailable: &Unavailable) {
88    if !wants_probe(unavailable, true) {
89        return;
90    }
91    let urgent = crate::backend::cold_hold::asks_to_wake(req.priority.as_deref());
92    let (mstore, identity, request) = (state.mstore.clone(), state.work_store.clone(), req.clone());
93    let now_ms = agentmux_common::time::now_ms_u64();
94    let key = tokio::task::spawn_blocking(move || {
95        let (uid, slug) = super::reactive::defined_here(&mstore, &request.target_agent)?;
96        let cannot_wait =
97            urgent || super::jekt_cold::hands_over_work(&identity, &request, &uid, &slug, agentmux_common::time::now_ms());
98        cannot_wait.then_some(uid)
99    })
100    .await
101    .ok()
102    .flatten();
103    let Some(key) = key else { return };
104    let Some(block_id) = state.reactive_handler.block_for_uid(&key) else { return };
105    if !take_slot(&key, now_ms) {
106        return;
107    }
108    // Before the turn starts, so no replay pass can see the pane working and unheld.
109    PROBING.lock().unwrap_or_else(|e| e.into_inner()).insert(block_id, now_ms);
110    match state.reactive_handler.deliver_system_note(&req.target_agent, PROBE_NOTE) {
111        Ok(()) => tracing::info!(target = %req.target_agent, "limit probe: started a turn to see whether the account can work again"),
112        Err(e) => tracing::info!(target = %req.target_agent, error = %e, "limit probe: not started"),
113    }
114}
115
116/// The least time between two checks a person's message starts on one agent.
117const PERSON_CHECK_EVERY_MS: u64 = 60 * 1000;
118
119/// What [`check_now`] did.
120#[derive(Debug, PartialEq, Eq)]
121pub(super) enum Check {
122    /// A check turn was started.
123    Started,
124    /// One is running, or one started less than a minute ago: its result is the answer.
125    Running,
126    /// None was started, and why (the agent isn't registered, or the note wasn't delivered).
127    NotStarted(String),
128}
129
130/// Starts a check turn on the agent of `block_id` because a person's message waits for it: it does
131/// not wait for the 15-minute slot a message between agents does, but one turn runs at a time and a
132/// new one starts no sooner than a minute after the last. The message itself never rides the turn.
133pub(super) fn check_now(block_id: &str, now_ms: u64) -> Check {
134    let handler = crate::backend::reactive::get_global_handler();
135    let Some(target) = handler
136        .list_agents()
137        .into_iter()
138        .find(|r| r.block_id == block_id)
139        .map(|r| r.uid.filter(|u| !u.is_empty()).unwrap_or(r.agent_id))
140    else {
141        return Check::NotStarted("the agent is not registered".to_string());
142    };
143    if !take_person_check(block_id, now_ms) {
144        return Check::Running;
145    }
146    match handler.deliver_system_note(&target, PROBE_NOTE) {
147        Ok(()) => Check::Started,
148        Err(e) => {
149            PROBING.lock().unwrap_or_else(|e| e.into_inner()).remove(block_id);
150            Check::NotStarted(e)
151        }
152    }
153}
154
155/// Takes the right to start a check on `block_id`, and marks its turn in flight (the hold lasts until it clears
156/// the limit, [`unavailable_while_probing`]). `false` when one runs or ran less than
157/// [`PERSON_CHECK_EVERY_MS`] ago.
158fn take_person_check(block_id: &str, now_ms: u64) -> bool {
159    let mut probing = PROBING.lock().unwrap_or_else(|e| e.into_inner());
160    if probing.get(block_id).is_some_and(|started| now_ms.saturating_sub(*started) < PERSON_CHECK_EVERY_MS) {
161        return false;
162    }
163    probing.insert(block_id.to_string(), now_ms);
164    true
165}
166
167/// The pause between the starts of the check turns of one account.
168const CHECK_STAGGER_MS: u64 = 2_000;
169
170/// How long after the first each check of one account starts: the first at once, the others
171/// [`CHECK_STAGGER_MS`] apart, so the agents of an account do not all start a turn in the same second.
172/// `accounts[i]` is pane `i`'s account (`None`: its own).
173pub(super) fn stagger_delays(accounts: &[Option<&str>]) -> Vec<u64> {
174    let mut seen: HashMap<&str, u64> = HashMap::new();
175    accounts
176        .iter()
177        .map(|account| match account {
178            Some(account) => {
179                let n = seen.entry(account).or_insert(0);
180                *n += 1;
181                (*n - 1) * CHECK_STAGGER_MS
182            }
183            None => 0,
184        })
185        .collect()
186}
187
188/// "Check now" for the panes `block_ids`: each one out of quota gets a check turn (`check_now`),
189/// staggered by account. `Ok` when its check started, runs, or starts in a moment; `Err` says why
190/// not (not out of quota, a route out of credits, not registered). The way to say "the plan changed,
191/// look again", so nobody needs to know that an urgent message is what starts one.
192pub(super) fn check_limited(mstore: &Store, block_ids: &[String]) -> Vec<(String, Result<(), String>)> {
193    let now_ms = agentmux_common::time::now_ms_u64();
194    let found: Vec<Result<Unavailable, String>> = block_ids
195        .iter()
196        .map(|id| match crate::backend::agent_state::unavailable_of_block(mstore, None, id, now_ms) {
197            Some(u) if super::person_hold::is_kept_for_check(&u) => Ok(u),
198            Some(u) => Err(format!("{}: a check cannot change that", u.reason())),
199            None => Err("not out of quota".to_string()),
200        })
201        .collect();
202    let accounts: Vec<Option<&str>> = found.iter().map(|f| f.as_ref().ok().and_then(|u| u.account_id.as_deref())).collect();
203    let delays = stagger_delays(&accounts);
204    block_ids
205        .iter()
206        .zip(found.iter().zip(delays))
207        .map(|(id, (found, delay_ms))| (id.clone(), found.as_ref().map_err(Clone::clone).and_then(|_| start_check(id, delay_ms, now_ms))))
208        .collect()
209}
210
211fn start_check(block_id: &str, delay_ms: u64, now_ms: u64) -> Result<(), String> {
212    if delay_ms == 0 {
213        return match check_now(block_id, now_ms) {
214            Check::NotStarted(why) => Err(why),
215            Check::Started | Check::Running => Ok(()),
216        };
217    }
218    let Ok(runtime) = tokio::runtime::Handle::try_current() else { return Err("no runtime to start the check on".to_string()) };
219    let block_id = block_id.to_string();
220    runtime.spawn(async move {
221        tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
222        if let Check::NotStarted(why) = check_now(&block_id, agentmux_common::time::now_ms_u64()) {
223            tracing::info!(block_id = %block_id, why = %why, "limit check: not started");
224        }
225    });
226    Ok(())
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232    use crate::agents::failure::FailureClass;
233
234    fn unavailable(state: AgentState, resets_at_ms: Option<u64>) -> Unavailable {
235        let code = if state == AgentState::Limited { FailureClass::UsageLimit } else { FailureClass::Auth };
236        Unavailable { state, code, title: String::new(), resets_at_ms, since_ms: 0, account_id: None }
237    }
238
239    #[test]
240    fn only_a_message_that_cannot_wait_probes_an_agent_limited_until_a_known_reset() {
241        assert!(wants_probe(&unavailable(AgentState::Limited, Some(5)), true));
242        assert!(!wants_probe(&unavailable(AgentState::Limited, Some(5)), false), "a routine message waits for the reset");
243        assert!(!wants_probe(&unavailable(AgentState::Limited, None), true), "no reset known: messages are delivered");
244        assert!(!wants_probe(&unavailable(AgentState::SignedOut, None), true), "a sign-in is what ends that");
245    }
246
247    #[test]
248    fn an_agent_is_probed_at_most_once_per_interval() {
249        let key = "probe-test-agent";
250        assert!(take_slot(key, 1_000_000));
251        assert!(!take_slot(key, 1_000_000 + PROBE_EVERY_MS - 1));
252        assert!(take_slot(key, 1_000_000 + PROBE_EVERY_MS));
253        assert!(take_slot("probe-test-other", 1_000_001), "another agent has its own slot");
254    }
255
256    #[test]
257    fn the_checks_of_one_account_start_two_seconds_apart_and_other_accounts_do_not_wait_for_it() {
258        let delays = stagger_delays(&[Some("a"), Some("b"), Some("a"), None, Some("a"), None]);
259        assert_eq!(delays, vec![0, 0, CHECK_STAGGER_MS, 0, 2 * CHECK_STAGGER_MS, 0]);
260    }
261
262    #[test]
263    fn only_a_pane_out_of_its_plans_quota_is_checked() {
264        let store = Store::open_in_memory().unwrap();
265        let now = agentmux_common::time::now_ms_u64();
266        limited_block(&store, "check-test-limited", now, true);
267        let mut healthy = Block { oid: "check-test-healthy".to_string(), ..Default::default() };
268        store.insert(&mut healthy).unwrap();
269        let answers = check_limited(&store, &["check-test-healthy".to_string(), "check-test-gone".to_string()]);
270        assert_eq!(
271            answers,
272            vec![
273                ("check-test-healthy".to_string(), Err("not out of quota".to_string())),
274                ("check-test-gone".to_string(), Err("not out of quota".to_string())),
275            ]
276        );
277        // A limited pane with a process but no agent registered on it: the check cannot start, and says so.
278        crate::backend::agent_state::test_support::register_stub(
279            "check-test-limited",
280            crate::backend::blockcontroller::BLOCK_CONTROLLER_PERSISTENT,
281            crate::backend::blockcontroller::STATUS_RUNNING,
282            false,
283        );
284        let answers = check_limited(&store, &["check-test-limited".to_string()]);
285        crate::backend::blockcontroller::delete_controller("check-test-limited");
286        assert_eq!(answers, vec![("check-test-limited".to_string(), Err("the agent is not registered".to_string()))]);
287    }
288
289    #[test]
290    fn a_persons_check_starts_at_once_but_one_runs_at_a_time_and_not_again_within_a_minute() {
291        let id = "check-test-pane";
292        assert!(take_person_check(id, 1_000_000), "no wait for the 15-minute slot");
293        assert!(!take_person_check(id, 1_000_000 + PERSON_CHECK_EVERY_MS - 1), "one is in flight");
294        assert!(take_person_check(id, 1_000_000 + PERSON_CHECK_EVERY_MS));
295        assert!(take_person_check("check-test-other-pane", 1_000_001), "another agent has its own");
296    }
297
298    fn limited_block(store: &Store, oid: &str, now: u64, with_failure: bool) {
299        let mut b = Block { oid: oid.to_string(), ..Default::default() };
300        if with_failure {
301            b.meta.insert(
302                crate::backend::blockcontroller::core::META_LAST_FAILURE.to_string(),
303                serde_json::json!({"code": "usage_limit", "title": "Usage limit reached", "detail": "", "retryable": false, "resetsAtMs": now + 60_000, "atMs": now - 1_000}),
304            );
305        }
306        store.insert(&mut b).unwrap();
307    }
308
309    #[test]
310    fn the_limit_holds_while_a_probe_runs_and_ends_with_the_probe_or_its_failure() {
311        let store = Store::open_in_memory().unwrap();
312        let now = 5_000_000;
313        limited_block(&store, "probe-test-limited", now, true);
314        limited_block(&store, "probe-test-cleared", now, false);
315        assert_eq!(unavailable_while_probing(&store, "probe-test-limited", now), None, "no probe in flight: the usual check decides");
316        PROBING.lock().unwrap().insert("probe-test-limited".to_string(), now);
317        PROBING.lock().unwrap().insert("probe-test-cleared".to_string(), now);
318        let held = unavailable_while_probing(&store, "probe-test-limited", now + 1).expect("held while the probe runs");
319        assert_eq!((held.state, held.resets_at_ms, held.since_ms), (AgentState::Limited, Some(now + 60_000), now - 1_000));
320        assert_eq!(unavailable_while_probing(&store, "probe-test-cleared", now + 1), None, "a clean turn cleared the failure: replay goes");
321        assert_eq!(unavailable_while_probing(&store, "probe-test-limited", now + 60_001), None, "the reset passed");
322        assert_eq!(unavailable_while_probing(&store, "probe-test-limited", now + PROBE_WINDOW_MS), None, "a probe that never ends stops holding");
323    }
324}