joularcore 0.2.0

Joular Core is a platform to measure power and energy across all systems, OSes and devices
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
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
/*
 * Copyright (c) 2025-2026, Adel Noureddine.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the
 * GNU Lesser General Public License v3.0 only (LGPL-3.0-only)
 * which accompanies this distribution, and is available at
 * https://www.gnu.org/licenses/lgpl-3.0.en.html
 *
 * Author : Adel Noureddine
 */

//! The sampling engine: turns sensor readings into [`MonitorSample`]s.

use crate::config::{Component, MonitorConfig, Target};
use crate::sensor::{
    AppCpuUtilization, CpuUtilization, Platform, PowerSensor, ProcessCpuUtilization,
    attribute_power,
};
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

/// One reading of the machine's power draw.
///
/// `cpu_power` and `gpu_power` are `None` when the component was not measured -
/// either because [`crate::config::MonitorConfig::component`] excluded it, or
/// because its sensor could not be read. That distinction matters: an
/// unreadable sensor is not the same as an idle one, and reporting `0.0` for both would hide a misconfigured machine.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct MonitorSample {
    /// When the sample was taken, in Unix seconds.
    pub timestamp: u64,
    /// CPU package power in watts, if measured.
    pub cpu_power: Option<f64>,
    /// GPU power in watts, if measured.
    pub gpu_power: Option<f64>,
    /// Whole-system CPU usage, as a percentage.
    pub cpu_usage: f64,
    /// Watts attributed to the monitored PID or application, if one is being
    /// monitored.
    pub target_power: Option<f64>,
    /// How many processes the monitored application was running at sample
    /// time. `None` unless the target is a [`crate::config::Target::App`].
    pub app_pid_count: Option<usize>,
}

impl MonitorSample {
    /// CPU power, or `0.0` when it was not measured.
    #[must_use]
    pub fn cpu_power_or_zero(&self) -> f64 {
        self.cpu_power.unwrap_or(0.0)
    }

    /// GPU power, or `0.0` when it was not measured.
    #[must_use]
    pub fn gpu_power_or_zero(&self) -> f64 {
        self.gpu_power.unwrap_or(0.0)
    }

    /// Sum of the components that were measured, in watts.
    #[must_use]
    pub fn total_power(&self) -> f64 {
        self.cpu_power_or_zero() + self.gpu_power_or_zero()
    }

    /// Power attributed to the monitored process or application, or `0.0` when
    /// nothing is being attributed.
    #[must_use]
    pub fn target_power_or_zero(&self) -> f64 {
        self.target_power.unwrap_or(0.0)
    }
}

/// One sample flattened to six plain numbers.
///
/// This is the shape that crosses a process boundary: it is what the
/// shared-memory [`crate::ringbuffer`] stores. It is read by programs written
/// in other languages, so the field set, the field order and the layout are a
/// stable contract — see [`crate::ringbuffer::RingBufferWriter`] for the wire
/// format.
///
/// Components that were not measured are flattened to `0.0` here. The
/// distinction between "unmeasured" and "idle" lives in [`MonitorSample`], which
/// is what a Rust caller should read.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct PowerRecord {
    /// When the sample was taken, in Unix seconds. Readers can compare this
    /// against the current time to detect stale or paused samples.
    pub timestamp: u64,
    /// CPU power in watts, or `0.0` if not measured.
    pub cpu_power: f64,
    /// GPU power in watts, or `0.0` if not measured.
    pub gpu_power: f64,
    /// Total power in watts.
    pub total_power: f64,
    /// Whole-system CPU usage, as a percentage.
    pub cpu_usage: f64,
    /// Power attributed to the monitored PID or application, or `0.0`.
    pub pid_or_app_power: f64,
}

impl From<&MonitorSample> for PowerRecord {
    fn from(sample: &MonitorSample) -> Self {
        Self {
            timestamp: sample.timestamp,
            cpu_power: sample.cpu_power_or_zero(),
            gpu_power: sample.gpu_power_or_zero(),
            total_power: sample.total_power(),
            cpu_usage: sample.cpu_usage,
            pid_or_app_power: sample.target_power_or_zero(),
        }
    }
}

/// Samples every configured sensor and attributes power to a process or
/// application.
///
/// Build one with [`JoularCoreMonitor::from_config`], or replace individual
/// sensors through [`JoularCoreMonitor::builder`] — which is how you substitute
/// a sensor of your own, such as `vm::VmSensor` under the `vm` feature.
pub struct JoularCoreMonitor {
    platform: Box<dyn Platform>,
    cpu_sensor: Box<dyn PowerSensor>,
    gpu_sensor: Box<dyn PowerSensor>,
    cpu_usage: Box<dyn CpuUtilization>,
    process_tracker: Option<Box<dyn ProcessCpuUtilization>>,
    app_tracker: Option<Box<dyn AppCpuUtilization>>,
    /// What this session measures. Kept whole rather than copied out field by
    /// field, so a tracker created later by [`Self::set_target`] still matches
    /// applications the way this session was configured to.
    config: MonitorConfig,
    /// The idle floor in watts, resolved from
    /// [`MonitorConfig::cpu_idle_baseline`] when the monitor was built.
    cpu_idle_baseline: f64,
}

impl JoularCoreMonitor {
    /// Build a monitor with default configuration for whole-system power.
    ///
    /// ```no_run
    /// use joularcore::JoularCoreMonitor;
    ///
    /// let mut monitor = JoularCoreMonitor::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self::from_config(&MonitorConfig::default())
    }

    /// Convenience constructor to monitor a specific target.
    ///
    /// ```no_run
    /// use joularcore::{JoularCoreMonitor, Target};
    ///
    /// let mut monitor = JoularCoreMonitor::for_target(Target::app("firefox"));
    /// ```
    #[must_use]
    pub fn for_target(target: Target) -> Self {
        Self::from_config(&MonitorConfig {
            target,
            ..Default::default()
        })
    }

    /// Convenience constructor to monitor an application by executable name.
    ///
    /// ```no_run
    /// use joularcore::JoularCoreMonitor;
    ///
    /// let mut monitor = JoularCoreMonitor::for_app("firefox");
    /// ```
    #[must_use]
    pub fn for_app(name: impl Into<String>) -> Self {
        Self::for_target(Target::App(name.into()))
    }

    /// Convenience constructor to monitor a specific process by PID.
    ///
    /// ```no_run
    /// use joularcore::JoularCoreMonitor;
    ///
    /// let mut monitor = JoularCoreMonitor::for_pid(1234);
    /// ```
    #[must_use]
    pub fn for_pid(pid: u32) -> Self {
        Self::for_target(Target::Pid(pid))
    }

    /// Start assembling a monitor for `config`, with this platform's own
    /// sensors already in place.
    ///
    /// Use this when you want to replace one of them — reading CPU power from a
    /// VM file, say — and leave the rest as they are. See
    /// [`MonitorBuilder::cpu_sensor`].
    #[must_use]
    pub fn builder(config: &MonitorConfig) -> MonitorBuilder {
        MonitorBuilder::new(config)
    }

    /// Build a monitor from `config`, using this platform's own sensors.
    ///
    /// Sensors that are unavailable do not fail construction: they report
    /// [`crate::Error::SensorUnavailable`] on each read, which surfaces as
    /// `None` in [`MonitorSample`]. To read power from somewhere else — a VM
    /// power file, a sensor of your own — use [`JoularCoreMonitor::builder`]
    /// instead.
    ///
    /// Building a monitor never blocks.
    ///
    /// ```no_run
    /// use joularcore::config::{MonitorConfig, Target};
    /// use joularcore::monitor::JoularCoreMonitor;
    ///
    /// let config = MonitorConfig {
    ///     target: Target::App("firefox".into()),
    ///     ..Default::default()
    /// };
    /// let mut monitor = JoularCoreMonitor::from_config(&config);
    /// ```
    #[must_use]
    pub fn from_config(config: &MonitorConfig) -> Self {
        MonitorBuilder::new(config).build()
    }

    /// The platform backend these sensors came from.
    #[must_use]
    pub fn platform(&self) -> &dyn Platform {
        self.platform.as_ref()
    }

    /// What this monitor was configured to measure.
    #[must_use]
    pub fn config(&self) -> &MonitorConfig {
        &self.config
    }

    /// Change what power is attributed to.
    ///
    /// Changing the target starts a new tracker, so its first attribution
    /// sample establishes a baseline. This keeps the target and system CPU
    /// intervals aligned after time spent monitoring something else.
    ///
    /// A tracker created here uses the `app_match` and `app_refresh_interval`
    /// this monitor was configured with, so retargeting does not quietly change
    /// how application names are matched.
    pub fn set_target(&mut self, target: Target) {
        if self.config.target == target {
            return;
        }

        // A tracker stores the previous counter values it saw. Reusing it after
        // a different target has been monitored would compare a long target
        // interval with one system-wide sample and can overstate attribution.
        self.process_tracker = None;
        self.app_tracker = None;

        match &target {
            Target::Pid(_) => {
                self.process_tracker = self.platform.process_cpu_usage();
            }
            Target::App(_) => {
                self.app_tracker = self
                    .platform
                    .app_cpu_usage(self.config.app_refresh_interval, self.config.app_match);
            }
            _ => {}
        }

        self.config.target = target;
    }

    /// Change which component is measured. `None` measures both.
    pub fn set_component(&mut self, component: Option<Component>) {
        self.config.component = component;
    }

    /// The idle CPU power currently subtracted before attribution, in watts.
    #[must_use]
    pub fn cpu_idle_baseline(&self) -> f64 {
        self.cpu_idle_baseline
    }

    /// Set the idle CPU power subtracted before attribution. Negative values
    /// are clamped to zero.
    pub fn set_cpu_idle_baseline(&mut self, baseline: f64) {
        self.cpu_idle_baseline = if baseline.is_finite() {
            baseline.max(0.0)
        } else {
            0.0
        };
    }

    /// Prime every sensor.
    ///
    /// Power and utilization are both derived from counter deltas, so the
    /// first reading only establishes a baseline and carries no information.
    /// Call this once before the first [`Self::poll`].
    pub fn prime(&mut self) {
        let _ = self.cpu_sensor.power();
        let _ = self.gpu_sensor.power();
        self.cpu_usage.cpu_utilization();
    }

    /// Measure idle CPU power and adopt it as the baseline, returning it.
    ///
    /// **Blocks the calling thread** for `samples * interval`. The machine
    /// should be idle throughout.
    ///
    /// # Errors
    ///
    /// Returns an error if the CPU sensor cannot be read. In that case the
    /// existing baseline is left unchanged.
    pub fn calibrate_cpu_idle_baseline(
        &mut self,
        samples: usize,
        interval: Duration,
    ) -> crate::Result<f64> {
        // Only the CPU sensor participates in calibration. Its first reading
        // establishes a counter baseline when needed and is deliberately not
        // included in the average.
        self.cpu_sensor.power()?;

        let samples = samples.max(1);
        let mut total = 0.0;
        for _ in 0..samples {
            // Sleep first: a reading taken immediately after the baseline
            // reading covers no real interval and would drag the average
            // towards zero.
            thread::sleep(interval);
            total += self.cpu_sensor.power()?;
        }

        let baseline = total / samples as f64;
        self.set_cpu_idle_baseline(baseline);
        Ok(baseline)
    }

    /// Take one sample, of the target and component this monitor was built for.
    ///
    /// Change either with [`Self::set_target`] or [`Self::set_component`].
    pub fn poll(&mut self) -> MonitorSample {
        let component = self.config.component;
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        // Skip the sensor read for a component the caller excluded. That avoids
        // the cost of shelling out to nvidia-smi / amd-smi, or of running the
        // powermetrics GPU sampler, when only CPU power was asked for.
        let cpu_active = component != Some(Component::Gpu);
        let gpu_active = component != Some(Component::Cpu);

        let cpu_power = cpu_active
            .then(|| read_sensor("CPU", self.cpu_sensor.power()))
            .flatten();
        let gpu_power = gpu_active
            .then(|| read_sensor("GPU", self.gpu_sensor.power()))
            .flatten();

        let cpu_usage = if cpu_active {
            self.cpu_usage.cpu_utilization() * 100.0
        } else {
            0.0
        };
        // Per-process trackers must measure the same interval as the
        // system-wide figure they are compared against.
        let cpu_total = self.cpu_usage.last_totals().map(|totals| totals.total);

        // Attribution is derived from CPU power, so it is meaningless when the
        // CPU is not being measured.
        let attributable = (cpu_power.unwrap_or(0.0) - self.cpu_idle_baseline).max(0.0);
        let mut target_power = None;
        let mut app_pid_count = None;

        if cpu_active {
            match &self.config.target {
                Target::System => {}
                Target::Pid(pid) => {
                    if let Some(tracker) = &mut self.process_tracker {
                        let utilization = tracker.process_cpu_utilization(*pid, cpu_total);
                        target_power = Some(attribute_power(utilization, attributable, cpu_usage));
                    }
                }
                Target::App(name) => {
                    if let Some(tracker) = &mut self.app_tracker {
                        let sample = tracker.app_snapshot(name, cpu_total);
                        target_power =
                            Some(attribute_power(sample.utilization, attributable, cpu_usage));
                        app_pid_count = Some(sample.pids.len());
                    }
                }
            }
        }

        MonitorSample {
            timestamp,
            cpu_power,
            gpu_power,
            cpu_usage,
            target_power,
            app_pid_count,
        }
    }
}

/// Assembles a [`JoularCoreMonitor`], replacing individual sensors.
///
/// Every sensor starts as the one this platform provides, so only the ones you
/// override need mentioning. Anything implementing
/// [`crate::sensor::PowerSensor`] can stand in for one:
///
/// ```no_run
/// use joularcore::sensor::PowerSensor;
/// use joularcore::{JoularCoreMonitor, MonitorConfig};
///
/// /// CPU power read from a source of your own.
/// struct MyCpuSensor;
///
/// impl PowerSensor for MyCpuSensor {
///     fn power(&mut self) -> joularcore::Result<f64> {
///         Ok(42.0)
///     }
/// }
///
/// let config = MonitorConfig::default();
/// let monitor = JoularCoreMonitor::builder(&config)
///     .cpu_sensor(Box::new(MyCpuSensor))
///     .build();
/// ```
///
/// With the `vm` feature, `vm::VmSensor` is exactly this: a `PowerSensor` that
/// reads watts from a file a hypervisor writes.
pub struct MonitorBuilder {
    platform: Box<dyn Platform>,
    config: MonitorConfig,
    /// `None` means "whatever the platform provides"; resolved in
    /// [`MonitorBuilder::build`].
    cpu_sensor: Option<Box<dyn PowerSensor>>,
    gpu_sensor: Option<Box<dyn PowerSensor>>,
    cpu_usage: Option<Box<dyn CpuUtilization>>,
    process_tracker: Option<Box<dyn ProcessCpuUtilization>>,
    app_tracker: Option<Box<dyn AppCpuUtilization>>,
}

impl MonitorBuilder {
    /// Start from `config` and this platform's own backend.
    fn new(config: &MonitorConfig) -> Self {
        Self::with_platform(crate::platform::current(config.elevation), config)
    }

    /// Start from `config` and a backend of your own.
    ///
    /// [`JoularCoreMonitor::builder`] uses the backend for the running
    /// platform; this takes one you implement yourself, for a machine or a
    /// sensor source this crate does not know about.
    #[must_use]
    pub fn with_platform(platform: Box<dyn Platform>, config: &MonitorConfig) -> Self {
        // Only build the tracker the target actually needs: enumerating
        // processes is not free, and neither is holding a `sysinfo::System`.
        let process_tracker = matches!(config.target, Target::Pid(_))
            .then(|| platform.process_cpu_usage())
            .flatten();
        let app_tracker = matches!(config.target, Target::App(_))
            .then(|| platform.app_cpu_usage(config.app_refresh_interval, config.app_match))
            .flatten();

        Self {
            platform,
            config: config.clone(),
            cpu_sensor: None,
            gpu_sensor: None,
            cpu_usage: None,
            process_tracker,
            app_tracker,
        }
    }

    /// Read CPU power from `sensor` instead of the platform's own.
    #[must_use]
    pub fn cpu_sensor(mut self, sensor: Box<dyn PowerSensor>) -> Self {
        self.cpu_sensor = Some(sensor);
        self
    }

    /// Read GPU power from `sensor` instead of the platform's own.
    #[must_use]
    pub fn gpu_sensor(mut self, sensor: Box<dyn PowerSensor>) -> Self {
        self.gpu_sensor = Some(sensor);
        self
    }

    /// Track whole-system CPU utilization with `usage` instead of the
    /// platform's own.
    #[must_use]
    pub fn cpu_usage(mut self, usage: Box<dyn CpuUtilization>) -> Self {
        self.cpu_usage = Some(usage);
        self
    }

    /// Attribute power to processes with `tracker` instead of the platform's
    /// own.
    #[must_use]
    pub fn process_tracker(mut self, tracker: Box<dyn ProcessCpuUtilization>) -> Self {
        self.process_tracker = Some(tracker);
        self
    }

    /// Attribute power to applications with `tracker` instead of the
    /// platform's own.
    #[must_use]
    pub fn app_tracker(mut self, tracker: Box<dyn AppCpuUtilization>) -> Self {
        self.app_tracker = Some(tracker);
        self
    }

    /// Assemble the monitor, applying the configured idle baseline.
    ///
    /// Never blocks.
    #[must_use]
    pub fn build(self) -> JoularCoreMonitor {
        // Only ask the platform for the sensors that were not replaced. On
        // macOS `platform.cpu()` starts `powermetrics`, so a caller reading CPU
        // power from a VM file must not pay for it.
        let cpu_sensor = self.cpu_sensor.unwrap_or_else(|| self.platform.cpu());
        let gpu_sensor = self.gpu_sensor.unwrap_or_else(|| self.platform.gpu());
        let cpu_usage = self.cpu_usage.unwrap_or_else(|| self.platform.cpu_usage());

        let mut monitor = JoularCoreMonitor {
            platform: self.platform,
            cpu_sensor,
            gpu_sensor,
            cpu_usage,
            process_tracker: self.process_tracker,
            app_tracker: self.app_tracker,
            config: self.config,
            cpu_idle_baseline: 0.0,
        };

        if let Some(watts) = monitor.config.cpu_idle_baseline {
            monitor.set_cpu_idle_baseline(watts);
        }

        monitor.prime();
        monitor
    }
}

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

/// Log a failed sensor read once per sample and fold it into `None`.
fn read_sensor(which: &str, reading: crate::Result<f64>) -> Option<f64> {
    match reading {
        Ok(power) => Some(power),
        Err(e) => {
            log::debug!("{which} sensor read failed: {e}");
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::AppMatch;
    use crate::sensor::{AppSample, CpuTotals};
    use std::sync::{Arc, Mutex};

    /// A sensor reporting a fixed wattage, or an unreadable one for `None`.
    struct Fixed(Option<f64>);
    impl PowerSensor for Fixed {
        fn power(&mut self) -> crate::Result<f64> {
            self.0
                .ok_or_else(|| crate::Error::sensor("test", "unavailable"))
        }
    }

    struct FixedUsage(f64);
    impl CpuUtilization for FixedUsage {
        fn cpu_utilization(&mut self) -> f64 {
            self.0
        }
        fn last_totals(&self) -> Option<CpuTotals> {
            Some(CpuTotals::new(1_000, 500))
        }
    }

    struct FixedProcess(f64);
    impl ProcessCpuUtilization for FixedProcess {
        fn process_cpu_utilization(&mut self, _pid: u32, _cpu_total: Option<u64>) -> f64 {
            self.0
        }
    }

    struct FixedApp(f64, usize);
    impl AppCpuUtilization for FixedApp {
        fn app_snapshot(&mut self, _app_name: &str, _cpu_total: Option<u64>) -> AppSample {
            AppSample {
                utilization: self.0,
                pids: (0..self.1 as u32).collect(),
            }
        }
    }

    /// How an app tracker was asked for, so a test can check what the monitor
    /// passed down.
    type AppRequests = Arc<Mutex<Vec<(Duration, AppMatch)>>>;
    /// How many process trackers a platform created.
    type ProcessRequests = Arc<Mutex<usize>>;

    #[derive(Default)]
    struct FakePlatform {
        app_requests: AppRequests,
        process_requests: ProcessRequests,
    }

    impl Platform for FakePlatform {
        fn cpu(&self) -> Box<dyn PowerSensor> {
            Box::new(Fixed(Some(0.0)))
        }
        fn gpu(&self) -> Box<dyn PowerSensor> {
            Box::new(Fixed(Some(0.0)))
        }
        fn cpu_usage(&self) -> Box<dyn CpuUtilization> {
            Box::new(FixedUsage(0.0))
        }
        fn process_cpu_usage(&self) -> Option<Box<dyn ProcessCpuUtilization>> {
            *self.process_requests.lock().unwrap() += 1;
            Some(Box::new(FixedProcess(0.25)))
        }
        fn app_cpu_usage(
            &self,
            refresh_interval: Duration,
            app_match: AppMatch,
        ) -> Option<Box<dyn AppCpuUtilization>> {
            self.app_requests
                .lock()
                .unwrap()
                .push((refresh_interval, app_match));
            Some(Box::new(FixedApp(0.25, 3)))
        }
    }

    fn monitor(cpu: Option<f64>, gpu: Option<f64>, usage: f64) -> JoularCoreMonitor {
        MonitorBuilder::with_platform(Box::<FakePlatform>::default(), &MonitorConfig::default())
            .cpu_sensor(Box::new(Fixed(cpu)))
            .gpu_sensor(Box::new(Fixed(gpu)))
            .cpu_usage(Box::new(FixedUsage(usage)))
            .process_tracker(Box::new(FixedProcess(0.25)))
            .app_tracker(Box::new(FixedApp(0.25, 3)))
            .build()
    }

    #[test]
    fn flattening_a_sample_reports_unmeasured_components_as_zero() {
        // Both wire formats are read by programs that have no way to express
        // "unmeasured", so the projection has to choose a number.
        let record = PowerRecord::from(&MonitorSample {
            timestamp: 7,
            cpu_power: None,
            gpu_power: Some(12.5),
            cpu_usage: 40.0,
            target_power: Some(3.0),
            app_pid_count: None,
        });

        assert_eq!(record.cpu_power, 0.0);
        assert_eq!(record.gpu_power, 12.5);
        assert_eq!(record.total_power, 12.5);
        assert_eq!(record.pid_or_app_power, 3.0);
    }

    #[test]
    fn unreadable_sensor_reports_none_not_zero() {
        let mut m = monitor(None, Some(5.0), 0.5);
        let sample = m.poll();

        assert_eq!(sample.cpu_power, None);
        assert_eq!(sample.cpu_power_or_zero(), 0.0);
        assert_eq!(sample.gpu_power, Some(5.0));
        assert_eq!(sample.total_power(), 5.0);
    }

    #[test]
    fn excluded_component_is_not_measured() {
        let mut m = monitor(Some(40.0), Some(5.0), 0.5);

        m.set_component(Some(Component::Cpu));
        let cpu_only = m.poll();
        assert_eq!(cpu_only.cpu_power, Some(40.0));
        assert_eq!(cpu_only.gpu_power, None);

        m.set_component(Some(Component::Gpu));
        let gpu_only = m.poll();
        assert_eq!(gpu_only.cpu_power, None);
        assert_eq!(gpu_only.gpu_power, Some(5.0));
        // Attribution is CPU-derived, so it is skipped in GPU-only mode.
        assert_eq!(gpu_only.cpu_usage, 0.0);
    }

    #[test]
    fn process_and_app_power_are_attributed_from_cpu_power() {
        let mut m = monitor(Some(40.0), Some(0.0), 0.5);

        m.set_target(Target::Pid(1));
        let pid = m.poll();
        // 25% of capacity used while the machine was 50% busy -> half of 40 W.
        assert_eq!(pid.target_power, Some(20.0));
        assert_eq!(pid.target_power_or_zero(), 20.0);
        // Only an application target counts processes.
        assert_eq!(pid.app_pid_count, None);

        m.set_target(Target::App("firefox".into()));
        let app = m.poll();
        assert_eq!(app.target_power, Some(20.0));
        assert_eq!(app.app_pid_count, Some(3));
    }

    #[test]
    fn retargeting_at_an_app_keeps_the_configured_matching() {
        // A monitor built for the whole system creates its app tracker lazily,
        // and that tracker has to match names the way this session was
        // configured to — not the way the library's defaults would.
        let platform = FakePlatform::default();
        let requests = platform.app_requests.clone();

        let config = MonitorConfig {
            app_match: AppMatch::Contains,
            app_refresh_interval: Duration::from_secs(10),
            ..Default::default()
        };

        let mut m = MonitorBuilder::with_platform(Box::new(platform), &config).build();
        // Built for Target::System, so nothing has been asked for yet.
        assert!(requests.lock().unwrap().is_empty());

        m.set_target(Target::App("firefox".into()));

        assert_eq!(
            requests.lock().unwrap().as_slice(),
            [(Duration::from_secs(10), AppMatch::Contains)]
        );
    }

    #[test]
    fn retargeting_restarts_the_relevant_tracker() {
        let platform = FakePlatform::default();
        let app_requests = platform.app_requests.clone();
        let process_requests = platform.process_requests.clone();
        let mut m =
            MonitorBuilder::with_platform(Box::new(platform), &MonitorConfig::default()).build();

        m.set_target(Target::Pid(1));
        // Setting the same target is a no-op and keeps its established baseline.
        m.set_target(Target::Pid(1));
        m.set_target(Target::System);
        m.set_target(Target::Pid(1));
        assert_eq!(*process_requests.lock().unwrap(), 2);

        m.set_target(Target::App("firefox".into()));
        m.set_target(Target::System);
        m.set_target(Target::App("firefox".into()));
        assert_eq!(app_requests.lock().unwrap().len(), 2);
    }

    #[test]
    fn idle_baseline_is_removed_before_attribution() {
        let mut m = monitor(Some(40.0), Some(0.0), 0.5);
        m.set_cpu_idle_baseline(20.0);

        m.set_target(Target::Pid(1));
        let sample = m.poll();
        // Reported CPU power stays raw; only attribution sees the baseline.
        assert_eq!(sample.cpu_power, Some(40.0));
        assert_eq!(sample.target_power, Some(10.0));
    }

    #[test]
    fn baseline_rejects_negative_and_non_finite_values() {
        let mut m = monitor(Some(40.0), Some(0.0), 0.5);

        m.set_cpu_idle_baseline(-5.0);
        assert_eq!(m.cpu_idle_baseline(), 0.0);

        m.set_cpu_idle_baseline(f64::NAN);
        assert_eq!(m.cpu_idle_baseline(), 0.0);
    }

    #[test]
    fn calibration_adopts_the_average_of_successful_readings() {
        let mut m = monitor(Some(40.0), Some(0.0), 0.5);

        assert_eq!(
            m.calibrate_cpu_idle_baseline(3, Duration::ZERO).unwrap(),
            40.0
        );
        assert_eq!(m.cpu_idle_baseline(), 40.0);
    }

    #[test]
    fn calibration_failure_preserves_the_existing_baseline() {
        let mut m = monitor(None, Some(0.0), 0.5);
        m.set_cpu_idle_baseline(12.0);

        assert!(m.calibrate_cpu_idle_baseline(1, Duration::ZERO).is_err());
        assert_eq!(m.cpu_idle_baseline(), 12.0);
    }

    #[test]
    fn convenience_constructors_set_expected_targets() {
        let default_m = JoularCoreMonitor::default();
        assert_eq!(default_m.config().target, Target::System);

        let new_m = JoularCoreMonitor::new();
        assert_eq!(new_m.config().target, Target::System);

        let app_m = JoularCoreMonitor::for_app("firefox");
        assert_eq!(app_m.config().target, Target::App("firefox".into()));

        let pid_m = JoularCoreMonitor::for_pid(42);
        assert_eq!(pid_m.config().target, Target::Pid(42));
    }
}