Skip to main content

agentmux_srv_core/backend/supervisor/
pacing.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! How fast the Supervisor continues, with no I/O: the wait between a turn's
5//! end and its continuation, the fleet budget of continuations per hour, and
6//! which notice group a stop belongs to. Spec ยง6.2.
7
8use std::collections::VecDeque;
9
10use super::policy::Action;
11use super::settings::NoticeGroup;
12use super::{SupervisorState, SupervisorStatus, Verdict};
13
14const HOUR_MS: u64 = 60 * 60 * 1000;
15
16/// Continuations sent in the last hour, across every pane. In memory: a restart starts a fresh hour.
17#[derive(Debug, Default)]
18pub struct Budget {
19    /// (reservation number, when) in the order they were taken.
20    sent: VecDeque<(u64, u64)>,
21    next: u64,
22}
23
24impl Budget {
25    /// Count a continuation sent at `now_ms` if fewer than `cap` went in the last
26    /// hour (`cap` 0 is no cap) and return its reservation number for [`Budget::refund`];
27    /// else `Err` with the milliseconds until one is free.
28    pub fn spend(&mut self, now_ms: u64, cap: u32) -> Result<u64, u64> {
29        while self.sent.front().is_some_and(|(_, t)| now_ms.saturating_sub(*t) >= HOUR_MS) {
30            self.sent.pop_front();
31        }
32        if cap > 0 && self.sent.len() >= cap as usize {
33            let oldest = self.sent.front().map_or(now_ms, |(_, t)| *t);
34            return Err((oldest + HOUR_MS).saturating_sub(now_ms));
35        }
36        self.next += 1;
37        self.sent.push_back((self.next, now_ms));
38        Ok(self.next)
39    }
40
41    /// How many continuations went in the hour before `now_ms`.
42    pub fn sent_in_hour(&self, now_ms: u64) -> usize {
43        self.sent.iter().filter(|(_, t)| now_ms.saturating_sub(*t) < HOUR_MS).count()
44    }
45}
46
47impl Budget {
48    /// Take back reservation `ticket` when its continuation turned out not to be sent,
49    /// whatever was reserved after it.
50    pub fn refund(&mut self, ticket: u64) {
51        self.sent.retain(|(n, _)| *n != ticket);
52    }
53}
54
55/// The sentence a pane shows when the fleet budget stops its continuation: what went out in the
56/// last hour, the cap, and when there is room again.
57pub fn budget_reached(sent: usize, cap: u32, wait_ms: u64) -> String {
58    let minutes = wait_ms.div_ceil(60_000).max(1);
59    let noun = if sent == 1 { "continuation" } else { "continuations" };
60    format!(
61        "Fleet budget reached: {sent} {noun} in the last hour (the cap is {cap}). It can continue again in about {minutes} min."
62    )
63}
64
65/// The start of a pane's reason while its continuation waits ("Continuing after a 30 s wait: ...").
66/// It names the wait, not the time left, so it is true for as long as the pane shows it.
67pub const WAIT_PREFIX: &str = "Continuing after a ";
68/// What v0.60.3 wrote, which a pane saved by it may still carry.
69const LEGACY_WAIT_PREFIX: &str = "Continuing in ";
70
71/// What a pane says when AgentMux restarted during a continuation's wait: the wait is not persisted.
72pub const RESTARTED: &str = "Not continued: AgentMux restarted.";
73
74/// Clear a "Continuing after a ..." line left by a previous run of srv, whose wait is gone. Whether it changed.
75pub fn drop_restarted_wait(state: &mut SupervisorState) -> bool {
76    if state.status != SupervisorStatus::Waiting || !(state.reason.starts_with(WAIT_PREFIX) || state.reason.starts_with(LEGACY_WAIT_PREFIX)) {
77        return false;
78    }
79    state.status = SupervisorStatus::Watching;
80    state.reason = RESTARTED.to_string();
81    true
82}
83
84/// What a waiting continuation checks when its wait is over.
85#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
86pub struct WaitOver {
87    /// A newer turn end or a mode change has taken the pane over.
88    pub superseded: bool,
89    pub switched_off: bool,
90    pub mode_changed: bool,
91    /// A turn is running now: the user's message, a jekt, a job, a Schedule injection.
92    pub turn_running: bool,
93    /// The user's Stop ended the turn.
94    pub stopped: bool,
95}
96
97impl WaitOver {
98    /// Why the continuation is dropped instead of sent, or `None` to send it.
99    /// A continuation never lands after a different turn than the one the judge saw.
100    pub fn drop_reason(&self) -> Option<&'static str> {
101        if self.superseded {
102            Some("superseded")
103        } else if self.switched_off {
104            Some("switched off")
105        } else if self.mode_changed {
106            Some("mode changed")
107        } else if self.turn_running {
108            Some("another turn started")
109        } else if self.stopped {
110            Some("stopped")
111        } else {
112            None
113        }
114    }
115}
116
117/// The notice group of a stop: a question or "blocked" needs the user; a
118/// Continue verdict that a limit turned into a pause hit a limit; an agent
119/// that can't run, or a continuation that couldn't be delivered, failed.
120pub fn pause_group(action: &Action, verdict: Option<Verdict>, undeliverable: bool) -> NoticeGroup {
121    match (action, verdict) {
122        _ if undeliverable => NoticeGroup::Failed,
123        (Action::Pause(_), Some(Verdict::NeedsUser | Verdict::Blocked)) => NoticeGroup::NeedsYou,
124        (Action::Pause(_), _) => NoticeGroup::Limit,
125        _ => NoticeGroup::Done,
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    #[test]
134    fn the_budget_stops_at_the_cap_and_frees_a_slot_as_the_hour_rolls() {
135        let mut b = Budget::default();
136        assert!(b.spend(1_000, 2).is_ok());
137        assert!(b.spend(2_000, 2).is_ok());
138        assert_eq!(b.spend(3_000, 2), Err(HOUR_MS - 2_000), "the first one frees a slot an hour after it");
139        assert!(b.spend(1_000 + HOUR_MS, 2).is_ok(), "an hour on, the oldest no longer counts");
140    }
141
142    #[test]
143    fn a_continuation_that_was_not_sent_gives_its_slot_back() {
144        let mut b = Budget::default();
145        let ticket = b.spend(1_000, 1).unwrap();
146        assert!(b.spend(2_000, 1).is_err());
147        b.refund(ticket);
148        assert!(b.spend(3_000, 1).is_ok());
149    }
150
151    #[test]
152    fn a_refund_takes_back_its_own_reservation_not_the_latest() {
153        let mut b = Budget::default();
154        let first = b.spend(1_000, 2).unwrap();
155        b.spend(2_000, 2).unwrap();
156        b.refund(first);
157        assert!(b.spend(3_000, 2).is_ok(), "the first one's slot is free again");
158        assert!(b.spend(4_000, 2).is_err(), "the second one still counts");
159    }
160
161    #[test]
162    fn a_cap_of_zero_is_no_cap() {
163        let mut b = Budget::default();
164        for t in 0..2_000 {
165            assert!(b.spend(t, 0).is_ok());
166        }
167    }
168
169    #[test]
170    fn lowering_the_cap_applies_to_what_was_already_sent() {
171        let mut b = Budget::default();
172        for t in 0..5 {
173            b.spend(t, 10).unwrap();
174        }
175        assert!(b.spend(10, 3).is_err());
176    }
177
178    #[test]
179    fn the_budget_sentence_rounds_up_to_whole_minutes() {
180        assert!(budget_reached(30, 30, 61_000).contains("about 2 min"));
181        assert!(budget_reached(30, 30, 1).contains("about 1 min"));
182    }
183
184    #[test]
185    fn the_budget_sentence_says_what_went_out_and_the_cap() {
186        assert_eq!(
187            budget_reached(1, 1, 3_420_000),
188            "Fleet budget reached: 1 continuation in the last hour (the cap is 1). It can continue again in about 57 min."
189        );
190        assert!(budget_reached(3, 1, 60_000).starts_with("Fleet budget reached: 3 continuations in the last hour (the cap is 1)."));
191    }
192
193    #[test]
194    fn the_budget_counts_only_the_last_hour() {
195        let mut b = Budget::default();
196        b.spend(0, 0).unwrap();
197        b.spend(1_000, 0).unwrap();
198        assert_eq!(b.sent_in_hour(2_000), 2);
199        assert_eq!(b.sent_in_hour(HOUR_MS + 500), 1);
200    }
201
202    #[test]
203    fn a_wait_left_by_a_previous_run_is_cleared_and_nothing_else_is() {
204        let waiting = |reason: &str, status| SupervisorState {
205            status,
206            reason: reason.to_string(),
207            ..SupervisorState::default()
208        };
209        let mut s = waiting("Continuing after a 30 s wait: still has work", SupervisorStatus::Waiting);
210        assert!(drop_restarted_wait(&mut s));
211        assert_eq!((s.status, s.reason.as_str()), (SupervisorStatus::Watching, RESTARTED));
212        assert!(!drop_restarted_wait(&mut s), "a second pass changes nothing");
213        // "Waiting" is also the status of a pane held for its background work.
214        // A wait saved by v0.60.3 reads "Continuing in N s: ...".
215        let mut old = waiting("Continuing in 30 s: still has work", SupervisorStatus::Waiting);
216        assert!(drop_restarted_wait(&mut old));
217        let mut bg = waiting("Waiting for its background work to finish.", SupervisorStatus::Waiting);
218        assert!(!drop_restarted_wait(&mut bg));
219        assert_eq!(bg.status, SupervisorStatus::Waiting);
220    }
221
222    #[test]
223    fn a_waiting_continuation_is_sent_only_when_nothing_has_changed() {
224        assert_eq!(WaitOver::default().drop_reason(), None);
225        let drops = [
226            WaitOver { superseded: true, ..Default::default() },
227            WaitOver { switched_off: true, ..Default::default() },
228            WaitOver { mode_changed: true, ..Default::default() },
229            WaitOver { turn_running: true, ..Default::default() },
230            WaitOver { stopped: true, ..Default::default() },
231        ];
232        for d in drops {
233            assert!(d.drop_reason().is_some(), "{d:?}");
234        }
235    }
236
237    #[test]
238    fn each_stop_belongs_to_one_notice_group() {
239        let pause = Action::Pause("x".into());
240        assert_eq!(pause_group(&pause, Some(Verdict::NeedsUser), false), NoticeGroup::NeedsYou);
241        assert_eq!(pause_group(&pause, Some(Verdict::Blocked), false), NoticeGroup::NeedsYou);
242        assert_eq!(pause_group(&pause, Some(Verdict::Continue), false), NoticeGroup::Limit);
243        assert_eq!(pause_group(&pause, Some(Verdict::Continue), true), NoticeGroup::Failed);
244        assert_eq!(pause_group(&Action::Done("x".into()), Some(Verdict::Done), false), NoticeGroup::Done);
245        assert_eq!(pause_group(&Action::NoVerdict, None, false), NoticeGroup::Done);
246    }
247}