ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
//! Hardware Profile Inspector — read-only inspection of vendor driver settings,
//! application profiles, and tunable hardware parameters.
//!
//! Inspired by [NVIDIA Profile Inspector](https://github.com/Orbmu2k/nvidiaProfileInspector),
//! Intel XTU, AMD Ryzen Master, Radeon Adrenalin, and `nvme-cli`, this module
//! exposes a unified, vendor-neutral view of "settings you can usually tweak"
//! across five subsystems:
//!
//! | Subsystem | Inspected sources |
//! |-----------|-------------------|
//! | `Gpu`     | NVIDIA NVAPI driver profile registry, AMD AMDKMDAG/UMD registry, Intel IGCL registry, Linux sysfs |
//! | `Cpu`     | MSR (Linux `/dev/cpu/N/msr`), RAPL, cpufreq governor/EPP, voltage offset state |
//! | `Nvme`    | Linux `/sys/class/nvme/*` feature attrs, Windows `IOCTL_STORAGE_PROTOCOL_COMMAND` admin pass-through |
//! | `Display` | Refresh rate options, HDR mode, color profile path, scale factor |
//! | `Memory`  | DIMM SPD XMP/EXPO profiles, active timings vs JEDEC |
//!
//! ## Design
//!
//! All providers are **read-only** in this initial pass. The API is built to
//! be extended with `apply()` semantics later (gated by elevation + an audit
//! log + per-setting safety classification), but no provider mutates state
//! today. This mirrors the safe foundation pattern used by the existing
//! [`crate::fan_control`] and [`crate::cpufreq`] modules.
//!
//! ## Example
//!
//! ```no_run
//! use ironmonitor::profile::{ProfileInspector, Subsystem};
//!
//! let mut inspector = ProfileInspector::new();
//! let snapshot = inspector.snapshot_all();
//!
//! for (subsystem, providers) in &snapshot.providers {
//!     println!("== {} ==", subsystem);
//!     for provider in providers {
//!         println!("  {} ({})", provider.display_name, provider.source);
//!         for setting in &provider.settings {
//!             println!("    {} = {}", setting.id, setting.value);
//!         }
//!     }
//! }
//! ```

use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;

pub mod active;
pub mod apply;
pub mod bench;
pub mod cache;
pub mod cpu;
pub mod deviation;
pub mod diff;
pub mod display;
pub mod edid;
pub mod explain;
pub mod gpu;
pub mod memory;
#[cfg(windows)]
pub mod nvidia_drs;
pub mod nvme;
pub mod nvme_features;
pub mod spd_xmp;

/// Top-level hardware subsystems exposed by the profile inspector.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Subsystem {
    /// GPU driver profiles (NVAPI / AMD / Intel)
    Gpu,
    /// CPU tuning (XTU / Ryzen Master / cpufreq)
    Cpu,
    /// NVMe controller parameters
    Nvme,
    /// Display modes and color profiles
    Display,
    /// Memory (DIMM XMP/EXPO)
    Memory,
}

impl Subsystem {
    pub const ALL: &'static [Subsystem] = &[
        Subsystem::Gpu,
        Subsystem::Cpu,
        Subsystem::Nvme,
        Subsystem::Display,
        Subsystem::Memory,
    ];

    pub fn as_str(self) -> &'static str {
        match self {
            Subsystem::Gpu => "gpu",
            Subsystem::Cpu => "cpu",
            Subsystem::Nvme => "nvme",
            Subsystem::Display => "display",
            Subsystem::Memory => "memory",
        }
    }

    pub fn parse(s: &str) -> Option<Self> {
        match s.to_ascii_lowercase().as_str() {
            "gpu" => Some(Subsystem::Gpu),
            "cpu" => Some(Subsystem::Cpu),
            "nvme" | "storage" => Some(Subsystem::Nvme),
            "display" => Some(Subsystem::Display),
            "memory" | "dimm" | "ram" => Some(Subsystem::Memory),
            _ => None,
        }
    }
}

impl fmt::Display for Subsystem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Classification of how risky it would be to *write* this setting. Today the
/// inspector is read-only; this hint exists so that a future `apply()` layer
/// can require elevation and explicit user confirmation for anything beyond
/// `Safe`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SettingRisk {
    /// Read-only metadata (no write semantics defined).
    Informational,
    /// Reversible toggle with no stability impact (e.g. per-app V-Sync).
    Safe,
    /// Affects driver/runtime behavior; reversible on reboot.
    Moderate,
    /// Touches power/thermal/voltage/MSR; can destabilize or damage hardware.
    Dangerous,
}

/// Storage type for a setting's value.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum SettingValue {
    /// Boolean toggle (on/off).
    Bool(bool),
    /// Signed integer (e.g. clock offset in MHz, voltage in mV).
    Int(i64),
    /// Unsigned integer (e.g. NVAPI DWORD setting).
    Uint(u64),
    /// Floating-point (e.g. fractional scale).
    Float(f64),
    /// String / enum-as-string (e.g. "performance", "DLSS Quality").
    Text(String),
    /// Hex blob (e.g. NVAPI binary settings, raw SPD bytes).
    Hex(String),
    /// Setting exists but the value is unreadable on this platform/permission.
    Unreadable(String),
}

impl fmt::Display for SettingValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SettingValue::Bool(b) => write!(f, "{}", b),
            SettingValue::Int(i) => write!(f, "{}", i),
            SettingValue::Uint(u) => write!(f, "{} (0x{:x})", u, u),
            SettingValue::Float(x) => write!(f, "{}", x),
            SettingValue::Text(s) => write!(f, "{}", s),
            SettingValue::Hex(h) => write!(f, "{}", h),
            SettingValue::Unreadable(reason) => write!(f, "<unreadable: {}>", reason),
        }
    }
}

/// A single inspectable setting. The shape mirrors NVPI's "setting" rows:
/// an ID (vendor-stable), a display name, the current value, and metadata
/// describing the value space.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Setting {
    /// Stable, machine-readable identifier (e.g. "0x10094F1F" for an NVAPI DWORD,
    /// or "power_limit_mw" for an AMD sysfs attr).
    pub id: String,
    /// Human-readable name.
    pub display_name: String,
    /// Current value.
    pub value: SettingValue,
    /// Optional unit suffix (W, MHz, mV, °C, %).
    pub unit: Option<String>,
    /// Optional default value reported by the driver / firmware.
    pub default: Option<SettingValue>,
    /// Optional enumerated choices (display name -> raw value).
    pub choices: Option<Vec<(String, SettingValue)>>,
    /// Optional numeric range (min, max) for Int/Uint/Float settings.
    pub range: Option<(SettingValue, SettingValue)>,
    /// Optional free-form description (driver doc string, manpage line).
    pub description: Option<String>,
    /// Write-risk classification (for future apply() support).
    pub risk: SettingRisk,
    /// Where this setting was read from (e.g. registry path, sysfs file).
    pub source: String,
    /// Whether this setting can be modified via [`apply::apply_setting`].
    /// Defaults to `false`; providers opt individual settings in.
    #[serde(default)]
    pub writable: bool,
}

impl Setting {
    pub fn info(id: impl Into<String>, name: impl Into<String>, value: SettingValue) -> Self {
        Self {
            id: id.into(),
            display_name: name.into(),
            value,
            unit: None,
            default: None,
            choices: None,
            range: None,
            description: None,
            risk: SettingRisk::Informational,
            source: String::new(),
            writable: false,
        }
    }

    pub fn with_writable(mut self, writable: bool) -> Self {
        self.writable = writable;
        self
    }

    pub fn with_unit(mut self, unit: impl Into<String>) -> Self {
        self.unit = Some(unit.into());
        self
    }

    pub fn with_source(mut self, src: impl Into<String>) -> Self {
        self.source = src.into();
        self
    }

    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }

    pub fn with_risk(mut self, risk: SettingRisk) -> Self {
        self.risk = risk;
        self
    }
}

/// A logical group of settings (one device, one application profile, one DIMM).
///
/// Examples:
/// - `("NVIDIA RTX 4090", "Global", [...])`
/// - `("NVIDIA RTX 4090", "Cyberpunk 2077", [...])`
/// - `("CPU0 — Intel Core i9-13900K", "Active state", [...])`
/// - `("NVMe nvme0n1 — Samsung 990 Pro 2TB", "Features", [...])`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileGroup {
    /// Subsystem this group belongs to.
    pub subsystem: Subsystem,
    /// Device or scope name (GPU model, NVMe path, DIMM slot, etc.).
    pub device: String,
    /// Profile / scope name. For NVPI-style data this is the app profile name
    /// ("Global", "Cyberpunk 2077.exe"); for other subsystems often "Default".
    pub display_name: String,
    /// Where the data came from (e.g. "registry: HKLM\\SOFTWARE\\NVIDIA...",
    /// "/sys/class/nvme/nvme0/", "MSR 0x610 (RAPL_POWER_LIMIT)").
    pub source: String,
    /// Settings in this profile.
    pub settings: Vec<Setting>,
    /// Free-form notes (capability hints, permission caveats).
    pub notes: Vec<String>,
    /// Stable identity for matching this group across snapshots (for example
    /// `nvme0`). Set it where `device` embeds a label that can change, such as
    /// a model name that read once and then failed. When absent, `device` is
    /// used.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,
}

impl ProfileGroup {
    pub fn new(
        subsystem: Subsystem,
        device: impl Into<String>,
        display_name: impl Into<String>,
        source: impl Into<String>,
    ) -> Self {
        Self {
            subsystem,
            device: device.into(),
            display_name: display_name.into(),
            source: source.into(),
            settings: Vec::new(),
            notes: Vec::new(),
            key: None,
        }
    }

    /// Set the stable identity used by [`diff`](diff::diff_snapshots).
    pub fn with_key(mut self, key: impl Into<String>) -> Self {
        self.key = Some(key.into());
        self
    }

    pub fn push(&mut self, setting: Setting) {
        self.settings.push(setting);
    }

    pub fn note(&mut self, msg: impl Into<String>) {
        self.notes.push(msg.into());
    }
}

/// What one platform scanner read.
///
/// `groups` are the items it read. `unread` names each item it found but could
/// not read, with the reason, so a failed read is not mistaken for an absent
/// item. A scanner returns `Err` only when it could not read anything at all.
#[derive(Debug, Default)]
pub struct ScanOutcome {
    pub groups: Vec<ProfileGroup>,
    pub unread: Vec<String>,
}

/// Split a scanner result into the groups it read and the reasons it could not
/// read. A whole-scan `Err` becomes a single unread reason.
pub(crate) fn split_scan(scan: Result<ScanOutcome, String>) -> (Vec<ProfileGroup>, Vec<String>) {
    match scan {
        Ok(outcome) => (outcome.groups, outcome.unread),
        Err(reason) => (Vec::new(), vec![reason]),
    }
}

/// The note group that reports a scanner's unread items, one note per reason
/// as `<scanner> not read: <reason>`. Empty when nothing was unread, so a
/// successful scan adds no row.
pub(crate) fn not_read_groups(
    subsystem: Subsystem,
    scanner: &str,
    reasons: &[String],
) -> Vec<ProfileGroup> {
    if reasons.is_empty() {
        return Vec::new();
    }
    let mut group = ProfileGroup::new(subsystem, format!("{scanner} (not read)"), scanner, scanner);
    for reason in reasons {
        group.note(format!("{scanner} not read: {reason}"));
    }
    vec![group]
}

/// Trait implemented by each subsystem provider.
pub trait ProfileProvider: Send {
    fn subsystem(&self) -> Subsystem;
    /// Snapshot all profile groups exposed by this provider. Must not panic.
    ///
    /// `Ok` with no groups means the provider looked and legitimately found
    /// nothing. `Err(reason)` means the underlying read failed, so no groups
    /// were obtained. Partial failures stay `Ok` and are shown as a group whose
    /// note says what could not be read. Callers must not treat `Err` as zero
    /// groups.
    fn snapshot(&mut self) -> Result<Vec<ProfileGroup>, String>;
}

/// Aggregate snapshot of all subsystems.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileSnapshot {
    /// Unix timestamp (seconds) when the snapshot was taken.
    pub timestamp: u64,
    /// Profile groups keyed by subsystem.
    pub providers: BTreeMap<Subsystem, Vec<ProfileGroup>>,
    /// Subsystems that errored out entirely with a short reason.
    pub errors: BTreeMap<Subsystem, String>,
}

impl ProfileSnapshot {
    pub fn total_settings(&self) -> usize {
        self.providers
            .values()
            .flat_map(|groups| groups.iter())
            .map(|g| g.settings.len())
            .sum()
    }

    pub fn total_groups(&self) -> usize {
        self.providers.values().map(|g| g.len()).sum()
    }

    /// Search settings across all subsystems by case-insensitive substring
    /// match against id, display name, description, or value.
    pub fn search(&self, needle: &str) -> Vec<(Subsystem, &ProfileGroup, &Setting)> {
        let needle = needle.to_ascii_lowercase();
        let mut out = Vec::new();
        for (sub, groups) in &self.providers {
            for group in groups {
                for setting in &group.settings {
                    let hay = format!(
                        "{} {} {} {}",
                        setting.id,
                        setting.display_name,
                        setting.description.as_deref().unwrap_or(""),
                        setting.value,
                    )
                    .to_ascii_lowercase();
                    if hay.contains(&needle) {
                        out.push((*sub, group, setting));
                    }
                }
            }
        }
        out
    }
}

/// Top-level inspector that fans out to each subsystem provider.
pub struct ProfileInspector {
    providers: Vec<Box<dyn ProfileProvider>>,
}

impl ProfileInspector {
    /// Construct an inspector with the default set of providers for the
    /// current platform.
    pub fn new() -> Self {
        let providers: Vec<Box<dyn ProfileProvider>> = vec![
            Box::new(gpu::GpuProfileProvider::new()),
            Box::new(cpu::CpuProfileProvider::new()),
            Box::new(nvme::NvmeProfileProvider::new()),
            Box::new(display::DisplayProfileProvider::new()),
            Box::new(memory::MemoryProfileProvider::new()),
        ];
        Self { providers }
    }

    pub fn with_providers(providers: Vec<Box<dyn ProfileProvider>>) -> Self {
        Self { providers }
    }

    /// Take a snapshot of all configured providers.
    ///
    /// A provider whose read failed is recorded in `errors` and has no entry
    /// in `providers`, so it cannot be mistaken for one that found no groups.
    pub fn snapshot_all(&mut self) -> ProfileSnapshot {
        let mut providers = BTreeMap::new();
        let mut errors = BTreeMap::new();
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);

        for p in self.providers.iter_mut() {
            let sub = p.subsystem();
            match p.snapshot() {
                Ok(groups) => providers.entry(sub).or_insert_with(Vec::new).extend(groups),
                Err(reason) => {
                    errors.entry(sub).or_insert(reason);
                }
            }
        }

        ProfileSnapshot {
            timestamp,
            providers,
            errors,
        }
    }

    /// Snapshot a single subsystem. Returns `Err` with the first provider
    /// failure for that subsystem.
    pub fn snapshot(&mut self, subsystem: Subsystem) -> Result<Vec<ProfileGroup>, String> {
        let mut out = Vec::new();
        for p in self.providers.iter_mut() {
            if p.subsystem() == subsystem {
                out.extend(p.snapshot()?);
            }
        }
        Ok(out)
    }
}

impl Default for ProfileInspector {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn subsystem_roundtrip() {
        for s in Subsystem::ALL {
            assert_eq!(Subsystem::parse(s.as_str()), Some(*s));
        }
        assert_eq!(Subsystem::parse("RAM"), Some(Subsystem::Memory));
        assert_eq!(Subsystem::parse("storage"), Some(Subsystem::Nvme));
        assert_eq!(Subsystem::parse("nonsense"), None);
    }

    #[test]
    fn snapshot_total_counts() {
        let mut snap = ProfileSnapshot {
            timestamp: 0,
            providers: BTreeMap::new(),
            errors: BTreeMap::new(),
        };
        let mut g = ProfileGroup::new(Subsystem::Gpu, "GPU0", "Global", "test");
        g.push(Setting::info("k1", "Key 1", SettingValue::Bool(true)));
        g.push(Setting::info("k2", "Key 2", SettingValue::Uint(42)));
        snap.providers.insert(Subsystem::Gpu, vec![g]);
        assert_eq!(snap.total_groups(), 1);
        assert_eq!(snap.total_settings(), 2);
        assert_eq!(snap.search("key 2").len(), 1);
        assert_eq!(snap.search("Key").len(), 2);
    }

    #[test]
    fn setting_value_display() {
        assert_eq!(SettingValue::Bool(true).to_string(), "true");
        assert_eq!(SettingValue::Uint(255).to_string(), "255 (0xff)");
        assert_eq!(SettingValue::Text("perf".into()).to_string(), "perf");
        assert!(SettingValue::Unreadable("perm".into())
            .to_string()
            .contains("perm"));
    }

    #[test]
    fn inspector_default_runs() {
        // Smoke test: the inspector must never panic on any platform, even
        // with zero hardware support. Result may legitimately be empty.
        let mut inspector = ProfileInspector::new();
        let _snap = inspector.snapshot_all();
    }

    /// A provider with a canned result, for exercising `snapshot_all`.
    struct FakeProvider {
        sub: Subsystem,
        result: Result<Vec<ProfileGroup>, String>,
    }

    impl ProfileProvider for FakeProvider {
        fn subsystem(&self) -> Subsystem {
            self.sub
        }
        fn snapshot(&mut self) -> Result<Vec<ProfileGroup>, String> {
            self.result.clone()
        }
    }

    #[test]
    fn snapshot_all_records_failing_provider_in_errors() {
        let ok_group = ProfileGroup::new(Subsystem::Cpu, "cpu0", "Default", "fake");
        let mut inspector = ProfileInspector::with_providers(vec![
            Box::new(FakeProvider {
                sub: Subsystem::Cpu,
                result: Ok(vec![ok_group]),
            }),
            Box::new(FakeProvider {
                sub: Subsystem::Gpu,
                result: Err("NVML init failed".to_string()),
            }),
        ]);
        let snap = inspector.snapshot_all();
        assert_eq!(
            snap.errors.get(&Subsystem::Gpu).map(String::as_str),
            Some("NVML init failed")
        );
        assert!(!snap.providers.contains_key(&Subsystem::Gpu));
        assert_eq!(snap.providers.get(&Subsystem::Cpu).map(Vec::len), Some(1));
        assert!(!snap.errors.contains_key(&Subsystem::Cpu));
    }

    #[test]
    fn failing_provider_is_not_the_same_as_empty_provider() {
        let mut inspector = ProfileInspector::with_providers(vec![
            Box::new(FakeProvider {
                sub: Subsystem::Nvme,
                result: Ok(Vec::new()),
            }),
            Box::new(FakeProvider {
                sub: Subsystem::Memory,
                result: Err("SMBIOS unreadable".to_string()),
            }),
        ]);
        let snap = inspector.snapshot_all();
        // Empty but read: present with zero groups, no error.
        assert_eq!(snap.providers.get(&Subsystem::Nvme).map(Vec::len), Some(0));
        assert!(!snap.errors.contains_key(&Subsystem::Nvme));
        // Failed: absent from providers, reason in errors.
        assert!(!snap.providers.contains_key(&Subsystem::Memory));
        assert!(snap.errors.contains_key(&Subsystem::Memory));
    }

    #[test]
    fn single_subsystem_snapshot_surfaces_failure() {
        let mut inspector = ProfileInspector::with_providers(vec![Box::new(FakeProvider {
            sub: Subsystem::Display,
            result: Err("no display stack".to_string()),
        })]);
        assert_eq!(
            inspector.snapshot(Subsystem::Display).unwrap_err(),
            "no display stack"
        );
        assert_eq!(inspector.snapshot(Subsystem::Gpu).map(|v| v.len()), Ok(0));
    }

    #[test]
    fn a_read_scan_with_nothing_unread_adds_no_row() {
        let outcome = ScanOutcome::default();
        let (groups, unread) = split_scan(Ok(outcome));
        assert!(groups.is_empty());
        assert!(unread.is_empty());
        assert!(not_read_groups(Subsystem::Display, "EDID", &unread).is_empty());
    }

    #[test]
    fn a_failed_scan_is_one_unread_reason_not_zero_groups() {
        let (groups, unread) = split_scan(Err("cannot list /sys/class/drm".to_string()));
        assert!(groups.is_empty());
        assert_eq!(unread, vec!["cannot list /sys/class/drm".to_string()]);
        let rows = not_read_groups(Subsystem::Display, "EDID", &unread);
        assert_eq!(rows.len(), 1);
        assert_eq!(
            rows[0].notes,
            vec!["EDID not read: cannot list /sys/class/drm"]
        );
    }

    #[test]
    fn partial_scan_keeps_its_groups_and_names_each_unread_item() {
        let mut found = ProfileGroup::new(Subsystem::Memory, "DIMM A0", "x", "x");
        found.push(Setting::info("ecc", "ECC", SettingValue::Bool(true)));
        let outcome = ScanOutcome {
            groups: vec![found],
            unread: vec!["a/eeprom: permission denied".into(), "b/eeprom: EIO".into()],
        };
        let (groups, unread) = split_scan(Ok(outcome));
        assert_eq!(groups.len(), 1);
        assert_eq!(unread.len(), 2);
        let rows = not_read_groups(Subsystem::Memory, "SPD/XMP", &unread);
        assert_eq!(rows[0].notes.len(), 2);
        assert_eq!(rows[0].notes[1], "SPD/XMP not read: b/eeprom: EIO");
    }
}