Skip to main content

agentmux_srv_core/backend/tower/
memory_ledger.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The last hour of AgentMux's memory, and what grows unusually in it
5//! (SPEC_TOWER_MEMORY_FIRST_AND_AGENTMUX_BREAKDOWN_2026_10_25.md §7).
6//!
7//! A ring of 360 points at 10-second steps for the total, each part and each
8//! row, in bytes. It lives in srv's memory only, starts empty on a restart,
9//! and is fed by whichever sample comes: Tower's own (every 2 s, thinned to
10//! the steps) or the timer in `app_api::tower_pane` when no Tower is open, so
11//! a Tower opened later shows the past hour.
12//!
13//! Warnings stay inside Tower (spec D6): nothing here notifies anyone or
14//! acts on the memory supervisor.
15
16use std::collections::{HashMap, VecDeque};
17use std::sync::{Mutex, MutexGuard, OnceLock};
18use std::time::{Duration, Instant};
19
20use crate::backend::rpc_types::{
21    TowerMemory, TowerMemoryGrowth, TowerMemoryHistory, TowerMemoryPartId, TowerMemorySeries,
22};
23
24/// The gap between points.
25pub const STEP_MS: u64 = 10_000;
26/// An hour of points.
27pub const POINTS: usize = 360;
28/// With no Tower open the timer samples every this many steps (30 s): one
29/// sample costs about 15-25 ms on a busy Windows machine (debug build), which
30/// every 10 s is over the 0.1% of a core the spec allows, and every 30 s is
31/// under it (spec section 5.4).
32pub const IDLE_EVERY_STEPS: u64 = 3;
33/// The most series kept. About 30 are normal (four parts, a row each for the
34/// agents, panes and AgentMux programs); the cap keeps a runaway of rows
35/// (a build starting hundreds of differently named processes) from growing it.
36const MAX_SERIES: usize = 400;
37
38/// "Grows unusually" (spec §7.3): all of these over the last [`Self::window`]
39/// points. First guesses to tune with the memory lab's noise data, kept in
40/// one place on purpose.
41pub struct GrowthRule {
42    /// At least this big now, bytes.
43    pub floor: u64,
44    /// The points looked at: 30 minutes.
45    pub window: usize,
46    /// The fewest points a line needs before it can be flagged: ten minutes.
47    /// A program starting up grows from nothing to its size in its first
48    /// minutes, which is not a leak.
49    pub min_points: usize,
50    /// Grown by at least this share over its lowest point in the window…
51    pub ratio: f64,
52    /// …and by at least this many bytes.
53    pub gain: u64,
54    /// Not already coming back: still at least this share of the window's highest.
55    pub retreat: f64,
56}
57
58const MB: u64 = 1024 * 1024;
59
60pub const GROWTH: GrowthRule = GrowthRule {
61    floor: 150 * MB,
62    window: 180,
63    min_points: 60,
64    ratio: 1.5,
65    gain: 100 * MB,
66    retreat: 0.9,
67};
68
69/// Whether `points` (one per step, newest last) grows unusually: from the
70/// lowest point in the window, to now, and how many whole minutes ago that
71/// lowest point was.
72pub fn grows_unusually(points: &[u64], rule: &GrowthRule) -> Option<(u64, u64, u32)> {
73    if points.len() < rule.min_points {
74        return None;
75    }
76    let window = &points[points.len().saturating_sub(rule.window)..];
77    let now = *window.last()?;
78    if now < rule.floor {
79        return None;
80    }
81    // The latest lowest point: when the growth began, not when it was flat.
82    let (at, low) = window
83        .iter()
84        .enumerate()
85        .rev()
86        .min_by_key(|(_, v)| **v)
87        .map(|(i, v)| (i, *v))?;
88    let high = *window.iter().max()?;
89    let grew = now.saturating_sub(low);
90    if grew < rule.gain
91        || (now as f64) < (low as f64) * rule.ratio
92        || (now as f64) < (high as f64) * rule.retreat
93    {
94        return None;
95    }
96    let minutes = ((window.len() - 1 - at) as u64 * STEP_MS / 60_000) as u32;
97    Some((low, now, minutes))
98}
99
100/// One key's points, contiguous from `start`.
101struct Series {
102    /// The step (`ms / STEP_MS`) of the first point.
103    start: u64,
104    points: VecDeque<u64>,
105}
106
107impl Series {
108    fn end(&self) -> u64 {
109        self.start + self.points.len() as u64 - 1
110    }
111}
112
113#[derive(Default)]
114pub struct Ledger {
115    series: HashMap<String, Series>,
116    /// The latest step recorded.
117    last: Option<u64>,
118    /// When the first point was taken, ms.
119    since_ms: u64,
120}
121
122fn part_key(part: TowerMemoryPartId) -> &'static str {
123    match part {
124        TowerMemoryPartId::Core => "part:core",
125        TowerMemoryPartId::Panes => "part:panes",
126        TowerMemoryPartId::Agents => "part:agents",
127        TowerMemoryPartId::NotPlaced => "part:not_placed",
128    }
129}
130
131impl Ledger {
132    /// Record `mem` for the step `at_ms` falls in. A step already recorded is
133    /// left alone, which is how Tower's 2-second samples thin to 10 seconds.
134    pub fn record(&mut self, at_ms: u64, mem: &TowerMemory) {
135        let step = at_ms / STEP_MS;
136        if self.last.is_some_and(|l| step <= l) {
137            return;
138        }
139        if self.last.is_none() {
140            self.since_ms = at_ms;
141        }
142        self.last = Some(step);
143        self.push("total", step, mem.total);
144        for part in &mem.parts {
145            self.push(part_key(part.part), step, part.mem);
146            for row in &part.rows {
147                self.push(&row.key, step, row.mem);
148            }
149        }
150        // A key not seen for an hour is gone; one that stopped sooner keeps
151        // its points, so its line ends where the process ended.
152        self.series.retain(|_, s| s.end() + POINTS as u64 > step);
153    }
154
155    fn push(&mut self, key: &str, step: u64, bytes: u64) {
156        if !self.series.contains_key(key) && self.series.len() >= MAX_SERIES {
157            return;
158        }
159        let s = self
160            .series
161            .entry(key.to_string())
162            .or_insert_with(|| Series {
163                start: step,
164                points: VecDeque::with_capacity(POINTS),
165            });
166        // Steps nobody sampled (no Tower is open and the timer runs every
167        // [`IDLE_EVERY_STEPS`], or the machine slept) are drawn as a straight
168        // line to the new point rather than a stair or a cliff.
169        if let Some(&from) = s.points.back() {
170            let missed = step.saturating_sub(s.end() + 1);
171            for k in 1..=missed {
172                let v = from as f64 + (bytes as f64 - from as f64) * k as f64 / (missed + 1) as f64;
173                s.points.push_back(v.round() as u64);
174                if s.points.len() > POINTS {
175                    s.points.pop_front();
176                    s.start += 1;
177                }
178            }
179        }
180        s.points.push_back(bytes);
181        if s.points.len() > POINTS {
182            s.points.pop_front();
183            s.start += 1;
184        }
185    }
186
187    /// What grows unusually now: the keys still being recorded whose
188    /// last half hour passes [`GROWTH`]. Part keys are `part:<id>`.
189    pub fn growth(&self) -> Vec<TowerMemoryGrowth> {
190        let Some(latest) = self.last else {
191            return vec![];
192        };
193        let mut out: Vec<TowerMemoryGrowth> = self
194            .series
195            .iter()
196            .filter(|(_, s)| s.end() == latest)
197            .filter_map(|(key, s)| {
198                let points: Vec<u64> = s.points.iter().copied().collect();
199                let (from, to, minutes) = grows_unusually(&points, &GROWTH)?;
200                Some(TowerMemoryGrowth {
201                    key: key.clone(),
202                    from,
203                    to,
204                    minutes,
205                })
206            })
207            .collect();
208        out.sort_by(|a, b| {
209            (b.to - b.from)
210                .cmp(&(a.to - a.from))
211                .then_with(|| a.key.cmp(&b.key))
212        });
213        out
214    }
215
216    /// Every series, for the charts.
217    pub fn history(&self) -> TowerMemoryHistory {
218        let mut series: Vec<TowerMemorySeries> = self
219            .series
220            .iter()
221            .map(|(key, s)| TowerMemorySeries {
222                key: key.clone(),
223                start_ms: s.start * STEP_MS,
224                points: s.points.iter().copied().collect(),
225            })
226            .collect();
227        series.sort_by(|a, b| a.key.cmp(&b.key));
228        TowerMemoryHistory {
229            step_ms: STEP_MS as u32,
230            since_ms: self.since_ms,
231            series,
232        }
233    }
234}
235
236struct Shared {
237    ledger: Ledger,
238    /// When a sample last reached the ledger, thinned or not.
239    fed: Option<Instant>,
240}
241
242fn shared() -> MutexGuard<'static, Shared> {
243    static GLOBAL: OnceLock<Mutex<Shared>> = OnceLock::new();
244    GLOBAL
245        .get_or_init(|| {
246            Mutex::new(Shared {
247                ledger: Ledger::default(),
248                fed: None,
249            })
250        })
251        .lock()
252        .unwrap_or_else(|e| e.into_inner())
253}
254
255/// Put a sample in srv's ledger and attach what it knows: the keys that grow
256/// unusually, and the hour when `with_history`.
257pub fn feed(mem: &mut TowerMemory, at_ms: u64, with_history: bool) {
258    let mut sh = shared();
259    sh.fed = Some(Instant::now());
260    sh.ledger.record(at_ms, mem);
261    mem.growth = sh.ledger.growth();
262    mem.history = with_history.then(|| sh.ledger.history());
263}
264
265/// Whether a sample reached the ledger within `within`: the timer samples
266/// only when none did.
267pub fn fed_within(within: Duration) -> bool {
268    shared().fed.is_some_and(|f| f.elapsed() < within)
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274    use crate::backend::rpc_types::{TowerMemoryPart, TowerMemoryRow};
275
276    fn row(key: &str, mem: u64) -> TowerMemoryRow {
277        TowerMemoryRow {
278            key: key.to_string(),
279            label: key.to_string(),
280            mem,
281            processes: 1,
282            kind: None,
283            task: None,
284            children: vec![],
285        }
286    }
287
288    /// A sample whose Core part holds one row.
289    fn sample(core: u64, rows: &[(&str, u64)]) -> TowerMemory {
290        let parts = [
291            TowerMemoryPartId::Core,
292            TowerMemoryPartId::Panes,
293            TowerMemoryPartId::Agents,
294            TowerMemoryPartId::NotPlaced,
295        ]
296        .into_iter()
297        .map(|part| TowerMemoryPart {
298            part,
299            mem: if part == TowerMemoryPartId::Core {
300                core
301            } else {
302                0
303            },
304            processes: 1,
305            rows: if part == TowerMemoryPartId::Core {
306                rows.iter().map(|(k, m)| row(k, *m)).collect()
307            } else {
308                vec![]
309            },
310        })
311        .collect();
312        TowerMemory {
313            total: core,
314            processes: 1,
315            unreadable: 0,
316            parts,
317            other_instances: None,
318            metric: "private working set".to_string(),
319            growth: vec![],
320            history: None,
321        }
322    }
323
324    fn get<'a>(h: &'a TowerMemoryHistory, key: &str) -> &'a TowerMemorySeries {
325        h.series
326            .iter()
327            .find(|s| s.key == key)
328            .unwrap_or_else(|| panic!("no series {key}"))
329    }
330
331    fn mbs(v: &[u64]) -> Vec<u64> {
332        v.iter().map(|m| m * MB).collect()
333    }
334
335    /// `n` points ramping from `a` to `b` MB.
336    fn ramp(a: u64, b: u64, n: usize) -> Vec<u64> {
337        (0..n)
338            .map(|i| ((a as i64 + (b as i64 - a as i64) * i as i64 / (n as i64 - 1)) as u64) * MB)
339            .collect()
340    }
341
342    // ── thinning, size, keys, restarts ─────────────────────────────────────
343
344    #[test]
345    fn two_second_samples_thin_to_ten_second_points() {
346        let mut l = Ledger::default();
347        for i in 0..30u64 {
348            l.record(
349                1_000_000 + i * 2_000,
350                &sample(100 + i, &[("core:srv", 100 + i)]),
351            );
352        }
353        // 60 s of 2 s samples: six steps (or seven if the first lands mid-step).
354        let n = get(&l.history(), "total").points.len();
355        assert!((6..=7).contains(&n), "{n} points");
356    }
357
358    #[test]
359    fn a_step_already_recorded_is_left_alone() {
360        let mut l = Ledger::default();
361        l.record(50_000, &sample(1, &[]));
362        l.record(52_000, &sample(2, &[]));
363        l.record(50_000, &sample(3, &[]));
364        assert_eq!(get(&l.history(), "total").points, vec![1]);
365    }
366
367    #[test]
368    fn the_ring_keeps_an_hour_and_its_start_moves_with_it() {
369        let mut l = Ledger::default();
370        for i in 0..(POINTS as u64 + 40) {
371            l.record(i * STEP_MS, &sample(i, &[]));
372        }
373        let h = l.history();
374        let total = get(&h, "total");
375        assert_eq!(total.points.len(), POINTS);
376        assert_eq!(*total.points.last().unwrap(), POINTS as u64 + 39);
377        assert_eq!(
378            total.start_ms,
379            40 * STEP_MS,
380            "the oldest 40 points fell off"
381        );
382        assert_eq!(h.step_ms, 10_000);
383        assert_eq!(
384            h.since_ms, 0,
385            "since the first sample, not the first point kept"
386        );
387    }
388
389    #[test]
390    fn parts_and_rows_have_their_own_series() {
391        let mut l = Ledger::default();
392        l.record(0, &sample(300, &[("core:gpu", 100), ("core:srv", 200)]));
393        let h = l.history();
394        assert_eq!(get(&h, "total").points, vec![300]);
395        assert_eq!(get(&h, "part:core").points, vec![300]);
396        assert_eq!(
397            get(&h, "part:agents").points,
398            vec![0],
399            "a zero part is kept"
400        );
401        assert_eq!(get(&h, "core:gpu").points, vec![100]);
402        assert_eq!(get(&h, "core:srv").points, vec![200]);
403    }
404
405    #[test]
406    fn a_row_that_ended_keeps_its_line_for_an_hour_then_goes() {
407        let mut l = Ledger::default();
408        l.record(0, &sample(10, &[("agent:a", 10)]));
409        l.record(STEP_MS, &sample(0, &[]));
410        let h = l.history();
411        assert_eq!(
412            get(&h, "agent:a").points,
413            vec![10],
414            "the line ends where the process ended"
415        );
416        assert_eq!(get(&h, "total").points.len(), 2);
417        for i in 2..(POINTS as u64) {
418            l.record(i * STEP_MS, &sample(0, &[]));
419        }
420        assert!(
421            l.history().series.iter().any(|s| s.key == "agent:a"),
422            "still within the hour"
423        );
424        l.record(POINTS as u64 * STEP_MS, &sample(0, &[]));
425        assert!(
426            !l.history().series.iter().any(|s| s.key == "agent:a"),
427            "not seen for an hour: dropped"
428        );
429    }
430
431    #[test]
432    fn missed_steps_are_drawn_as_a_straight_line() {
433        let mut l = Ledger::default();
434        l.record(0, &sample(5, &[]));
435        l.record(4 * STEP_MS, &sample(9, &[]));
436        assert_eq!(get(&l.history(), "total").points, vec![5, 6, 7, 8, 9]);
437    }
438
439    #[test]
440    fn a_new_ledger_is_empty_and_says_nothing_grows() {
441        let l = Ledger::default();
442        assert!(l.history().series.is_empty());
443        assert!(l.growth().is_empty());
444    }
445
446    #[test]
447    fn the_series_are_capped() {
448        let mut l = Ledger::default();
449        let names: Vec<String> = (0..MAX_SERIES + 50).map(|i| format!("np:p{i}")).collect();
450        let rows: Vec<(&str, u64)> = names.iter().map(|n| (n.as_str(), 1)).collect();
451        l.record(0, &sample(1, &rows));
452        assert!(l.history().series.len() <= MAX_SERIES);
453        assert!(
454            l.history().series.iter().any(|s| s.key == "total"),
455            "the total is always kept"
456        );
457    }
458
459    // ── the growth flag, the cases the spec pins ───────────────────────────
460
461    fn flagged(points: &[u64]) -> bool {
462        grows_unusually(points, &GROWTH).is_some()
463    }
464
465    #[test]
466    fn steady_800_mb_is_not_flagged() {
467        assert!(!flagged(&mbs(&[800; 180])));
468    }
469
470    #[test]
471    fn growing_from_200_to_400_mb_in_20_minutes_is_flagged() {
472        // Flat for ten minutes, then up over twenty.
473        let mut p = mbs(&[200; 60]);
474        p.extend(ramp(200, 400, 120));
475        let (from, to, minutes) = grows_unusually(&p, &GROWTH).expect("flagged");
476        assert_eq!((from / MB, to / MB), (200, 400));
477        assert!(
478            (19..=20).contains(&minutes),
479            "counted from where it began to grow: {minutes}"
480        );
481    }
482
483    #[test]
484    fn falling_from_900_to_300_then_350_is_not_flagged() {
485        let mut p = ramp(900, 300, 120);
486        p.extend(ramp(300, 350, 60));
487        assert!(!flagged(&p), "+50 MB over its low is under 100 MB");
488    }
489
490    #[test]
491    fn going_from_100_to_160_mb_is_not_flagged() {
492        let mut p = mbs(&[100; 120]);
493        p.extend(ramp(100, 160, 60));
494        assert!(!flagged(&p), "+60% but only +60 MB");
495    }
496
497    #[test]
498    fn going_from_120_to_300_mb_is_flagged() {
499        let mut p = mbs(&[120; 60]);
500        p.extend(ramp(120, 300, 120));
501        assert!(flagged(&p));
502    }
503
504    #[test]
505    fn small_is_never_flagged_whatever_the_share() {
506        assert!(!flagged(&ramp(10, 140, 180)), "under 150 MB now");
507    }
508
509    #[test]
510    fn already_coming_back_is_not_flagged() {
511        let mut p = ramp(200, 600, 120);
512        p.extend(ramp(600, 400, 60));
513        assert!(!flagged(&p), "fell by a third from its highest");
514        let mut q = ramp(200, 600, 120);
515        q.extend(ramp(600, 570, 60));
516        assert!(flagged(&q), "a small dip from the top is still growth");
517    }
518
519    #[test]
520    fn a_line_still_starting_up_is_not_flagged() {
521        assert!(
522            !flagged(&ramp(100, 400, 30)),
523            "five minutes of points: a program warming up"
524        );
525        assert!(
526            flagged(&ramp(100, 400, 60)),
527            "ten minutes of the same climb is"
528        );
529    }
530
531    #[test]
532    fn only_the_last_half_hour_counts() {
533        // Grew long ago, flat since: the last 30 minutes are flat.
534        let mut p = ramp(100, 600, 120);
535        p.extend(mbs(&[600; 200]));
536        assert!(!flagged(&p));
537    }
538
539    #[test]
540    fn the_ledger_flags_a_growing_row_and_its_part() {
541        let mut l = Ledger::default();
542        let mut total = 0;
543        for i in 0..120u64 {
544            let mem = 200 * MB + 200 * MB * i / 119;
545            total = mem;
546            l.record(i * STEP_MS, &sample(mem, &[("core:srv", mem)]));
547        }
548        let g = l.growth();
549        let keys: Vec<&str> = g.iter().map(|g| g.key.as_str()).collect();
550        assert!(
551            keys.contains(&"core:srv") && keys.contains(&"part:core") && keys.contains(&"total"),
552            "{keys:?}"
553        );
554        assert!(!keys.contains(&"part:agents"));
555        assert_eq!(g[0].to, total);
556        assert_eq!(g[0].from, 200 * MB);
557    }
558
559    #[test]
560    fn a_row_that_ended_is_not_flagged() {
561        let mut l = Ledger::default();
562        for i in 0..120u64 {
563            let mem = 200 * MB + 200 * MB * i / 119;
564            l.record(i * STEP_MS, &sample(0, &[("agent:gone", mem)]));
565        }
566        l.record(120 * STEP_MS, &sample(0, &[]));
567        assert!(l.growth().iter().all(|g| g.key != "agent:gone"));
568    }
569}