all-smi 0.26.2

Command-line utility for monitoring GPU hardware. It provides a real-time view of GPU utilization, memory usage, temperature, power consumption, and other metrics.
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
// Copyright 2025 Lablup Inc. and Jeongkyu Shin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Unit tests for the Intel Level Zero backend. These tests run on any
//! host because they exercise the pure-logic surface: enum value
//! locks, BDF formatting, delta math, integration with `GpuInfo`.
//! Real-runtime tests would require a host with the Level Zero loader
//! installed and a supported Intel GPU; those are deferred to
//! maintainer hardware verification (issue #248).

use super::ffi;
use super::loader::{
    LIBZE_PATHS, MAX_L0_HANDLES, cap_handle_count, format_pci_bdf, normalise_pci_bdf,
    try_load_library,
};
use super::refresh::{
    compute_engine_busy_pct, compute_power_watts, make_engine_sample, make_power_sample,
};
use super::*;

#[path = "tests/apply.rs"]
mod apply;
#[path = "tests/ffi_layout.rs"]
mod ffi_layout;
// ----- Enum value locks ---------------------------------------------
//
// These tests lock in the `zes_engine_group_t` integer values against
// the Level Zero spec at
// <https://oneapi-src.github.io/level-zero-spec/level-zero/latest/sysman/api.html#zes-engine-group-t>.
// If Intel ever renumbers the enum (or if a developer accidentally
// changes the constants), CI catches it before the change ships and
// silently misclassifies engine telemetry.

#[test]
fn engine_group_enum_values_match_spec() {
    // Values cross-checked against the upstream Sysman header at
    // <https://github.com/oneapi-src/level-zero/blob/master/include/zes_api.h>
    // (`typedef enum _zes_engine_group_t`). Several of the 9..=14 slots
    // are marked DEPRECATED in the spec but we still lock their numeric
    // values to detect any accidental renumbering during future updates.
    assert_eq!(ffi::ZES_ENGINE_GROUP_ALL, 0);
    assert_eq!(ffi::ZES_ENGINE_GROUP_COMPUTE_ALL, 1);
    assert_eq!(ffi::ZES_ENGINE_GROUP_MEDIA_ALL, 2);
    assert_eq!(ffi::ZES_ENGINE_GROUP_COPY_ALL, 3);
    assert_eq!(ffi::ZES_ENGINE_GROUP_COMPUTE_SINGLE, 4);
    assert_eq!(ffi::ZES_ENGINE_GROUP_RENDER_SINGLE, 5);
    assert_eq!(ffi::ZES_ENGINE_GROUP_MEDIA_DECODE_SINGLE, 6);
    assert_eq!(ffi::ZES_ENGINE_GROUP_MEDIA_ENCODE_SINGLE, 7);
    assert_eq!(ffi::ZES_ENGINE_GROUP_COPY_SINGLE, 8);
    assert_eq!(ffi::ZES_ENGINE_GROUP_MEDIA_ENHANCEMENT_SINGLE, 9);
    assert_eq!(ffi::ZES_ENGINE_GROUP_3D_SINGLE, 10);
    assert_eq!(ffi::ZES_ENGINE_GROUP_3D_RENDER_COMPUTE_ALL, 11);
    assert_eq!(ffi::ZES_ENGINE_GROUP_RENDER_ALL, 12);
    assert_eq!(ffi::ZES_ENGINE_GROUP_3D_ALL, 13);
    assert_eq!(ffi::ZES_ENGINE_GROUP_MEDIA_CODEC_SINGLE, 14);
}

#[test]
fn init_flags_match_spec() {
    assert_eq!(ffi::ZE_INIT_FLAG_DEFAULT, 0);
    assert_eq!(ffi::ZE_RESULT_SUCCESS, 0);
}

#[test]
fn structure_type_constants_match_spec() {
    assert_eq!(ffi::ZES_STRUCTURE_TYPE_PCI_PROPERTIES, 0x0000_0002);
    assert_eq!(ffi::ZES_STRUCTURE_TYPE_ENGINE_PROPERTIES, 0x0000_0005);
}

// ----- FFI struct ABI locks -----------------------------------------
//
// The Level Zero driver writes into Rust-allocated buffers using the C
// struct layout from `ze_api.h` / `zes_api.h`. If the Rust struct size
// drifts from the C struct size, the driver either over- or under-writes
// our buffer and we read garbage (or worse). These tests measure the
// Rust struct sizes against the spec-documented C sizes on x86_64 LP64,
// the only platform combination the L0 backend currently targets.
//
// Values verified against the upstream level-zero header at
// <https://github.com/oneapi-src/level-zero/blob/master/include/zes_api.h>
// compiled with the system C compiler on x86_64 Linux.

#[cfg(target_pointer_width = "64")]
#[test]
fn zes_pci_address_t_size_matches_spec() {
    assert_eq!(std::mem::size_of::<ffi::zes_pci_address_t>(), 16);
}

#[cfg(target_pointer_width = "64")]
#[test]
fn zes_pci_speed_t_size_matches_spec() {
    assert_eq!(std::mem::size_of::<ffi::zes_pci_speed_t>(), 16);
}

#[cfg(target_pointer_width = "64")]
#[test]
fn zes_pci_properties_t_size_matches_spec() {
    // C spec on x86_64 LP64: stype (4) + pad (4) + pNext (8) +
    // address (16) + maxSpeed (16) + 3x ze_bool_t (3) + trailing pad
    // (5) = 56 bytes. A previous version of this file declared the
    // three booleans as u32 each, inflating the Rust struct to 64
    // bytes; this assertion guards against a regression.
    assert_eq!(std::mem::size_of::<ffi::zes_pci_properties_t>(), 56);
}

#[cfg(target_pointer_width = "64")]
#[test]
fn zes_engine_properties_t_size_matches_spec() {
    // C spec on x86_64 LP64: stype (4) + pad (4) + pNext (8) +
    // type (4) + onSubdevice (1) + pad (3) + subdeviceId (4) = 28,
    // with trailing pad to the 8-byte struct alignment = 32 bytes.
    assert_eq!(std::mem::size_of::<ffi::zes_engine_properties_t>(), 32);
}

#[cfg(target_pointer_width = "64")]
#[test]
fn zes_engine_stats_t_size_matches_spec() {
    // Two u64 fields = 16 bytes.
    assert_eq!(std::mem::size_of::<ffi::zes_engine_stats_t>(), 16);
}

#[cfg(target_pointer_width = "64")]
#[test]
fn zes_power_energy_counter_t_size_matches_spec() {
    // Two u64 fields = 16 bytes.
    assert_eq!(std::mem::size_of::<ffi::zes_power_energy_counter_t>(), 16);
}

// ----- Engine label classification ----------------------------------

#[test]
fn engine_label_maps_known_groups() {
    assert_eq!(
        engine_label(ffi::ZES_ENGINE_GROUP_COMPUTE_SINGLE),
        "compute (XMX)"
    );
    assert_eq!(engine_label(ffi::ZES_ENGINE_GROUP_RENDER_SINGLE), "render");
    assert_eq!(engine_label(ffi::ZES_ENGINE_GROUP_COPY_SINGLE), "copy");
    assert_eq!(
        engine_label(ffi::ZES_ENGINE_GROUP_MEDIA_DECODE_SINGLE),
        "media-decode"
    );
    assert_eq!(
        engine_label(ffi::ZES_ENGINE_GROUP_MEDIA_ENCODE_SINGLE),
        "media-encode"
    );
}

#[test]
fn engine_label_unknown_becomes_other() {
    // Aggregated _ALL groups are not tracked; they'd fall through to "other".
    assert_eq!(engine_label(ffi::ZES_ENGINE_GROUP_ALL), "other");
    assert_eq!(engine_label(ffi::ZES_ENGINE_GROUP_3D_SINGLE), "other");
    assert_eq!(engine_label(999), "other");
}

#[test]
fn is_tracked_engine_only_singletons() {
    assert!(is_tracked_engine(ffi::ZES_ENGINE_GROUP_COMPUTE_SINGLE));
    assert!(is_tracked_engine(ffi::ZES_ENGINE_GROUP_RENDER_SINGLE));
    assert!(is_tracked_engine(ffi::ZES_ENGINE_GROUP_COPY_SINGLE));
    assert!(is_tracked_engine(ffi::ZES_ENGINE_GROUP_MEDIA_DECODE_SINGLE));
    assert!(is_tracked_engine(ffi::ZES_ENGINE_GROUP_MEDIA_ENCODE_SINGLE));

    // Aggregated groups MUST be excluded — including them would
    // double-count against the per-engine _SINGLE readings the same
    // device exposes.
    assert!(!is_tracked_engine(ffi::ZES_ENGINE_GROUP_ALL));
    assert!(!is_tracked_engine(ffi::ZES_ENGINE_GROUP_COMPUTE_ALL));
    assert!(!is_tracked_engine(ffi::ZES_ENGINE_GROUP_MEDIA_ALL));
    assert!(!is_tracked_engine(ffi::ZES_ENGINE_GROUP_COPY_ALL));
    assert!(!is_tracked_engine(
        ffi::ZES_ENGINE_GROUP_3D_RENDER_COMPUTE_ALL
    ));
    assert!(!is_tracked_engine(ffi::ZES_ENGINE_GROUP_3D_ALL));
    assert!(!is_tracked_engine(ffi::ZES_ENGINE_GROUP_RENDER_ALL));
}

// ----- PCI BDF formatting ------------------------------------------

#[test]
fn pci_bdf_format_matches_sysfs() {
    let addr = ffi::zes_pci_address_t {
        domain: 0,
        bus: 0x03,
        device: 0x00,
        function: 0,
    };
    // Format MUST match the layout of `/sys/class/drm/cardN/device` symlink
    // targets (e.g. `0000:03:00.0`) so the per-card readers can do a
    // string-equality lookup.
    assert_eq!(format_pci_bdf(&addr), "0000:03:00.0");
}

#[test]
fn pci_bdf_format_handles_nonzero_domain() {
    let addr = ffi::zes_pci_address_t {
        domain: 0xABCD,
        bus: 0xEF,
        device: 0x12,
        function: 7,
    };
    assert_eq!(format_pci_bdf(&addr), "abcd:ef:12.7");
}

#[test]
fn normalise_pci_bdf_lowercases() {
    assert_eq!(normalise_pci_bdf("0000:03:00.0"), "0000:03:00.0");
    assert_eq!(normalise_pci_bdf("ABCD:EF:12.7"), "abcd:ef:12.7");
}

// ----- Engine busy delta math --------------------------------------

#[test]
fn engine_busy_first_call_seeds_zero() {
    // last_timestamp_us == 0 means "no baseline yet" — must return 0.0
    // so the first refresh per card reports a clean zero instead of a
    // huge bogus delta against an uninitialised baseline.
    let sample = make_engine_sample(ffi::ZES_ENGINE_GROUP_COMPUTE_SINGLE, 0, 0);
    let stats = ffi::zes_engine_stats_t {
        active_time: 1_000,
        timestamp: 10_000,
    };
    assert_eq!(compute_engine_busy_pct(&sample, &stats), 0.0);
}

#[test]
fn engine_busy_percent_correct() {
    // 500us active over 1000us wall -> 50%.
    let sample = make_engine_sample(ffi::ZES_ENGINE_GROUP_COMPUTE_SINGLE, 1_000, 5_000);
    let stats = ffi::zes_engine_stats_t {
        active_time: 1_500, // delta = 500us
        timestamp: 6_000,   // delta = 1000us
    };
    let pct = compute_engine_busy_pct(&sample, &stats);
    assert!((pct - 50.0).abs() < 1e-9, "pct={pct}");
}

#[test]
fn engine_busy_clamps_to_100_on_overrun() {
    // Driver bug: active_time advances faster than wall — clamp to 100%
    // so a buggy driver does not poison downstream consumers.
    let sample = make_engine_sample(ffi::ZES_ENGINE_GROUP_COMPUTE_SINGLE, 1_000, 5_000);
    let stats = ffi::zes_engine_stats_t {
        active_time: 10_000, // delta = 9000us
        timestamp: 6_000,    // delta = 1000us
    };
    assert_eq!(compute_engine_busy_pct(&sample, &stats), 100.0);
}

#[test]
fn engine_busy_handles_backwards_clock() {
    // Counter reset / timestamp regression: must return 0.0, not panic.
    let sample = make_engine_sample(ffi::ZES_ENGINE_GROUP_COMPUTE_SINGLE, 1_000, 6_000);
    let stats = ffi::zes_engine_stats_t {
        active_time: 0,
        timestamp: 5_000,
    };
    assert_eq!(compute_engine_busy_pct(&sample, &stats), 0.0);
}

#[test]
fn engine_busy_handles_zero_delta_t() {
    let sample = make_engine_sample(ffi::ZES_ENGINE_GROUP_COMPUTE_SINGLE, 1_000, 5_000);
    let stats = ffi::zes_engine_stats_t {
        active_time: 1_500,
        timestamp: 5_000,
    };
    assert_eq!(compute_engine_busy_pct(&sample, &stats), 0.0);
}

// ----- Energy counter delta math -----------------------------------

#[test]
fn power_first_call_seeds_none() {
    let sample = make_power_sample(0, 0);
    let counter = ffi::zes_power_energy_counter_t {
        energy: 1_000_000_000,
        timestamp: 10_000,
    };
    assert!(compute_power_watts(&sample, &counter).is_none());
}

#[test]
fn power_watts_correct() {
    // 30 J over 1s -> 30 W.
    let sample = make_power_sample(0, 5_000_000); // 5s baseline
    let counter = ffi::zes_power_energy_counter_t {
        energy: 30_000_000,   // 30 J in microjoules (delta = 30_000_000)
        timestamp: 6_000_000, // 1s later (delta = 1_000_000us)
    };
    let watts = compute_power_watts(&sample, &counter).unwrap();
    assert!((watts - 30.0).abs() < 1e-9, "watts={watts}");
}

#[test]
fn power_handles_backwards_clock() {
    // Counter reset or driver bug: return None rather than negative
    // watts (which would corrupt the downstream histograms).
    let sample = make_power_sample(1_000, 6_000_000);
    let counter = ffi::zes_power_energy_counter_t {
        energy: 0,
        timestamp: 5_000_000,
    };
    assert!(compute_power_watts(&sample, &counter).is_none());
}

#[test]
fn power_handles_zero_delta_t() {
    let sample = make_power_sample(1_000, 5_000_000);
    let counter = ffi::zes_power_energy_counter_t {
        energy: 10_000,
        timestamp: 5_000_000,
    };
    assert!(compute_power_watts(&sample, &counter).is_none());
}

#[test]
fn power_handles_energy_reset() {
    // Sometimes the energy counter wraps or resets. That interval is
    // not fresh enough to override a fallback power reading.
    let sample = make_power_sample(1_000_000, 5_000_000);
    let counter = ffi::zes_power_energy_counter_t {
        energy: 500_000, // smaller than last_energy_uj
        timestamp: 6_000_000,
    };
    assert!(compute_power_watts(&sample, &counter).is_none());
}

// ----- Primary utilization picker ---------------------------------

#[test]
fn primary_utilization_prefers_render_or_compute() {
    let engines = vec![
        ("compute (XMX)", 80.0_f64),
        ("render", 30.0_f64),
        ("copy", 90.0_f64),
        ("media-decode", 5.0_f64),
    ];
    // 80 (compute XMX) beats 30 (render) — copy 90% must NOT win.
    assert_eq!(primary_utilization(&engines), Some(80.0));
}

#[test]
fn primary_utilization_falls_back_when_no_compute() {
    let engines = vec![("copy", 12.0_f64), ("media-decode", 7.0_f64)];
    assert_eq!(primary_utilization(&engines), Some(12.0));
}

#[test]
fn primary_utilization_empty_returns_none() {
    let engines: Vec<(&'static str, f64)> = Vec::new();
    assert_eq!(primary_utilization(&engines), None);
}

// ----- Library-not-found behaviour --------------------------------

#[test]
fn try_load_library_returns_none_for_nonexistent_path() {
    // Verifies the runtime degrades gracefully on hosts (like CI) that
    // do not have a Level Zero loader at all. Passing a bogus path
    // must NOT panic — it must return None so the caller silently
    // falls back to the sysfs/WMI baseline.
    let bogus = "/nonexistent/path/to/libze_loader.so.1";
    // SAFETY: nonexistent path → dlopen fails → returns None without
    // dereferencing any function pointers.
    let result = unsafe { try_load_library(bogus) };
    assert!(
        result.is_none(),
        "expected None for nonexistent loader path"
    );
}

/// Environment key CI sets once it has installed a real Level Zero loader.
///
/// Opt-in rather than always-on because the assertion below is only
/// meaningful when the loader is actually present, and a developer host
/// usually has no reason to install it.
const EXPECT_LOADER_ENV: &str = "ALL_SMI_EXPECT_LEVEL_ZERO_LOADER";

/// Printed only after the assertion below has actually run. The CI step
/// that sets [`EXPECT_LOADER_ENV`] greps for it.
///
/// Without this the test is indistinguishable from a skip: rename the
/// environment key, drop the `env:` block from the workflow, or move the
/// test, and it silently stops asserting while the job stays green. That
/// is the failure mode this whole check exists to prevent, so it should
/// not have one of its own.
const LOADER_ASSERTED_MARKER: &str = "all-smi: level-zero-loader-assertion-ran";

/// Load a real `libze_loader.so.1` and resolve every symbol we require.
///
/// This is the one part of the FFI surface a runner without a GPU can
/// still check, and until now nothing checked it. The loader is packaged
/// separately from the GPU driver on Linux, so CI can install it on a
/// plain cloud instance. What that proves is not small: that every path in
/// `LIBZE_PATHS` is a name the dynamic linker actually resolves, and that
/// every mandatory symbol in `LzApi` is spelled the way the real library
/// exports it. A typo in either is invisible to the compiler and turns the
/// whole backend into a silent no-op on real hardware.
///
/// It deliberately stops short of `zeInit`. A machine with no Intel GPU
/// has no driver for the loader to hand back, so initialisation failing
/// there is correct behaviour rather than a defect, and asserting on it
/// would make this test fail for the wrong reason.
#[test]
fn the_installed_loader_exports_every_symbol_we_resolve() {
    if std::env::var_os(EXPECT_LOADER_ENV).is_none() {
        // No loader installed on this host; nothing to assert.
        return;
    }
    // SAFETY: same contract as production. Only canonical Level Zero
    // loader paths are passed, and no resolved pointer is called here.
    let loaded = LIBZE_PATHS
        .iter()
        .find_map(|path| unsafe { try_load_library(path) });
    assert!(
        loaded.is_some(),
        "{EXPECT_LOADER_ENV} is set, so a Level Zero loader is installed, but none of \
         {LIBZE_PATHS:?} loaded with every required symbol resolved. Either a path in \
         LIBZE_PATHS no longer matches what the loader package installs, or a symbol \
         name in LzApi is wrong."
    );
    println!("{LOADER_ASSERTED_MARKER}");
}

#[test]
fn enumerated_pci_bdfs_empty_when_runtime_absent() {
    // On hosts without the Level Zero loader (the canonical case for
    // CI), the BDF enumeration helper must return an empty list, not
    // panic. The Windows reader relies on this contract to skip the
    // ordinal-based pairing loop entirely when no L0 hardware is
    // reachable.
    let bdfs = enumerated_pci_bdfs();
    // Either zero (no loader) or some non-empty list (developer host
    // with Intel GPU). Both are valid; the contract is "does not
    // panic and returns a Vec<String>".
    let _: Vec<String> = bdfs;
}

#[test]
fn refresh_returns_none_without_runtime() {
    // Refresh against a fresh state on a host without an L0 loader
    // must return None — the per-OS readers rely on this to leave
    // the sysfs / WMI baseline untouched.
    let mut state = LevelZeroState::empty();
    let result = refresh(&mut state, "0000:03:00.0");
    // None when the loader is unavailable. On a host where the loader
    // happens to be present but the BDF does not match any L0 device,
    // we also expect None (bind_attempted flips to true, device stays
    // None).
    if let Some(readout) = result {
        // If we DID get a runtime, refresh against an unknown BDF must
        // still produce no data — bind to an unknown card fails.
        assert!(
            !readout.has_fresh_data(),
            "unknown BDF must not produce data, got {readout:?}"
        );
    }
}

// ----- Diagnostic helpers -----------------------------------------

#[test]
fn diagnostic_helpers_on_empty_state() {
    let state = LevelZeroState::empty();
    assert_eq!(engine_count(&state), 0);
    assert_eq!(power_domain_count(&state), 0);
    assert!(!is_bound(&state));
}

#[test]
fn sort_engine_entries_canonical_order() {
    let mut engines = vec![
        ("media-encode", 10.0_f64),
        ("compute (XMX)", 50.0_f64),
        ("render", 30.0_f64),
        ("copy", 5.0_f64),
        ("media-decode", 2.0_f64),
    ];
    sort_engine_entries(&mut engines);
    let order: Vec<&'static str> = engines.iter().map(|(l, _)| *l).collect();
    // render first, then compute (XMX), then copy, then media-decode, then media-encode.
    assert_eq!(
        order,
        vec![
            "render",
            "compute (XMX)",
            "copy",
            "media-decode",
            "media-encode"
        ]
    );
}

// ----- MAX_L0_HANDLES cap arithmetic ----------------------------------
//
// `cap_handle_count` guards every Vec allocation against a buggy or
// hostile driver that reports a giant count (DoS via OOM). These tests
// exercise the cap math directly without requiring a real L0 runtime.

#[test]
fn cap_handle_count_passes_through_when_under_cap() {
    // Normal hardware: a few engines plus a couple of power domains.
    // The count must pass through unchanged so the Vec is sized exactly.
    let (safe, capped_u32) = cap_handle_count(6, "engine groups");
    assert_eq!(safe, 6);
    assert_eq!(capped_u32, 6);
}

#[test]
fn cap_handle_count_clamps_when_over_cap() {
    // Driver reports u32::MAX — without the cap this would attempt a
    // ~32 GiB Vec allocation and OOM the process. The cap must reduce
    // both the usize (for Vec::with_capacity) and the u32 (for the
    // second "fill" call of the count-then-buffer idiom) to MAX_L0_HANDLES.
    let giant: u32 = u32::MAX;
    let (safe, capped_u32) = cap_handle_count(giant, "drivers");
    assert_eq!(safe, MAX_L0_HANDLES);
    assert_eq!(capped_u32, MAX_L0_HANDLES as u32);
    // The capped values must agree with each other.
    assert_eq!(safe, capped_u32 as usize);
}

#[test]
fn cap_handle_count_at_exact_boundary() {
    // Exactly MAX_L0_HANDLES — must pass through, not be clamped.
    let at_limit = MAX_L0_HANDLES as u32;
    let (safe, capped_u32) = cap_handle_count(at_limit, "devices");
    assert_eq!(safe, MAX_L0_HANDLES);
    assert_eq!(capped_u32, at_limit);
}

#[test]
fn cap_handle_count_one_over_boundary_is_clamped() {
    // MAX_L0_HANDLES + 1 must be clamped to MAX_L0_HANDLES.
    let one_over = (MAX_L0_HANDLES + 1) as u32;
    let (safe, capped_u32) = cap_handle_count(one_over, "power domains");
    assert_eq!(safe, MAX_L0_HANDLES);
    assert_eq!(capped_u32, MAX_L0_HANDLES as u32);
}