ironmonitor 7.0.2

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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
//! Memory bandwidth monitoring and estimation.
//!
//! Monitors memory bus utilization via hardware performance counters
//! (Intel IMC / AMD Data Fabric) when available, and provides bandwidth
//! estimation from DIMM configuration parameters (speed, channels, width).
//!
//! ## Platform Support
//!
//! - **Linux**: `/sys/devices/uncore_imc_*/`, perf events, DIMM config inference
//! - **Windows**: Performance counters, DIMM config inference
//! - **macOS**: none. The memory configuration is not exposed, so
//!   [`MemoryBandwidthMonitor::new`] returns an error with the reason.

use serde::{Deserialize, Serialize};

use crate::error::IronError;

/// Memory technology generation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MemoryGeneration {
    DDR3,
    DDR4,
    DDR5,
    LPDDR4,
    LPDDR4X,
    LPDDR5,
    LPDDR5X,
    HBM2,
    HBM2E,
    HBM3,
    HBM3E,
    GDDR6,
    GDDR6X,
    Unknown,
}

impl MemoryGeneration {
    /// Bus width in bits for this technology.
    pub fn bus_width_bits(&self) -> u32 {
        match self {
            Self::DDR3 | Self::DDR4 | Self::DDR5 => 64,
            Self::LPDDR4 | Self::LPDDR4X => 32, // per channel
            Self::LPDDR5 | Self::LPDDR5X => 32,
            Self::HBM2 => 128, // per channel, 8 channels per stack
            Self::HBM2E => 128,
            Self::HBM3 => 128,
            Self::HBM3E => 128,
            Self::GDDR6 => 32,
            Self::GDDR6X => 32,
            Self::Unknown => 64,
        }
    }

    /// Typical peak speed in MT/s for each generation.
    pub fn typical_speed_mts(&self) -> u32 {
        match self {
            Self::DDR3 => 1600,
            Self::DDR4 => 3200,
            Self::DDR5 => 5600,
            Self::LPDDR4 => 4267,
            Self::LPDDR4X => 4267,
            Self::LPDDR5 => 6400,
            Self::LPDDR5X => 8533,
            Self::HBM2 => 2000,
            Self::HBM2E => 3200,
            Self::HBM3 => 6400,
            Self::HBM3E => 9600,
            Self::GDDR6 => 16000,
            Self::GDDR6X => 21000,
            Self::Unknown => 3200,
        }
    }
}

impl std::fmt::Display for MemoryGeneration {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::DDR3 => write!(f, "DDR3"),
            Self::DDR4 => write!(f, "DDR4"),
            Self::DDR5 => write!(f, "DDR5"),
            Self::LPDDR4 => write!(f, "LPDDR4"),
            Self::LPDDR4X => write!(f, "LPDDR4X"),
            Self::LPDDR5 => write!(f, "LPDDR5"),
            Self::LPDDR5X => write!(f, "LPDDR5X"),
            Self::HBM2 => write!(f, "HBM2"),
            Self::HBM2E => write!(f, "HBM2E"),
            Self::HBM3 => write!(f, "HBM3"),
            Self::HBM3E => write!(f, "HBM3E"),
            Self::GDDR6 => write!(f, "GDDR6"),
            Self::GDDR6X => write!(f, "GDDR6X"),
            Self::Unknown => write!(f, "Unknown"),
        }
    }
}

/// Memory channel configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelConfig {
    /// Number of active channels.
    pub active_channels: u32,
    /// Maximum supported channels.
    pub max_channels: u32,
    /// Whether running in interleaved mode.
    pub interleaved: bool,
    /// Channel mode description.
    pub mode: String,
}

/// Bandwidth estimation from DIMM configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BandwidthEstimate {
    /// Memory generation.
    pub generation: MemoryGeneration,
    /// Speed in MT/s, or `None` where no DIMM speed was read.
    ///
    /// **This was filled from `MemoryGeneration::typical_speed_mts()` whenever
    /// the real speed was missing** -- a lookup table keyed on the generation,
    /// published by the ontology as a `specification` of *this* machine's
    /// memory. A DDR5 system whose SMBIOS speed field was unreadable reported
    /// 5600 MT/s because that is what DDR5 typically runs at. That is the exact
    /// defect class `AGENTS.md` cites: a plausible constant arriving through
    /// the same field as a reading.
    pub speed_mts: Option<u32>,
    /// Channel configuration.
    pub channels: ChannelConfig,
    /// Theoretical peak bandwidth (GB/s), or `None` without a speed to compute it from.
    pub peak_bandwidth_gbs: Option<f64>,
    /// Estimated achievable bandwidth (GB/s) — typically 70-85% of peak, or `None` without a speed to compute it from.
    pub achievable_bandwidth_gbs: Option<f64>,
    /// Estimated read bandwidth (GB/s), or `None` without a speed to compute it from.
    pub estimated_read_gbs: Option<f64>,
    /// Estimated write bandwidth (GB/s), or `None` without a speed to compute it from.
    pub estimated_write_gbs: Option<f64>,
    /// STREAM Triad estimate (GB/s), or `None` without a speed to compute it from.
    pub stream_triad_estimate_gbs: Option<f64>,
}

/// Live bandwidth measurement (if hardware counters available).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BandwidthMeasurement {
    /// Measured read bandwidth (GB/s).
    pub read_gbs: f64,
    /// Measured write bandwidth (GB/s).
    pub write_gbs: f64,
    /// Total measured bandwidth (GB/s).
    pub total_gbs: f64,
    /// Measurement source.
    pub source: String,
    /// Measurement duration (microseconds).
    pub duration_us: u64,
    /// Bus utilization percentage.
    pub utilization_pct: f64,
}

/// Bandwidth analysis and recommendations.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BandwidthAnalysis {
    /// Bandwidth estimate (always available).
    pub estimate: BandwidthEstimate,
    /// Live measurement (if hardware counters available).
    pub measurement: Option<BandwidthMeasurement>,
    /// Latency estimate in nanoseconds.
    pub estimated_latency_ns: f64,
    /// Score (0-100) based on bandwidth per core, or `None` when the core count
    /// could not be read.
    ///
    /// Both this and `potential_bottleneck` are quotients over
    /// `available_parallelism()`, which used to fall back to `4.0`. Defined
    /// arithmetic is not the same as a defined result: a machine whose core
    /// count is unreadable got a score and a bottleneck verdict computed from an
    /// invented denominator, and neither carried any sign of it. Neither field is
    /// published to the ontology — scores are a judgement rather than a reading,
    /// the same call made for `single_thread_score` and `acceleration_score`.
    pub bandwidth_score: Option<u32>,
    /// Whether memory is likely a bottleneck, or `None` when the core count could
    /// not be read.
    pub potential_bottleneck: Option<bool>,
    /// Recommendations.
    pub recommendations: Vec<String>,
}

/// Memory bandwidth monitor.
pub struct MemoryBandwidthMonitor {
    analysis: BandwidthAnalysis,
}

impl MemoryBandwidthMonitor {
    /// Create a new memory bandwidth monitor.
    pub fn new() -> Result<Self, IronError> {
        let analysis = Self::analyze()?;
        Ok(Self { analysis })
    }

    /// Refresh.
    pub fn refresh(&mut self) -> Result<(), IronError> {
        self.analysis = Self::analyze()?;
        Ok(())
    }

    /// Get analysis.
    pub fn analysis(&self) -> &BandwidthAnalysis {
        &self.analysis
    }

    /// Get the bandwidth estimate.
    pub fn estimate(&self) -> &BandwidthEstimate {
        &self.analysis.estimate
    }

    fn analyze() -> Result<BandwidthAnalysis, IronError> {
        let (generation, speed_mts, channels) = Self::detect_memory_config()?;

        // Every figure below is computed from the speed. Without one there is
        // nothing to compute from, and a typical speed for the generation would
        // make each of them an estimate of a different machine.
        let peak = speed_mts.map(|speed| {
            Self::compute_peak_bandwidth(speed, channels.active_channels, &generation)
        });

        // Achievable is typically 70-85% of peak depending on technology
        let efficiency = match generation {
            MemoryGeneration::DDR5 => 0.82,
            MemoryGeneration::DDR4 => 0.78,
            MemoryGeneration::DDR3 => 0.72,
            MemoryGeneration::LPDDR5 | MemoryGeneration::LPDDR5X => 0.80,
            MemoryGeneration::LPDDR4 | MemoryGeneration::LPDDR4X => 0.75,
            MemoryGeneration::HBM2 | MemoryGeneration::HBM2E => 0.90,
            MemoryGeneration::HBM3 | MemoryGeneration::HBM3E => 0.92,
            _ => 0.75,
        };

        let achievable = peak.map(|p| p * efficiency);
        let read_ratio = 0.65; // Typical workloads are ~65% reads
        let stream_triad_ratio = 0.72; // STREAM Triad typically achieves ~72% of peak

        let estimate = BandwidthEstimate {
            generation,
            speed_mts,
            channels,
            peak_bandwidth_gbs: peak,
            achievable_bandwidth_gbs: achievable,
            estimated_read_gbs: achievable.map(|a| a * read_ratio),
            estimated_write_gbs: achievable.map(|a| a * (1.0 - read_ratio)),
            stream_triad_estimate_gbs: peak.map(|p| p * stream_triad_ratio),
        };

        // Try live measurement
        let measurement = Self::try_measure(&estimate);

        // Latency estimate
        let latency_ns = match generation {
            MemoryGeneration::DDR5 => 85.0, // CAS latency offset by higher speed
            MemoryGeneration::DDR4 => 70.0,
            MemoryGeneration::DDR3 => 55.0,
            MemoryGeneration::LPDDR5 | MemoryGeneration::LPDDR5X => 90.0,
            MemoryGeneration::LPDDR4 | MemoryGeneration::LPDDR4X => 80.0,
            MemoryGeneration::HBM2 | MemoryGeneration::HBM2E => 30.0,
            MemoryGeneration::HBM3 | MemoryGeneration::HBM3E => 25.0,
            _ => 70.0,
        };

        // Score: bandwidth per core. Absent when either side of the quotient
        // is: the core count, or -- now that it can be missing -- the
        // achievable bandwidth. A per-core figure from a typical speed would
        // put a bottleneck recommendation in front of someone on the strength
        // of a lookup table.
        let bw_per_core = std::thread::available_parallelism()
            .ok()
            .zip(achievable)
            .map(|(n, a)| a / n.get() as f64);
        let score = bw_per_core.map(|b| (b * 10.0).min(100.0) as u32);

        // < 3 GB/s per core is concerning
        let potential_bottleneck = bw_per_core.map(|b| b < 3.0);

        let mut recommendations = Vec::new();

        if estimate.channels.active_channels < estimate.channels.max_channels {
            recommendations.push(format!(
                "Running {}-channel; {} channels available. Adding DIMMs could increase bandwidth {:.0}%",
                estimate.channels.active_channels,
                estimate.channels.max_channels,
                (estimate.channels.max_channels as f64 / estimate.channels.active_channels as f64 - 1.0) * 100.0
            ));
        }

        // Only advise on a per-core figure that was actually computed.
        if let (Some(true), Some(per_core)) = (potential_bottleneck, bw_per_core) {
            recommendations.push(format!(
                "Low bandwidth per core ({:.1} GB/s). Consider faster memory or more channels",
                per_core
            ));
        }

        if generation == MemoryGeneration::DDR4 {
            recommendations.push("DDR5 upgrade could provide ~40-75% more bandwidth".into());
        }

        Ok(BandwidthAnalysis {
            estimate,
            measurement,
            estimated_latency_ns: latency_ns,
            bandwidth_score: score,
            potential_bottleneck,
            recommendations,
        })
    }

    fn compute_peak_bandwidth(speed_mts: u32, channels: u32, gen: &MemoryGeneration) -> f64 {
        let bus_width = gen.bus_width_bits();
        // Peak BW = speed_mts × bus_width_bytes × channels / 1000 (to GB/s)
        let bus_width_bytes = bus_width as f64 / 8.0;
        speed_mts as f64 * bus_width_bytes * channels as f64 / 1000.0
    }

    #[cfg(target_os = "linux")]
    fn detect_memory_config() -> Result<(MemoryGeneration, Option<u32>, ChannelConfig), IronError> {
        // Try dmidecode first
        let output = std::process::Command::new("dmidecode")
            .args(["-t", "memory"])
            .output();

        if let Ok(out) = output {
            let text = String::from_utf8_lossy(&out.stdout);
            return Self::parse_dmidecode(&text);
        }

        // Nothing read.
        Self::memory_config_unreadable()
    }

    #[cfg(target_os = "linux")]
    fn parse_dmidecode(
        text: &str,
    ) -> Result<(MemoryGeneration, Option<u32>, ChannelConfig), IronError> {
        let mut generation = MemoryGeneration::Unknown;
        let mut max_speed = 0u32;
        let mut populated_count = 0u32;
        let mut total_slots = 0u32;

        let mut in_device = false;

        for line in text.lines() {
            let trimmed = line.trim();

            if trimmed.starts_with("Memory Device") {
                in_device = true;
                total_slots += 1;
                continue;
            }

            if !in_device {
                continue;
            }

            if trimmed.starts_with("Type:") {
                let val = trimmed.strip_prefix("Type:").unwrap_or("").trim();
                match val {
                    "DDR3" => generation = MemoryGeneration::DDR3,
                    "DDR4" => generation = MemoryGeneration::DDR4,
                    "DDR5" => generation = MemoryGeneration::DDR5,
                    "LPDDR4" => generation = MemoryGeneration::LPDDR4,
                    "LPDDR5" => generation = MemoryGeneration::LPDDR5,
                    _ => {}
                }
            }

            if trimmed.starts_with("Speed:") {
                if let Some(speed_str) = trimmed.strip_prefix("Speed:").and_then(|s| {
                    s.trim()
                        .strip_suffix("MT/s")
                        .or_else(|| s.trim().strip_suffix("MHz"))
                }) {
                    if let Ok(speed) = speed_str.trim().parse::<u32>() {
                        if speed > max_speed {
                            max_speed = speed;
                        }
                        if speed > 0 {
                            populated_count += 1;
                        }
                    }
                }
            }

            if trimmed.is_empty() {
                in_device = false;
            }
        }

        // No substitution. `max_speed == 0` means no DIMM reported a speed,
        // and a typical speed for the generation is not this machine's.
        let speed = (max_speed > 0).then_some(max_speed);

        let (active_channels, max_channels) =
            Self::infer_channels(populated_count, total_slots, &generation);

        Ok((
            generation,
            speed,
            ChannelConfig {
                active_channels,
                max_channels,
                interleaved: active_channels > 1 && populated_count >= active_channels,
                mode: format!("{}-channel", active_channels),
            },
        ))
    }

    #[cfg(target_os = "windows")]
    fn detect_memory_config() -> Result<(MemoryGeneration, Option<u32>, ChannelConfig), IronError> {
        let output = std::process::Command::new("powershell")
            .args([
                "-NoProfile",
                "-Command",
                "Get-CimInstance Win32_PhysicalMemory | Select-Object Speed, SMBIOSMemoryType, DeviceLocator | ConvertTo-Json",
            ])
            .output();

        if let Ok(out) = output {
            let text = String::from_utf8_lossy(&out.stdout);
            if let Ok(val) = serde_json::from_str::<serde_json::Value>(&text) {
                let items = if val.is_array() {
                    val.as_array().cloned().unwrap_or_default()
                } else {
                    vec![val]
                };

                let populated = items.len() as u32;
                let mut max_speed = 0u32;
                let mut gen = MemoryGeneration::Unknown;

                for item in &items {
                    if let Some(speed) = item["Speed"].as_u64() {
                        max_speed = max_speed.max(speed as u32);
                    }
                    if let Some(smbios_type) = item["SMBIOSMemoryType"].as_u64() {
                        gen = match smbios_type {
                            24 => MemoryGeneration::DDR3,
                            26 => MemoryGeneration::DDR4,
                            34 => MemoryGeneration::DDR5,
                            _ => MemoryGeneration::Unknown,
                        };
                    }
                }

                // No substitution; see the Linux reader.
                let speed = (max_speed > 0).then_some(max_speed);

                let (active, max) = Self::infer_channels(populated, populated, &gen);

                return Ok((
                    gen,
                    speed,
                    ChannelConfig {
                        active_channels: active,
                        max_channels: max,
                        interleaved: active > 1,
                        mode: format!("{}-channel", active),
                    },
                ));
            }
        }

        Self::memory_config_unreadable()
    }

    #[cfg(target_os = "macos")]
    fn detect_memory_config() -> Result<(MemoryGeneration, Option<u32>, ChannelConfig), IronError> {
        // This matched the CPU brand string -- `M4` to LPDDR5X-8533 on eight
        // channels, `M3` and `M2` to LPDDR5-6400 on eight, anything else to
        // LPDDR5-6400 on four -- and the resolver published the result as a
        // `specification` of this machine. It read no memory. It was also
        // wrong where it could be checked: `M3` matched the M3, M3 Pro and M3
        // Max, whose memory buses differ, and the last arm gave the original M1
        // a memory generation it did not ship with.
        //
        // It is not rebuilt as a per-chip table because Apple does not publish
        // what one would need: its specifications give a bandwidth per chip,
        // not a generation, transfer rate and channel count. Reconstructing
        // those three from recall is the defect this replaced, with better
        // numbers. Declining leaves `memory.bandwidth.<none>` saying why.
        Err(IronError::FeatureNotAvailable(
            concat!(
                "macOS exposes no memory generation, transfer rate or channel ",
                "count to read; Apple publishes a bandwidth per chip, but not ",
                "the configuration an estimate is built from"
            )
            .into(),
        ))
    }

    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
    fn detect_memory_config() -> Result<(MemoryGeneration, Option<u32>, ChannelConfig), IronError> {
        Self::memory_config_unreadable()
    }

    /// The memory configuration could not be read on this path.
    ///
    /// **This was `infer_from_cpu`, and it inferred nothing.** It returned
    /// `DDR4`, 3200 MT/s and a dual-channel layout as constants whenever SMBIOS
    /// could not be read -- and because it said `DDR4` rather than `Unknown`,
    /// it defeated the resolver guard written specifically to withhold figures
    /// built on an unidentified generation. A machine whose memory was not read
    /// at all published DDR4-3200 dual-channel as a specification of itself.
    ///
    /// An error is the honest answer, and the resolver already has the right
    /// path for one: it reports the configuration as unreadable and publishes
    /// nothing built on it.
    ///
    /// Not compiled on macOS, which declines with its own reason: there is no
    /// SMBIOS path there to have failed.
    #[cfg(not(target_os = "macos"))]
    fn memory_config_unreadable(
    ) -> Result<(MemoryGeneration, Option<u32>, ChannelConfig), IronError> {
        Err(IronError::FeatureNotAvailable(
            "the memory configuration (generation, speed, channels) could not be read from SMBIOS"
                .into(),
        ))
    }

    fn infer_channels(populated: u32, total_slots: u32, _gen: &MemoryGeneration) -> (u32, u32) {
        // Heuristic: 2 DIMMs per channel, max 4 channels for desktop, 8 for server
        let max = if total_slots >= 8 {
            (total_slots / 2).min(8)
        } else if total_slots >= 4 {
            (total_slots / 2).min(4)
        } else {
            total_slots.max(1)
        };

        let active = if populated > 0 { populated.min(max) } else { 1 };

        (active, max)
    }

    fn try_measure(estimate: &BandwidthEstimate) -> Option<BandwidthMeasurement> {
        #[cfg(target_os = "linux")]
        {
            // Try reading IMC counters
            Self::read_imc_counters(estimate)
        }
        #[cfg(not(target_os = "linux"))]
        {
            let _ = estimate;
            None
        }
    }

    #[cfg(target_os = "linux")]
    fn read_imc_counters(estimate: &BandwidthEstimate) -> Option<BandwidthMeasurement> {
        // Check for uncore IMC perf events
        let imc_path = std::path::Path::new("/sys/devices");
        if !imc_path.exists() {
            return None;
        }

        // Look for uncore_imc_* directories
        let entries = std::fs::read_dir(imc_path).ok()?;
        let has_imc = entries
            .filter_map(|e| e.ok())
            .any(|e| e.file_name().to_string_lossy().starts_with("uncore_imc"));

        if has_imc {
            // IMC counters found but would need perf_event_open() to read
            // Return a stub indicating capability exists
            Some(BandwidthMeasurement {
                read_gbs: 0.0,
                write_gbs: 0.0,
                total_gbs: 0.0,
                source: "uncore_imc (counters detected, perf_event needed)".into(),
                duration_us: 0,
                utilization_pct: 0.0,
            })
        } else {
            // No hardware counters, just use estimate
            let _ = estimate;
            None
        }
    }
}

impl Default for MemoryBandwidthMonitor {
    fn default() -> Self {
        Self::new().unwrap_or(Self {
            analysis: BandwidthAnalysis {
                estimate: BandwidthEstimate {
                    generation: MemoryGeneration::Unknown,
                    speed_mts: None,
                    channels: ChannelConfig {
                        active_channels: 0,
                        max_channels: 0,
                        interleaved: false,
                        mode: String::new(),
                    },
                    peak_bandwidth_gbs: None,
                    achievable_bandwidth_gbs: None,
                    estimated_read_gbs: None,
                    estimated_write_gbs: None,
                    stream_triad_estimate_gbs: None,
                },
                measurement: None,
                estimated_latency_ns: 0.0,
                bandwidth_score: None,
                potential_bottleneck: None,
                recommendations: Vec::new(),
            },
        })
    }
}

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

    /// macOS exposes no memory configuration, so there is nothing to estimate
    /// from. This used to succeed with a configuration looked up from the CPU
    /// brand string, which the resolver then published as a specification.
    #[cfg(target_os = "macos")]
    #[test]
    fn macos_declines_rather_than_looking_up_a_configuration() {
        match MemoryBandwidthMonitor::new() {
            Err(IronError::FeatureNotAvailable(why)) => {
                assert!(why.contains("macOS"), "{why}")
            }
            Err(e) => panic!("expected FeatureNotAvailable, got {e}"),
            Ok(m) => panic!(
                "macOS produced a memory configuration it cannot read: {:?}",
                m.analysis()
            ),
        }
    }

    #[test]
    fn test_peak_bandwidth_ddr4() {
        // DDR4-3200 dual channel: 3200 × 8 × 2 / 1000 = 51.2 GB/s
        let bw = MemoryBandwidthMonitor::compute_peak_bandwidth(3200, 2, &MemoryGeneration::DDR4);
        assert!((bw - 51.2).abs() < 0.1);
    }

    #[test]
    fn test_peak_bandwidth_ddr5() {
        // DDR5-5600 dual channel: 5600 × 8 × 2 / 1000 = 89.6 GB/s
        let bw = MemoryBandwidthMonitor::compute_peak_bandwidth(5600, 2, &MemoryGeneration::DDR5);
        assert!((bw - 89.6).abs() < 0.1);
    }

    #[test]
    fn test_generation_display() {
        assert_eq!(MemoryGeneration::DDR5.to_string(), "DDR5");
        assert_eq!(MemoryGeneration::LPDDR5X.to_string(), "LPDDR5X");
        assert_eq!(MemoryGeneration::HBM3E.to_string(), "HBM3E");
    }

    #[test]
    fn test_channel_inference() {
        // 2 populated out of 4 slots
        let (active, max) = MemoryBandwidthMonitor::infer_channels(2, 4, &MemoryGeneration::DDR4);
        assert_eq!(active, 2);
        assert_eq!(max, 2);

        // Server: 8 populated out of 16 slots
        let (active, max) = MemoryBandwidthMonitor::infer_channels(8, 16, &MemoryGeneration::DDR5);
        assert_eq!(active, 8);
        assert_eq!(max, 8);
    }

    #[test]
    fn test_monitor_default() {
        let monitor = MemoryBandwidthMonitor::default();
        let _analysis = monitor.analysis();
    }

    #[test]
    fn test_serialization() {
        let estimate = BandwidthEstimate {
            generation: MemoryGeneration::DDR5,
            speed_mts: Some(5600),
            channels: ChannelConfig {
                active_channels: 2,
                max_channels: 4,
                interleaved: true,
                mode: "dual-channel".into(),
            },
            peak_bandwidth_gbs: Some(89.6),
            achievable_bandwidth_gbs: Some(73.5),
            estimated_read_gbs: Some(47.8),
            estimated_write_gbs: Some(25.7),
            stream_triad_estimate_gbs: Some(64.5),
        };
        let json = serde_json::to_string(&estimate).unwrap();
        assert!(json.contains("DDR5"));
        let _: BandwidthEstimate = serde_json::from_str(&json).unwrap();
    }
}

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

    /// The per-core figures are a quotient, and a quotient over an unread
    /// denominator is not a reading. `available_parallelism()` answers on every
    /// platform this runs on, so the absent arm cannot be reached from a test —
    /// what is asserted here is the invariant that ties the three fields
    /// together, which holds whichever arm was taken.
    #[test]
    fn the_score_and_the_bottleneck_verdict_agree_on_whether_they_were_computed() {
        let analysis = MemoryBandwidthMonitor::new()
            .map(|m| m.analysis().clone())
            .unwrap_or_else(|_| return_empty());

        assert_eq!(
            analysis.bandwidth_score.is_some(),
            analysis.potential_bottleneck.is_some(),
            "both derive from the same core count, so one cannot be present \
             while the other is absent"
        );

        if let Some(score) = analysis.bandwidth_score {
            assert!(score <= 100, "the score is a 0-100 scale, got {score}");
        }
    }

    /// A bottleneck recommendation quotes a per-core figure, so it may only
    /// appear when that figure exists.
    #[test]
    fn no_per_core_advice_is_given_without_a_per_core_figure() {
        let analysis = MemoryBandwidthMonitor::new()
            .map(|m| m.analysis().clone())
            .unwrap_or_else(|_| return_empty());

        if analysis.potential_bottleneck.is_none() {
            assert!(
                !analysis
                    .recommendations
                    .iter()
                    .any(|r| r.contains("bandwidth per core")),
                "advised on a per-core figure that was never computed"
            );
        }
    }

    fn return_empty() -> BandwidthAnalysis {
        MemoryBandwidthMonitor::default().analysis().clone()
    }
}