keyhog 0.5.86

GPU-accelerated secret scanner for code, Git history, cloud, containers, browser assets, and live credential verification
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
//! `keyhog backend --self-test`: execute the real GPU probes and report a
//! pass/degrade/fail verdict.
//!
//! Unlike the heuristic report this DISPATCHES work, so its JSON is measured
//! evidence about this host rather than a capability guess.

use super::{is_known_vyre_lowering_gap, KEYHOG_GPU_MAX_BUFFER_CAP_MB};
use crate::exit_codes::{EXIT_BACKEND_SELF_TEST_FAILED, EXIT_SUCCESS};
use crate::style::{self, Palette};
use anyhow::Result;
use keyhog_scanner::hw_probe::{probe_hardware, HardwareCaps};
use serde::Serialize;
use std::process::ExitCode;

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum BackendSelfTestStatus {
    Pass,
    Fail,
    Warning,
    Known,
    Skip,
}

#[derive(Debug, Serialize)]
pub(crate) struct BackendSelfTestProbe {
    pub(crate) name: &'static str,
    pub(crate) status: BackendSelfTestStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) message: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) direct_matches: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) coalesced_matches: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) matches: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) backend_id: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) backend_route: Option<&'static str>,
}

impl BackendSelfTestProbe {
    fn pass(name: &'static str) -> Self {
        Self {
            name,
            status: BackendSelfTestStatus::Pass,
            message: None,
            direct_matches: None,
            coalesced_matches: None,
            matches: None,
            backend_id: None,
            backend_route: None,
        }
    }

    fn fail(name: &'static str, message: String) -> Self {
        Self {
            status: BackendSelfTestStatus::Fail,
            message: Some(message),
            ..Self::pass(name)
        }
    }

    fn known(name: &'static str, message: impl Into<String>) -> Self {
        Self {
            status: BackendSelfTestStatus::Known,
            message: Some(message.into()),
            ..Self::pass(name)
        }
    }

    fn warning(name: &'static str, message: impl Into<String>) -> Self {
        Self {
            status: BackendSelfTestStatus::Warning,
            message: Some(message.into()),
            ..Self::pass(name)
        }
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum BackendSelfTestRouteSelection {
    NotMeasured,
}

#[derive(Debug, Serialize)]
pub(crate) struct BackendSelfTestReport {
    pub(crate) ok: bool,
    pub(crate) status: BackendSelfTestStatus,
    pub(crate) exit_code: u8,
    pub(crate) gpu_available: bool,
    pub(crate) gpu_is_software: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) gpu_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) gpu_max_buffer_mb: Option<u64>,
    pub(crate) healthy_gpu_backends: Vec<&'static str>,
    /// A health probe does not measure comparative route performance.
    pub(crate) route_selection: BackendSelfTestRouteSelection,
    pub(crate) probes: Vec<BackendSelfTestProbe>,
}

impl BackendSelfTestReport {
    fn exit_code(&self) -> ExitCode {
        ExitCode::from(self.exit_code)
    }
}

pub(super) fn run_self_test(json: bool, require_gpu: bool, gpu_disabled: bool) -> Result<ExitCode> {
    let report = if gpu_disabled {
        disabled_gpu_self_test_report()
    } else {
        collect_self_test_report(require_gpu)
    };
    if json {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        print_self_test_report(&report);
    }
    Ok(report.exit_code())
}

fn disabled_gpu_self_test_report() -> BackendSelfTestReport {
    BackendSelfTestReport {
        ok: true,
        status: BackendSelfTestStatus::Skip,
        exit_code: EXIT_SUCCESS,
        gpu_available: false,
        gpu_is_software: false,
        gpu_name: None,
        gpu_max_buffer_mb: None,
        healthy_gpu_backends: Vec::new(),
        route_selection: BackendSelfTestRouteSelection::NotMeasured,
        probes: vec![BackendSelfTestProbe {
            name: "gpu_adapter",
            status: BackendSelfTestStatus::Skip,
            message: Some("GPU probing disabled by --no-gpu".to_string()),
            direct_matches: None,
            coalesced_matches: None,
            matches: None,
            backend_id: None,
            backend_route: None,
        }],
    }
}

fn collect_self_test_report(require_gpu: bool) -> BackendSelfTestReport {
    // Self-test probe collection, profiled as preprocessing.
    let _collect_span = keyhog_profile::span(keyhog_profile::Stage::Preprocess);
    let hw = probe_hardware();
    let region_presence = keyhog_scanner::gpu::gpu_region_presence_self_test();
    let acquired_backends: Vec<_> = match &region_presence {
        Ok(report) => report.peers.iter().map(|peer| peer.backend).collect(),
        Err(error) => error.acquired_backends.clone(),
    };

    if (!hw.gpu_available || hw.gpu_is_software) && acquired_backends.is_empty() {
        return unavailable_gpu_self_test_report(hw, require_gpu);
    }

    let mut all_ok = true;
    let mut probes = Vec::with_capacity(1 + acquired_backends.len());
    let has_wgpu = acquired_backends.contains(&keyhog_scanner::ScanBackend::GpuWgpu);
    let healthy_gpu_backends = region_presence
        .as_ref()
        // LAW10: a region-presence error is emitted as the failing `gpu_region_presence` probe below; this list contains only successful peers.
        .ok()
        .map(|report| {
            report
                .peers
                .iter()
                .map(|peer| crate::orchestrator_config::backend_override_cli_value(peer.backend))
                .collect()
        })
        // LAW10: an errored region-presence report has no healthy peers and is surfaced as a failed self-test probe below.
        .unwrap_or_default();

    // Test 1: VYRE's direct match-triple literal-set diagnostic. Production
    // scanning uses the scratch region-presence API exercised end to end by
    // the next probe. A direct-mode failure with the classified lowering
    // signature is visible as KNOWN, but never exempts the production probe.
    if !has_wgpu {
        probes.push(BackendSelfTestProbe::warning(
            "vyre_literal_set",
            "WGPU peer was not acquired; direct WGPU match-triple diagnostics are not applicable",
        ));
    } else {
        match keyhog_scanner::gpu::vyre_gpu_self_test() {
            Ok(report) => {
                let mut probe = BackendSelfTestProbe::pass("vyre_literal_set");
                probe.direct_matches = Some(report.direct_matches);
                probe.coalesced_matches = Some(report.coalesced_matches);
                probes.push(probe);
            }
            Err(error) => {
                let known_lowering_gap = is_known_vyre_lowering_gap(&error);
                if known_lowering_gap {
                    probes.push(BackendSelfTestProbe::known(
                    "vyre_literal_set",
                    "VYRE IR lowering rejects the direct match-triple form; the production region-presence path is checked separately below",
                ));
                } else {
                    probes.push(BackendSelfTestProbe::warning(
                    "vyre_literal_set",
                    format!(
                        "VYRE direct match-triple diagnostic failed ({error}); production scan eligibility is determined by gpu_region_presence"
                    ),
                ));
                }
            }
        }
    }

    // Test 2: the production region-presence route. It builds a minimal
    // detector, dispatches through the same scanner path as a selected GPU
    // scan, and compares the final findings with the portable CPU reference.
    match region_presence {
        Ok(report) => {
            for peer in report.peers {
                let mut probe = BackendSelfTestProbe::pass("gpu_region_presence");
                probe.matches = Some(peer.matches);
                probe.backend_id = Some(peer.backend_id);
                probe.backend_route = Some(crate::orchestrator_config::backend_override_cli_value(
                    peer.backend,
                ));
                probes.push(probe);
            }
        }
        Err(error) => {
            probes.push(BackendSelfTestProbe::fail(
                "gpu_region_presence",
                error.to_string(),
            ));
            all_ok = false;
        }
    }

    BackendSelfTestReport {
        ok: all_ok,
        status: if all_ok {
            BackendSelfTestStatus::Pass
        } else {
            BackendSelfTestStatus::Fail
        },
        exit_code: if all_ok {
            0
        } else {
            EXIT_BACKEND_SELF_TEST_FAILED
        },
        gpu_available: hw.gpu_available || !acquired_backends.is_empty(),
        gpu_is_software: hw.gpu_is_software && acquired_backends.is_empty(),
        gpu_name: hw.gpu_name.clone(),
        gpu_max_buffer_mb: hw.gpu_vram_mb,
        healthy_gpu_backends,
        route_selection: BackendSelfTestRouteSelection::NotMeasured,
        probes,
    }
}

pub(super) fn unavailable_gpu_self_test_report(
    hw: &HardwareCaps,
    require_gpu: bool,
) -> BackendSelfTestReport {
    let reason = if hw.gpu_is_software {
        "GPU adapter is a software renderer and is disabled for scans"
    } else if hw.gpu_name.is_some() {
        if !keyhog_scanner::hw_probe::gpu_backend_compiled() {
            keyhog_scanner::hw_probe::uncompiled_gpu_backend_explanation()
        } else {
            "GPU runtime unavailable or failed initialization"
        }
    } else if !keyhog_scanner::hw_probe::gpu_backend_compiled() {
        keyhog_scanner::hw_probe::uncompiled_gpu_backend_explanation()
    } else {
        "no GPU adapter detected"
    };
    let status = if require_gpu {
        BackendSelfTestStatus::Fail
    } else {
        BackendSelfTestStatus::Skip
    };
    let message = if require_gpu {
        format!("--require-gpu requested but {reason}")
    } else {
        reason.to_string()
    };
    BackendSelfTestReport {
        ok: !require_gpu,
        status,
        exit_code: if require_gpu {
            EXIT_BACKEND_SELF_TEST_FAILED
        } else {
            EXIT_SUCCESS
        },
        gpu_available: hw.gpu_available,
        gpu_is_software: hw.gpu_is_software,
        gpu_name: hw.gpu_name.clone(),
        gpu_max_buffer_mb: hw.gpu_vram_mb,
        healthy_gpu_backends: Vec::new(),
        route_selection: BackendSelfTestRouteSelection::NotMeasured,
        probes: vec![BackendSelfTestProbe {
            name: "gpu_adapter",
            status,
            message: Some(message),
            direct_matches: None,
            coalesced_matches: None,
            matches: None,
            backend_id: None,
            backend_route: None,
        }],
    }
}

fn print_self_test_report(report: &BackendSelfTestReport) {
    let palette = style::for_stdout();
    println!("## GPU self-test");
    if report.status == BackendSelfTestStatus::Skip {
        let message = report
            .probes
            .first()
            .and_then(|probe| probe.message.as_deref())
            .unwrap_or("GPU self-test skipped"); // LAW10: absent name/label => display default; reporting-only, recall-safe
        println!("  {}: {message}", style::warn("SKIP", &palette));
        return;
    }

    for probe in &report.probes {
        print!("  {:<17} ... ", probe.name);
        match probe.status {
            BackendSelfTestStatus::Pass => print_pass_probe(probe, &palette),
            BackendSelfTestStatus::Fail => {
                let message = probe.message.as_deref().unwrap_or("probe failed"); // LAW10: absent name/label => display default; reporting-only, recall-safe
                println!("{}  {message}", style::fail("FAIL", &palette));
            }
            BackendSelfTestStatus::Warning => {
                let message = probe.message.as_deref().unwrap_or("diagnostic warning"); // LAW10: absent probe detail => reporting-only display label; status remains visible
                println!("{}  {message}", style::warn("WARN", &palette));
            }
            BackendSelfTestStatus::Known => {
                let message = probe.message.as_deref().unwrap_or("known limitation"); // LAW10: absent name/label => display default; reporting-only, recall-safe
                println!("{} {message}.", style::warn("KNOWN", &palette));
            }
            BackendSelfTestStatus::Skip => {
                let message = probe.message.as_deref().unwrap_or("probe skipped"); // LAW10: absent name/label => display default; reporting-only, recall-safe
                println!("{}  {message}", style::warn("SKIP", &palette));
            }
        }
    }

    println!();
    if report.ok {
        println!(
            "{} GPU self-test passed, scans on this box can route to GPU.",
            style::pass("PASS", &palette)
        );
        println!(
            "  Self-test proves backend health only. `keyhog backend --autoroute` shows the measured route."
        );
    } else {
        let stderr_palette = style::for_stderr();
        eprintln!(
            "{} GPU self-test failed; GPU routes are unavailable until fixed. \
             Use --backend simd/cpu or --no-gpu for an explicit CPU-only scan.",
            style::fail("FAIL", &stderr_palette)
        );
    }
}

fn print_pass_probe(probe: &BackendSelfTestProbe, palette: &Palette) {
    let pass = style::pass("PASS", palette);
    match probe.name {
        "vyre_literal_set" => println!(
            "{pass}  (direct={}, coalesced={})",
            format_probe_metric(probe.direct_matches),
            format_probe_metric(probe.coalesced_matches)
        ),
        "gpu_region_presence" => println!(
            "{pass}  (matches={}, route={}, backend={})",
            format_probe_metric(probe.matches),
            probe.backend_route.unwrap_or("unknown"), // LAW10: absent name/label => display default; reporting-only, recall-safe
            probe.backend_id.unwrap_or("unknown") // LAW10: absent name/label => display default; reporting-only, recall-safe
        ),
        _ => println!("{pass}"),
    }
}

pub(super) fn format_probe_metric<T: std::fmt::Display>(value: Option<T>) -> String {
    value.map_or_else(|| "unknown".to_string(), |value| value.to_string())
}

pub(super) fn render_self_test_json_for_contract(report: &BackendSelfTestReport) -> Result<String> {
    serde_json::to_string_pretty(report).map_err(Into::into)
}

pub(super) fn format_gpu_max_buffer(max_buffer_mb: u64) -> String {
    let base = if max_buffer_mb >= 1024 {
        format!("{} GB", max_buffer_mb / 1024)
    } else {
        format!("{max_buffer_mb} MB")
    };
    if max_buffer_mb >= KEYHOG_GPU_MAX_BUFFER_CAP_MB {
        format!(">={base} (keyhog cap; wgpu max_buffer_size)")
    } else {
        format!("{base} (wgpu max_buffer_size)")
    }
}