Skip to main content

agentmux_srv_core/backend/gpu/
aggregate.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A read of the GPU counters, made into what the status bar and the panel show: per adapter its use and
5//! memory, per process its use and memory. Pure: the counters' instances in, figures out, so every case
6//! (several adapters, an adapter no process uses, a counter set the machine lacks) is a test on any platform.
7
8use super::names::{parse_adapter, parse_engine, parse_process_memory};
9use crate::backend::rpc_types::{GpuAdapter, GpuAdapterKind};
10use std::collections::{HashMap, HashSet};
11
12/// One counter's instances: the name and the value.
13pub type Instances = Vec<(String, f64)>;
14
15/// What one read of the counters returned. `None` is a counter set the machine doesn't have, which is not the
16/// same as one with no instances (an adapter no process is using).
17#[derive(Debug, Default, Clone)]
18pub struct RawCounters {
19    /// `GPU Engine\Utilization Percentage`, a process's use of one engine, percent.
20    pub engines: Option<Instances>,
21    /// `GPU Adapter Memory\Dedicated Usage` and `\Shared Usage`, bytes.
22    pub adapter_dedicated: Option<Instances>,
23    pub adapter_shared: Option<Instances>,
24    /// `GPU Process Memory\Dedicated Usage` and `\Shared Usage`, bytes: read only while the panel is open.
25    pub process_dedicated: Option<Instances>,
26    pub process_shared: Option<Instances>,
27}
28
29/// What Windows says an adapter is: its name and the memory it was built with (DXGI), and what kind of device it is
30/// (the kernel's adapter type, [`AdapterType`]). The counters name an adapter by its id only.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct AdapterInfo {
33    pub luid: String,
34    pub name: String,
35    pub software: bool,
36    /// A display adapter that is not a GPU to be listed: an indirect display device (a remote-desktop or virtual
37    /// monitor driver's), or an adapter that cannot render. Decided by [`AdapterType::is_virtual_display`], never by name.
38    pub virtual_display: bool,
39    pub dedicated_total: u64,
40    pub shared_total: u64,
41}
42
43/// The kernel's account of an adapter (`D3DKMT_ADAPTERTYPE`, the bits of its `Value`): what Windows says the adapter is,
44/// which no name can say. Only the bits this module reads are named.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct AdapterType(pub u32);
47
48impl AdapterType {
49    const RENDER_SUPPORTED: u32 = 1 << 0;
50    const SOFTWARE_DEVICE: u32 = 1 << 2;
51    const INDIRECT_DISPLAY_DEVICE: u32 = 1 << 6;
52
53    /// The OS's software renderer.
54    pub fn is_software(self) -> bool {
55        self.0 & Self::SOFTWARE_DEVICE != 0
56    }
57
58    /// An adapter that is no GPU of its own to list: an indirect display device (the driver of a remote-desktop or virtual
59    /// monitor, which DXGI lists under the name and memory of the GPU that draws for it), or one that cannot render (a
60    /// display-only or compute-only device). A paravirtualized adapter, the GPU a virtual machine is given, renders and is kept.
61    pub fn is_virtual_display(self) -> bool {
62        !self.is_software() && (self.0 & Self::INDIRECT_DISPLAY_DEVICE != 0 || self.0 & Self::RENDER_SUPPORTED == 0)
63    }
64}
65
66/// One process's figures, before it is named.
67#[derive(Debug, Clone, PartialEq)]
68pub struct ProcessFigures {
69    pub pid: u32,
70    pub use_pct: Option<f64>,
71    pub dedicated: Option<u64>,
72    pub shared: Option<u64>,
73}
74
75/// A read, in figures.
76#[derive(Debug, Clone, Default, PartialEq)]
77pub struct Reading {
78    pub adapters: Vec<GpuAdapter>,
79    pub processes: Vec<ProcessFigures>,
80    /// The per-process memory was read (the panel asked), so a row's memory is known rather than absent.
81    pub per_process_memory: bool,
82}
83
84/// Below this much dedicated memory an adapter is the CPU's own graphics, which use system memory: its
85/// memory pressure is the shared figure. (An integrated GPU's "dedicated" is a carve-out of 64 MB to 512 MB.)
86const INTEGRATED_BELOW: u64 = 1 << 30;
87
88/// Whether a name is the CPU's own graphics. DXGI has no flag for it (an AMD APU reserves a gigabyte or two, which looks
89/// like a card), so the names of the CPU makers' graphics are the other half of the rule: Intel's, except its Arc cards,
90/// and AMD's "Radeon Graphics" and "Vega n Graphics", which end in "Graphics" where a card ends in a model.
91fn named_integrated(name: &str) -> bool {
92    let n = name.to_ascii_lowercase();
93    if n.contains("intel") {
94        return !n.contains("arc");
95    }
96    (n.contains("radeon") || n.contains("amd")) && n.trim_end().ends_with("graphics") && !n.contains(" rx ")
97}
98
99/// An adapter's kind, from what DXGI says.
100fn kind_of(info: &AdapterInfo) -> GpuAdapterKind {
101    if info.software {
102        GpuAdapterKind::Software
103    } else if info.dedicated_total < INTEGRATED_BELOW || named_integrated(&info.name) {
104        GpuAdapterKind::Integrated
105    } else {
106        GpuAdapterKind::Discrete
107    }
108}
109
110/// An adapter's use of its memory, as a share the status bar can turn a warning on: dedicated for a card with its
111/// own memory, shared for one that uses the machine's.
112pub fn memory_share(a: &GpuAdapter) -> Option<f64> {
113    let (used, total) = match a.kind {
114        GpuAdapterKind::Discrete => (a.dedicated_used?, a.dedicated_total?),
115        _ => (a.shared_used?, a.shared_total?),
116    };
117    (total > 0).then(|| (used as f64 / total as f64 * 100.0).clamp(0.0, 100.0))
118}
119
120fn bytes(v: f64) -> u64 {
121    if v.is_finite() && v > 0.0 {
122        v as u64
123    } else {
124        0
125    }
126}
127
128/// Sum the instances by what `key` makes of their names; the instances `key` does not understand are left out.
129fn sum_by<K: std::hash::Hash + Eq>(
130    instances: &Instances,
131    key: impl Fn(&str) -> Option<K>,
132) -> HashMap<K, f64> {
133    let mut sums = HashMap::new();
134    for (name, v) in instances {
135        if let Some(k) = key(name) {
136            *sums.entry(k).or_insert(0.0) += v.max(0.0);
137        }
138    }
139    sums
140}
141
142/// The adapters the panel does not list, by id: the OS's software renderer (DXGI always lists it, and no one asked about it)
143/// and any virtual display adapter, as Windows says what each is ([`AdapterInfo`]). Only while another adapter is listed: a
144/// machine with nothing else (a virtual machine without a GPU, a software-only one) shows its one adapter. What the counters
145/// report under a dropped id (use, memory, a process's share) is left out of every figure: Windows does not say which
146/// adapter a virtual display draws on, so none is credited with it.
147fn unlisted_adapters(infos: &[AdapterInfo]) -> HashSet<String> {
148    let real = |i: &AdapterInfo| !i.software && !i.virtual_display;
149    if !infos.iter().any(real) {
150        return HashSet::new();
151    }
152    infos.iter().filter(|i| !real(i)).map(|i| i.luid.clone()).collect()
153}
154
155/// The figures of one read. `infos` are the adapters DXGI lists, which name them and give their memory; an adapter
156/// the counters know and DXGI doesn't (one that went away) is shown by its id.
157pub fn aggregate(raw: &RawCounters, infos: &[AdapterInfo]) -> Reading {
158    let dropped = unlisted_adapters(infos);
159    // One engine's load is the sum of what every process asks of it; an adapter is as busy as its busiest engine
160    // (what Task Manager shows too), and a process as busy as its engines added up, within a whole.
161    let mut engine_load: HashMap<(String, String), f64> = HashMap::new();
162    let mut process_use: HashMap<u32, HashMap<String, f64>> = HashMap::new();
163    for (name, v) in raw.engines.iter().flatten() {
164        let Some(e) = parse_engine(name) else { continue };
165        if dropped.contains(&e.adapter) {
166            continue;
167        }
168        *engine_load.entry((e.adapter.clone(), e.engine)).or_insert(0.0) += v.max(0.0);
169        *process_use.entry(e.pid).or_default().entry(e.adapter).or_insert(0.0) += v.max(0.0);
170    }
171    let listed = |name: &str| parse_adapter(name).filter(|l| !dropped.contains(l));
172    let dedicated = raw.adapter_dedicated.as_ref().map(|i| sum_by(i, listed));
173    let shared = raw.adapter_shared.as_ref().map(|i| sum_by(i, listed));
174
175    let mut ids: Vec<String> = infos.iter().filter(|i| !dropped.contains(&i.luid)).map(|i| i.luid.clone()).collect();
176    let known = |luid: &str, ids: &mut Vec<String>| {
177        if !ids.iter().any(|i| i == luid) {
178            ids.push(luid.to_string());
179        }
180    };
181    for (adapter, _) in engine_load.keys() {
182        known(adapter, &mut ids);
183    }
184    for map in [&dedicated, &shared].into_iter().flatten() {
185        for adapter in map.keys() {
186            known(adapter, &mut ids);
187        }
188    }
189    let mut adapters: Vec<GpuAdapter> = ids
190        .into_iter()
191        .map(|luid| {
192            let info = infos.iter().find(|i| i.luid == luid);
193            let busiest = engine_load
194                .iter()
195                .filter(|((a, _), _)| *a == luid)
196                .map(|(_, v)| *v)
197                .fold(0.0_f64, f64::max);
198            let used = |m: &Option<HashMap<String, f64>>| m.as_ref().map(|m| bytes(m.get(&luid).copied().unwrap_or(0.0)));
199            GpuAdapter {
200                name: info.map_or_else(|| format!("GPU {luid}"), |i| i.name.clone()),
201                kind: info.map_or(GpuAdapterKind::Discrete, kind_of),
202                // A counter set the machine has, with nothing in it for this adapter: nothing is using it. The
203                // software renderer has no engines to read: its use is unknown, not idle.
204                use_pct: raw
205                    .engines
206                    .as_ref()
207                    .filter(|_| !info.is_some_and(|i| i.software))
208                    .map(|_| busiest.min(100.0)),
209                dedicated_used: used(&dedicated),
210                dedicated_total: info.map(|i| i.dedicated_total),
211                shared_used: used(&shared),
212                shared_total: info.map(|i| i.shared_total),
213                luid,
214            }
215        })
216        .collect();
217    let held_by_listed = |n: &str| parse_process_memory(n).filter(|(_, l)| !dropped.contains(l)).map(|(pid, _)| pid);
218    let pdm = raw.process_dedicated.as_ref().map(|i| sum_by(i, held_by_listed));
219    let psm = raw.process_shared.as_ref().map(|i| sum_by(i, held_by_listed));
220    let mut pids: Vec<u32> = process_use.keys().copied().collect();
221    for map in [&pdm, &psm].into_iter().flatten() {
222        pids.extend(map.keys().copied().filter(|p| !process_use.contains_key(p)));
223    }
224    pids.sort_unstable();
225    pids.dedup();
226    let processes = pids
227        .into_iter()
228        .map(|pid| ProcessFigures {
229            pid,
230            // Per adapter, its busiest: a process using two adapters is shown at the one it uses most.
231            use_pct: raw.engines.as_ref().map(|_| {
232                process_use
233                    .get(&pid)
234                    .map_or(0.0, |per| per.values().copied().fold(0.0_f64, f64::max))
235                    .min(100.0)
236            }),
237            dedicated: pdm.as_ref().map(|m| bytes(m.get(&pid).copied().unwrap_or(0.0))),
238            shared: psm.as_ref().map(|m| bytes(m.get(&pid).copied().unwrap_or(0.0))),
239        })
240        .collect();
241    Reading { adapters, processes, per_process_memory: pdm.is_some() || psm.is_some() }
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247
248    const A: &str = "0x00000000_0x0000F3A8";
249    const B: &str = "0x00000000_0x00010AAA";
250
251    fn inst(name: &str, v: f64) -> (String, f64) {
252        (name.to_string(), v)
253    }
254    fn engine(pid: u32, luid: &str, eng: u32, ty: &str, v: f64) -> (String, f64) {
255        inst(&format!("pid_{pid}_luid_{luid}_phys_0_eng_{eng}_engtype_{ty}"), v)
256    }
257    fn info(luid: &str, name: &str, dedicated_mb: u64) -> AdapterInfo {
258        AdapterInfo {
259            luid: luid.into(),
260            name: name.into(),
261            software: false,
262            virtual_display: false,
263            dedicated_total: dedicated_mb << 20,
264            shared_total: 16 << 30,
265        }
266    }
267    /// What DXGI says of a virtual display adapter: the name and memory of the GPU that draws for it.
268    fn twin(luid: &str, of: &AdapterInfo) -> AdapterInfo {
269        AdapterInfo { luid: luid.into(), virtual_display: true, ..of.clone() }
270    }
271    const C: &str = "0x00000000_0x0001D96F";
272
273    #[test]
274    fn an_adapter_is_as_busy_as_its_busiest_engine() {
275        let raw = RawCounters {
276            engines: Some(vec![
277                engine(10, A, 0, "3D", 30.0),
278                engine(11, A, 0, "3D", 20.0),
279                engine(10, A, 1, "Copy", 40.0),
280            ]),
281            ..Default::default()
282        };
283        let r = aggregate(&raw, &[info(A, "RTX", 8192)]);
284        assert_eq!(r.adapters.len(), 1);
285        assert_eq!(r.adapters[0].use_pct, Some(50.0));
286    }
287
288    #[test]
289    fn a_process_is_as_busy_as_its_engines_added_up_within_a_whole() {
290        let raw = RawCounters {
291            engines: Some(vec![
292                engine(10, A, 0, "3D", 70.0),
293                engine(10, A, 1, "Copy", 50.0),
294                engine(11, A, 0, "3D", 5.0),
295            ]),
296            ..Default::default()
297        };
298        let r = aggregate(&raw, &[info(A, "RTX", 8192)]);
299        let p = |pid| r.processes.iter().find(|p| p.pid == pid).unwrap().use_pct;
300        assert_eq!(p(10), Some(100.0));
301        assert_eq!(p(11), Some(5.0));
302    }
303
304    #[test]
305    fn several_adapters_are_one_row_each_and_a_process_is_shown_at_the_one_it_uses_most() {
306        let raw = RawCounters {
307            engines: Some(vec![engine(10, A, 0, "3D", 10.0), engine(10, B, 0, "3D", 60.0), engine(12, B, 0, "3D", 5.0)]),
308            adapter_dedicated: Some(vec![
309                inst("luid_0x00000000_0x0000F3A8_phys_0", 1e9),
310                inst("luid_0x00000000_0x00010AAA_phys_0", 2e9),
311            ]),
312            ..Default::default()
313        };
314        let r = aggregate(&raw, &[info(A, "Intel UHD", 128), info(B, "RTX", 8192)]);
315        assert_eq!(r.adapters.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["Intel UHD", "RTX"]);
316        assert_eq!(r.adapters[0].kind, GpuAdapterKind::Integrated);
317        assert_eq!(r.adapters[1].kind, GpuAdapterKind::Discrete);
318        assert_eq!(r.adapters[0].use_pct, Some(10.0));
319        assert_eq!(r.adapters[1].use_pct, Some(65.0));
320        assert_eq!(r.adapters[1].dedicated_used, Some(2_000_000_000));
321        assert_eq!(r.processes.iter().find(|p| p.pid == 10).unwrap().use_pct, Some(60.0));
322    }
323
324    #[test]
325    fn the_cpus_own_graphics_are_integrated_whatever_they_reserve() {
326        let kind = |name: &str, mb: u64| kind_of(&info(A, name, mb));
327        assert_eq!(kind("AMD Radeon(TM) Graphics", 2048), GpuAdapterKind::Integrated);
328        assert_eq!(kind("AMD Radeon(TM) Vega 8 Graphics", 2048), GpuAdapterKind::Integrated);
329        assert_eq!(kind("Intel(R) UHD Graphics 770", 128), GpuAdapterKind::Integrated);
330        assert_eq!(kind("Intel(R) Iris(R) Xe Graphics", 2048), GpuAdapterKind::Integrated);
331        assert_eq!(kind("Intel(R) Arc(TM) A770 Graphics", 16384), GpuAdapterKind::Discrete);
332        assert_eq!(kind("AMD Radeon RX 7900 XTX", 24576), GpuAdapterKind::Discrete);
333        assert_eq!(kind("NVIDIA GeForce RTX 3060", 12288), GpuAdapterKind::Discrete);
334    }
335
336    #[test]
337    fn the_software_renderer_is_a_row_only_when_it_is_all_there_is() {
338        let soft = AdapterInfo { software: true, ..info(B, "Microsoft Basic Render Driver", 0) };
339        let both = aggregate(&RawCounters::default(), &[info(A, "RTX", 8192), soft.clone()]);
340        assert_eq!(both.adapters.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["RTX"]);
341        let alone = aggregate(&RawCounters::default(), &[soft]);
342        assert_eq!(alone.adapters.len(), 1);
343        assert_eq!(alone.adapters[0].kind, GpuAdapterKind::Software);
344    }
345
346    fn names(r: &Reading) -> Vec<&str> {
347        r.adapters.iter().map(|a| a.name.as_str()).collect()
348    }
349
350    #[test]
351    fn a_virtual_display_adapter_with_nothing_on_it_is_not_a_second_copy_of_the_gpu() {
352        let rtx = info(A, "RTX", 12288);
353        let raw = RawCounters {
354            engines: Some(vec![engine(10, A, 0, "3D", 30.0)]),
355            adapter_dedicated: Some(vec![inst("luid_0x00000000_0x0000F3A8_phys_0", 4e9), inst("luid_0x00000000_0x00010AAA_phys_0", 0.0)]),
356            adapter_shared: Some(vec![inst("luid_0x00000000_0x0000F3A8_phys_0", 1e9), inst("luid_0x00000000_0x00010AAA_phys_0", 8192.0)]),
357            ..Default::default()
358        };
359        let r = aggregate(&raw, &[rtx.clone(), twin(B, &rtx)]);
360        assert_eq!(names(&r), ["RTX"]);
361        assert_eq!(r.adapters[0].luid, A);
362        assert_eq!((r.adapters[0].use_pct, r.adapters[0].dedicated_used, r.adapters[0].shared_used), (Some(30.0), Some(4_000_000_000), Some(1_000_000_000)));
363    }
364
365    #[test]
366    fn what_is_counted_on_a_virtual_display_adapter_is_left_out_of_every_figure() {
367        let rtx = info(A, "RTX", 12288);
368        let raw = RawCounters {
369            engines: Some(vec![engine(10, A, 0, "3D", 30.0), engine(20, B, 0, "3D", 70.0), engine(10, B, 1, "Copy", 90.0)]),
370            adapter_dedicated: Some(vec![inst("luid_0x00000000_0x0000F3A8_phys_0", 4e9), inst("luid_0x00000000_0x00010AAA_phys_0", 2e9)]),
371            process_dedicated: Some(vec![
372                inst("pid_10_luid_0x00000000_0x0000F3A8_phys_0", 100.0),
373                inst("pid_20_luid_0x00000000_0x00010AAA_phys_0", 500.0),
374                inst("pid_10_luid_0x00000000_0x00010AAA_phys_0", 7.0),
375            ]),
376            ..Default::default()
377        };
378        let r = aggregate(&raw, &[rtx.clone(), twin(B, &rtx)]);
379        assert_eq!(names(&r), ["RTX"]);
380        // The adapter is as busy as it is: not 90%, which the virtual one's engine reads.
381        assert_eq!((r.adapters[0].use_pct, r.adapters[0].dedicated_used), (Some(30.0), Some(4_000_000_000)));
382        // A process that only used the virtual adapter has nothing to show; one that used both shows the real one's share.
383        assert!(r.processes.iter().all(|p| p.pid != 20));
384        let p10 = r.processes.iter().find(|p| p.pid == 10).unwrap();
385        assert_eq!((p10.use_pct, p10.dedicated), (Some(30.0), Some(100)));
386    }
387
388    #[test]
389    fn two_real_identical_cards_stay_two_rows() {
390        let card = info(A, "RTX", 12288);
391        let other = AdapterInfo { luid: B.into(), ..card.clone() };
392        let r = aggregate(&RawCounters::default(), &[card, other]);
393        assert_eq!(names(&r), ["RTX", "RTX"]);
394        assert_eq!(r.adapters.iter().map(|a| a.luid.as_str()).collect::<Vec<_>>(), [A, B]);
395    }
396
397    #[test]
398    fn a_real_card_a_twin_of_it_and_a_second_real_card_leave_both_real_cards() {
399        let a = info(A, "RTX", 12288);
400        let r = aggregate(&RawCounters::default(), &[a.clone(), twin(B, &a), AdapterInfo { luid: C.into(), ..a }]);
401        assert_eq!(r.adapters.iter().map(|x| x.luid.as_str()).collect::<Vec<_>>(), [A, C]);
402    }
403
404    #[test]
405    fn the_only_adapter_is_shown_even_if_it_is_a_virtual_display_one() {
406        let only = twin(A, &info(A, "RTX", 12288));
407        let r = aggregate(&RawCounters::default(), &[only]);
408        assert_eq!(r.adapters.len(), 1);
409        // And it is not dropped when the OS's software renderer is the other one.
410        let soft = AdapterInfo { software: true, ..info(B, "Microsoft Basic Render Driver", 0) };
411        let r = aggregate(&RawCounters::default(), &[twin(A, &info(A, "RTX", 12288)), soft]);
412        assert_eq!(r.adapters.len(), 2, "neither is a real GPU: both stay rather than none");
413    }
414
415    #[test]
416    fn the_kernels_adapter_type_says_which_adapter_is_virtual() {
417        // The bits of D3DKMT_ADAPTERTYPE: render 0, display 1, software 2, post 3, hybrid discrete 4, hybrid integrated 5,
418        // indirect display 6, paravirtualized 7, compute only 11.
419        let bits = |v: &[u32]| AdapterType(v.iter().fold(0, |a, b| a | (1 << b)));
420        assert!(!bits(&[0, 1]).is_virtual_display(), "an ordinary GPU renders and displays");
421        assert!(!bits(&[0, 1, 4]).is_virtual_display(), "a hybrid laptop's discrete GPU");
422        assert!(!bits(&[0, 1, 5]).is_virtual_display(), "a hybrid laptop's integrated GPU");
423        assert!(!bits(&[0, 7]).is_virtual_display(), "the GPU a virtual machine is given is kept");
424        assert!(bits(&[0, 1, 6]).is_virtual_display(), "an indirect display device, even one that says it renders");
425        assert!(bits(&[1]).is_virtual_display(), "an adapter that cannot render");
426        assert!(bits(&[11]).is_virtual_display(), "a compute-only device is no display GPU");
427        assert!(bits(&[2, 0, 1]).is_software() && !bits(&[2, 0, 1]).is_virtual_display(), "the software renderer is its own case");
428        assert!(!AdapterType(0).is_software());
429    }
430
431    #[test]
432    fn an_adapter_no_process_uses_is_idle_not_unknown() {
433        let raw = RawCounters { engines: Some(vec![]), ..Default::default() };
434        let r = aggregate(&raw, &[info(A, "RTX", 8192)]);
435        assert_eq!(r.adapters[0].use_pct, Some(0.0));
436    }
437
438    #[test]
439    fn a_missing_counter_set_leaves_its_figure_unknown_never_zero() {
440        let raw = RawCounters::default();
441        let r = aggregate(&raw, &[info(A, "RTX", 8192)]);
442        assert_eq!(r.adapters.len(), 1);
443        assert_eq!(r.adapters[0].use_pct, None);
444        assert_eq!(r.adapters[0].dedicated_used, None);
445        assert!(r.processes.is_empty());
446        assert!(!r.per_process_memory);
447    }
448
449    #[test]
450    fn no_counters_and_no_adapter_is_nothing_to_show() {
451        assert_eq!(aggregate(&RawCounters::default(), &[]), Reading::default());
452    }
453
454    #[test]
455    fn an_adapter_the_counters_know_and_dxgi_does_not_is_shown_by_its_id() {
456        let raw = RawCounters { engines: Some(vec![engine(10, A, 0, "3D", 1.0)]), ..Default::default() };
457        let r = aggregate(&raw, &[]);
458        assert_eq!(r.adapters[0].name, format!("GPU {A}"));
459        assert_eq!(r.adapters[0].dedicated_total, None);
460    }
461
462    #[test]
463    fn a_process_memory_row_adds_the_processes_that_only_hold_memory() {
464        let raw = RawCounters {
465            engines: Some(vec![engine(10, A, 0, "3D", 1.0)]),
466            process_dedicated: Some(vec![
467                inst("pid_10_luid_0x00000000_0x0000F3A8_phys_0", 100.0),
468                inst("pid_77_luid_0x00000000_0x0000F3A8_phys_0", 500.0),
469            ]),
470            process_shared: Some(vec![inst("pid_10_luid_0x00000000_0x0000F3A8_phys_0", 7.0)]),
471            ..Default::default()
472        };
473        let r = aggregate(&raw, &[info(A, "RTX", 8192)]);
474        assert!(r.per_process_memory);
475        let get = |pid| r.processes.iter().find(|p| p.pid == pid).unwrap().clone();
476        assert_eq!(get(10), ProcessFigures { pid: 10, use_pct: Some(1.0), dedicated: Some(100), shared: Some(7) });
477        assert_eq!(get(77), ProcessFigures { pid: 77, use_pct: Some(0.0), dedicated: Some(500), shared: Some(0) });
478    }
479
480    #[test]
481    fn the_memory_share_is_of_the_memory_the_adapter_really_uses() {
482        let discrete = GpuAdapter {
483            luid: A.into(),
484            name: "RTX".into(),
485            kind: GpuAdapterKind::Discrete,
486            use_pct: Some(1.0),
487            dedicated_used: Some(9 << 30),
488            dedicated_total: Some(10 << 30),
489            shared_used: Some(1 << 30),
490            shared_total: Some(16 << 30),
491        };
492        assert_eq!(memory_share(&discrete), Some(90.0));
493        let integrated = GpuAdapter { kind: GpuAdapterKind::Integrated, ..discrete.clone() };
494        assert_eq!(memory_share(&integrated), Some(6.25));
495        let unknown = GpuAdapter { dedicated_total: None, ..discrete };
496        assert_eq!(memory_share(&unknown), None);
497    }
498}