Skip to main content

agentmux_srv_core/backend/sampler/
late_tick.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The sampler's own lateness, as a log line. A chart draws a break after 3 s without a sample, and the
5//! sampler runs on the same runtime as everything else, so a tick that comes late is that runtime (or the
6//! machine) not running it. Without a record, whether chart gaps happen, and how often, is a guess.
7//! docs/analysis/ANALYSIS_SRV_HTTP_STALL_IO_DRIVER_STARVATION_2026_09_26.md section 9.
8
9/// A tick later than this is logged: close enough to the chart's 3 s break to show it coming.
10pub const LATE_TICK_WARN_MS: u64 = 2_000;
11/// At most one line per this long; the ones in between are counted into the next.
12pub const LATE_TICK_LOG_EVERY_MS: u64 = 60_000;
13
14/// What to say about one late tick.
15#[derive(Debug, PartialEq, Eq)]
16pub struct LateTick {
17    pub late_ms: u64,
18    /// Late ticks not logged since the last line.
19    pub also: u32,
20}
21
22#[derive(Default)]
23pub struct LateTickLog {
24    last_logged_ms: Option<u64>,
25    held: u32,
26}
27
28impl LateTickLog {
29    /// A tick the scheduler planned for `due_ms` (even if that was already past when the loop got there)
30    /// that ran at `now_ms` (the same clock): `Some` when it is late enough to log and the last line was
31    /// long enough ago.
32    pub fn check(&mut self, due_ms: u64, now_ms: u64) -> Option<LateTick> {
33        let late_ms = now_ms.saturating_sub(due_ms);
34        if late_ms < LATE_TICK_WARN_MS {
35            return None;
36        }
37        if self.last_logged_ms.is_some_and(|t| now_ms.saturating_sub(t) < LATE_TICK_LOG_EVERY_MS) {
38            self.held += 1;
39            return None;
40        }
41        self.last_logged_ms = Some(now_ms);
42        Some(LateTick { late_ms, also: std::mem::take(&mut self.held) })
43    }
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49
50    #[test]
51    fn a_tick_on_time_or_a_little_late_says_nothing() {
52        let mut log = LateTickLog::default();
53        assert_eq!(log.check(10_000, 10_000), None);
54        assert_eq!(log.check(10_000, 10_000 + LATE_TICK_WARN_MS - 1), None);
55        assert_eq!(log.check(10_000, 9_000), None, "early is not late");
56    }
57
58    #[test]
59    fn a_late_tick_is_logged_and_the_next_ones_are_held_then_counted() {
60        let mut log = LateTickLog::default();
61        assert_eq!(log.check(10_000, 13_000), Some(LateTick { late_ms: 3_000, also: 0 }));
62        assert_eq!(log.check(20_000, 24_000), None);
63        assert_eq!(log.check(30_000, 35_000), None);
64        let after = 13_000 + LATE_TICK_LOG_EVERY_MS;
65        assert_eq!(log.check(after - 2_500, after), Some(LateTick { late_ms: 2_500, also: 2 }));
66    }
67}