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
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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
// 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.

//! Support-bundle packer — writes a tar.gz containing the rendered
//! report plus a curated set of system context files.

use std::fs::File;
use std::path::Path;
// Only the Unix-gated context collectors (uname/lspci/lsmod/dmesg/
// system_profiler) use these; on Windows none are compiled in.
#[cfg(unix)]
use std::time::Duration;

use anyhow::{Context, Result};
use flate2::Compression;
use flate2::write::GzEncoder;

#[cfg(unix)]
use crate::doctor::exec::try_exec;
use crate::doctor::redact::{RedactOptions, scrub};
use crate::doctor::report::{render_human_string, render_json_string};
use crate::doctor::{DoctorOptions, Report};

/// Build the support bundle at `path`. The archive layout is:
///
/// ```text
/// all-smi-doctor/
/// +-- report.txt         (human-readable)
/// +-- report.json        (machine-readable)
/// +-- env.txt            (filtered env vars, redacted)
/// +-- uname.txt          (Unix only)
/// +-- lspci.txt          (Linux only, GPU/accel keyword filter)
/// +-- lsmod.txt          (Linux only)
/// +-- dmesg-gpu.txt      (Linux only, last 200 GPU-keyword lines)
/// +-- version.txt        (package name+version+features+target)
/// +-- system_profiler_display.txt   (macOS only, --verbose only)
/// ```
pub fn write_bundle(path: &Path, report: &Report, opts: &DoctorOptions) -> Result<()> {
    let redact = opts.redact_options();

    // Compose the archive in-memory first so we can include derived pieces
    // (like the short-form version.txt that references the other files).
    let entries = collect_entries(report, opts, &redact)?;

    // Wrap the file in a gzip encoder feeding a tar builder. Both layers
    // are buffered; we only need one `finish()` per wrapper.
    if let Some(parent) = path.parent()
        && !parent.as_os_str().is_empty()
    {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("failed to create bundle parent {parent:?}"))?;
    }
    let f =
        open_bundle_file(path).with_context(|| format!("failed to create bundle file {path:?}"))?;
    let gz = GzEncoder::new(f, Compression::default());
    let mut tar = tar::Builder::new(gz);

    for (name, bytes) in &entries {
        let mut header = tar::Header::new_gnu();
        header.set_size(bytes.len() as u64);
        header.set_mode(0o600);
        header.set_mtime(
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0),
        );
        header.set_cksum();
        tar.append_data(&mut header, name, bytes.as_slice())
            .with_context(|| format!("failed to append {name} to bundle"))?;
    }

    let gz = tar.into_inner().context("failed to finalise tar stream")?;
    let f = gz.finish().context("failed to finalise gzip stream")?;
    // Persist the archive to disk before returning so a subsequent
    // tampering attempt cannot race a short-lived file descriptor
    // flush.
    if let Err(e) = f.sync_all() {
        return Err(e).with_context(|| format!("failed to fsync bundle {path:?}"));
    }
    Ok(())
}

/// Open the bundle file with symlink-safe, owner-only permissions.
///
/// On Unix the file is created with `O_NOFOLLOW | O_CREAT | O_EXCL`-style
/// semantics via `custom_flags(libc::O_NOFOLLOW)` and mode `0o600`. This
/// mirrors the hardening used for snapshot (`src/snapshot/mod.rs`) and
/// record (`src/record/writer.rs`) output and addresses the same TOCTOU
/// risk: a pre-existing symlink at `path` must NOT cause the writer to
/// follow into an unintended destination (e.g., `/etc/shadow`).
///
/// On Windows the file is opened with `share_mode(0)` (exclusive
/// sharing) which blocks other processes from opening it while the tar
/// stream is being written. Fine-grained symlink TOCTOU mitigation on
/// Windows needs different primitives and is out of scope for this
/// helper.
///
/// A pre-existing symlink at `path` surfaces `ErrorKind::InvalidInput`
/// (via `ELOOP` on Linux) rather than the write silently going through
/// the symlink.
fn open_bundle_file(path: &Path) -> std::io::Result<File> {
    use std::fs::OpenOptions;

    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .custom_flags(libc::O_NOFOLLOW)
            .mode(0o600)
            .open(path)
    }
    #[cfg(all(windows, not(unix)))]
    {
        use std::os::windows::fs::OpenOptionsExt;
        OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .share_mode(0)
            .open(path)
    }
    #[cfg(not(any(unix, windows)))]
    {
        OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(path)
    }
}

fn collect_entries(
    report: &Report,
    opts: &DoctorOptions,
    redact: &RedactOptions,
) -> Result<Vec<(String, Vec<u8>)>> {
    let mut out: Vec<(String, Vec<u8>)> = vec![
        (
            "all-smi-doctor/report.txt".to_string(),
            render_human_string(report, redact, opts)?.into_bytes(),
        ),
        (
            "all-smi-doctor/report.json".to_string(),
            render_json_string(report, redact)?.into_bytes(),
        ),
        (
            "all-smi-doctor/env.txt".to_string(),
            env_dump(redact).into_bytes(),
        ),
        (
            "all-smi-doctor/version.txt".to_string(),
            version_dump(report).into_bytes(),
        ),
    ];

    if let Some(bytes) = uname_bytes(redact) {
        out.push(("all-smi-doctor/uname.txt".to_string(), bytes));
    }
    if let Some(bytes) = lspci_bytes(redact) {
        out.push(("all-smi-doctor/lspci.txt".to_string(), bytes));
    }
    if let Some(bytes) = lsmod_bytes(redact) {
        out.push(("all-smi-doctor/lsmod.txt".to_string(), bytes));
    }
    if let Some(bytes) = dmesg_gpu_bytes(redact) {
        out.push(("all-smi-doctor/dmesg-gpu.txt".to_string(), bytes));
    }

    #[cfg(target_os = "macos")]
    if opts.verbose
        && let Some(bytes) = macos_system_profiler_bytes(redact)
    {
        out.push((
            "all-smi-doctor/system_profiler_display.txt".to_string(),
            bytes,
        ));
    }

    // TODO: once the effective merged config file (issue #192) ships,
    // append `all-smi-doctor/config.toml` here with the sensitive fields
    // redacted. Intentionally skipped for now because the config-file
    // tree does not yet exist.

    // Silence unused variable warnings on non-macOS builds.
    let _ = opts;

    Ok(out)
}

/// Case-insensitive substrings that mark a variable name as likely to
/// contain a secret. When any of these appear in the variable name (e.g.
/// `BACKENDAI_SECRET_KEY`, `NVIDIA_API_TOKEN`, `HUGGINGFACE_HUB_TOKEN`),
/// the value is replaced with a redaction marker before it is written to
/// the bundle. Match is substring-based so variant spellings such as
/// `ACCESS_KEY_ID`, `CLIENT_SECRET`, `BEARER_TOKEN` are all covered.
///
/// This list is applied even when `--include-identifiers` is set —
/// that flag opts back in to hostnames / IPs / usernames, not to
/// credential values which should never appear in a support bundle.
const SECRET_NAME_SUBSTRINGS: &[&str] = &[
    "TOKEN",
    "SECRET",
    "PASSWORD",
    "PASSWD",
    "API_KEY",
    "APIKEY",
    "ACCESS_KEY",
    "PRIVATE_KEY",
    "CREDENTIAL",
    "AUTH",
    "SESSION",
    "COOKIE",
    "BEARER",
    "SIGNATURE",
    "ENCRYPTION_KEY",
    "CLIENT_SECRET",
];

/// Redaction marker substituted for the value of any variable whose
/// name matches [`SECRET_NAME_SUBSTRINGS`].
pub(crate) const REDACT_SECRET_VALUE: &str = "<redacted:secret>";

/// Returns `true` when `name` looks like a credential-bearing env var.
/// Matching is case-insensitive and substring-based so both
/// `BACKENDAI_SECRET_KEY` and `backendai_secret_key` are caught.
pub(crate) fn is_secret_env_name(name: &str) -> bool {
    let upper = name.to_ascii_uppercase();
    SECRET_NAME_SUBSTRINGS.iter().any(|p| upper.contains(p))
}

fn env_dump(redact: &RedactOptions) -> String {
    // Keep the env dump focused on hardware-related prefixes so we
    // do not leak the whole environment unnecessarily. `PATH` and
    // `LD_LIBRARY_PATH` are intentionally *not* included verbatim —
    // their values frequently contain `/home/<username>` segments
    // and private build directories. A compact length-only summary
    // is emitted for them instead so the bundle still reflects
    // whether they are set without leaking personal filesystem
    // layout.
    let keep = [
        "ALL_SMI_",
        "CUDA_",
        "NVIDIA_",
        "ROCR_",
        "HIP_",
        "HSA_",
        "TPU_",
        "CLOUD_TPU_",
        "HL_",
        "HABANA_",
        "NO_COLOR",
        "USER",
        "HOSTNAME",
        "KUBERNETES_",
        "BACKENDAI_",
        "HOME",
    ];
    let mut vars: Vec<(String, String)> = std::env::vars()
        .filter(|(k, _)| keep.iter().any(|p| k.starts_with(*p) || k == p))
        .map(|(k, v)| {
            if is_secret_env_name(&k) {
                (k, REDACT_SECRET_VALUE.to_string())
            } else {
                (k, v)
            }
        })
        .collect();
    vars.sort_by(|a, b| a.0.cmp(&b.0));

    let mut text = String::new();
    for (k, v) in vars {
        text.push_str(&format!("{k}={v}\n"));
    }

    // Summarise PATH / LD_LIBRARY_PATH without their content: the
    // fact of being set and the number of entries is useful for
    // debugging; the actual paths are not.
    for var in ["PATH", "LD_LIBRARY_PATH"] {
        match std::env::var(var) {
            Ok(v) if !v.is_empty() => {
                let sep = if cfg!(windows) { ';' } else { ':' };
                let entries = v.split(sep).filter(|s| !s.is_empty()).count();
                text.push_str(&format!("{var}=<redacted:path-list {entries} entries>\n"));
            }
            _ => {}
        }
    }

    scrub(&text, redact)
}

fn version_dump(report: &Report) -> String {
    let features = enabled_features().join(",");
    let level_zero = level_zero_effective();
    let triple = crate::doctor::checks::platform::checks()
        .iter()
        .find(|c| c.id == "platform.runtime")
        .map(|c| (c.run)(&Default::default()))
        .map(|r| r.message().to_string())
        .unwrap_or_else(|| "target unknown".to_string());
    let version = &report.version;
    let schema = report.schema;
    let timestamp = &report.timestamp;
    format!(
        "all-smi {version}\nschema: {schema}\ntimestamp: {timestamp}\nfeatures: {features}\nlevel_zero: {level_zero}\nruntime: {triple}\n"
    )
}

/// Whether the Intel Level Zero backend was compiled into this binary.
///
/// Deliberately separate from [`enabled_features`], which is contractually
/// a list of enabled *cargo features*. Level Zero is not purely a feature:
/// `build.rs` turns it on for every Windows target regardless of
/// `--features level_zero`, so on Windows the feature list says nothing
/// about whether the backend is there. That is exactly what someone
/// reading a support bundle needs to know, because it decides whether GPU
/// temperature, power, and frequency can be collected at all.
fn level_zero_effective() -> &'static str {
    if cfg!(all_smi_level_zero) {
        "compiled-in"
    } else {
        "absent"
    }
}

fn enabled_features() -> Vec<&'static str> {
    let mut v = vec![
        #[cfg(feature = "cli")]
        "cli",
        // Retained as a cargo-feature record for compatibility. It is a no-op;
        // `amd.libamdgpu_top.abi` in the doctor report carries effective plugin
        // availability and the exact runtime failure reason.
        #[cfg(feature = "amd")]
        "amd",
        #[cfg(feature = "mock")]
        "mock",
        #[cfg(feature = "furiosa")]
        "furiosa",
        // Recorded because this feature decides what the Intel GPU readers can
        // collect at all: with it the readers dlopen the Level Zero loader and
        // surface per-engine activity plus Sysman power, without it they fall
        // back to the sysfs/WMI baseline. Omitting it hid the one fact that
        // explains why two builds report different Intel GPU metrics (issue
        // #362). Every feature declared in Cargo.toml except `default` must have
        // an arm here; `bundle_covers_every_declared_feature` enforces that.
        //
        // This arm tracks the cargo feature and nothing else. On Windows the
        // backend is compiled in whether or not the feature is set, so read the
        // `level_zero:` line of version.txt for the effective state; see
        // `level_zero_effective`.
        #[cfg(feature = "level_zero")]
        "level_zero",
    ];
    if v.is_empty() {
        v.push("none");
    }
    v
}

fn uname_bytes(redact: &RedactOptions) -> Option<Vec<u8>> {
    #[cfg(unix)]
    {
        let out = try_exec("uname", &["-a"], Duration::from_millis(500))?;
        if out.success() {
            return Some(scrub(out.stdout.trim_end(), redact).into_bytes());
        }
        None
    }
    #[cfg(not(unix))]
    {
        let _ = redact;
        None
    }
}

fn lspci_bytes(redact: &RedactOptions) -> Option<Vec<u8>> {
    #[cfg(target_os = "linux")]
    {
        let out = try_exec("lspci", &["-vv"], Duration::from_millis(2_500))?;
        if !out.success() {
            return None;
        }
        // Filter to GPU-relevant lines plus their indented continuations
        // so reviewers see the accompanying capability / driver block.
        let mut keep: Vec<String> = Vec::new();
        let mut in_match = false;
        let keywords = [
            "VGA",
            "3D",
            "Display",
            "NVIDIA",
            "AMD",
            "Habana",
            "Tenstorrent",
            "Accel",
        ];
        for line in out.stdout.lines() {
            let trimmed = line.trim_start();
            if trimmed == line && !line.is_empty() {
                // New device block — decide whether to keep it.
                in_match = keywords.iter().any(|k| line.contains(k));
            }
            if in_match {
                keep.push(line.to_string());
            }
        }
        let text = keep.join("\n");
        Some(scrub(&text, redact).into_bytes())
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = redact;
        None
    }
}

fn lsmod_bytes(redact: &RedactOptions) -> Option<Vec<u8>> {
    #[cfg(target_os = "linux")]
    {
        let out = try_exec("lsmod", &[], Duration::from_millis(1_000))?;
        if !out.success() {
            return None;
        }
        Some(scrub(&out.stdout, redact).into_bytes())
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = redact;
        None
    }
}

fn dmesg_gpu_bytes(redact: &RedactOptions) -> Option<Vec<u8>> {
    #[cfg(target_os = "linux")]
    {
        // `dmesg` on modern kernels requires CAP_SYSLOG or `kernel.dmesg_restrict=0`.
        // If it fails (permission denied) we silently omit the file, per the
        // issue spec.
        let out = try_exec("dmesg", &["-T"], Duration::from_millis(2_500))?;
        if !out.success() {
            return None;
        }
        let keywords = ["nvidia", "amdgpu", "i915", "habanalabs", "drm", "tt-kmd"];
        let filtered: Vec<&str> = out
            .stdout
            .lines()
            .filter(|l| keywords.iter().any(|k| l.to_lowercase().contains(k)))
            .collect();
        // Last 200 lines only.
        let start = filtered.len().saturating_sub(200);
        let text = filtered[start..].join("\n");
        Some(scrub(&text, redact).into_bytes())
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = redact;
        None
    }
}

#[cfg(target_os = "macos")]
fn macos_system_profiler_bytes(redact: &RedactOptions) -> Option<Vec<u8>> {
    // system_profiler SPDisplaysDataType is expensive — gated behind
    // --verbose in the CLI surface.
    let out = try_exec(
        "system_profiler",
        &["SPDisplaysDataType"],
        Duration::from_millis(2_900),
    )?;
    if !out.success() {
        return None;
    }
    Some(scrub(&out.stdout, redact).into_bytes())
}

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

    /// Both sources are embedded at compile time. `Cargo.toml` is reached
    /// through `CARGO_MANIFEST_DIR` and this module's own file through a
    /// relative include, so neither depends on the working directory.
    const MANIFEST: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml"));
    const BUNDLE_SOURCE: &str = include_str!("bundle.rs");

    /// Feature names declared in the `[features]` table of `Cargo.toml`.
    ///
    /// Continuation lines of multi-line arrays carry no `=` and are skipped,
    /// as are comments and blank lines. Keys that are not bare identifiers
    /// are ignored so a stray quoted entry cannot be mistaken for a feature.
    fn declared_features(manifest: &str) -> Vec<&str> {
        let mut out = Vec::new();
        let mut in_features = false;
        for line in manifest.lines() {
            let trimmed = line.trim();
            if trimmed.starts_with('[') {
                in_features = trimmed == "[features]";
                continue;
            }
            if !in_features || trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }
            let Some((name, _)) = trimmed.split_once('=') else {
                continue;
            };
            let name = name.trim();
            if !name.is_empty()
                && name
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
            {
                out.push(name);
            }
        }
        out
    }

    /// Source text of `enabled_features`, from its signature to the next
    /// top-level `fn`. Restricting the scan to this span keeps unrelated
    /// feature gates elsewhere in the file, and the literals in this test
    /// module, from satisfying the coverage assertion.
    fn enabled_features_body(source: &str) -> &str {
        let start = source.find("fn enabled_features()").expect(
            "fn enabled_features() not found in bundle.rs; if it was renamed or moved, update \
             this test to point at the new location",
        );
        let rest = &source[start..];
        let end = rest.find("\nfn ").unwrap_or(rest.len());
        &rest[..end]
    }

    /// Feature names appearing in `#[cfg(feature = "...")]` attributes.
    fn cfg_gated_features(body: &str) -> Vec<&str> {
        const MARKER: &str = "#[cfg(feature = \"";
        let mut out = Vec::new();
        let mut rest = body;
        while let Some(i) = rest.find(MARKER) {
            rest = &rest[i + MARKER.len()..];
            let Some((name, tail)) = rest.split_once('"') else {
                break;
            };
            out.push(name);
            rest = tail;
        }
        out
    }

    /// Every declared cargo feature must be representable in the bundle's
    /// feature list.
    ///
    /// The arms are `#[cfg]`-gated, so a running test only observes the
    /// features it was itself built with and cannot notice a missing arm for
    /// a disabled one. Comparing the manifest against the source text is what
    /// makes the check independent of the build configuration. This function
    /// has already drifted twice (`amd` arrived late in #358, `level_zero` was
    /// missing from the start, #362), which is what the assertion is for.
    ///
    /// `default` is excluded: it is an alias for other features rather than a
    /// runtime capability of its own.
    #[test]
    fn bundle_covers_every_declared_feature() {
        let declared = declared_features(MANIFEST);
        assert!(
            declared.contains(&"default") && declared.contains(&"cli"),
            "parsing the [features] table of Cargo.toml looks broken, got {declared:?}"
        );

        let covered = cfg_gated_features(enabled_features_body(BUNDLE_SOURCE));
        for feature in declared {
            if feature == "default" {
                continue;
            }
            assert!(
                covered.contains(&feature),
                "cargo feature `{feature}` is declared in Cargo.toml but enabled_features() has \
                 no arm for it, so a build with it would understate itself in support bundles; \
                 arms found: {covered:?}"
            );
        }
    }

    /// The reported list must match what the binary was actually built with,
    /// in both directions: a compiled-in feature appears and a compiled-out
    /// one does not.
    #[test]
    fn enabled_features_matches_build_configuration() {
        let features = enabled_features();
        for (name, compiled_in) in [
            ("cli", cfg!(feature = "cli")),
            ("amd", cfg!(feature = "amd")),
            ("mock", cfg!(feature = "mock")),
            ("furiosa", cfg!(feature = "furiosa")),
            ("level_zero", cfg!(feature = "level_zero")),
        ] {
            assert_eq!(
                features.contains(&name),
                compiled_in,
                "feature `{name}` compiled in: {compiled_in}, but reported list is {features:?}"
            );
        }
    }

    #[test]
    fn bundle_writes_expected_entries() {
        // A `NamedTempFile` stays open at the path it owns, and
        // `write_bundle` creates or replaces a file at that same path.
        // Windows refuses that while the handle is alive (os error 32);
        // Unix permits it, which is why this passed everywhere else. Hand
        // the writer a path inside a temp directory instead, so nothing
        // else holds it open.
        let dir = tempfile::tempdir().expect("tempdir");
        let bundle = dir.path().join("bundle.tar.gz");
        let report = Report {
            schema: 1,
            version: "0.99.9".to_string(),
            timestamp: "2026-04-20T00:00:00Z".to_string(),
            summary: Summary {
                pass: 1,
                warn: 0,
                fail: 0,
                skip: 0,
            },
            checks: vec![],
        };
        let opts = DoctorOptions {
            json: false,
            verbose: false,
            bundle_path: Some(bundle.clone()),
            include_identifiers: true,
            remote_checks: vec![],
            skip: vec![],
            only: vec![],
            use_color: false,
        };
        write_bundle(&bundle, &report, &opts).expect("bundle ok");
        let bytes = std::fs::read(&bundle).expect("read bundle");
        // Cheap sanity check: the gzip header magic should be present.
        assert!(bytes.len() > 2);
        assert_eq!(bytes[0], 0x1f);
        assert_eq!(bytes[1], 0x8b);
    }

    #[test]
    fn is_secret_env_name_matches_common_patterns() {
        assert!(is_secret_env_name("BACKENDAI_SECRET_KEY"));
        assert!(is_secret_env_name("BACKENDAI_ACCESS_KEY"));
        assert!(is_secret_env_name("AWS_SESSION_TOKEN"));
        assert!(is_secret_env_name("HUGGINGFACE_HUB_TOKEN"));
        assert!(is_secret_env_name("MY_API_KEY"));
        assert!(is_secret_env_name("github_client_secret"));
        assert!(is_secret_env_name("SERVICE_PASSWORD"));
        assert!(is_secret_env_name("BEARER_TOKEN_PROD"));

        assert!(!is_secret_env_name("NVIDIA_VISIBLE_DEVICES"));
        assert!(!is_secret_env_name("CUDA_VISIBLE_DEVICES"));
        assert!(!is_secret_env_name("HOME"));
        assert!(!is_secret_env_name("USER"));
        assert!(!is_secret_env_name("PATH"));
    }

    #[test]
    fn env_dump_redacts_secret_values_and_summarises_path() {
        // SAFETY: env var mutation is unsafe in Rust 2024. This test
        // mutates process-global state; parallel tests that also read
        // these names might see transient values, but the matrix here
        // uses unique test-scoped names.
        unsafe {
            std::env::set_var("ALL_SMI_DOCTOR_TEST_TOKEN", "hunter2");
            std::env::set_var("ALL_SMI_DOCTOR_TEST_PLAIN", "public-value");
            std::env::set_var("PATH", "/a:/b:/c");
        }
        let opts = RedactOptions {
            hostname: None,
            username: None,
            scrub_kernel_pointers: false,
            enabled: true,
        };
        let dump = env_dump(&opts);
        unsafe {
            std::env::remove_var("ALL_SMI_DOCTOR_TEST_TOKEN");
            std::env::remove_var("ALL_SMI_DOCTOR_TEST_PLAIN");
        }

        // Secret value replaced with redaction marker.
        assert!(
            dump.contains("ALL_SMI_DOCTOR_TEST_TOKEN=<redacted:secret>"),
            "secret value must be redacted: {dump}"
        );
        assert!(
            !dump.contains("hunter2"),
            "raw secret must not appear in bundle: {dump}"
        );

        // Non-secret value preserved verbatim.
        assert!(
            dump.contains("ALL_SMI_DOCTOR_TEST_PLAIN=public-value"),
            "non-secret value must be preserved: {dump}"
        );

        // PATH entries replaced with a length-only summary.
        assert!(
            dump.contains("PATH=<redacted:path-list"),
            "PATH must be summarised: {dump}"
        );
        assert!(
            !dump.contains("/a:/b:/c"),
            "raw PATH contents must not leak: {dump}"
        );
    }

    #[test]
    fn bundle_unix_mode_is_0o600() {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let tmp = tempfile::NamedTempFile::new().expect("tempfile");
            let report = Report {
                schema: 1,
                version: "0.99.9".to_string(),
                timestamp: "2026-04-20T00:00:00Z".to_string(),
                summary: Summary::default(),
                checks: vec![],
            };
            let opts = DoctorOptions {
                json: false,
                verbose: false,
                bundle_path: Some(tmp.path().to_path_buf()),
                include_identifiers: true,
                remote_checks: vec![],
                skip: vec![],
                only: vec![],
                use_color: false,
            };
            write_bundle(tmp.path(), &report, &opts).expect("bundle ok");
            let meta = std::fs::metadata(tmp.path()).expect("metadata");
            let mode = meta.permissions().mode() & 0o777;
            assert_eq!(
                mode, 0o600,
                "bundle file must be owner-read/write only, got {mode:o}"
            );
        }
    }

    #[test]
    fn bundle_refuses_preexisting_symlink() {
        #[cfg(unix)]
        {
            // Build a symlink and ask write_bundle to overwrite its
            // target. With O_NOFOLLOW the open must fail rather than
            // dereferencing the symlink.
            use std::os::unix::fs::symlink;
            let dir = tempfile::tempdir().expect("tempdir");
            let decoy_target = dir.path().join("DECOY");
            std::fs::write(&decoy_target, b"sensitive").expect("decoy write");
            let link_path = dir.path().join("bundle.tar.gz");
            symlink(&decoy_target, &link_path).expect("symlink");

            let report = Report {
                schema: 1,
                version: "0.99.9".to_string(),
                timestamp: "2026-04-20T00:00:00Z".to_string(),
                summary: Summary::default(),
                checks: vec![],
            };
            let opts = DoctorOptions {
                json: false,
                verbose: false,
                bundle_path: Some(link_path.clone()),
                include_identifiers: true,
                remote_checks: vec![],
                skip: vec![],
                only: vec![],
                use_color: false,
            };
            let result = write_bundle(&link_path, &report, &opts);
            assert!(
                result.is_err(),
                "write_bundle must refuse to follow a pre-existing symlink"
            );

            // Decoy target must not have been overwritten.
            let decoy_contents = std::fs::read(&decoy_target).expect("decoy read");
            assert_eq!(
                decoy_contents, b"sensitive",
                "symlink target was overwritten despite O_NOFOLLOW"
            );
        }
    }

    /// The effective Level Zero state is reported separately from the
    /// cargo-feature list, and tracks the `all_smi_level_zero` cfg rather
    /// than `--features level_zero`.
    ///
    /// The two no longer agree anywhere: `build.rs` turns the backend on
    /// for every Linux and Windows target regardless of the feature, so a
    /// default build on either reports `level_zero: compiled-in` while
    /// `features:` correctly omits it. That divergence is the whole reason
    /// this line exists.
    #[test]
    fn level_zero_effective_tracks_the_cfg_alias() {
        assert_eq!(
            level_zero_effective() == "compiled-in",
            cfg!(all_smi_level_zero)
        );

        // The rule build.rs implements. Only the positive direction is
        // asserted: the compiler enforces the other half, because a target
        // without the backend's `libloading` dependency does not build with
        // the cfg forced on, which is a louder failure than this test. A
        // scratch probe that widens the gate by hand is also allowed to
        // turn it on anywhere, and should not have to fail here to do it.
        if cfg!(target_os = "linux") || cfg!(target_os = "windows") {
            assert_eq!(level_zero_effective(), "compiled-in");
        }
    }

    /// The line has to be in version.txt itself, not merely computable: a
    /// support bundle is read by someone who does not have the build.
    #[test]
    fn version_dump_reports_the_level_zero_state() {
        let report = Report {
            schema: 1,
            version: "0.99.9".to_string(),
            timestamp: "2026-04-20T00:00:00Z".to_string(),
            summary: Summary {
                pass: 0,
                warn: 0,
                fail: 0,
                skip: 0,
            },
            checks: vec![],
        };
        let dump = version_dump(&report);
        assert!(
            dump.contains(&format!("level_zero: {}", level_zero_effective())),
            "version.txt must record the effective Level Zero state, got:\n{dump}"
        );
    }
}