Skip to main content

agentmux_srv_core/backend/sampler/
schedule.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which sources to sample now, and how soon to look again.
5//!
6//! A **source** is one thing worth measuring (the machine's counters, the
7//! processes of each pane). Nothing runs unless someone holds a **lease** on it:
8//! a named holder asking for it at an interval, until it is released or its
9//! expiry passes. A source runs at the shortest interval among its live leases,
10//! never faster than its own minimum, and slows down while it keeps taking longer
11//! than its budget.
12//!
13//! This is the whole decision, kept pure so it is tested with a fake clock:
14//! [`Scheduler::due`] says what to run, the caller runs it and reports
15//! [`Scheduler::finished`], [`Scheduler::next_wakeup`] says when to look again.
16//! Times are milliseconds on one monotonic clock the caller owns.
17//! docs/reports/REPORT_SYSINFO_REWRITE_AND_MODERN_MONITOR_2026_10_13.md section 5.5.
18
19use std::collections::HashMap;
20
21/// Milliseconds on the caller's monotonic clock.
22pub type Ms = u64;
23
24/// The most a source's interval is stretched for running over budget.
25const MAX_STRETCH: u32 = 4;
26/// Runs well inside the budget, in a row, before a stretch is halved.
27const CALM_RUNS: u32 = 3;
28
29/// The things that can be sampled.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
31pub enum SourceId {
32    /// CPU, memory, network and disk counters for the whole machine.
33    Machine,
34    /// Each pane's processes: CPU, memory and process count, and the cleanup of
35    /// panes whose shell is gone.
36    Panes,
37}
38
39impl SourceId {
40    pub fn name(self) -> &'static str {
41        match self {
42            Self::Machine => "machine",
43            Self::Panes => "panes",
44        }
45    }
46}
47
48/// What a source costs and needs.
49#[derive(Debug, Clone)]
50pub struct SourceSpec {
51    pub id: SourceId,
52    /// Never run more often than this, whatever a lease asks.
53    pub min_interval_ms: Ms,
54    /// How long one run should take. A longer one stretches the interval.
55    pub budget_ms: Ms,
56    /// Sources this one reads, which run first in the same pass. They must be
57    /// declared before it.
58    pub needs: &'static [SourceId],
59}
60
61#[derive(Debug, Clone)]
62struct Lease {
63    holder: String,
64    source: SourceId,
65    interval_ms: Ms,
66    /// `None`: held until released.
67    expires_at: Option<Ms>,
68}
69
70#[derive(Debug, Clone, Default)]
71struct SourceState {
72    /// When it runs next; `None` while nothing holds a lease on it.
73    next_due: Option<Ms>,
74    last_start: Option<Ms>,
75    last_took: Ms,
76    /// 1, 2 or 4: how many times its interval is stretched.
77    stretch: u32,
78    calm: u32,
79    runs: u64,
80    overruns: u64,
81    /// Runs that were due and didn't start for a whole interval or more.
82    skipped: u64,
83}
84
85/// What `sampler.status` reports for one source.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct SourceStatus {
88    pub id: SourceId,
89    pub holders: Vec<String>,
90    /// Between runs now, stretch included; `None` with no lease.
91    pub interval_ms: Option<Ms>,
92    pub stretch: u32,
93    pub last_took_ms: Ms,
94    pub runs: u64,
95    pub overruns: u64,
96    pub skipped: u64,
97}
98
99pub struct Scheduler {
100    specs: Vec<SourceSpec>,
101    leases: Vec<Lease>,
102    state: HashMap<SourceId, SourceState>,
103    /// Sources due within this much of each other run in one pass, so a shared
104    /// input (one process snapshot) is read once for all of them.
105    coalesce_ms: Ms,
106}
107
108impl Scheduler {
109    /// `specs` in dependency order: each source's `needs` come before it.
110    pub fn new(specs: Vec<SourceSpec>, coalesce_ms: Ms) -> Self {
111        for (i, s) in specs.iter().enumerate() {
112            assert!(
113                s.needs.iter().all(|n| specs[..i].iter().any(|p| p.id == *n)),
114                "source {:?} needs a source declared after it",
115                s.id
116            );
117        }
118        let state = specs.iter().map(|s| (s.id, SourceState { stretch: 1, ..Default::default() })).collect();
119        Self { specs, leases: Vec::new(), state, coalesce_ms }
120    }
121
122    /// `holder` wants `source` every `interval_ms` until `expires_at` (`None`:
123    /// until released). A holder has one lease per source, so asking again
124    /// renews it.
125    pub fn lease(&mut self, holder: &str, source: SourceId, interval_ms: Ms, expires_at: Option<Ms>, now: Ms) {
126        match self.leases.iter_mut().find(|l| l.holder == holder && l.source == source) {
127            Some(l) => {
128                l.interval_ms = interval_ms;
129                l.expires_at = expires_at;
130            }
131            None => self.leases.push(Lease { holder: holder.to_string(), source, interval_ms, expires_at }),
132        }
133        self.reschedule(source, now);
134    }
135
136    /// Drops all of `holder`'s leases.
137    pub fn release(&mut self, holder: &str, now: Ms) {
138        let sources: Vec<SourceId> = self.leases.iter().filter(|l| l.holder == holder).map(|l| l.source).collect();
139        self.leases.retain(|l| l.holder != holder);
140        for source in sources {
141            self.reschedule(source, now);
142        }
143    }
144
145    /// Drops `holder`'s lease on `source`.
146    pub fn release_source(&mut self, holder: &str, source: SourceId, now: Ms) {
147        self.leases.retain(|l| !(l.holder == holder && l.source == source));
148        self.reschedule(source, now);
149    }
150
151    /// The leases changed, so the interval may have: a source that already ran
152    /// is next due one (new) interval after that run, sooner or later than it was
153    /// planned, and a pending run isn't kept for a viewer that has gone.
154    fn reschedule(&mut self, source: SourceId, now: Ms) {
155        let Some(interval) = self.effective_interval_ms(source, now) else {
156            // Nothing holds it now: forget the plan, so a lease that comes before the
157            // next `due` starts it at once instead of waiting out the old schedule.
158            if let Some(st) = self.state.get_mut(&source) {
159                st.next_due = None;
160            }
161            return;
162        };
163        if let Some(st) = self.state.get_mut(&source) {
164            if let (Some(_), Some(last)) = (st.next_due, st.last_start) {
165                st.next_due = Some((last + interval).max(last + st.last_took));
166            }
167        }
168    }
169
170    fn spec(&self, id: SourceId) -> &SourceSpec {
171        self.specs.iter().find(|s| s.id == id).expect("every SourceId has a spec")
172    }
173
174    fn live(&self, source: SourceId, now: Ms) -> impl Iterator<Item = &Lease> {
175        self.leases.iter().filter(move |l| l.source == source && l.expires_at.is_none_or(|e| e > now))
176    }
177
178    /// Between runs now: the shortest live lease, floored at the source's
179    /// minimum, times its stretch. `None` with no live lease.
180    pub fn effective_interval_ms(&self, source: SourceId, now: Ms) -> Option<Ms> {
181        let wanted = self.live(source, now).map(|l| l.interval_ms).min()?;
182        let stretch = self.state.get(&source).map_or(1, |s| s.stretch.max(1));
183        Some(wanted.max(self.spec(source).min_interval_ms) * Ms::from(stretch))
184    }
185
186    /// The sources to run now, dependencies first, each once. A source with no
187    /// live lease isn't run, and starts at once when it gets one.
188    pub fn due(&mut self, now: Ms) -> Vec<SourceId> {
189        self.leases.retain(|l| l.expires_at.is_none_or(|e| e > now));
190        let ids: Vec<SourceId> = self.specs.iter().map(|s| s.id).collect();
191        let mut run = Vec::new();
192        for id in ids {
193            let leased = self.live(id, now).next().is_some();
194            let st = self.state.get_mut(&id).expect("state for every source");
195            if !leased {
196                st.next_due = None;
197                continue;
198            }
199            let due = *st.next_due.get_or_insert(now);
200            if due <= now + self.coalesce_ms {
201                run.push(id);
202            }
203        }
204        // What a due source reads runs with it, leased or not.
205        let mut wanted = run.clone();
206        for id in &run {
207            wanted.extend_from_slice(self.spec(*id).needs);
208        }
209        self.specs.iter().map(|s| s.id).filter(|id| wanted.contains(id)).collect()
210    }
211
212    /// When to call [`Self::due`] next; `None` when nothing is leased.
213    pub fn next_wakeup(&self, now: Ms) -> Option<Ms> {
214        self.planned_wakeup(now).map(|t| t.max(now))
215    }
216
217    /// When the next run was planned for, even if that is already past: how late the loop got round to it
218    /// is `now` less this.
219    pub fn planned_wakeup(&self, now: Ms) -> Option<Ms> {
220        self.specs
221            .iter()
222            .filter(|s| self.live(s.id, now).next().is_some())
223            .map(|s| self.state[&s.id].next_due.unwrap_or(now))
224            .min()
225    }
226
227    /// A run of `id` that started at `started` took `took_ms`. Schedules its next
228    /// run from its start, never sooner than its end, and never to make up for a
229    /// late one: a source that fell behind is counted as having skipped.
230    pub fn finished(&mut self, id: SourceId, started: Ms, took_ms: Ms) {
231        let budget = self.spec(id).budget_ms;
232        let interval_before = self.effective_interval_ms(id, started).unwrap_or(1).max(1);
233        let st = self.state.get_mut(&id).expect("state for every source");
234        let planned = st.next_due.unwrap_or(started);
235        st.skipped += started.saturating_sub(planned) / interval_before;
236        st.runs += 1;
237        st.last_start = Some(started);
238        st.last_took = took_ms;
239        if took_ms > budget {
240            st.overruns += 1;
241            st.calm = 0;
242            st.stretch = (st.stretch.max(1) * 2).min(MAX_STRETCH);
243        } else if took_ms * 2 <= budget {
244            st.calm += 1;
245            if st.calm >= CALM_RUNS && st.stretch > 1 {
246                st.stretch /= 2;
247                st.calm = 0;
248            }
249        } else {
250            st.calm = 0;
251        }
252        let end = started + took_ms;
253        let interval = self.effective_interval_ms(id, end).unwrap_or(interval_before);
254        let st = self.state.get_mut(&id).expect("state for every source");
255        st.next_due = Some((started + interval).max(end));
256    }
257
258    pub fn status(&self, now: Ms) -> Vec<SourceStatus> {
259        self.specs
260            .iter()
261            .map(|s| {
262                let st = &self.state[&s.id];
263                SourceStatus {
264                    id: s.id,
265                    holders: self.live(s.id, now).map(|l| l.holder.clone()).collect(),
266                    interval_ms: self.effective_interval_ms(s.id, now),
267                    stretch: st.stretch.max(1),
268                    last_took_ms: st.last_took,
269                    runs: st.runs,
270                    overruns: st.overruns,
271                    skipped: st.skipped,
272                }
273            })
274            .collect()
275    }
276}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281    use SourceId::{Machine, Panes};
282
283    fn spec(id: SourceId, min: Ms, budget: Ms, needs: &'static [SourceId]) -> SourceSpec {
284        SourceSpec { id, min_interval_ms: min, budget_ms: budget, needs }
285    }
286
287    fn sched() -> Scheduler {
288        Scheduler::new(vec![spec(Machine, 200, 100, &[]), spec(Panes, 500, 200, &[])], 50)
289    }
290
291    /// Runs whatever is due at `now`, each taking `took`, and returns what ran.
292    fn tick(s: &mut Scheduler, now: Ms, took: Ms) -> Vec<SourceId> {
293        let ran = s.due(now);
294        for id in &ran {
295            s.finished(*id, now, took);
296        }
297        ran
298    }
299
300    #[test]
301    fn nothing_leased_means_nothing_due_and_no_wakeup() {
302        let mut s = sched();
303        assert!(s.due(0).is_empty());
304        assert_eq!(s.next_wakeup(0), None);
305    }
306
307    #[test]
308    fn a_new_lease_runs_at_once_then_every_interval() {
309        let mut s = sched();
310        s.lease("bar", Machine, 1000, None, 0);
311        assert_eq!(tick(&mut s, 0, 10), [Machine]);
312        assert_eq!(s.next_wakeup(0), Some(1000));
313        assert!(tick(&mut s, 500, 10).is_empty());
314        assert_eq!(tick(&mut s, 1000, 10), [Machine]);
315        assert_eq!(s.next_wakeup(1000), Some(2000));
316    }
317
318    #[test]
319    fn the_shortest_live_lease_wins_and_releasing_it_slows_the_source() {
320        let mut s = sched();
321        s.lease("janitor", Panes, 30_000, None, 0);
322        tick(&mut s, 0, 10);
323        assert_eq!(s.effective_interval_ms(Panes, 0), Some(30_000));
324        assert_eq!(s.next_wakeup(0), Some(30_000));
325        // A viewer arrives: the source is pulled in to the new interval.
326        s.lease("badge", Panes, 1000, None, 100);
327        assert_eq!(s.effective_interval_ms(Panes, 100), Some(1000));
328        assert_eq!(s.next_wakeup(100), Some(1000));
329        tick(&mut s, 1000, 10);
330        s.release("badge", 1100);
331        assert_eq!(s.effective_interval_ms(Panes, 1100), Some(30_000));
332        // No extra run at the old fast schedule: its next is 30 s after its last.
333        assert_eq!(s.next_wakeup(1100), Some(31_000));
334        assert!(tick(&mut s, 2000, 10).is_empty());
335    }
336
337    #[test]
338    fn releasing_the_last_lease_stops_the_source() {
339        let mut s = sched();
340        s.lease("badge", Panes, 1000, None, 0);
341        tick(&mut s, 0, 10);
342        s.release_source("badge", Panes, 500);
343        assert_eq!(s.next_wakeup(500), None);
344        assert!(tick(&mut s, 1000, 10).is_empty());
345    }
346
347    #[test]
348    fn a_lease_taken_right_after_the_last_was_released_starts_the_source_at_once() {
349        let mut s = sched();
350        s.lease("badge", Panes, 30_000, None, 0);
351        tick(&mut s, 0, 10);
352        // Released and taken again with no `due` in between, well before its run at 30 s.
353        s.release_source("badge", Panes, 500);
354        s.lease("badge", Panes, 30_000, None, 600);
355        assert_eq!(s.next_wakeup(600), Some(600));
356        assert_eq!(tick(&mut s, 600, 10), [Panes]);
357    }
358
359    #[test]
360    fn an_expired_lease_is_forgotten_the_same_way_when_a_new_one_follows() {
361        let mut s = sched();
362        s.lease("badge", Panes, 30_000, Some(1000), 0);
363        tick(&mut s, 0, 10);
364        s.lease("other", Panes, 30_000, None, 2000);
365        assert_eq!(s.next_wakeup(2000), Some(30_000), "the other lease is the only one, and it just ran at 0 on a 30 s interval");
366    }
367
368    #[test]
369    fn renewing_a_lease_with_a_longer_interval_pushes_the_next_run_out() {
370        let mut s = sched();
371        s.lease("bar", Machine, 1000, None, 0);
372        tick(&mut s, 0, 10);
373        s.lease("bar", Machine, 5000, None, 200);
374        assert_eq!(s.next_wakeup(200), Some(5000));
375    }
376
377    #[test]
378    fn a_source_never_runs_faster_than_its_own_minimum() {
379        let mut s = sched();
380        s.lease("fast", Machine, 10, None, 0);
381        assert_eq!(s.effective_interval_ms(Machine, 0), Some(200));
382    }
383
384    #[test]
385    fn an_expired_lease_stops_the_source_and_a_new_one_restarts_it_at_once() {
386        let mut s = sched();
387        s.lease("popover", Machine, 1000, Some(3000), 0);
388        assert_eq!(tick(&mut s, 0, 10), [Machine]);
389        assert_eq!(tick(&mut s, 2000, 10), [Machine]);
390        assert!(tick(&mut s, 3000, 10).is_empty(), "expired exactly at 3000");
391        assert_eq!(s.next_wakeup(3000), None);
392        s.lease("popover", Machine, 1000, Some(9000), 5000);
393        assert_eq!(tick(&mut s, 5000, 10), [Machine], "no waiting out the old schedule");
394    }
395
396    #[test]
397    fn renewing_a_lease_replaces_it() {
398        let mut s = sched();
399        s.lease("a", Machine, 1000, Some(2000), 0);
400        s.lease("a", Machine, 1000, Some(8000), 1500);
401        assert_eq!(s.status(1500)[0].holders, ["a"]);
402        assert_eq!(tick(&mut s, 3000, 10), [Machine]);
403    }
404
405    #[test]
406    fn sources_due_close_together_run_in_one_pass() {
407        let mut s = sched();
408        s.lease("a", Machine, 1000, None, 0);
409        s.lease("a", Panes, 1000, None, 0);
410        tick(&mut s, 0, 10);
411        tick(&mut s, 0, 10);
412        // Machine is due at 1000, Panes at 1000 too; one arriving 30 ms late is
413        // still in the pass, one 200 ms late is not.
414        s.finished(Panes, 30, 10);
415        assert_eq!(s.due(1000), [Machine, Panes]);
416    }
417
418    #[test]
419    fn what_a_due_source_reads_runs_with_it_even_without_a_lease() {
420        let mut s = Scheduler::new(vec![spec(Machine, 200, 100, &[]), spec(Panes, 500, 200, &[Machine])], 50);
421        s.lease("badge", Panes, 1000, None, 0);
422        assert_eq!(s.due(0), [Machine, Panes]);
423        // Not leased itself, so it isn't in the status as wanted.
424        assert!(s.status(0)[0].holders.is_empty());
425    }
426
427    #[test]
428    #[should_panic(expected = "declared after")]
429    fn a_need_declared_later_is_refused() {
430        Scheduler::new(vec![spec(Panes, 500, 200, &[Machine]), spec(Machine, 200, 100, &[])], 50);
431    }
432
433    #[test]
434    fn a_source_over_budget_is_stretched_up_to_four_times_and_eases_back_when_calm() {
435        let mut s = sched();
436        s.lease("bar", Panes, 1000, None, 0);
437        let mut now = 0;
438        for expected in [2, 4, 4] {
439            tick(&mut s, now, 400); // budget 200
440            assert_eq!(s.status(now)[1].stretch, expected);
441            now = s.next_wakeup(now).unwrap();
442        }
443        assert_eq!(s.status(now)[1].overruns, 3);
444        assert_eq!(s.effective_interval_ms(Panes, now), Some(4000));
445        // Three quick runs in a row halve it, three more halve it again.
446        for _ in 0..3 {
447            tick(&mut s, now, 50);
448            now = s.next_wakeup(now).unwrap();
449        }
450        assert_eq!(s.status(now)[1].stretch, 2);
451        for _ in 0..3 {
452            tick(&mut s, now, 50);
453            now = s.next_wakeup(now).unwrap();
454        }
455        assert_eq!(s.status(now)[1].stretch, 1);
456    }
457
458    #[test]
459    fn a_run_in_the_middle_of_the_budget_neither_stretches_nor_eases() {
460        let mut s = sched();
461        s.lease("bar", Panes, 1000, None, 0);
462        tick(&mut s, 0, 400);
463        assert_eq!(s.status(0)[1].stretch, 2);
464        let mut now = s.next_wakeup(0).unwrap();
465        for _ in 0..6 {
466            tick(&mut s, now, 150); // over half the budget, under all of it
467            now = s.next_wakeup(now).unwrap();
468        }
469        assert_eq!(s.status(now)[1].stretch, 2);
470    }
471
472    #[test]
473    fn a_late_tick_is_counted_and_never_made_up_for() {
474        let mut s = sched();
475        s.lease("bar", Machine, 1000, None, 0);
476        tick(&mut s, 0, 10);
477        // The next was due at 1000 but the loop only got round to it at 4500.
478        assert_eq!(tick(&mut s, 4500, 10), [Machine]);
479        assert_eq!(s.status(4500)[0].skipped, 3);
480        assert_eq!(s.next_wakeup(4500), Some(5500), "one interval on, not four runs in a burst");
481    }
482
483    #[test]
484    fn the_planned_wakeup_stays_in_the_past_when_the_loop_is_behind() {
485        let mut s = sched();
486        s.lease("bar", Machine, 1000, None, 0);
487        tick(&mut s, 0, 10);
488        assert_eq!(s.planned_wakeup(5000), Some(1000), "planned for 1000, however late it is now");
489        assert_eq!(s.next_wakeup(5000), Some(5000), "the sleep target is never in the past");
490    }
491
492    #[test]
493    fn a_run_longer_than_its_interval_is_not_started_again_before_it_ends() {
494        let mut s = sched();
495        s.lease("bar", Machine, 200, None, 0);
496        tick(&mut s, 0, 900);
497        assert!(s.next_wakeup(0).unwrap() >= 900);
498    }
499
500    #[test]
501    fn status_names_holders_interval_and_counts() {
502        let mut s = sched();
503        s.lease("bar", Machine, 1000, None, 0);
504        s.lease("popover", Machine, 2000, None, 0);
505        tick(&mut s, 0, 10);
506        let m = &s.status(0)[0];
507        assert_eq!(m.id, Machine);
508        assert_eq!(m.holders, ["bar", "popover"]);
509        assert_eq!((m.interval_ms, m.runs, m.last_took_ms), (Some(1000), 1, 10));
510        let p = &s.status(0)[1];
511        assert_eq!((p.id, p.interval_ms, p.runs), (Panes, None, 0));
512    }
513}