1use 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
27pub(super) const PROBE_EVERY_MS: u64 = 15 * 60 * 1000;
29
30pub(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
34const PROBE_WINDOW_MS: u64 = 10 * 60 * 1000;
36
37static LAST_PROBE: LazyLock<Mutex<HashMap<String, u64>>> = LazyLock::new(Default::default);
38static PROBING: LazyLock<Mutex<HashMap<String, u64>>> = LazyLock::new(Default::default);
40
41pub(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
48pub(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
59pub(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
85pub(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 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
116const PERSON_CHECK_EVERY_MS: u64 = 60 * 1000;
118
119#[derive(Debug, PartialEq, Eq)]
121pub(super) enum Check {
122 Started,
124 Running,
126 NotStarted(String),
128}
129
130pub(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
155fn 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
167const CHECK_STAGGER_MS: u64 = 2_000;
169
170pub(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
188pub(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 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}