Skip to main content

agentmux_srv_core/backend/gpu/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The GPU's use and memory, for the status bar's GPU meter and its panel
5//! (SPEC_STATUS_BAR_GPU_PANEL_2026_11_15.md).
6//!
7//! **One sampler, and it is srv's:** [`GpuSampler::global`] holds the one open set of counters. The status bar's
8//! compact figure asks it every few seconds from the telemetry thread ([`CompactPoller`]); the panel asks it every
9//! two seconds while it is open (`gpu.sample`). A read newer than the asker's reuse window is handed back instead
10//! of made again, so two askers never read twice in a row. Per-process names are not made here: the panel's handler
11//! takes them from Tower's own sample, which is the one place that names a process.
12//!
13//! **Cost:** reading the counters is the cost, so it is bounded. A read that takes longer than its budget
14//! ([`Budget`]) widens the interval to the next read, and the panel's footer says so; reads never run back to back.
15//! `cost_tests` measures a read (run in CI, and on a machine of its own: `cargo test -p agentmux-srv-core gpu::cost
16//! -- --ignored --nocapture`).
17//!
18//! Windows reads the PDH counters (`pdh`). Linux reads what the kernel and the driver publish (`linux`: AMD's sysfs files,
19//! NVIDIA through NVML loaded at run time, `fdinfo` for the processes, Intel's memory only). macOS is a later phase and
20//! reports [`GpuSampleState::Unsupported`].
21//!
22//! **The panel lists real GPUs only, on every OS, decided by what the OS says an adapter is and never by its name.**
23//! Windows asks the kernel's adapter type (`aggregate::AdapterType`) and drops an indirect display device, an adapter that
24//! cannot render, and the software renderer; Linux lists the PCI bus's display controllers, so a virtual DRM device is
25//! never a row (`linux`). A macOS reader, when it is written, must list only the devices Metal itself reports as GPUs
26//! and treat anything else the same way. Everywhere the one adapter a machine has is shown, however virtual.
27
28pub mod aggregate;
29#[cfg(any(target_os = "linux", test))]
30pub mod drm;
31#[cfg(target_os = "linux")]
32mod linux;
33pub mod names;
34#[cfg(target_os = "linux")]
35mod nvml;
36#[cfg(windows)]
37mod pdh;
38
39use crate::backend::rpc_types::{GpuOthers, GpuProcess, GpuSampleState, TowerProcessKind};
40use aggregate::{memory_share, ProcessFigures, Reading};
41use std::sync::{Mutex, OnceLock};
42use std::time::{Duration, Instant};
43
44/// A read slower than this widens the interval to the next one.
45pub const READ_BUDGET: Duration = Duration::from_millis(50);
46/// How often the status bar's figure is read, and the longest it is stretched to.
47pub const COMPACT_EVERY: Duration = Duration::from_secs(5);
48const COMPACT_MAX: Duration = Duration::from_secs(60);
49/// How often the open panel is read, and the longest it is stretched to.
50pub const PANEL_EVERY: Duration = Duration::from_secs(2);
51const PANEL_MAX: Duration = Duration::from_secs(10);
52/// A read this recent answers the status bar's tick, and the panel's.
53const COMPACT_REUSE: Duration = Duration::from_secs(4);
54const PANEL_REUSE: Duration = Duration::from_millis(1000);
55/// A computer with no counters is asked again this often (a driver installed, a GPU plugged in).
56const UNAVAILABLE_RETRY: Duration = Duration::from_secs(300);
57/// Reads in a row that fail before the counters are given up on for [`UNAVAILABLE_RETRY`].
58const FAILURES_ALLOWED: u32 = 3;
59/// The biggest other users of the GPU that are listed by name.
60pub const OTHERS_LISTED: usize = 5;
61
62/// An interval that stretches when a read costs too much and comes back when it doesn't.
63#[derive(Debug, Clone)]
64pub struct Budget {
65    base: Duration,
66    max: Duration,
67    current: Duration,
68}
69
70impl Budget {
71    pub fn new(base: Duration, max: Duration) -> Self {
72        Self { base, max, current: base }
73    }
74
75    /// Note that a read took `took`; returns the interval to the next one.
76    pub fn record(&mut self, took: Duration) -> Duration {
77        if took > READ_BUDGET {
78            self.current = (self.current * 2).min(self.max);
79        } else if took < READ_BUDGET / 2 {
80            self.current = (self.current / 2).max(self.base);
81        }
82        self.current
83    }
84
85    pub fn interval(&self) -> Duration {
86        self.current
87    }
88
89    /// Whether the interval is longer than it would be if reads were cheap.
90    pub fn widened(&self) -> bool {
91        self.current > self.base
92    }
93}
94
95/// A read, as the sampler hands it out.
96#[derive(Debug, Clone)]
97pub struct Sample {
98    pub state: GpuSampleState,
99    pub reading: Reading,
100    /// How long the read took (the one this was made from).
101    pub took: Duration,
102    /// It includes the processes' memory.
103    full: bool,
104}
105
106impl Sample {
107    fn without_gpu(state: GpuSampleState) -> Self {
108        Self { state, reading: Reading::default(), took: Duration::ZERO, full: true }
109    }
110}
111
112struct Inner {
113    #[cfg(windows)]
114    gpu: Option<pdh::Gpu>,
115    #[cfg(target_os = "linux")]
116    gpu: Option<linux::Gpu>,
117    /// Counters could not be opened or read: not before this.
118    retry_at: Option<Instant>,
119    failures: u32,
120    last: Option<(Instant, Sample)>,
121    panel: Budget,
122    compact: Budget,
123}
124
125/// The one open set of GPU counters (module doc).
126pub struct GpuSampler {
127    inner: Mutex<Inner>,
128}
129
130impl Default for GpuSampler {
131    fn default() -> Self {
132        Self::new()
133    }
134}
135
136impl GpuSampler {
137    pub fn new() -> Self {
138        Self {
139            inner: Mutex::new(Inner {
140                #[cfg(any(windows, target_os = "linux"))]
141                gpu: None,
142                retry_at: None,
143                failures: 0,
144                last: None,
145                panel: Budget::new(PANEL_EVERY, PANEL_MAX),
146                compact: Budget::new(COMPACT_EVERY, COMPACT_MAX),
147            }),
148        }
149    }
150
151    pub fn global() -> &'static GpuSampler {
152        static GLOBAL: OnceLock<GpuSampler> = OnceLock::new();
153        GLOBAL.get_or_init(GpuSampler::new)
154    }
155
156    /// The panel's sample: adapters, processes and their memory. BLOCKING (module doc); call it off the async workers.
157    /// Returns the interval to ask again after, and whether it was widened.
158    pub fn sample_for_panel(&self) -> (Sample, Duration, bool) {
159        let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
160        let sample = inner.read(true, PANEL_REUSE);
161        (sample, inner.panel.interval(), inner.panel.widened())
162    }
163
164    /// The status bar's figures from a read, or the panel's read if it is new enough, and the interval to the next:
165    /// `None` while the panel is reading (`try_lock`: a telemetry tick never waits for it), `Some(None)` for a
166    /// computer with no GPU counters.
167    fn read_compact(&self) -> Option<(Option<Compact>, Duration)> {
168        let mut inner = self.inner.try_lock().ok()?;
169        let sample = inner.read(false, COMPACT_REUSE);
170        Some((compact_of(&sample.reading), inner.compact.interval()))
171    }
172}
173
174impl Inner {
175    /// A read, or the last one if it is newer than `reuse` (and has the processes' memory when `full` wants it).
176    fn read(&mut self, full: bool, reuse: Duration) -> Sample {
177        if let Some((at, s)) = &self.last {
178            if at.elapsed() < reuse && (s.full || !full) {
179                return s.clone();
180            }
181        }
182        if self.retry_at.is_some_and(|t| Instant::now() < t) {
183            return Sample::without_gpu(GpuSampleState::Unavailable);
184        }
185        let started = Instant::now();
186        let outcome = self.read_now(full);
187        let took = started.elapsed();
188        let budget = if full { &mut self.panel } else { &mut self.compact };
189        let widened = budget.record(took);
190        tracing::trace!(took_ms = took.as_millis() as u64, next_ms = widened.as_millis() as u64, full, "gpu: read");
191        let sample = match outcome {
192            Ok((state, reading)) => {
193                self.failures = 0;
194                Sample { state, reading, took, full }
195            }
196            Err(why) => {
197                self.failures += 1;
198                tracing::debug!(error = %why, failures = self.failures, "gpu: could not read the counters");
199                if self.failures >= FAILURES_ALLOWED {
200                    self.retry_at = Some(Instant::now() + UNAVAILABLE_RETRY);
201                    self.drop_counters();
202                }
203                Sample { took, ..Sample::without_gpu(GpuSampleState::Unavailable) }
204            }
205        };
206        self.last = Some((Instant::now(), sample.clone()));
207        sample
208    }
209
210    #[cfg(any(windows, target_os = "linux"))]
211    fn drop_counters(&mut self) {
212        self.gpu = None;
213    }
214
215    #[cfg(not(any(windows, target_os = "linux")))]
216    fn drop_counters(&mut self) {}
217
218    #[cfg(windows)]
219    fn read_now(&mut self, full: bool) -> Result<(GpuSampleState, Reading), String> {
220        if self.gpu.is_none() {
221            match pdh::Gpu::open() {
222                Ok(gpu) => self.gpu = Some(gpu),
223                Err(why) => {
224                    self.retry_at = Some(Instant::now() + UNAVAILABLE_RETRY);
225                    tracing::debug!(error = %why, "gpu: no counters on this computer");
226                    return Ok((GpuSampleState::Unavailable, Reading::default()));
227                }
228            }
229        }
230        let gpu = self.gpu.as_mut().expect("opened above");
231        match gpu.read(full)? {
232            pdh::Read::Warming => Ok((GpuSampleState::Warming, Reading::default())),
233            pdh::Read::Counters(raw, infos) => Ok((GpuSampleState::Ok, aggregate::aggregate(&raw, &infos))),
234        }
235    }
236
237    #[cfg(target_os = "linux")]
238    fn read_now(&mut self, full: bool) -> Result<(GpuSampleState, Reading), String> {
239        if self.gpu.is_none() {
240            match linux::Gpu::open() {
241                Ok(gpu) => self.gpu = Some(gpu),
242                Err(why) => {
243                    self.retry_at = Some(Instant::now() + UNAVAILABLE_RETRY);
244                    tracing::debug!(error = %why, "gpu: no counters on this computer");
245                    return Ok((GpuSampleState::Unavailable, Reading::default()));
246                }
247            }
248        }
249        let gpu = self.gpu.as_mut().expect("opened above");
250        match gpu.read(full)? {
251            linux::Read::Warming => Ok((GpuSampleState::Warming, Reading::default())),
252            linux::Read::Reading(reading) => Ok((GpuSampleState::Ok, reading)),
253        }
254    }
255
256    #[cfg(not(any(windows, target_os = "linux")))]
257    fn read_now(&mut self, _full: bool) -> Result<(GpuSampleState, Reading), String> {
258        Ok((GpuSampleState::Unsupported, Reading::default()))
259    }
260}
261
262/// The status bar's two figures: the busiest adapter's use, and the fullest adapter's memory, percent.
263#[derive(Debug, Clone, Copy, PartialEq)]
264pub struct Compact {
265    pub use_pct: f64,
266    pub mem_pct: Option<f64>,
267}
268
269/// The status bar's figures from a read; `None` when no adapter's use is known (nothing readable: the meter is
270/// hidden, not shown as 0% or an error).
271pub fn compact_of(reading: &Reading) -> Option<Compact> {
272    let use_pct = reading.adapters.iter().filter_map(|a| a.use_pct).fold(None, |m: Option<f64>, v| Some(m.map_or(v, |m| m.max(v))))?;
273    let mem_pct = reading.adapters.iter().filter_map(memory_share).fold(None, |m: Option<f64>, v| Some(m.map_or(v, |m| m.max(v))));
274    Some(Compact { use_pct, mem_pct })
275}
276
277/// The telemetry tick's view of the sampler: asks it every [`COMPACT_EVERY`] (stretched when reads are slow) and
278/// keeps the answer for the ticks between.
279#[derive(Default)]
280pub struct CompactPoller {
281    next: Option<Instant>,
282    shown: Option<Compact>,
283}
284
285impl CompactPoller {
286    /// The figures to put in this tick's event, `None` while nothing is readable.
287    pub fn poll(&mut self, sampler: &GpuSampler) -> Option<Compact> {
288        let now = Instant::now();
289        if self.next.is_none_or(|t| now >= t) {
290            if let Some((shown, wait)) = sampler.read_compact() {
291                self.shown = shown;
292                self.next = Some(now + wait);
293            } else {
294                // The panel is reading: its read is the answer in a moment.
295                self.next = Some(now + Duration::from_millis(500));
296            }
297        }
298        self.shown
299    }
300}
301
302/// Puts the status bar's GPU figures, `gpu` and `gpu:mem`, in a telemetry tick's values: read every few seconds by the
303/// one sampler (module doc) and repeated in the ticks between. Nothing is put in while nothing is readable, so the
304/// meter is hidden, not shown as 0%.
305pub fn add_compact_values(values: &mut std::collections::HashMap<String, f64>) {
306    static POLLER: OnceLock<Mutex<CompactPoller>> = OnceLock::new();
307    let mut poller = POLLER.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
308    if let Some(c) = poller.poll(GpuSampler::global()) {
309        values.insert("gpu".to_string(), c.use_pct);
310        if let Some(mem) = c.mem_pct {
311            values.insert("gpu:mem".to_string(), mem);
312        }
313    }
314}
315
316/// What Tower knows of a process by its id: an image name, and for AgentMux's own what it is.
317#[derive(Debug, Clone)]
318pub struct Named {
319    pub name: String,
320    pub label: Option<String>,
321    pub kind: Option<TowerProcessKind>,
322}
323
324/// The most one process can hold: the biggest adapter's dedicated memory and the most shared memory the OS lets the GPU
325/// have. `None` where the adapters said nothing, so nothing is dropped.
326#[derive(Debug, Clone, Copy, Default, PartialEq)]
327pub struct MemoryLimits {
328    pub dedicated: Option<u64>,
329    pub shared: Option<u64>,
330}
331
332impl MemoryLimits {
333    pub fn of(adapters: &[crate::backend::rpc_types::GpuAdapter]) -> Self {
334        Self {
335            dedicated: adapters.iter().filter_map(|a| a.dedicated_total).max(),
336            shared: adapters.iter().filter_map(|a| a.shared_total).max(),
337        }
338    }
339}
340
341/// Whether a process is worth a row: it uses the GPU, or holds a megabyte of its memory. Where the use is not known at
342/// all (Intel's GPUs say none), the machine's memory it holds is the one thing there is to show.
343fn active(f: &ProcessFigures) -> bool {
344    const MEMORY: u64 = 1 << 20;
345    f.use_pct.is_some_and(|u| u >= 0.5)
346        || f.dedicated.unwrap_or(0) >= MEMORY
347        || (f.use_pct.is_none() && f.shared.unwrap_or(0) >= MEMORY)
348}
349
350/// The rows of the panel: AgentMux's own processes and the biggest [`OTHERS_LISTED`] others, sorted by use and then
351/// memory (AgentMux's first where those are equal), and the rest of the others added up.
352///
353/// A row's memory is what it holds on the card, and only where it holds none there, what it holds of the machine's.
354/// A figure over what the adapters have is the OS's own mistake (it reports 113 GB for a compositor on a 12 GB card, and
355/// 23 TB for another process), and is not shown as a number: see [`MemoryLimits`].
356pub fn shape_processes(
357    figures: &[ProcessFigures],
358    limits: MemoryLimits,
359    name_of: impl Fn(u32) -> Option<Named>,
360) -> (Vec<GpuProcess>, Option<GpuOthers>) {
361    let sane = |v: Option<u64>, limit: Option<u64>| v.filter(|v| limit.is_none_or(|l| *v <= l));
362    let figures: Vec<ProcessFigures> = figures
363        .iter()
364        .map(|f| ProcessFigures {
365            dedicated: sane(f.dedicated, limits.dedicated),
366            shared: sane(f.shared, limits.shared),
367            ..f.clone()
368        })
369        .collect();
370    let row = |f: &ProcessFigures| {
371        let n = name_of(f.pid);
372        GpuProcess {
373            pid: f.pid,
374            name: n.as_ref().map_or_else(|| format!("pid {}", f.pid), |n| n.name.clone()),
375            label: n.as_ref().and_then(|n| n.label.clone()),
376            kind: n.as_ref().and_then(|n| n.kind),
377            use_pct: f.use_pct,
378            dedicated: f.dedicated,
379            shared: f.shared.filter(|_| f.dedicated.unwrap_or(0) == 0),
380        }
381    };
382    let (mut own, mut others): (Vec<GpuProcess>, Vec<GpuProcess>) =
383        figures.iter().filter(|f| active(f)).map(row).partition(|r| r.label.is_some());
384    let memory = |r: &GpuProcess| r.dedicated.unwrap_or(0) + r.shared.unwrap_or(0);
385    // A tie is a tie as the panel prints it: whole percent.
386    let by_use_then_memory = |a: &GpuProcess, b: &GpuProcess| {
387        let pct = |r: &GpuProcess| r.use_pct.unwrap_or(0.0).round() as i64;
388        pct(b).cmp(&pct(a)).then(memory(b).cmp(&memory(a)))
389    };
390    others.sort_by(|a, b| by_use_then_memory(a, b).then(a.pid.cmp(&b.pid)));
391    let rest = others.split_off(others.len().min(OTHERS_LISTED));
392    let sum = |f: fn(&GpuProcess) -> Option<f64>| rest.iter().filter_map(f).reduce(|a, b| a + b);
393    let tail = (!rest.is_empty()).then(|| GpuOthers {
394        processes: rest.len() as u32,
395        use_pct: sum(|r| r.use_pct),
396        dedicated: sum(|r| r.dedicated.map(|v| v as f64)).map(|v| v as u64),
397        shared: sum(|r| r.shared.map(|v| v as f64)).map(|v| v as u64),
398    });
399    own.append(&mut others);
400    // Own rows were pushed first, so the stable sort keeps them first inside a tie.
401    own.sort_by(by_use_then_memory);
402    (own, tail)
403}
404
405#[cfg(test)]
406mod tests;
407
408#[cfg(test)]
409mod cost_tests;