agentmux_srv_core/backend/gpu/
mod.rs1pub 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
44pub const READ_BUDGET: Duration = Duration::from_millis(50);
46pub const COMPACT_EVERY: Duration = Duration::from_secs(5);
48const COMPACT_MAX: Duration = Duration::from_secs(60);
49pub const PANEL_EVERY: Duration = Duration::from_secs(2);
51const PANEL_MAX: Duration = Duration::from_secs(10);
52const COMPACT_REUSE: Duration = Duration::from_secs(4);
54const PANEL_REUSE: Duration = Duration::from_millis(1000);
55const UNAVAILABLE_RETRY: Duration = Duration::from_secs(300);
57const FAILURES_ALLOWED: u32 = 3;
59pub const OTHERS_LISTED: usize = 5;
61
62#[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 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 pub fn widened(&self) -> bool {
91 self.current > self.base
92 }
93}
94
95#[derive(Debug, Clone)]
97pub struct Sample {
98 pub state: GpuSampleState,
99 pub reading: Reading,
100 pub took: Duration,
102 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 retry_at: Option<Instant>,
119 failures: u32,
120 last: Option<(Instant, Sample)>,
121 panel: Budget,
122 compact: Budget,
123}
124
125pub 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq)]
264pub struct Compact {
265 pub use_pct: f64,
266 pub mem_pct: Option<f64>,
267}
268
269pub 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#[derive(Default)]
280pub struct CompactPoller {
281 next: Option<Instant>,
282 shown: Option<Compact>,
283}
284
285impl CompactPoller {
286 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 self.next = Some(now + Duration::from_millis(500));
296 }
297 }
298 self.shown
299 }
300}
301
302pub 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#[derive(Debug, Clone)]
318pub struct Named {
319 pub name: String,
320 pub label: Option<String>,
321 pub kind: Option<TowerProcessKind>,
322}
323
324#[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
341fn 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
350pub 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 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.sort_by(by_use_then_memory);
402 (own, tail)
403}
404
405#[cfg(test)]
406mod tests;
407
408#[cfg(test)]
409mod cost_tests;