Skip to main content

all_smi/ui/aggregation/
user.rs

1// Copyright 2025 Lablup Inc. and Jeongkyu Shin
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Cluster-wide user aggregation for the `V` tab (issue #189).
16//!
17//! Given a per-host view of GPUs and their running processes, this module
18//! produces a list of `UserAggregate` records — one per distinct
19//! operator, plus a synthetic "unattributed" bucket for rows that lost
20//! their `user` label on scrape (Windows API mode) — along with a
21//! partial-coverage summary so the UI can warn when only a subset of
22//! hosts reported process data.
23//!
24//! The only I/O the module performs is string allocation.  All inputs
25//! are borrowed, so the function composes cleanly with the existing
26//! `RenderSnapshot` pipeline and can be memoised against
27//! `AppState::data_version`.
28
29use std::collections::{BTreeSet, HashMap, HashSet};
30
31use crate::network::metrics_parser::ParsedProcessRow;
32
33/// Username assigned to rows whose `user` label was empty on the wire.
34/// Rendered as-is (not translated) so operators can grep for it.
35pub const UNATTRIBUTED_USER: &str = "(unattributed)";
36
37/// Display string for a row whose username is unknown.  This is the
38/// glyph the renderer puts in the `USER` column; the aggregator itself
39/// groups those rows under [`UNATTRIBUTED_USER`].
40pub const UNATTRIBUTED_DISPLAY: &str = "?";
41
42/// Minimal per-GPU snapshot the aggregator needs.  `total_memory_used`
43/// is the sum of all processes' VRAM on that GPU; it is the denominator
44/// of the weighted-power formula.  The aggregator derives it from the
45/// process list itself (summing over every `ParsedProcessRow` with the
46/// same `(host, gpu_index)`) so callers don't have to care whether the
47/// scrape exposed `all_smi_gpu_memory_used_bytes` with matching numbers.
48#[derive(Clone, Debug)]
49pub struct GpuForAggregation {
50    pub host: String,
51    pub gpu_index: u32,
52    pub power_watts: f64,
53}
54
55/// Per-host view passed into [`aggregate_users`].
56///
57/// A host is considered "reporting process data" if **either** its
58/// `processes` slice is non-empty **or** it is currently `connected`.
59/// The connected-but-silent case is how an *idle* host with
60/// `--processes` enabled shows up: the API exporter legitimately emits
61/// zero rows when nothing is running on the GPUs, and we must not flag
62/// that as "not reporting" — otherwise the partial-coverage chip
63/// scares operators on a cluster that is working exactly as intended.
64///
65/// Hosts that deliberately opt out of `--processes` (or that are
66/// disconnected) contribute to the denominator of the partial-coverage
67/// chip but not to the numerator.
68#[derive(Clone, Debug)]
69pub struct HostSnapshot {
70    pub host: String,
71    pub gpus: Vec<GpuForAggregation>,
72    pub processes: Vec<ParsedProcessRow>,
73    /// Whether the remote scraper currently considers this host
74    /// connected.  `true` on local-mode hosts (there's nothing to
75    /// disconnect from).  Consumed by [`aggregate_users`] when
76    /// computing `reporting_hosts`.
77    pub is_connected: bool,
78}
79
80/// Per-host breakdown the drill-down view renders when the operator
81/// hits `Enter` on a user.
82#[derive(Clone, Debug)]
83pub struct UserPerHost {
84    pub host: String,
85    pub gpu_indices: BTreeSet<u32>,
86    pub vram_bytes: u64,
87    pub power_watts: f64,
88    pub pid_count: usize,
89    pub top_command: String,
90}
91
92/// One row in the Users tab table.
93#[derive(Clone, Debug)]
94pub struct UserAggregate {
95    /// Canonical user name.  Equal to [`UNATTRIBUTED_USER`] for rows
96    /// with missing `user` labels.
97    pub user: String,
98    pub is_system: bool,
99    /// Number of hosts the user has at least one process on.
100    pub node_count: usize,
101    /// Number of distinct `(host, gpu_index)` pairs touched.
102    pub gpu_count: usize,
103    /// Number of distinct `(host, pid)` pairs — "same PID on two hosts
104    /// = different processes" per the issue spec.
105    pub process_count: usize,
106    /// Sum of `gpu_memory_bytes` across every matching row.
107    pub vram_bytes: u64,
108    /// Weighted power approximation in watts.  Always >= 0; see
109    /// [`aggregate_users`] for the formula.
110    pub power_watts: f64,
111    /// Largest `start_time_seconds` the user has in the cluster.  0 on
112    /// fleets where none of the user's processes reported a start time.
113    pub longest_seconds: u64,
114    /// The command string that owns the largest `gpu_memory_bytes`
115    /// among the user's processes.  Empty when the user has no GPU
116    /// memory attached (e.g. root's containerd-shim processes).
117    pub top_command: String,
118    /// Per-host breakdown used by the drill-down view.  Sorted by host.
119    pub per_host: Vec<UserPerHost>,
120}
121
122/// Summary returned by [`aggregate_users`] along with the list of
123/// `UserAggregate` rows.
124#[derive(Clone, Debug, Default)]
125pub struct UserAggregationResult {
126    pub users: Vec<UserAggregate>,
127    /// Number of hosts whose `processes` slice was non-empty.
128    pub reporting_hosts: usize,
129    /// Total number of hosts in the input (reporting + silent).
130    pub total_hosts: usize,
131}
132
133impl UserAggregationResult {
134    /// True when only a subset of hosts reported process data.
135    pub fn is_partial(&self) -> bool {
136        self.total_hosts > 0 && self.reporting_hosts < self.total_hosts
137    }
138}
139
140/// Threshold below which a user is treated as a system account.
141///
142/// Mirrors Linux's `UID_MIN` default (1000) — anything smaller is a
143/// system UID, plus the literal string `root` which does not always
144/// parse as an integer (e.g. on `sudo` lines where the raw name is
145/// emitted).  We keep this behind the in-tab `f` filter; it is NOT
146/// applied by the parser.
147pub const SYSTEM_UID_THRESHOLD: u32 = 1000;
148
149/// Heuristic: is the given user name a system account?
150///
151/// Accepts integer UIDs and the literal "root".  Non-numeric,
152/// non-"root" names are always treated as real users.
153pub fn is_system_user(user: &str) -> bool {
154    if user == "root" {
155        return true;
156    }
157    if let Ok(uid) = user.parse::<u32>() {
158        return uid < SYSTEM_UID_THRESHOLD;
159    }
160    false
161}
162
163/// Compute per-user aggregates across the cluster.
164///
165/// The function runs in `O(P + G + U)` where `P` is the total number of
166/// process rows, `G` is the total number of GPU rows, and `U` is the
167/// number of distinct users — a single pass over the inputs is enough
168/// because we never cross-compare two users.
169///
170/// The **power approximation** works as follows:
171///
172/// ```text
173///                        user_vram_on_gpu
174///   power += gpu_power × ───────────────────
175///                        total_vram_on_gpu
176/// ```
177///
178/// For every GPU the user touches we multiply the GPU's reported power
179/// by the user's share of the VRAM in use on that GPU, then sum across
180/// GPUs.  Negative values are clamped to zero (guards against malformed
181/// scrapes where process VRAM sums exceed the GPU total due to race
182/// conditions between NVML and the Linux accounting paths).  The UI
183/// marks this column with `*` to make the approximation explicit.
184pub fn aggregate_users(snapshots: &[HostSnapshot]) -> UserAggregationResult {
185    // --- Pass 1: total VRAM per (host, gpu_index) -----------------
186    //
187    // This is the denominator of the weighted-power formula.  We don't
188    // trust `all_smi_gpu_memory_used_bytes` for this because a scrape
189    // without `--processes` won't emit process rows at all, and the GPU
190    // total can drift from the sum-of-processes by allocator overhead.
191    // Summing the process rows keeps the ratios self-consistent.
192    // Pre-size both maps: GPUs are capped at 256 per host (see
193    // `MAX_DEVICES_PER_TYPE` in the parser). Pre-sizing avoids rehashing
194    // on every insert in the hot path and materially reduces allocation
195    // traffic on 100-node clusters.
196    let gpu_capacity_hint = snapshots.iter().map(|s| s.gpus.len()).sum::<usize>();
197
198    let mut total_vram_by_gpu: HashMap<(String, u32), u64> =
199        HashMap::with_capacity(gpu_capacity_hint);
200    for snap in snapshots {
201        for p in &snap.processes {
202            // Single-lookup accumulation: one `entry(...)` call,
203            // `+=` into the returned `&mut u64`. The previous pattern
204            // (`*entry().or_insert(0) = get().unwrap_or().add()`) did
205            // two lookups and two `host.clone()` calls per row; for
206            // 100 hosts × 50 procs that was ~5 000 extra clones per
207            // scrape tick on the single-threaded UI path.
208            let entry = total_vram_by_gpu
209                .entry((snap.host.clone(), p.gpu_index))
210                .or_insert(0);
211            *entry = entry.saturating_add(p.gpu_memory_bytes);
212        }
213    }
214
215    // --- Pass 2: GPU power lookup (host, gpu_index) -> watts ------
216    let mut power_by_gpu: HashMap<(String, u32), f64> = HashMap::new();
217    for snap in snapshots {
218        for g in &snap.gpus {
219            // We take the last occurrence if duplicates exist — in
220            // practice each `(host, gpu_index)` appears once per
221            // scrape tick.
222            power_by_gpu.insert((g.host.clone(), g.gpu_index), g.power_watts.max(0.0));
223        }
224    }
225
226    // --- Pass 3: per-user accumulation ----------------------------
227    let mut user_scratch: HashMap<String, UserScratch> = HashMap::new();
228    let mut reporting_hosts: HashSet<&str> = HashSet::new();
229    for snap in snapshots {
230        // A host counts as "reporting" when it produced process rows
231        // **or** when it is connected (and thus capable of producing
232        // rows — an empty list on a connected host just means the GPUs
233        // are idle, which is very different from "the remote scraper
234        // has lost contact" and must not trigger the partial-coverage
235        // warning).
236        if !snap.processes.is_empty() || snap.is_connected {
237            reporting_hosts.insert(snap.host.as_str());
238        }
239        for p in &snap.processes {
240            let canonical_user = if p.user.is_empty() {
241                UNATTRIBUTED_USER.to_string()
242            } else {
243                p.user.clone()
244            };
245            let scratch = user_scratch.entry(canonical_user).or_default();
246            scratch.absorb(p, snap.host.as_str());
247        }
248    }
249
250    // --- Pass 4: finalise -----------------------------------------
251    let mut users: Vec<UserAggregate> = user_scratch
252        .into_iter()
253        .map(|(user, scratch)| scratch.finalize(user, &total_vram_by_gpu, &power_by_gpu))
254        .collect();
255
256    // Stable default ordering: alphabetical by username so the UI has a
257    // deterministic baseline before the in-tab sort keys kick in.
258    users.sort_by(|a, b| a.user.cmp(&b.user));
259
260    UserAggregationResult {
261        users,
262        reporting_hosts: reporting_hosts.len(),
263        total_hosts: snapshots.len(),
264    }
265}
266
267// ---------------------------------------------------------------------
268// Private scratch structures
269// ---------------------------------------------------------------------
270
271#[derive(Default, Clone)]
272struct PerHostScratch {
273    gpu_indices: BTreeSet<u32>,
274    vram_bytes: u64,
275    /// Distinct PIDs on this host for this user.
276    pids: HashSet<u32>,
277    /// Best-so-far command on this host (owner of the largest VRAM).
278    top_command_vram: u64,
279    top_command: String,
280}
281
282#[derive(Default)]
283struct UserScratch {
284    /// Keyed by `(host, gpu_index)` for the node-count computation and
285    /// to let the final pass look up each `total_vram_by_gpu` cell.
286    touched_gpus: HashSet<(String, u32)>,
287    /// Keyed by `(host, pid)` — same PID on two hosts counts twice.
288    touched_pids: HashSet<(String, u32)>,
289    /// Sum of gpu_memory_bytes across every row.
290    vram_bytes: u64,
291    /// Weighted-power numerators keyed by `(host, gpu_index)`.  The
292    /// final pass divides each by the matching denominator.
293    vram_by_gpu: HashMap<(String, u32), u64>,
294    /// Maximum start_time_seconds seen across rows.
295    longest_seconds: u64,
296    /// Owner of the single row with the largest gpu_memory_bytes
297    /// (cluster-wide).
298    top_command_vram: u64,
299    top_command: String,
300    /// Per-host accumulation for the drill-down view.
301    per_host: HashMap<String, PerHostScratch>,
302}
303
304impl UserScratch {
305    fn absorb(&mut self, row: &ParsedProcessRow, host: &str) {
306        // Each of these inserts/entry calls costs one `host.to_string()`
307        // (host is a &str). The previous implementation called
308        // `host.to_string()` 4–5 times per row; we keep 3 calls here
309        // (touched_gpus / touched_pids need owned tuples; vram_by_gpu
310        // and per_host share the same arena), paying for them once per
311        // row rather than on every hash lookup. On 5 000-row scrapes
312        // that's a measurable reduction in allocator traffic.
313        self.touched_gpus.insert((host.to_string(), row.gpu_index));
314        self.touched_pids.insert((host.to_string(), row.pid));
315        self.vram_bytes = self.vram_bytes.saturating_add(row.gpu_memory_bytes);
316
317        // Single-lookup accumulation (formerly two lookups + two clones).
318        {
319            let entry = self
320                .vram_by_gpu
321                .entry((host.to_string(), row.gpu_index))
322                .or_insert(0);
323            *entry = entry.saturating_add(row.gpu_memory_bytes);
324        }
325
326        if row.start_time_seconds > self.longest_seconds {
327            self.longest_seconds = row.start_time_seconds;
328        }
329        if row.gpu_memory_bytes > self.top_command_vram {
330            self.top_command_vram = row.gpu_memory_bytes;
331            self.top_command = pick_display_command(row);
332        }
333
334        let ph = self.per_host.entry(host.to_string()).or_default();
335        ph.gpu_indices.insert(row.gpu_index);
336        ph.vram_bytes = ph.vram_bytes.saturating_add(row.gpu_memory_bytes);
337        ph.pids.insert(row.pid);
338        if row.gpu_memory_bytes > ph.top_command_vram {
339            ph.top_command_vram = row.gpu_memory_bytes;
340            ph.top_command = pick_display_command(row);
341        }
342    }
343
344    fn finalize(
345        self,
346        user: String,
347        total_vram_by_gpu: &HashMap<(String, u32), u64>,
348        power_by_gpu: &HashMap<(String, u32), f64>,
349    ) -> UserAggregate {
350        // Weighted power: for each (host, gpu) the user touches,
351        //   gpu_power × (user_vram / total_vram_on_that_gpu)
352        // Summed over GPUs, clamped to non-negative.
353        let mut power_watts = 0.0_f64;
354        for ((host, gpu_index), user_vram) in &self.vram_by_gpu {
355            let total = total_vram_by_gpu
356                .get(&(host.clone(), *gpu_index))
357                .copied()
358                .unwrap_or(0);
359            if total == 0 {
360                continue;
361            }
362            let gpu_power = power_by_gpu
363                .get(&(host.clone(), *gpu_index))
364                .copied()
365                .unwrap_or(0.0);
366            let ratio = (*user_vram as f64) / (total as f64);
367            // Even with non-negative inputs, f64 noise (denormals,
368            // subtraction in the caller) could in principle push the
369            // product below zero.  Clamp defensively.
370            power_watts += (gpu_power * ratio).max(0.0);
371        }
372        if power_watts < 0.0 {
373            power_watts = 0.0;
374        }
375
376        let node_count: HashSet<&String> = self.touched_gpus.iter().map(|(h, _)| h).collect();
377        let is_system = is_system_user(&user);
378
379        // Freeze per-host breakdown (sorted by host for deterministic
380        // drill-down ordering).
381        let mut host_keys: Vec<String> = self.per_host.keys().cloned().collect();
382        host_keys.sort();
383        let per_host: Vec<UserPerHost> = host_keys
384            .into_iter()
385            .map(|host| {
386                let ph = self.per_host.get(&host).cloned().unwrap_or_default();
387                // Per-host power is the sum over this host's GPUs of
388                // the same ratio; we recompute it here so drill-down
389                // adds up to the top-level number.
390                let mut host_power = 0.0_f64;
391                for g in &ph.gpu_indices {
392                    let total = total_vram_by_gpu
393                        .get(&(host.clone(), *g))
394                        .copied()
395                        .unwrap_or(0);
396                    if total == 0 {
397                        continue;
398                    }
399                    let user_vram = self
400                        .vram_by_gpu
401                        .get(&(host.clone(), *g))
402                        .copied()
403                        .unwrap_or(0);
404                    let gpu_power = power_by_gpu
405                        .get(&(host.clone(), *g))
406                        .copied()
407                        .unwrap_or(0.0);
408                    host_power += (gpu_power * (user_vram as f64) / (total as f64)).max(0.0);
409                }
410                if host_power < 0.0 {
411                    host_power = 0.0;
412                }
413                UserPerHost {
414                    host,
415                    gpu_indices: ph.gpu_indices,
416                    vram_bytes: ph.vram_bytes,
417                    power_watts: host_power,
418                    pid_count: ph.pids.len(),
419                    top_command: ph.top_command,
420                }
421            })
422            .collect();
423
424        UserAggregate {
425            user,
426            is_system,
427            node_count: node_count.len(),
428            gpu_count: self.touched_gpus.len(),
429            process_count: self.touched_pids.len(),
430            vram_bytes: self.vram_bytes,
431            power_watts,
432            longest_seconds: self.longest_seconds,
433            top_command: self.top_command,
434            per_host,
435        }
436    }
437}
438
439/// Choose the display string for the user's `top_command`.
440///
441/// Prefers the full command line; falls back to the short process name
442/// so the column is never empty (e.g. kernel threads that only emit
443/// `name`).
444fn pick_display_command(row: &ParsedProcessRow) -> String {
445    if !row.command.is_empty() {
446        row.command.clone()
447    } else if !row.name.is_empty() {
448        row.name.clone()
449    } else {
450        String::new()
451    }
452}
453
454// ---------------------------------------------------------------------
455// Sorting keys used by the Users tab in-tab hotkeys (u / m / p / n / t).
456// Kept on the aggregation side so the renderer can stay UI-only.
457// ---------------------------------------------------------------------
458
459/// In-tab sort selection.
460#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
461pub enum UserSortKey {
462    /// Alphabetical by username (default).
463    #[default]
464    User,
465    /// Descending VRAM.
466    Memory,
467    /// Descending approximated power.
468    Power,
469    /// Descending node count.
470    Nodes,
471    /// Descending oldest start time (LONGEST column).
472    Longest,
473}
474
475/// Compare two users under `key`.  Ties are broken by `user`
476/// alphabetically so the order is stable across renders.
477pub fn compare_users(a: &UserAggregate, b: &UserAggregate, key: UserSortKey) -> std::cmp::Ordering {
478    use std::cmp::Ordering;
479    let primary = match key {
480        UserSortKey::User => a.user.cmp(&b.user),
481        UserSortKey::Memory => b.vram_bytes.cmp(&a.vram_bytes),
482        UserSortKey::Power => b
483            .power_watts
484            .partial_cmp(&a.power_watts)
485            .unwrap_or(Ordering::Equal),
486        UserSortKey::Nodes => b.node_count.cmp(&a.node_count),
487        UserSortKey::Longest => b.longest_seconds.cmp(&a.longest_seconds),
488    };
489    primary.then_with(|| a.user.cmp(&b.user))
490}
491
492/// Sort a `UserAggregate` slice in place according to `key` (see
493/// [`compare_users`]). Library API; the TUI itself sorts indices through
494/// [`visible_user_order`] so it never clones rows.
495#[allow(dead_code)] // Unused by the binary; kept for library callers.
496pub fn sort_users(users: &mut [UserAggregate], key: UserSortKey) {
497    users.sort_by(|a, b| compare_users(a, b, key));
498}
499
500/// Indices into `users` of the rows the Users table shows, in display
501/// order: system accounts dropped when `filter_sys` is set, the rest
502/// sorted by `key` (see [`compare_users`]).
503///
504/// The table, the `Enter` drill-down and the CSV export all read rows
505/// through this order, so they agree on which user sits at which row
506/// without cloning any `UserAggregate`.
507pub fn visible_user_order(
508    users: &[UserAggregate],
509    key: UserSortKey,
510    filter_sys: bool,
511) -> Vec<usize> {
512    let mut order: Vec<usize> = users
513        .iter()
514        .enumerate()
515        .filter(|(_, u)| !(filter_sys && u.is_system))
516        .map(|(i, _)| i)
517        .collect();
518    order.sort_by(|&a, &b| compare_users(&users[a], &users[b], key));
519    order
520}
521
522/// Format an elapsed-seconds value as `<days>d HH:MM:SS` or `HH:MM:SS`
523/// for the LONGEST column.  Values of 0 render as `—`.
524pub fn format_longest(seconds: u64) -> String {
525    if seconds == 0 {
526        return "—".to_string();
527    }
528    let days = seconds / 86_400;
529    let rem = seconds % 86_400;
530    let hours = rem / 3_600;
531    let minutes = (rem % 3_600) / 60;
532    let secs = rem % 60;
533    if days > 0 {
534        format!("{days}d {hours:02}:{minutes:02}:{secs:02}")
535    } else {
536        format!("{hours:02}:{minutes:02}:{secs:02}")
537    }
538}
539
540#[cfg(test)]
541mod tests {
542    use super::*;
543
544    fn row(
545        pid: u32,
546        user: &str,
547        gpu_index: u32,
548        gpu_memory_bytes: u64,
549        start_time_seconds: u64,
550        command: &str,
551    ) -> ParsedProcessRow {
552        ParsedProcessRow {
553            host: String::new(), // host comes from the enclosing HostSnapshot
554            pid,
555            user: user.to_string(),
556            command: command.to_string(),
557            name: command.to_string(),
558            gpu_index,
559            gpu_uuid: format!("GPU-{gpu_index}"),
560            gpu_memory_bytes,
561            cpu_pct_tenths: 0,
562            start_time_seconds,
563        }
564    }
565
566    fn gpu(host: &str, gpu_index: u32, power_watts: f64) -> GpuForAggregation {
567        GpuForAggregation {
568            host: host.to_string(),
569            gpu_index,
570            power_watts,
571        }
572    }
573
574    #[test]
575    fn empty_input_produces_empty_result() {
576        let result = aggregate_users(&[]);
577        assert!(result.users.is_empty());
578        assert!(!result.is_partial());
579    }
580
581    fn snap(
582        host: &str,
583        gpus: Vec<GpuForAggregation>,
584        processes: Vec<ParsedProcessRow>,
585    ) -> HostSnapshot {
586        HostSnapshot {
587            host: host.to_string(),
588            gpus,
589            processes,
590            is_connected: true,
591        }
592    }
593
594    fn snap_disconnected(
595        host: &str,
596        gpus: Vec<GpuForAggregation>,
597        processes: Vec<ParsedProcessRow>,
598    ) -> HostSnapshot {
599        HostSnapshot {
600            host: host.to_string(),
601            gpus,
602            processes,
603            is_connected: false,
604        }
605    }
606
607    #[test]
608    fn same_pid_on_two_hosts_counts_as_two_processes() {
609        let snapshots = vec![
610            snap(
611                "a",
612                vec![gpu("a", 0, 100.0)],
613                vec![row(42, "alice", 0, 1000, 100, "train")],
614            ),
615            snap(
616                "b",
617                vec![gpu("b", 0, 100.0)],
618                vec![row(42, "alice", 0, 2000, 200, "train")],
619            ),
620        ];
621        let result = aggregate_users(&snapshots);
622        assert_eq!(result.users.len(), 1);
623        let u = &result.users[0];
624        assert_eq!(u.user, "alice");
625        assert_eq!(u.process_count, 2, "(host, pid) must disambiguate");
626        assert_eq!(u.node_count, 2);
627        assert_eq!(u.vram_bytes, 3000);
628        assert_eq!(u.longest_seconds, 200);
629    }
630
631    #[test]
632    fn root_is_marked_as_system_user() {
633        let snapshots = vec![snap(
634            "h",
635            vec![gpu("h", 0, 50.0)],
636            vec![row(1, "root", 0, 0, 10, "containerd-shim")],
637        )];
638        let result = aggregate_users(&snapshots);
639        assert_eq!(result.users.len(), 1);
640        assert!(result.users[0].is_system);
641    }
642
643    #[test]
644    fn numeric_system_uid_is_marked_as_system_user() {
645        assert!(is_system_user("0"));
646        assert!(is_system_user("999"));
647        assert!(!is_system_user("1000"));
648        assert!(!is_system_user("alice"));
649    }
650
651    #[test]
652    fn user_spanning_multiple_gpus_accumulates_correctly() {
653        let snapshots = vec![
654            snap(
655                "h1",
656                vec![gpu("h1", 0, 200.0), gpu("h1", 1, 300.0)],
657                vec![
658                    row(100, "bob", 0, 1_000, 50, "a"),
659                    row(100, "bob", 1, 2_000, 50, "a"),
660                ],
661            ),
662            snap(
663                "h2",
664                vec![gpu("h2", 0, 400.0)],
665                vec![row(200, "bob", 0, 5_000, 100, "b")],
666            ),
667        ];
668        let result = aggregate_users(&snapshots);
669        assert_eq!(result.users.len(), 1);
670        let u = &result.users[0];
671        assert_eq!(u.node_count, 2);
672        assert_eq!(u.gpu_count, 3, "two GPUs on h1 + one on h2");
673        assert_eq!(u.process_count, 2);
674        assert_eq!(u.vram_bytes, 8_000);
675    }
676
677    #[test]
678    fn oldest_start_time_wins_longest() {
679        let snapshots = vec![snap(
680            "h",
681            vec![gpu("h", 0, 10.0)],
682            vec![
683                row(1, "alice", 0, 10, 500, "a"),
684                row(2, "alice", 0, 20, 1_500_000, "b"),
685                row(3, "alice", 0, 30, 100, "c"),
686            ],
687        )];
688        let result = aggregate_users(&snapshots);
689        assert_eq!(result.users[0].longest_seconds, 1_500_000);
690    }
691
692    #[test]
693    fn top_command_is_the_owner_of_the_largest_vram_row() {
694        let snapshots = vec![snap(
695            "h",
696            vec![gpu("h", 0, 10.0)],
697            vec![
698                row(1, "alice", 0, 1_000, 0, "small"),
699                row(2, "alice", 0, 9_000, 0, "big"),
700                row(3, "alice", 0, 5_000, 0, "medium"),
701            ],
702        )];
703        let result = aggregate_users(&snapshots);
704        assert_eq!(result.users[0].top_command, "big");
705    }
706
707    #[test]
708    fn partial_coverage_is_detected() {
709        // Two hosts; only one reported process rows. The silent host
710        // is explicitly disconnected so the new "connected =
711        // reporting" rule from the partial-chip fix does not rescue
712        // it; partial coverage must still trigger.
713        let snapshots = vec![
714            snap(
715                "a",
716                vec![gpu("a", 0, 100.0)],
717                vec![row(1, "alice", 0, 10, 0, "x")],
718            ),
719            snap_disconnected("b", vec![gpu("b", 0, 100.0)], vec![]),
720        ];
721        let result = aggregate_users(&snapshots);
722        assert!(result.is_partial());
723        assert_eq!(result.reporting_hosts, 1);
724        assert_eq!(result.total_hosts, 2);
725    }
726
727    /// Regression for F4 in PR #199: a connected host with
728    /// `--processes` enabled but no running GPU workload legitimately
729    /// emits zero process rows. The partial-coverage chip must **not**
730    /// fire on the basis that such a host appears "silent" — its
731    /// connection is live, and the operator has configured the scrape
732    /// exactly as intended. Only genuinely-disconnected (or
733    /// scrape-less) hosts should count against the numerator.
734    #[test]
735    fn idle_connected_host_is_not_flagged_as_partial() {
736        let snapshots = vec![
737            snap(
738                "a",
739                vec![gpu("a", 0, 100.0)],
740                vec![row(1, "alice", 0, 10, 0, "x")],
741            ),
742            // Host `b` is connected but idle: no processes, yet the
743            // scraper is alive. This is the false-positive case.
744            snap("b", vec![gpu("b", 0, 100.0)], vec![]),
745        ];
746        let result = aggregate_users(&snapshots);
747        assert!(
748            !result.is_partial(),
749            "idle-but-connected host must not trigger the partial chip"
750        );
751        assert_eq!(result.reporting_hosts, 2);
752        assert_eq!(result.total_hosts, 2);
753    }
754
755    #[test]
756    fn power_approximation_clamps_negatives_to_zero() {
757        // A GPU reports negative power (malformed sensor).  The
758        // aggregator must clamp at zero rather than propagate the bad
759        // value.
760        let snapshots = vec![snap(
761            "h",
762            vec![gpu("h", 0, -50.0)],
763            vec![row(1, "alice", 0, 1000, 0, "x")],
764        )];
765        let result = aggregate_users(&snapshots);
766        assert_eq!(result.users[0].power_watts, 0.0);
767    }
768
769    #[test]
770    fn power_approximation_weights_by_vram_share() {
771        // Two users share a single GPU 70/30; the 400 W GPU power
772        // should split ~280/120.
773        let snapshots = vec![snap(
774            "h",
775            vec![gpu("h", 0, 400.0)],
776            vec![
777                row(1, "alice", 0, 7_000, 0, "a"),
778                row(2, "bob", 0, 3_000, 0, "b"),
779            ],
780        )];
781        let result = aggregate_users(&snapshots);
782        let alice = result.users.iter().find(|u| u.user == "alice").unwrap();
783        let bob = result.users.iter().find(|u| u.user == "bob").unwrap();
784        let total = alice.power_watts + bob.power_watts;
785        // Sum of weighted-power shares must equal the GPU power when
786        // every user's VRAM is accounted for.
787        assert!((total - 400.0).abs() < 1e-6, "got {total}");
788        assert!(
789            (alice.power_watts - 280.0).abs() < 1e-6,
790            "got {}",
791            alice.power_watts
792        );
793    }
794
795    #[test]
796    fn missing_user_label_becomes_unattributed() {
797        let snapshots = vec![snap(
798            "h",
799            vec![gpu("h", 0, 100.0)],
800            vec![row(1, "", 0, 100, 0, "x")],
801        )];
802        let result = aggregate_users(&snapshots);
803        assert_eq!(result.users.len(), 1);
804        assert_eq!(result.users[0].user, UNATTRIBUTED_USER);
805    }
806
807    #[test]
808    fn per_host_breakdown_sums_to_the_aggregate_power() {
809        // Invariant: per-host power shares add up to the top-level
810        // number (within f64 rounding).  If this ever breaks the
811        // drill-down will disagree with the main table, so guard it.
812        let snapshots = vec![
813            snap(
814                "h1",
815                vec![gpu("h1", 0, 200.0), gpu("h1", 1, 300.0)],
816                vec![
817                    row(1, "alice", 0, 1_000, 0, "a"),
818                    row(1, "alice", 1, 3_000, 0, "a"),
819                ],
820            ),
821            snap(
822                "h2",
823                vec![gpu("h2", 0, 400.0)],
824                vec![row(2, "alice", 0, 5_000, 0, "b")],
825            ),
826        ];
827        let result = aggregate_users(&snapshots);
828        let u = &result.users[0];
829        let per_host_sum: f64 = u.per_host.iter().map(|h| h.power_watts).sum();
830        assert!((per_host_sum - u.power_watts).abs() < 1e-6);
831        // Each host must appear exactly once.
832        let mut hosts: Vec<&str> = u.per_host.iter().map(|h| h.host.as_str()).collect();
833        hosts.sort();
834        assert_eq!(hosts, vec!["h1", "h2"]);
835    }
836
837    #[test]
838    fn visible_user_order_by_memory_descending() {
839        let mut u1 = UserAggregate {
840            user: "alice".into(),
841            is_system: false,
842            node_count: 1,
843            gpu_count: 1,
844            process_count: 1,
845            vram_bytes: 100,
846            power_watts: 0.0,
847            longest_seconds: 0,
848            top_command: "".into(),
849            per_host: vec![],
850        };
851        let mut u2 = UserAggregate {
852            user: "bob".into(),
853            is_system: false,
854            node_count: 1,
855            gpu_count: 1,
856            process_count: 1,
857            vram_bytes: 300,
858            power_watts: 0.0,
859            longest_seconds: 0,
860            top_command: "".into(),
861            per_host: vec![],
862        };
863        u1.longest_seconds = 10;
864        u2.longest_seconds = 20;
865        let v = vec![u1, u2];
866        let order = visible_user_order(&v, UserSortKey::Memory, false);
867        assert_eq!(v[order[0]].user, "bob", "highest VRAM first");
868    }
869
870    #[test]
871    fn visible_user_order_matches_filter_then_sort_for_every_key() {
872        // Ties on every key except `User`, a system account, and an
873        // unsorted input order: the index order must equal what the
874        // renderer, drill-down and CSV export computed before by cloning,
875        // filtering and sorting the rows.
876        let make =
877            |user: &str, is_system: bool, vram: u64, power: f64, nodes: usize| UserAggregate {
878                user: user.into(),
879                is_system,
880                node_count: nodes,
881                gpu_count: 1,
882                process_count: 1,
883                vram_bytes: vram,
884                power_watts: power,
885                longest_seconds: vram,
886                top_command: String::new(),
887                per_host: vec![],
888            };
889        let users = vec![
890            make("dave", false, 100, 5.0, 2),
891            make("root", true, 900, 50.0, 3),
892            make("alice", false, 300, 5.0, 2),
893            make("carol", false, 100, 9.0, 1),
894            make("bob", false, 300, 1.0, 2),
895        ];
896        let keys = [
897            UserSortKey::User,
898            UserSortKey::Memory,
899            UserSortKey::Power,
900            UserSortKey::Nodes,
901            UserSortKey::Longest,
902        ];
903        for key in keys {
904            for filter_sys in [false, true] {
905                let mut expected: Vec<UserAggregate> = users
906                    .iter()
907                    .filter(|u| !(filter_sys && u.is_system))
908                    .cloned()
909                    .collect();
910                sort_users(&mut expected, key);
911                let order = visible_user_order(&users, key, filter_sys);
912                let got: Vec<&str> = order.iter().map(|&i| users[i].user.as_str()).collect();
913                let want: Vec<&str> = expected.iter().map(|u| u.user.as_str()).collect();
914                assert_eq!(got, want, "key={key:?} filter_sys={filter_sys}");
915            }
916        }
917    }
918
919    #[test]
920    fn format_longest_renders_days_when_over_a_day() {
921        // 1 day 3 hours 12 minutes 7 seconds = 97 927 seconds.
922        let s = format_longest(97_927);
923        assert!(s.contains("1d"), "expected days prefix, got {s}");
924    }
925
926    #[test]
927    fn format_longest_returns_dash_for_zero() {
928        assert_eq!(format_longest(0), "—");
929    }
930
931    #[test]
932    fn aggregation_handles_large_cluster_quickly() {
933        // Synthetic 100 nodes × 50 procs over 4 users, enforcing the
934        // <50 ms budget in the issue's acceptance criteria.  Run in
935        // debug mode by default since `cargo test` disables --release;
936        // we set a generous cap to keep the test stable on CI.
937        let users = ["alice", "bob", "carol", "dave"];
938        let mut snaps = Vec::with_capacity(100);
939        for h in 0..100 {
940            let host = format!("h{h}");
941            let gpus = (0..8)
942                .map(|i| GpuForAggregation {
943                    host: host.clone(),
944                    gpu_index: i,
945                    power_watts: 200.0,
946                })
947                .collect();
948            let procs = (0..50)
949                .map(|p| ParsedProcessRow {
950                    host: host.clone(),
951                    pid: p as u32,
952                    user: users[(p as usize) % users.len()].to_string(),
953                    command: "python".to_string(),
954                    name: "python".to_string(),
955                    gpu_index: (p % 8) as u32,
956                    gpu_uuid: format!("GPU-{h}-{}", p % 8),
957                    gpu_memory_bytes: 1_000_000_000,
958                    cpu_pct_tenths: 0,
959                    start_time_seconds: (p * 7) as u64,
960                })
961                .collect();
962            snaps.push(HostSnapshot {
963                host,
964                gpus,
965                processes: procs,
966                is_connected: true,
967            });
968        }
969        let start = std::time::Instant::now();
970        let result = aggregate_users(&snaps);
971        let elapsed = start.elapsed();
972        assert_eq!(result.users.len(), users.len());
973        // 500 ms is way above the spec target; we only need to catch
974        // quadratic regressions.  The aggregation for 100×50 rows is
975        // several orders of magnitude below this on any modern CPU.
976        assert!(
977            elapsed.as_millis() < 500,
978            "aggregate_users took {elapsed:?} for 100 hosts × 50 procs"
979        );
980    }
981
982    #[test]
983    #[ignore = "adversarial stress — run manually with `cargo test -- --ignored`"]
984    fn aggregation_survives_adversarial_50k_per_host() {
985        // Adversarial input: a malicious remote host pushes the
986        // 50 000-row per-host process cap (the limit enforced in
987        // `metrics_parser.rs`). With 10 such hosts that is 500 000 rows,
988        // which is still the parser's worst case over a multi-host
989        // cluster.  The aggregation must not turn quadratic on this
990        // input.
991        //
992        // Marked #[ignore] so CI stays fast; this is for developers to
993        // run locally when touching the aggregation hot path.
994        let rows_per_host = 50_000;
995        let host_count = 10;
996        let users = ["alice", "bob", "carol", "dave", "eve", "frank"];
997        let mut snaps = Vec::with_capacity(host_count);
998        for h in 0..host_count {
999            let host = format!("h{h}");
1000            let gpus = (0..8)
1001                .map(|i| GpuForAggregation {
1002                    host: host.clone(),
1003                    gpu_index: i,
1004                    power_watts: 400.0,
1005                })
1006                .collect();
1007            let procs = (0..rows_per_host)
1008                .map(|p| ParsedProcessRow {
1009                    host: host.clone(),
1010                    pid: p as u32,
1011                    user: users[(p as usize) % users.len()].to_string(),
1012                    command: "python".to_string(),
1013                    name: "python".to_string(),
1014                    gpu_index: (p % 8) as u32,
1015                    gpu_uuid: format!("GPU-{h}-{}", p % 8),
1016                    gpu_memory_bytes: 1024,
1017                    cpu_pct_tenths: 0,
1018                    start_time_seconds: (p * 7) as u64,
1019                })
1020                .collect();
1021            snaps.push(HostSnapshot {
1022                host,
1023                gpus,
1024                processes: procs,
1025                is_connected: true,
1026            });
1027        }
1028        let start = std::time::Instant::now();
1029        let result = aggregate_users(&snaps);
1030        let elapsed = start.elapsed();
1031        assert_eq!(result.users.len(), users.len());
1032        // Loose 5-second ceiling catches quadratic blow-ups; in release
1033        // mode the real number is well under 1 s for 500 000 rows.
1034        assert!(
1035            elapsed.as_secs() < 5,
1036            "adversarial aggregation took {elapsed:?} for              {host_count}×{rows_per_host} rows — possible O(n^2) regression"
1037        );
1038    }
1039}