Skip to main content

agentmux_srv_core/backend/
limit_evidence.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A clean turn on an account is evidence for the whole account.
5//!
6//! A pane whose run ended on the plan's usage limit stays `limited` until the provider's reset, a clean
7//! turn of its own, a sign-in or an account move (`limit_wake`, `limit_probe`). When the plan is raised
8//! or the limit lifted before the reset, other agents on the same account are already working, and
9//! every pane still marked limited, and the account itself (its state is read from its panes' stored
10//! failures, `account_blocks_at`), waited for the reset days away. So when a turn ends clean on an
11//! account, every other pane of that account whose usage limit was stored before that turn began
12//! has its failure cleared at once, the held-message replay wakes, and each of those agents is told
13//! once to continue, staggered as the reset wake is.
14//!
15//! The scan is a map lookup unless some account has a stored limit: [`note_limited_blocks`] records
16//! the accounts when a limit is stored and at start.
17
18use std::collections::HashSet;
19use std::sync::{Arc, Mutex};
20
21use crate::agents::failure::{AgentFailure, FailureClass, ROUTE_CREDITS_TITLE};
22use crate::backend::agent_state::{failure_of_block, RUN_ACCOUNT_META_KEY};
23use crate::backend::eventbus::EventBus;
24use crate::backend::obj::Block;
25use crate::backend::storage::store::Store;
26
27/// A limit stored less than this before a turn ended clean is left alone: that turn may have been
28/// served just before the limit was hit.
29pub const GRACE_MS: u64 = 30_000;
30
31/// The accounts with a pane whose stored failure is a usage limit.
32static LIMITED_ACCOUNTS: Mutex<Option<HashSet<String>>> = Mutex::new(None);
33
34/// The account a pane's run launched on.
35fn account_of(block: &Block) -> Option<String> {
36    block.meta.get(RUN_ACCOUNT_META_KEY).and_then(|a| a.as_str()).filter(|a| !a.is_empty()).map(str::to_string)
37}
38
39/// Whether `block` holds a usage limit a clean turn on its account can clear: a plan's limit, not a
40/// route out of credits (its own episode ends it, `route_credits`).
41fn holds_plan_limit(block: &Block) -> bool {
42    failure_of_block(block).is_some_and(|f| f.code == FailureClass::UsageLimit && f.title != ROUTE_CREDITS_TITLE)
43}
44
45/// Records the accounts of the panes in `blocks` that hold a usage limit.
46pub fn note_limited_blocks(blocks: &[Block]) {
47    let accounts: Vec<String> = blocks.iter().filter(|b| holds_plan_limit(b)).filter_map(account_of).collect();
48    if accounts.is_empty() {
49        return;
50    }
51    LIMITED_ACCOUNTS.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashSet::new).extend(accounts);
52}
53
54/// A usage limit is being stored for `block_id` (`persist_last_failure`, before the write): records the
55/// pane's account so a clean turn on it looks for the panes to clear. Reads the account from the pane,
56/// not the stored limit, which is not there yet.
57pub fn note_failure(block_id: &str, failure: &AgentFailure, store: &Store) {
58    if failure.code != FailureClass::UsageLimit || failure.title == ROUTE_CREDITS_TITLE {
59        return;
60    }
61    if let Some(account) = store.get::<Block>(block_id).ok().flatten().as_ref().and_then(account_of) {
62        LIMITED_ACCOUNTS.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashSet::new).insert(account);
63    }
64}
65
66fn is_noted(account: &str) -> bool {
67    LIMITED_ACCOUNTS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|set| set.contains(account))
68}
69
70fn forget(account: &str) {
71    if let Some(set) = LIMITED_ACCOUNTS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
72        set.remove(account);
73    }
74}
75
76/// What a clean turn on `account` clears: the panes (other than the one that ran) whose usage limit
77/// was stored at least [`GRACE_MS`] before `now_ms`, and whether any pane of the account still
78/// holds one afterwards.
79#[derive(Debug, PartialEq, Eq)]
80pub(crate) struct Plan {
81    pub clear: Vec<String>,
82    pub still_limited: bool,
83}
84
85pub(crate) fn plan(blocks: &[Block], account: &str, clean_block: &str, now_ms: u64) -> Plan {
86    let mut plan = Plan { clear: Vec::new(), still_limited: false };
87    for block in blocks.iter().filter(|b| b.oid != clean_block && holds_plan_limit(b)) {
88        if account_of(block).as_deref() != Some(account) {
89            continue;
90        }
91        let stored_at = failure_of_block(block).and_then(|f| f.at_ms);
92        // One stored before the field existed has no time: it is old.
93        if stored_at.is_none_or(|at| at.saturating_add(GRACE_MS) <= now_ms) {
94            plan.clear.push(block.oid.clone());
95        } else {
96            plan.still_limited = true;
97        }
98    }
99    plan
100}
101
102/// A turn on `block_id` ended clean. When its account has other panes still marked limited, clears
103/// them, wakes the replay and tells their agents to continue. Returns how many were cleared. A map
104/// lookup when no account has a stored limit. BLOCKING when it has (store reads and writes).
105pub fn clean_turn(block_id: &str, mstore: &Option<Arc<Store>>, event_bus: &Option<Arc<EventBus>>) -> usize {
106    let Some(store) = mstore else { return 0 };
107    if LIMITED_ACCOUNTS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_none_or(HashSet::is_empty) {
108        return 0;
109    }
110    let Some(account) = store.get::<Block>(block_id).ok().flatten().as_ref().and_then(account_of) else { return 0 };
111    if !is_noted(&account) {
112        return 0;
113    }
114    let blocks = store.get_all::<Block>().unwrap_or_default();
115    let Plan { clear, still_limited } = plan(&blocks, &account, block_id, agentmux_common::time::now_ms_u64());
116    for id in &clear {
117        super::blockcontroller::core::persist_last_failure(id, None, mstore, event_bus);
118    }
119    if !still_limited {
120        forget(&account);
121    }
122    if clear.is_empty() {
123        return 0;
124    }
125    tracing::info!(cleared = clear.len(), "limit evidence: a clean turn on the account cleared the limit of its other panes");
126    super::reactive::held_jekt_wake().notify_one();
127    for (n, id) in clear.iter().enumerate() {
128        super::limit_wake::nudge_after(id, n as u64 * super::limit_wake::NUDGE_STAGGER_MS);
129    }
130    clear.len()
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    fn pane(store: &Store, account: Option<&str>, failure: Option<serde_json::Value>) -> Block {
138        let mut b = Block { oid: uuid::Uuid::new_v4().to_string(), ..Default::default() };
139        if let Some(account) = account {
140            b.meta.insert(RUN_ACCOUNT_META_KEY.to_string(), serde_json::json!(account));
141        }
142        if let Some(failure) = failure {
143            b.meta.insert(crate::backend::blockcontroller::core::META_LAST_FAILURE.to_string(), failure);
144        }
145        store.insert(&mut b).unwrap();
146        b
147    }
148
149    fn limit(at_ms: Option<u64>, resets_at_ms: Option<u64>) -> serde_json::Value {
150        let mut f = serde_json::json!({"code": "usage_limit", "title": "Usage limit reached", "detail": "", "retryable": false});
151        if let Some(at) = at_ms {
152            f[crate::backend::blockcontroller::core::META_FAILURE_AT_MS] = serde_json::json!(at);
153        }
154        if let Some(r) = resets_at_ms {
155            f["resetsAtMs"] = serde_json::json!(r);
156        }
157        f
158    }
159
160    const NOW: u64 = 10_000_000;
161
162    #[test]
163    fn a_clean_turn_clears_the_other_panes_of_its_account_that_were_limited_before_it() {
164        let store = Store::open_in_memory().unwrap();
165        let ran = pane(&store, Some("acct-a"), None);
166        let old = pane(&store, Some("acct-a"), Some(limit(Some(NOW - 600_000), Some(NOW + 86_400_000))));
167        let no_time = pane(&store, Some("acct-a"), Some(limit(None, None)));
168        let other_account = pane(&store, Some("acct-b"), Some(limit(Some(NOW - 600_000), None)));
169        let no_account = pane(&store, None, Some(limit(Some(NOW - 600_000), None)));
170        let plan = plan(&[ran.clone(), old.clone(), no_time.clone(), other_account, no_account], "acct-a", &ran.oid, NOW);
171        assert_eq!(plan, Plan { clear: vec![old.oid, no_time.oid], still_limited: false });
172    }
173
174    #[test]
175    fn a_limit_stored_just_before_the_turn_ended_is_kept_and_keeps_the_account_noted() {
176        let store = Store::open_in_memory().unwrap();
177        let ran = pane(&store, Some("acct-a"), None);
178        let fresh = pane(&store, Some("acct-a"), Some(limit(Some(NOW - GRACE_MS + 1), Some(NOW + 60_000))));
179        assert_eq!(plan(&[ran.clone(), fresh], "acct-a", &ran.oid, NOW), Plan { clear: vec![], still_limited: true });
180    }
181
182    #[test]
183    fn a_route_out_of_credits_and_other_failures_are_not_cleared_by_a_clean_turn() {
184        let store = Store::open_in_memory().unwrap();
185        let ran = pane(&store, Some("acct-a"), None);
186        let credits = pane(
187            &store,
188            Some("acct-a"),
189            Some(serde_json::json!({"code": "usage_limit", "title": ROUTE_CREDITS_TITLE, "detail": "", "retryable": false, "atMs": 1})),
190        );
191        let signed_out = pane(&store, Some("acct-a"), Some(serde_json::json!({"code": "auth", "title": "x", "detail": "", "retryable": false, "atMs": 1})));
192        assert_eq!(plan(&[ran.clone(), credits, signed_out], "acct-a", &ran.oid, NOW), Plan { clear: vec![], still_limited: false });
193    }
194
195    #[test]
196    fn a_clean_turn_clears_the_stored_failures_of_its_accounts_other_panes() {
197        let store = Arc::new(Store::open_in_memory().unwrap());
198        let account = format!("acct-{}", uuid::Uuid::new_v4());
199        let ran = pane(&store, Some(&account), None);
200        let limited = pane(&store, Some(&account), Some(limit(Some(1), Some(u64::MAX / 2))));
201        let elsewhere = pane(&store, Some("acct-elsewhere"), Some(limit(Some(1), Some(u64::MAX / 2))));
202        let (mstore, bus) = (Some(store.clone()), None);
203
204        assert_eq!(clean_turn(&ran.oid, &mstore, &bus), 0, "nothing noted yet: nothing is scanned");
205        note_limited_blocks(&store.get_all::<Block>().unwrap());
206        assert_eq!(clean_turn(&ran.oid, &mstore, &bus), 1);
207
208        let stored = |b: &Block| store.get::<Block>(&b.oid).unwrap().unwrap().meta.contains_key("agent:last_failure");
209        assert!(!stored(&limited), "the account's other pane is no longer limited");
210        assert!(stored(&elsewhere), "another account is not spoken for");
211        assert_eq!(clean_turn(&ran.oid, &mstore, &bus), 0, "the account is forgotten once nothing on it is limited");
212    }
213
214    #[test]
215    fn a_limit_stored_through_persist_last_failure_is_noted_before_it_is_written() {
216        let store = Arc::new(Store::open_in_memory().unwrap());
217        let account = format!("acct-{}", uuid::Uuid::new_v4());
218        let ran = pane(&store, Some(&account), None);
219        let hit = pane(&store, Some(&account), None);
220        let (mstore, bus) = (Some(store.clone()), None);
221        let failure: AgentFailure = serde_json::from_value(serde_json::json!({"code": "usage_limit", "title": "Usage limit reached", "detail": "", "stderrTail": "", "retryable": false})).unwrap();
222
223        // The pane hits the limit after startup: nothing was noted by hand.
224        crate::backend::blockcontroller::core::persist_last_failure(&hit.oid, Some(&failure), &mstore, &bus);
225        let stored = |b: &Block| store.get::<Block>(&b.oid).unwrap().unwrap().meta.contains_key("agent:last_failure");
226        assert!(stored(&hit));
227        // Made old enough for the grace window.
228        let mut meta = crate::backend::obj::MetaMapType::new();
229        let mut f = store.get::<Block>(&hit.oid).unwrap().unwrap().meta["agent:last_failure"].clone();
230        f[crate::backend::blockcontroller::core::META_FAILURE_AT_MS] = serde_json::json!(1);
231        meta.insert("agent:last_failure".to_string(), f);
232        crate::backend::wcore::object_meta::update_object_meta(&store, &format!("block:{}", hit.oid), &meta).unwrap();
233
234        assert_eq!(clean_turn(&ran.oid, &mstore, &bus), 1, "a clean turn on the account clears the pane that hit the limit");
235        assert!(!stored(&hit));
236    }
237}