Skip to main content

agentmux_srv/server/app_api/
fleet_pacing.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! When each delivery of a broadcast starts (`fleet::fleet_broadcast_impl`).
5//!
6//! A broadcast used to start a turn on every target in the same second. Each
7//! turn that starts in a pane on screen costs that window's page a burst of
8//! work on its one thread, and sixteen of them in four seconds left the page
9//! drawing four or five frames a second
10//! (docs/reports/REPORT_UI_CHOP_ON_FLEET_BROADCAST_AND_UI_BUSY_METER_2026_11_19.md).
11//!
12//! The starts are spread by what each one costs this AgentMux, as a token
13//! bucket: a small burst goes at once, the rest follow at a steady rate with a
14//! little jitter, and the whole spread has a ceiling. A broadcast to two agents
15//! is as fast as before; one to thirty takes a few seconds. A target that costs
16//! this AgentMux nothing (another machine, another channel) is never delayed,
17//! and a delivery that is slow or fails holds up no other: each starts at its
18//! own time.
19
20use std::collections::HashSet;
21use std::sync::Arc;
22use std::time::Duration;
23
24use super::AppState;
25use crate::backend::obj::{self, Block, Workspace};
26use crate::backend::rpc_types::FleetBroadcastProgressEvent;
27use crate::backend::storage::store::Store;
28
29/// A turn that starts in a pane a window of this AgentMux is showing: its
30/// page draws it.
31pub(crate) const COST_ON_SCREEN: f32 = 1.0;
32/// A turn that starts on this AgentMux in a pane no window is showing: the
33/// machine starts the work and the page gets its messages, but draws nothing.
34pub(crate) const COST_OFF_SCREEN: f32 = 0.25;
35/// A target this AgentMux only hands on (another machine or channel), or one
36/// that has no route and fails at once.
37pub(crate) const COST_NONE: f32 = 0.0;
38
39/// Cost that goes at once, before pacing begins: two panes on screen.
40const BURST: f32 = 2.0;
41/// The time one unit of cost takes after the burst: two and a half turn starts
42/// a second on screen, against the four a second that was too many.
43const GAP: Duration = Duration::from_millis(400);
44/// Each paced start moves by up to this share of its gap, either way, so the
45/// starts do not land on a fixed beat.
46const JITTER: f64 = 0.2;
47/// The last delivery starts no later than this after the send: past it the
48/// gap shrinks instead.
49pub(crate) const CEILING: Duration = Duration::from_secs(6);
50
51/// How long after the send each target's delivery starts, in the order of
52/// `costs` (one per target, a `COST_*`). `noise` gives a value in `0..1` for
53/// each paced start; 0.5 is no jitter.
54pub(crate) fn start_offsets(costs: &[f32], mut noise: impl FnMut() -> f64) -> Vec<Duration> {
55    let total: f32 = costs.iter().map(|c| c.max(0.0)).sum();
56    let paced = (total - BURST).max(0.0) as f64;
57    // The gap for one unit of cost: the steady one, or less when that would pass the ceiling.
58    let gap = if paced > 0.0 { GAP.as_secs_f64().min(CEILING.as_secs_f64() / paced) } else { 0.0 };
59    let mut spent = 0.0_f32;
60    costs
61        .iter()
62        .map(|cost| {
63            let cost = cost.max(0.0);
64            spent += cost;
65            let over = (spent - BURST) as f64;
66            if cost == 0.0 || over <= 0.0 {
67                return Duration::ZERO;
68            }
69            let jitter = (noise().clamp(0.0, 1.0) * 2.0 - 1.0) * JITTER * gap * cost as f64;
70            // In whole milliseconds, so the ceiling is met exactly and not a rounding step short of it.
71            let at_ms = ((over * gap + jitter) * 1000.0).round().clamp(0.0, CEILING.as_millis() as f64);
72            Duration::from_millis(at_ms as u64)
73        })
74        .collect()
75}
76
77/// A repeatable stream of values in `0..1` from `seed` (splitmix64), for the
78/// jitter: a broadcast's own id seeds it, so no random source is needed.
79pub(crate) fn noise_from(seed: u64) -> impl FnMut() -> f64 {
80    let mut state = seed;
81    move || {
82        state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
83        let mut z = state;
84        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
85        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
86        z ^= z >> 31;
87        (z >> 11) as f64 / (1u64 << 53) as f64
88    }
89}
90
91/// Told as each delivery ends: how many have ended, of how many.
92type Progress = Arc<dyn Fn(usize, usize) + Send + Sync>;
93
94/// One broadcast's pace: when each target starts, and who hears as each
95/// delivery ends.
96pub(crate) struct Pace {
97    offsets: Vec<Duration>,
98    began: tokio::time::Instant,
99    progress: Option<Progress>,
100}
101
102impl Pace {
103    /// Every delivery at once, and nobody told.
104    pub(crate) fn at_once() -> Self {
105        Self::new(Vec::new(), None)
106    }
107
108    /// `offsets` in the order of the targets; a target past its end starts at once.
109    pub(crate) fn new(offsets: Vec<Duration>, progress: Option<Progress>) -> Self {
110        Self { offsets, began: tokio::time::Instant::now(), progress }
111    }
112
113    /// Returns when target `index` may start.
114    pub(crate) async fn until_start(&self, index: usize) {
115        if let Some(offset) = self.offsets.get(index).filter(|d| !d.is_zero()) {
116            tokio::time::sleep_until(self.began + *offset).await;
117        }
118    }
119
120    /// One more delivery has ended, delivered or failed: `done` of `total`.
121    pub(crate) fn ended(&self, done: usize, total: usize) {
122        if let Some(progress) = &self.progress {
123            progress(done, total);
124        }
125    }
126}
127
128/// Those of `block_ids` a window of this AgentMux is showing: in the active
129/// tab of a workspace that a window has open.
130pub(crate) fn blocks_on_screen(store: &Store, block_ids: &[String]) -> HashSet<String> {
131    let windows = store.get_all::<obj::Window>().unwrap_or_default();
132    let shown_tabs: HashSet<String> = store
133        .get_all::<Workspace>()
134        .unwrap_or_default()
135        .into_iter()
136        .filter(|ws| !ws.activetabid.is_empty() && windows.iter().any(|w| w.workspaceid == ws.oid))
137        .map(|ws| ws.activetabid)
138        .collect();
139    block_ids
140        .iter()
141        .filter(|id| {
142            let tab = store.get::<Block>(id).ok().flatten().and_then(|b| b.parentoref.strip_prefix("tab:").map(str::to_string));
143            tab.is_some_and(|t| shown_tabs.contains(&t))
144        })
145        .cloned()
146        .collect()
147}
148
149/// What each of `targets` costs this AgentMux: `local` holds the ones that
150/// start a turn here, `on_screen` those of them a window is showing.
151pub(crate) fn costs_of(targets: &[String], local: &HashSet<String>, on_screen: &HashSet<String>) -> Vec<f32> {
152    targets
153        .iter()
154        .map(|t| match (local.contains(t), on_screen.contains(t)) {
155            (true, true) => COST_ON_SCREEN,
156            (true, false) => COST_OFF_SCREEN,
157            (false, _) => COST_NONE,
158        })
159        .collect()
160}
161
162/// The longest `progress_id` a sender may give (a UUID is 36).
163const PROGRESS_ID_MAX: usize = 64;
164
165/// The pace for one broadcast to `targets`, of which `local` start a turn on
166/// this AgentMux. With a `progress_id`, each delivery that ends is published
167/// as `fleetbroadcastprogress`.
168pub(crate) async fn pace_for(state: &AppState, targets: &[String], local: HashSet<String>, msg_id: &str, progress_id: Option<String>) -> Pace {
169    let (store, ids) = (state.mstore.clone(), local.iter().cloned().collect::<Vec<_>>());
170    // If the look fails every local target counts as off screen: paced lightly, never held up.
171    let on_screen = tokio::task::spawn_blocking(move || blocks_on_screen(&store, &ids)).await.unwrap_or_default();
172    let seed = uuid::Uuid::parse_str(msg_id).map(|id| id.as_u128() as u64).unwrap_or_default();
173    let offsets = start_offsets(&costs_of(targets, &local, &on_screen), noise_from(seed));
174    let progress = progress_id.filter(|id| !id.is_empty() && id.len() <= PROGRESS_ID_MAX).map(|id| {
175        let broker = state.broker.clone();
176        Arc::new(move |done: usize, total: usize| {
177            let event = FleetBroadcastProgressEvent { id: id.clone(), sent: done as u32, total: total as u32 };
178            broker.publish_event::<crate::backend::mps_events::FleetBroadcastProgress>(&event, vec![], 0);
179        }) as Progress
180    });
181    Pace::new(offsets, progress)
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187
188    fn ms(costs: &[f32]) -> Vec<u64> {
189        start_offsets(costs, || 0.5).iter().map(|d| d.as_millis() as u64).collect()
190    }
191
192    #[test]
193    fn one_or_two_agents_get_it_at_once() {
194        assert_eq!(ms(&[COST_ON_SCREEN]), vec![0]);
195        assert_eq!(ms(&[COST_ON_SCREEN, COST_ON_SCREEN]), vec![0, 0]);
196        assert!(ms(&[]).is_empty());
197    }
198
199    #[test]
200    fn past_the_burst_the_starts_follow_at_a_steady_rate() {
201        assert_eq!(ms(&[COST_ON_SCREEN; 5]), vec![0, 0, 400, 800, 1200]);
202    }
203
204    #[test]
205    fn thirty_panes_on_screen_finish_at_the_ceiling_not_after_it() {
206        let offsets = ms(&[COST_ON_SCREEN; 30]);
207        assert_eq!(&offsets[..2], &[0, 0]);
208        assert_eq!(*offsets.last().unwrap(), CEILING.as_millis() as u64);
209        assert!(offsets.windows(2).all(|w| w[0] <= w[1]));
210        // The gap shrank: 28 paced starts in 6 s, not 28 x 400 ms.
211        assert_eq!(offsets[2], 214);
212    }
213
214    #[test]
215    fn a_target_that_costs_nothing_is_never_delayed_wherever_it_sits() {
216        let costs = [COST_ON_SCREEN, COST_NONE, COST_ON_SCREEN, COST_ON_SCREEN, COST_NONE, COST_ON_SCREEN];
217        assert_eq!(ms(&costs), vec![0, 0, 0, 400, 0, 800]);
218        assert_eq!(ms(&[COST_NONE; 40]), vec![0; 40]);
219    }
220
221    #[test]
222    fn a_pane_no_window_shows_takes_a_quarter_of_a_slot() {
223        let costs = [COST_ON_SCREEN, COST_ON_SCREEN, COST_OFF_SCREEN, COST_OFF_SCREEN, COST_OFF_SCREEN, COST_OFF_SCREEN, COST_ON_SCREEN];
224        assert_eq!(ms(&costs), vec![0, 0, 100, 200, 300, 400, 800]);
225    }
226
227    // The broadcast the report describes: 31 targets, 14 of them panes in the sender's window.
228    #[test]
229    fn fourteen_panes_among_thirty_one_targets_start_over_about_five_seconds() {
230        let mut costs = vec![COST_NONE; 31];
231        for c in costs.iter_mut().step_by(2).take(14) {
232            *c = COST_ON_SCREEN;
233        }
234        let offsets = ms(&costs);
235        let on_screen: Vec<u64> = offsets.iter().zip(&costs).filter(|(_, c)| **c > 0.0).map(|(o, _)| *o).collect();
236        assert_eq!(on_screen.len(), 14);
237        assert_eq!(on_screen.last(), Some(&4800));
238        // Four starts on screen in the first second (the burst and two more), three in any later one.
239        for (i, at) in on_screen.iter().enumerate() {
240            let in_the_next_second = on_screen[i..].iter().filter(|o| **o < at + 1000).count();
241            assert!(in_the_next_second <= 4, "{in_the_next_second} starts within a second of {at} ms");
242        }
243        assert!(offsets.iter().zip(&costs).filter(|(_, c)| **c == 0.0).all(|(o, _)| *o == 0));
244    }
245
246    #[test]
247    fn jitter_moves_a_start_by_a_fifth_of_its_gap_at_most_and_never_before_the_send_or_past_the_ceiling() {
248        let early: Vec<u64> = start_offsets(&[COST_ON_SCREEN; 5], || 0.0).iter().map(|d| d.as_millis() as u64).collect();
249        let late: Vec<u64> = start_offsets(&[COST_ON_SCREEN; 5], || 1.0).iter().map(|d| d.as_millis() as u64).collect();
250        assert_eq!(early, vec![0, 0, 320, 720, 1120]);
251        assert_eq!(late, vec![0, 0, 480, 880, 1280]);
252        let capped = start_offsets(&[COST_ON_SCREEN; 30], || 1.0);
253        assert!(capped.iter().all(|d| *d <= CEILING));
254        // A value outside 0..1 is treated as the nearest end.
255        assert_eq!(start_offsets(&[COST_ON_SCREEN; 3], || 7.0)[2].as_millis(), 480);
256    }
257
258    #[test]
259    fn the_noise_is_repeatable_per_seed_and_stays_in_range() {
260        let mut a = noise_from(42);
261        let mut b = noise_from(42);
262        let mut c = noise_from(43);
263        let first: Vec<f64> = (0..50).map(|_| a()).collect();
264        assert_eq!(first, (0..50).map(|_| b()).collect::<Vec<f64>>());
265        assert_ne!(first, (0..50).map(|_| c()).collect::<Vec<f64>>());
266        assert!(first.iter().all(|v| (0.0..1.0).contains(v)));
267        // Not stuck on one side of the middle.
268        assert!(first.iter().any(|v| *v < 0.5) && first.iter().any(|v| *v > 0.5));
269    }
270
271    fn tab_in(store: &Store, active: bool, with_window: bool) -> String {
272        use crate::backend::obj::Tab;
273        let mut shown = Tab { oid: uuid::Uuid::new_v4().to_string(), ..Default::default() };
274        let mut other = Tab { oid: uuid::Uuid::new_v4().to_string(), ..Default::default() };
275        store.insert(&mut shown).unwrap();
276        store.insert(&mut other).unwrap();
277        let mut ws = Workspace { oid: uuid::Uuid::new_v4().to_string(), tabids: vec![shown.oid.clone(), other.oid.clone()], activetabid: shown.oid.clone(), ..Default::default() };
278        store.insert(&mut ws).unwrap();
279        if with_window {
280            let mut w = obj::Window { oid: uuid::Uuid::new_v4().to_string(), workspaceid: ws.oid.clone(), ..Default::default() };
281            store.insert(&mut w).unwrap();
282        }
283        if active { shown.oid } else { other.oid }
284    }
285
286    fn block_in(store: &Store, tab_id: &str) -> String {
287        let mut block = Block { oid: uuid::Uuid::new_v4().to_string(), parentoref: format!("tab:{tab_id}"), ..Default::default() };
288        store.insert(&mut block).unwrap();
289        block.oid
290    }
291
292    #[test]
293    fn a_pane_is_on_screen_only_in_the_active_tab_of_a_workspace_a_window_shows() {
294        let store = Store::open_in_memory().unwrap();
295        let shown = block_in(&store, &tab_in(&store, true, true));
296        let background_tab = block_in(&store, &tab_in(&store, false, true));
297        let no_window = block_in(&store, &tab_in(&store, true, false));
298        let ids = vec![shown.clone(), background_tab, no_window, "no-such-block".to_string()];
299        assert_eq!(blocks_on_screen(&store, &ids), HashSet::from([shown]));
300        assert!(blocks_on_screen(&store, &[]).is_empty());
301    }
302
303    #[test]
304    fn a_target_costs_by_where_its_turn_runs_and_whether_a_window_shows_it() {
305        let targets: Vec<String> = ["shown", "hidden", "remote"].iter().map(|s| s.to_string()).collect();
306        let local = HashSet::from(["shown".to_string(), "hidden".to_string()]);
307        let on_screen = HashSet::from(["shown".to_string()]);
308        assert_eq!(costs_of(&targets, &local, &on_screen), vec![COST_ON_SCREEN, COST_OFF_SCREEN, COST_NONE]);
309    }
310
311    fn ids(n: usize) -> Vec<String> {
312        (0..n).map(|i| format!("blk-{i}")).collect()
313    }
314
315    /// Runs a broadcast to `n` panes on screen, each delivery taking `each`, and gives back when each started
316    /// (ms after the send, in target order) and the progress reports as they came.
317    async fn paced_run(n: usize, each: Duration) -> (Vec<u64>, Vec<(usize, usize)>) {
318        use std::sync::Mutex;
319        let began = tokio::time::Instant::now();
320        let starts: Arc<Mutex<Vec<(String, u64)>>> = Arc::default();
321        let reports: Arc<Mutex<Vec<(usize, usize)>>> = Arc::default();
322        let (starts2, reports2) = (starts.clone(), reports.clone());
323        let pace = Pace::new(start_offsets(&vec![COST_ON_SCREEN; n], || 0.5), Some(Arc::new(move |done: usize, total: usize| reports2.lock().unwrap().push((done, total)))));
324        let out = super::super::fleet::run_broadcast(ids(n), "x", "m", pace, |b| Some(format!("agent-{b}")), move |block, _text, _origin| {
325            starts2.lock().unwrap().push((block, began.elapsed().as_millis() as u64));
326            async move {
327                tokio::time::sleep(each).await;
328                Ok(())
329            }
330        })
331        .await;
332        assert_eq!(out.iter().map(|o| o.block_id.clone()).collect::<Vec<_>>(), ids(n), "outcomes come back in target order");
333        let starts = starts.lock().unwrap();
334        let at = |id: &String| starts.iter().find(|(b, _)| b == id).map(|(_, ms)| *ms).unwrap();
335        let in_order = ids(n).iter().map(at).collect();
336        let reports = reports.lock().unwrap().clone();
337        (in_order, reports)
338    }
339
340    #[tokio::test(start_paused = true)]
341    async fn deliveries_start_at_their_paced_times_and_the_sender_hears_of_each() {
342        let (starts, reports) = paced_run(5, Duration::ZERO).await;
343        assert_eq!(starts, vec![0, 0, 400, 800, 1200]);
344        assert_eq!(reports, vec![(1, 5), (2, 5), (3, 5), (4, 5), (5, 5)]);
345    }
346
347    // Each delivery takes two seconds, far longer than the gap: the later ones still start on time.
348    #[tokio::test(start_paused = true)]
349    async fn a_slow_delivery_holds_up_no_other() {
350        let (starts, reports) = paced_run(5, Duration::from_secs(2)).await;
351        assert_eq!(starts, vec![0, 0, 400, 800, 1200]);
352        assert_eq!(reports.last(), Some(&(5, 5)));
353    }
354
355    #[tokio::test(start_paused = true)]
356    async fn two_agents_are_sent_to_at_once() {
357        let (starts, reports) = paced_run(2, Duration::ZERO).await;
358        assert_eq!(starts, vec![0, 0]);
359        assert_eq!(reports, vec![(1, 2), (2, 2)]);
360    }
361}