perf-sentinel-core 0.9.7

Core library for perf-sentinel: polyglot performance anti-pattern detector
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
//! Embedded `SPECpower` instance type lookup table.
//!
//! Maps cloud instance types to their `(idle_watts, max_watts)` envelope.
//! All entries now follow a single homogeneous methodology after the
//! 2026-04-24 refresh:
//!
//! `idle_watts = vCPU * idle_per_vcpu_coefficient`
//! `max_watts  = vCPU * max_per_vcpu_coefficient`
//!
//! Coefficients are taken per provider from the [Cloud Carbon
//! Footprint coefficients] CSVs (`coefficients-{aws,gcp,azure}-use.csv`,
//! current snapshot in the `table_data.rs` header). No baseboard
//! overhead is reconstructed: since the 2026-04-24 snapshot CCF no
//! longer publishes a separate baseboard column for AWS. Entries
//! covered by the CSVs align to CCF for source-of-truth homogeneity
//! and live in `table_data.rs` (regenerated by
//! `scripts/refresh-instance-power.py`); the direct-compute
//! `SPECpower_ssj 2008` entries absent from the provider CSV are kept
//! as-is in [`MANUAL_INSTANCE_ROWS`] below.
//!
//! Graviton 2 / 3 / 3E / 4 share the CCF EPYC 2nd Gen coefficient (no
//! published `SPECpower` submissions for these silicon variants). The
//! Cobalt 100 ARM and Ampere Altra entries that are absent from the
//! Azure / GCP CSV are kept on the `SPECpower` direct compute.
//! Sierra Forest entries (`xeon-6780e`) are 1-chip system level for
//! bare-metal users owning the full chip, not vCPU-scaled.
//!
//! Memory-optimized families (AWS r-series, GCP `n2-highmem-*`, Azure
//! `Standard_E*`) get an additive DRAM premium of `0.02 W/GB` idle and
//! `0.05 W/GB` max, applied on top of the per-vCPU CPU coefficient. The
//! coefficient is sourced from Crucial DDR4 RDIMM datasheets and the
//! Boavizta DIMM model. Memory ratio is 8 GB per vCPU for the families
//! above, giving a per-vCPU uplift of `+0.16` idle and `+0.40` max.
//! CCF 2026-04-24 does not publish a memory-class premium so this is
//! one of the two methodology departures from the CSV (the other being
//! the Turin override below). General-purpose families (`m*`) carry
//! ~4 GB/vCPU of DRAM and compute-optimized families (`c*`) carry
//! ~2 GB/vCPU; neither receives the DRAM premium under the current
//! rule, so their idle is under-counted by ~6-8 percent and ~3-4
//! percent respectively. Both stay inside the 2x uncertainty bracket.
//! EPYC 5th Gen Turin (AWS `m8a` / `c8a`) is proxied to Genoa instead
//! of importing the CCF row verbatim (the CCF Turin coefficient is
//! ~5x higher than neighbouring architectures, likely measured at chip
//! granularity by an upstream `SPECpower` submission). See
//! `docs/LIMITATIONS.md` for both rationale and uncertainty brackets.
//!
//! Full methodology, uncertainty bounds, and per-architecture caveats
//! are in `docs/LIMITATIONS.md` "Cloud `SPECpower` precision bounds".
//!
//! [Cloud Carbon Footprint coefficients]: https://github.com/cloud-carbon-footprint/ccf-coefficients

use std::collections::HashMap;
use std::sync::LazyLock;

// The vintage lives in the generated file, stamped by the refresh
// script. Re-exported to keep `embedded_specpower_vintage` stable.
pub(crate) use super::table_data::SPECPOWER_VINTAGE;

/// Memory-optimized DRAM premium, applied additively on top of the
/// per-vCPU CPU coefficient for r-series / highmem / `Standard_E*`
/// families. `0.02 W/GB` idle, `0.05 W/GB` max, sourced from Crucial
/// DDR4 RDIMM datasheets and the Boavizta DIMM model. The 8 GB / vCPU
/// memory ratio of those families gives a per-vCPU uplift of
/// `+0.16` idle / `+0.40` max, embedded inline in the row values.
#[allow(dead_code)]
pub(crate) const DRAM_PREMIUM_W_PER_GB_IDLE: f64 = 0.02;
#[allow(dead_code)]
pub(crate) const DRAM_PREMIUM_W_PER_GB_MAX: f64 = 0.05;

/// Entries absent from the CCF CSVs, kept on `SPECpower` direct
/// compute or documented blends and refreshed by hand. The CSV-derived
/// bulk lives in `table_data.rs`. The refresh script warns when a new
/// CCF snapshot starts covering one of these families.
static MANUAL_INSTANCE_ROWS: &[(&str, f64, f64)] = &[
    // --- c4d (GCP, AMD Turin, EPYC 9005 Zen 5) ---
    // CCF GCP CSV 2026-04-24 does not publish EPYC 5th Gen Turin
    // coefficients (Google's deployment was not yet mapped at the
    // CCF snapshot). Kept on the SPECpower direct compute (n=9
    // EPYC 9655/9755, 0.32/1.91 W/vCPU) from 2024 Q4 - 2026 Q2.
    ("c4d-standard-2", 0.6, 3.8),
    ("c4d-standard-4", 1.3, 7.6),
    ("c4d-standard-8", 2.6, 15.3),
    ("c4d-standard-16", 5.1, 30.6),
    ("c4d-standard-32", 10.2, 61.1),
    ("c4d-standard-96", 30.7, 183.4),
    // --- t2a (GCP, Ampere Altra, Neoverse N1) ---
    // CCF GCP CSV 2026-04-24 has no Ampere Altra entry. Kept on the
    // SPECpower direct compute (n=1 Altra Q80-30, 0.67/1.75 W/vCPU).
    ("t2a-standard-1", 0.7, 1.8),
    ("t2a-standard-2", 1.3, 3.5),
    ("t2a-standard-4", 2.7, 7.0),
    ("t2a-standard-8", 5.4, 14.0),
    ("t2a-standard-16", 10.7, 28.0),
    ("t2a-standard-32", 21.4, 56.0),
    // --- Standard_D v6 (Azure, Emerald Rapids, Xeon Platinum 8573C) ---
    // Not in CCF Azure CSV 2026-04-24. Kept on SPECpower direct
    // compute (2024 Q1-Q2, n=18 Platinum 8592+/8581V, 0.55/3.20 W/vCPU).
    ("Standard_D2s_v6", 1.1, 6.4),
    ("Standard_D4s_v6", 2.2, 12.8),
    ("Standard_D8s_v6", 4.4, 25.6),
    ("Standard_D16s_v6", 8.8, 51.2),
    ("Standard_D32s_v6", 17.6, 102.4),
    ("Standard_D64s_v6", 35.2, 204.8),
    ("Standard_D96s_v6", 52.8, 307.2),
    // --- Standard_Dads v6 (Azure, AMD Genoa, EPYC 9004) ---
    // Not in CCF Azure CSV 2026-04-24. Kept on SPECpower direct
    // compute, 0.40/2.05 W/vCPU per Genoa coefficient.
    ("Standard_D2ads_v6", 0.8, 4.1),
    ("Standard_D4ads_v6", 1.6, 8.2),
    ("Standard_D8ads_v6", 3.2, 16.4),
    ("Standard_D16ads_v6", 6.4, 32.8),
    ("Standard_D32ads_v6", 12.8, 65.6),
    ("Standard_D64ads_v6", 25.6, 131.2),
    ("Standard_D96ads_v6", 38.4, 196.8),
    // --- Standard_Dps v6 (Azure, Microsoft Cobalt 100, Neoverse N2 ARM) ---
    // N2 sits between Altra N1 (0.67/1.75) and Graviton 3 V1 (0.53/2.63).
    // Midpoint blend = 0.60/2.20 W/vCPU pending direct Cobalt SPECpower data.
    ("Standard_D2ps_v6", 1.2, 4.4),
    ("Standard_D4ps_v6", 2.4, 8.8),
    ("Standard_D8ps_v6", 4.8, 17.6),
    ("Standard_D16ps_v6", 9.6, 35.2),
    ("Standard_D32ps_v6", 19.2, 70.4),
    ("Standard_D64ps_v6", 38.4, 140.8),
    ("Standard_D96ps_v6", 57.6, 211.2),
    // --- Standard_E v6 (Azure, Emerald Rapids, memory-optimized) ---
    // Not in CCF Azure CSV 2026-04-24. SPECpower direct compute
    // (0.55/3.20 W/vCPU) + DRAM premium. Final 0.71/3.60.
    ("Standard_E2s_v6", 1.4, 7.2),
    ("Standard_E4s_v6", 2.8, 14.4),
    ("Standard_E8s_v6", 5.7, 28.8),
    ("Standard_E16s_v6", 11.4, 57.6),
    ("Standard_E32s_v6", 22.7, 115.2),
    ("Standard_E64s_v6", 45.4, 230.4),
    ("Standard_E96s_v6", 68.2, 345.6),
    // --- xeon-6780e (Sierra Forest 144 E-core, 1-chip system level) ---
    // ASSUMES FULL CHIP OWNERSHIP. For partial-vCPU bare-metal,
    // override via [green.cloud.services.X] idle_watts/max_watts.
    ("xeon-6780e", 100.0, 420.0),
];

/// `(idle_watts, max_watts)` per instance type.
///
/// Idle watts represent power at near-zero CPU load. Max watts represent
/// power at 100% CPU utilization. Chains the CSV-derived rows
/// (`table_data.rs`) with [`MANUAL_INSTANCE_ROWS`] above; keys are
/// disjoint by construction. See the module-level docs for the
/// methodology.
static INSTANCE_POWER: LazyLock<HashMap<&'static str, (f64, f64)>> = LazyLock::new(|| {
    super::table_data::GENERATED_INSTANCE_ROWS
        .iter()
        .chain(MANUAL_INSTANCE_ROWS)
        .map(|&(name, idle, max)| (name, (idle, max)))
        .collect()
});

/// Generic default `(idle_watts, max_watts)` per cloud provider.
///
/// Used as a fallback when an instance type is not found in the
/// [`INSTANCE_POWER`] table. Values are approximate medians across
/// each provider's most common general-purpose 2-vCPU instances.
static PROVIDER_DEFAULTS: LazyLock<HashMap<&'static str, (f64, f64)>> = LazyLock::new(|| {
    // Defaults track the most common 2-vCPU general-purpose instance
    // per provider, derived from the table so a dataset refresh moves
    // them automatically. Operators wanting a different default should
    // set `default_instance_type`.
    let reference = |name: &str| *INSTANCE_POWER.get(name).expect("reference instance");
    let mut m = HashMap::with_capacity(4);
    m.insert("aws", reference("m5.large"));
    m.insert("gcp", reference("n2-standard-2"));
    m.insert("azure", reference("Standard_D2s_v6"));
    m.insert("generic", (3.0, 20.0)); // Conservative on-prem server estimate
    m
});

/// Look up `(idle_watts, max_watts)` for an instance type.
///
/// Falls back to the provider default if the instance type is not in
/// the embedded table. Falls back to the `"generic"` default if the
/// provider is also unknown.
///
/// # Panics
///
/// Panics if the `"generic"` key is missing from `PROVIDER_DEFAULTS`
/// (compile-time invariant, cannot happen in practice).
#[must_use]
pub fn lookup_instance_power(instance_type: &str, provider: &str) -> (f64, f64) {
    if let Some(&power) = INSTANCE_POWER.get(instance_type) {
        return power;
    }
    if let Some(&power) = PROVIDER_DEFAULTS.get(provider) {
        return power;
    }
    // Ultimate fallback: generic on-prem estimate.
    *PROVIDER_DEFAULTS
        .get("generic")
        .expect("generic default must exist")
}

/// Returns `true` if the instance type is known in the embedded table.
#[must_use]
pub fn is_known_instance_type(instance_type: &str) -> bool {
    INSTANCE_POWER.contains_key(instance_type)
}

/// Linearly interpolate watts from CPU utilization percentage.
///
/// Formula: `idle_watts + (max_watts - idle_watts) * (cpu_percent / 100.0)`.
/// `cpu_percent` is clamped to `[0.0, 100.0]` to prevent extrapolation.
/// Non-finite inputs (NaN, infinity) return `idle_watts` as a safe default.
#[must_use]
pub fn interpolate_watts(idle_watts: f64, max_watts: f64, cpu_percent: f64) -> f64 {
    if !cpu_percent.is_finite() {
        return idle_watts;
    }
    let clamped = cpu_percent.clamp(0.0, 100.0);
    idle_watts + (max_watts - idle_watts) * (clamped / 100.0)
}

/// Compute energy per I/O op in kWh from interpolated watts, scrape
/// interval, and op count.
///
/// Returns `None` if `ops` is zero, watts is non-finite, or watts is
/// negative. The formula mirrors the Scaphandre integration:
/// `energy_kwh = (watts / 1000) * (interval_secs / 3600)`, then
/// divided by the number of ops in the window.
#[must_use]
pub fn compute_cloud_energy_per_op_kwh(
    watts: f64,
    scrape_interval_secs: f64,
    ops: u64,
) -> Option<f64> {
    if ops == 0 || !watts.is_finite() || watts < 0.0 {
        return None;
    }
    let kwh = (watts / 1000.0) * (scrape_interval_secs / 3600.0);
    let per_op = kwh / ops as f64;
    if per_op.is_finite() {
        Some(per_op)
    } else {
        None
    }
}

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

    // ------------------------------------------------------------------
    // lookup_instance_power
    // ------------------------------------------------------------------

    // Sizes within a family must scale linearly with vCPU count, per
    // the `vCPU * coefficient` methodology. Relation-based so a data
    // refresh does not break them, exact values are reviewed on the
    // refresh PR diff.
    #[test]
    fn known_aws_instance_scales_with_vcpu() {
        let (idle_2, max_2) = lookup_instance_power("m5.large", "aws");
        let (idle_4, max_4) = lookup_instance_power("m5.xlarge", "aws");
        assert!((idle_4 - 2.0 * idle_2).abs() < 0.1);
        assert!((max_4 - 2.0 * max_2).abs() < 0.2);
    }

    #[test]
    fn known_gcp_instance_scales_with_vcpu() {
        let (idle_2, max_2) = lookup_instance_power("n2-standard-2", "gcp");
        let (idle_8, max_8) = lookup_instance_power("n2-standard-8", "gcp");
        assert!((idle_8 - 4.0 * idle_2).abs() < 0.2);
        assert!((max_8 - 4.0 * max_2).abs() < 0.4);
    }

    #[test]
    fn known_azure_instance_scales_with_vcpu() {
        let (idle_2, max_2) = lookup_instance_power("Standard_D2s_v3", "azure");
        let (idle_8, max_8) = lookup_instance_power("Standard_D8s_v3", "azure");
        assert!((idle_8 - 4.0 * idle_2).abs() < 0.2);
        assert!((max_8 - 4.0 * max_2).abs() < 0.4);
    }

    #[test]
    fn unknown_instance_falls_back_to_provider_default() {
        let fallback = lookup_instance_power("m999.future", "aws");
        let default = *PROVIDER_DEFAULTS.get("aws").expect("aws default");
        assert_eq!(fallback, default);
    }

    // The generated/manual split relies on disjoint keys: a HashMap
    // collision would silently shadow a generated row with a stale
    // manual one (the exact mistake the refresh-script watchlist
    // invites when a family moves from manual to generated).
    #[test]
    fn generated_and_manual_instance_keys_are_disjoint() {
        assert_eq!(
            INSTANCE_POWER.len(),
            super::super::table_data::GENERATED_INSTANCE_ROWS.len() + MANUAL_INSTANCE_ROWS.len(),
            "a manual instance row shadows a generated one"
        );
    }

    // Cross-CSV sanity anchor: the same architecture (Cascade Lake, 2
    // vCPU) must land in the same ballpark across provider CSVs. A
    // mis-scaled or mis-parsed Azure CSV passes the positivity and
    // linear-scaling tests, but not this one.
    #[test]
    fn azure_scale_sane_vs_aws_same_architecture() {
        let (aws_idle, aws_max) = lookup_instance_power("m5.large", "aws");
        let (az_idle, az_max) = lookup_instance_power("Standard_D2s_v4", "azure");
        assert!(
            az_idle > aws_idle * 0.5 && az_idle < aws_idle * 2.0,
            "Azure Cascade Lake idle {az_idle} out of 2x band vs AWS {aws_idle}"
        );
        assert!(
            az_max > aws_max * 0.5 && az_max < aws_max * 2.0,
            "Azure Cascade Lake max {az_max} out of 2x band vs AWS {aws_max}"
        );
    }

    #[test]
    fn modern_architecture_keys_present() {
        for key in [
            "m7i.large",
            "c7a.large",
            "r7a.large",
            "m6a.xlarge",
            "c7g.large",
            "m8g.large",
            "m8a.large",
            "c8a.large",
            "m8i.large",
            "c8i.large",
            "c4-standard-4",
            "c4d-standard-8",
            "c4a-standard-2",
            "t2a-standard-2",
            "Standard_D2s_v6",
            "Standard_D2ps_v6",
            "xeon-6780e",
        ] {
            assert!(is_known_instance_type(key), "missing modern entry: {key}");
        }
    }

    #[test]
    fn turin_overrides_to_genoa_proxy() {
        // EPYC 5th Gen Turin (m8a/c8a) is proxied to EPYC 4th Gen Genoa
        // (m7a/c7a) because the CCF 2026-04-24 Turin row is anomalously
        // high. If this test fails, re-evaluate the override against the
        // current CCF snapshot before silently aligning to a new value.
        // See docs/LIMITATIONS.md section "EPYC 5th Gen Turin" for the
        // rationale and the revalidation procedure.
        let sizes = [
            "large", "xlarge", "2xlarge", "4xlarge", "8xlarge", "16xlarge",
        ];
        for size in sizes {
            for (turin, genoa) in [("m8a", "m7a"), ("c8a", "c7a")] {
                let turin_key = format!("{turin}.{size}");
                let genoa_key = format!("{genoa}.{size}");
                assert_eq!(
                    lookup_instance_power(&turin_key, "aws"),
                    lookup_instance_power(&genoa_key, "aws"),
                    "{turin_key} (Turin) must alias to {genoa_key} (Genoa) until CCF correction"
                );
            }
        }
    }

    #[test]
    fn m_series_does_not_carry_dram_premium() {
        // m5 and c5 share the bare Cascade Lake coefficient (CCF does
        // not differentiate general-purpose vs compute). If a refactor
        // applied the DRAM premium to general-purpose families, m5
        // would drift away from c5 and this equality would break.
        assert_eq!(
            lookup_instance_power("m5.large", "aws"),
            lookup_instance_power("c5.large", "aws"),
            "m5.large must stay on the bare coefficient, like c5.large"
        );
    }

    #[test]
    fn r_series_includes_dram_premium_over_general_purpose() {
        // r5.large (2 vCPU memory-optimized, Cascade Lake) should carry
        // an additive DRAM premium over m5.large (2 vCPU general-purpose,
        // same Cascade Lake): 2 vCPU * 8 GB/vCPU * 0.02 W/GB = 0.32 idle,
        // 2 vCPU * 8 GB/vCPU * 0.05 W/GB = 0.80 max. If this test fails,
        // re-check that DRAM_PREMIUM_W_PER_GB_{IDLE,MAX} and the inline
        // r-series values stay in sync.
        let (m5_idle, m5_max) = lookup_instance_power("m5.large", "aws");
        let (r5_idle, r5_max) = lookup_instance_power("r5.large", "aws");
        assert!(
            (r5_idle - m5_idle - 0.32).abs() < 0.05,
            "DRAM idle uplift drift: r5 {r5_idle} - m5 {m5_idle} expected ~0.32"
        );
        assert!(
            (r5_max - m5_max - 0.80).abs() < 0.05,
            "DRAM max uplift drift: r5 {r5_max} - m5 {m5_max} expected ~0.80"
        );
    }

    #[test]
    fn sierra_forest_entries_are_chip_level_not_vcpu_level() {
        // Sierra Forest entries are 1-chip system-level watts, not vCPU-scaled.
        // A vCPU-scaled value would never exceed ~6 W idle for a 144-thread
        // entry, so floor at 50 W idle catches accidental rescaling errors.
        let (idle, _) = lookup_instance_power("xeon-6780e", "generic");
        assert!(
            idle >= 50.0,
            "xeon-6780e must be system-level (>=50W idle), got {idle}"
        );
    }

    #[test]
    fn unknown_provider_falls_back_to_generic() {
        let (idle, max) = lookup_instance_power("custom.instance", "onprem");
        assert!((idle - 3.0).abs() < 0.01);
        assert!((max - 20.0).abs() < 0.01);
    }

    #[test]
    fn is_known_true_for_table_entry() {
        assert!(is_known_instance_type("c5.4xlarge"));
    }

    #[test]
    fn is_known_false_for_missing_entry() {
        assert!(!is_known_instance_type("m99.jumbo"));
    }

    // ------------------------------------------------------------------
    // interpolate_watts
    // ------------------------------------------------------------------

    #[test]
    fn interpolate_at_zero_percent() {
        let w = interpolate_watts(2.0, 20.0, 0.0);
        assert!((w - 2.0).abs() < 1e-10);
    }

    #[test]
    fn interpolate_at_fifty_percent() {
        let w = interpolate_watts(2.0, 20.0, 50.0);
        assert!((w - 11.0).abs() < 1e-10);
    }

    #[test]
    fn interpolate_at_hundred_percent() {
        let w = interpolate_watts(2.0, 20.0, 100.0);
        assert!((w - 20.0).abs() < 1e-10);
    }

    #[test]
    fn interpolate_clamps_below_zero() {
        let w = interpolate_watts(2.0, 20.0, -10.0);
        assert!((w - 2.0).abs() < 1e-10, "should clamp to idle");
    }

    #[test]
    fn interpolate_clamps_above_hundred() {
        let w = interpolate_watts(2.0, 20.0, 150.0);
        assert!((w - 20.0).abs() < 1e-10, "should clamp to max");
    }

    #[test]
    fn interpolate_nan_returns_idle() {
        let w = interpolate_watts(2.0, 20.0, f64::NAN);
        assert!((w - 2.0).abs() < 1e-10, "NaN input should return idle");
    }

    #[test]
    fn interpolate_infinity_returns_idle() {
        let w = interpolate_watts(2.0, 20.0, f64::INFINITY);
        assert!((w - 2.0).abs() < 1e-10, "Inf input should return idle");
    }

    // ------------------------------------------------------------------
    // compute_cloud_energy_per_op_kwh
    // ------------------------------------------------------------------

    #[test]
    fn basic_energy_computation() {
        // 10 W for 15 seconds, 100 ops.
        // kWh = 10/1000 * 15/3600 = 0.0000416667
        // per_op = 0.0000416667 / 100 = 4.16667e-7
        let result = compute_cloud_energy_per_op_kwh(10.0, 15.0, 100);
        assert!(result.is_some());
        let per_op = result.unwrap();
        let expected = (10.0 / 1000.0) * (15.0 / 3600.0) / 100.0;
        assert!((per_op - expected).abs() < 1e-15);
    }

    #[test]
    fn zero_ops_returns_none() {
        assert!(compute_cloud_energy_per_op_kwh(10.0, 15.0, 0).is_none());
    }

    #[test]
    fn negative_watts_returns_none() {
        assert!(compute_cloud_energy_per_op_kwh(-1.0, 15.0, 100).is_none());
    }

    #[test]
    fn nan_watts_returns_none() {
        assert!(compute_cloud_energy_per_op_kwh(f64::NAN, 15.0, 100).is_none());
    }

    #[test]
    fn infinite_watts_returns_none() {
        assert!(compute_cloud_energy_per_op_kwh(f64::INFINITY, 15.0, 100).is_none());
    }

    // ------------------------------------------------------------------
    // Table integrity
    // ------------------------------------------------------------------

    #[test]
    fn all_entries_have_positive_values() {
        for (name, &(idle, max)) in INSTANCE_POWER.iter() {
            assert!(idle > 0.0, "{name}: idle must be positive, got {idle}");
            assert!(max > 0.0, "{name}: max must be positive, got {max}");
            assert!(max >= idle, "{name}: max ({max}) must be >= idle ({idle})");
        }
    }

    #[test]
    fn table_has_expected_entry_count() {
        // CCF 2026-04-24 vCPU * coefficient across AWS/GCP/Azure, plus a
        // handful of direct-SPECpower entries where the provider CSV has
        // no row (Azure v6, GCP t2a/c4d, Cobalt 100), plus 1 Sierra Forest
        // CPU-named system-level row. Conservative floor so the count
        // survives minor entry pruning during review.
        assert!(
            INSTANCE_POWER.len() >= 300,
            "expected >= 300 entries, got {}",
            INSTANCE_POWER.len()
        );
    }
}