keyhog-scanner 0.5.73

keyhog-scanner: high-performance SIMD-accelerated secret detection engine
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
use super::super::gpu_region_batch::{
    build_region_presence_batch, validate_region_presence_batch_len, validation_window_range,
    with_region_presence_batch, with_test_region_presence_byte_limit, RegionPresenceBatchMode,
    RegionPresenceScratch, ZeroRegionPresenceScratch, REGION_PRESENCE_BATCH_BYTE_LIMIT,
};
use super::*;

#[test]
fn region_presence_batch_preserves_raw_bytes_separates_and_clears_scratch() {
    let chunks = [
        keyhog_core::Chunk::from("GhP_TOKEN"),
        keyhog_core::Chunk::from("Zz9"),
    ];
    let mut scratch = RegionPresenceScratch::default();

    {
        let mut guard = ZeroRegionPresenceScratch::new(&mut scratch);
        build_region_presence_batch(&chunks, guard.as_mut()).expect("batch");
        assert_eq!(guard.haystack(), b"GhP_TOKEN\0Zz9");
        assert_eq!(guard.region_starts(), &[0, 10]);
    }

    assert!(scratch.is_empty());
}

#[test]
fn region_presence_batch_borrows_single_chunk() {
    let chunks = [keyhog_core::Chunk::from("ghp_lowercase_token_123")];
    let source_ptr = chunks[0].data.as_bytes().as_ptr();

    with_region_presence_batch(&chunks, |haystack, region_starts, mode| {
        assert_eq!(mode, RegionPresenceBatchMode::BorrowedSingleChunk);
        assert_eq!(haystack, chunks[0].data.as_bytes());
        assert_eq!(haystack.as_ptr(), source_ptr);
        assert_eq!(region_starts, &[0]);
        Ok(())
    })
    .expect("borrowed single-chunk batch");
}

#[test]
fn region_presence_batch_borrows_uppercase_single_chunk_without_rewriting() {
    let chunks = [keyhog_core::Chunk::from("GhP_TOKEN")];
    let source_ptr = chunks[0].data.as_bytes().as_ptr();

    with_region_presence_batch(&chunks, |haystack, region_starts, mode| {
        assert_eq!(mode, RegionPresenceBatchMode::BorrowedSingleChunk);
        assert_eq!(haystack, b"GhP_TOKEN");
        assert_eq!(haystack.as_ptr(), source_ptr);
        assert_eq!(region_starts, &[0]);
        Ok(())
    })
    .expect("borrowed uppercase single-chunk batch");
}

#[test]
fn region_presence_batch_enforces_the_real_vyre_scan_ceiling() {
    assert_eq!(
        REGION_PRESENCE_BATCH_BYTE_LIMIT,
        vyre::scan::dispatch_io::DEFAULT_MAX_SCAN_BYTES as usize
    );
    assert!(validate_region_presence_batch_len(REGION_PRESENCE_BATCH_BYTE_LIMIT).is_ok());
    let error = validate_region_presence_batch_len(REGION_PRESENCE_BATCH_BYTE_LIMIT + 1)
        .expect_err("ceiling plus one must fail before allocation");
    assert!(error.contains("VYRE") && error.contains("Fix:"), "{error}");
}

#[test]
fn validation_window_range_preserves_utf8_boundaries() {
    let text = "αβghp_secretδ";
    let (start, end) = validation_window_range(text, 6, 5).expect("window");

    assert!(text.is_char_boundary(start));
    assert!(text.is_char_boundary(end));
    assert!(text[start..end].contains("ghp"));
}

#[test]
fn bounded_gpu_firing_rejects_window_miss_without_full_chunk_scan() {
    let rx = regex::Regex::new(r"SECRET-[0-9]{4}").expect("regex");
    let text = "prefix bait hit here\n\nlots of filler\n\nSECRET-1234";
    let distant_match_offset = text.find("SECRET-1234").expect("match");

    assert!(
        validate_detector_match(
            text,
            &rx,
            Some(distant_match_offset),
            Some("SECRET-1234".len())
        ),
        "bounded validator must accept a real local match"
    );
    assert!(
        !validate_detector_match(text, &rx, Some(0), Some("SECRET-1234".len())),
        "bounded GPU over-fire validation must not fall back to a full-chunk \
             regex scan after the local window misses"
    );
}

#[test]
fn unbounded_and_cpu_floor_validation_keep_full_chunk_oracle() {
    let rx = regex::Regex::new(r"SECRET=.*END").expect("regex");
    let text = "prefix bait hit here\nSECRET=abc123END";

    assert!(
        validate_detector_match(text, &rx, Some(0), None),
        "unbounded detector validation keeps the full prepared-chunk oracle"
    );
    assert!(
        validate_detector_match(text, &rx, None, Some(8)),
        "CPU recall-floor validation has no GPU offset, so it keeps the full \
             prepared-chunk oracle"
    );
}

#[test]
fn coalesce_rate_reports_zero_for_zero_duration() {
    assert_eq!(
        mib_per_second(8 * 1024 * 1024, std::time::Duration::ZERO),
        0.0
    );
    assert_eq!(mib_per_second(0, std::time::Duration::from_secs(1)), 0.0);
}

#[cfg(feature = "gpu")]
fn gpu_recovery_fixture() -> (
    CompiledScanner,
    crate::hw_probe::ScanBackend,
    Vec<keyhog_core::Chunk>,
    Vec<Vec<keyhog_core::RawMatch>>,
) {
    let detector = keyhog_core::DetectorSpec {
        id: "gpu-range-recovery-fixture".into(),
        name: "GPU recovery fixture".into(),
        service: "fixture".into(),
        severity: keyhog_core::Severity::High,
        patterns: vec![keyhog_core::PatternSpec {
            regex: r"(tok_[A-Za-z0-9]{16})".into(),
            group: Some(1),
            required_literals: vec!["tok_".into()],
            ..Default::default()
        }],
        ..keyhog_scanner::testing::named_detector_fixture_defaults()
    };
    let scanner = CompiledScanner::compile_with_gpu_policy(
        vec![detector],
        crate::GpuInitPolicy::ForceEnabled,
    )
    .expect("compile GPU recovery fixture");
    let backend = [
        crate::hw_probe::ScanBackend::GpuCuda,
        crate::hw_probe::ScanBackend::GpuWgpu,
    ]
    .into_iter()
    .find(|backend| scanner.gpu_backend(*backend).is_some())
    .expect("known GPU test host must acquire a hardware backend");
    let chunks = vec![
        keyhog_core::Chunk::from(format!("{}tok_AAAAAAAAAAAAAAAA", "a".repeat(24))),
        keyhog_core::Chunk::from(format!("{}tok_BBBBBBBBBBBBBBBB", "b".repeat(24))),
        keyhog_core::Chunk::from(format!("{}tok_CCCCCCCCCCCCCCCC", "c".repeat(24))),
    ];
    let expected = scanner
        .scan_coalesced_with_backend(&chunks, crate::hw_probe::ScanBackend::CpuFallback)
        .expect("scalar recovery-fixture scan succeeds");
    scanner.clear_fragment_cache();
    (scanner, backend, chunks, expected)
}

#[cfg(feature = "gpu")]
/// Proves an injected resident-dispatch fault replays only unfinished ranges
/// without racing another live GPU test on the shared adapter.
#[test]
fn automatic_gpu_recovery_rescans_only_unprocessed_dispatch_ranges() {
    let _gpu_test_guard = crate::testing::gpu_test_lock();
    let (scanner, backend, chunks, expected) = gpu_recovery_fixture();

    let outcome = with_test_region_presence_byte_limit(64, || {
        crate::gpu::with_test_resident_dispatch_failure(1, || {
            scanner
                .scan_coalesced_gpu_region_presence_recovering(
                    &chunks,
                    backend,
                    scanner.default_execution_route(),
                    true,
                    None,
                )
                .expect("automatic route must recover stable dispatch ranges")
        })
    });

    assert_eq!(outcome.matches, expected);
    let recovery = outcome.recovery.expect("typed recovery receipt");
    assert_eq!(recovery.failed_backend, backend);
    assert_eq!(
        recovery.ranges,
        vec![
            crate::RecoveredInputRange::new(1, 0, chunks[1].data.len()),
            crate::RecoveredInputRange::new(2, 0, chunks[2].data.len()),
        ],
        "the completed first GPU shard must not be replayed"
    );
}

#[cfg(feature = "gpu")]
/// Proves every eligible calibrated depth submits bounded independent resident
/// IO slots while the production scanner restores exact scalar result order.
#[test]
fn issue32_gpu_region_batches_use_every_eligible_resident_depth() {
    let _gpu_test_guard = crate::testing::gpu_test_lock();
    let (scanner, backend, mut chunks, _) = gpu_recovery_fixture();
    chunks.push(keyhog_core::Chunk::from(format!(
        "{}tok_DDDDDDDDDDDDDDDD",
        "d".repeat(24)
    )));
    chunks.push(keyhog_core::Chunk::from(format!(
        "{}tok_EEEEEEEEEEEEEEEE",
        "e".repeat(24)
    )));
    let expected = scanner
        .scan_coalesced_with_backend(&chunks, crate::hw_probe::ScanBackend::CpuFallback)
        .expect("scalar depth-matrix reference succeeds");
    let eligible_depths = scanner
        .eligible_gpu_resident_pipeline_depths(backend)
        .expect("selected GPU exposes resident dispatch capability");

    for depth in eligible_depths {
        scanner
            .reset_autoroute_calibration_gpu_workload()
            .expect("each depth starts from clean resident state");
        crate::gpu::reset_test_max_in_flight_slots();
        let mut route = scanner.default_execution_route();
        route.gpu_pipeline_depth = depth;
        let outcome = with_test_region_presence_byte_limit(64, || {
            scanner
                .scan_coalesced_gpu_region_presence_recovering(&chunks, backend, route, false, None)
                .expect("resident depth must preserve production scan parity")
        });
        assert_eq!(outcome.matches, expected, "finding drift at depth {depth}");
        let observed = crate::gpu::test_max_in_flight_slots();
        if depth == 1
            && scanner
                .gpu_resident_dispatch_capability(backend)
                .expect("capability remains available")
                == "synchronous"
        {
            assert_eq!(
                observed, 0,
                "borrowed synchronous path has no pending fence"
            );
        } else {
            assert_eq!(
                observed,
                usize::from(depth),
                "resident slot count must equal calibrated depth"
            );
        }
    }
}

#[cfg(feature = "gpu")]
/// Regression: direct GPU workers share one resident slot ring. Concurrent
/// callers must serialize complete rings rather than treating another worker's
/// in-flight fence as a backend failure. Ordered multi-device dispatch is not
/// covered here because each acquired device set owns its own dispatch lock.
#[test]
fn issue32_concurrent_direct_gpu_batches_share_the_resident_ring() {
    let _gpu_test_guard = crate::testing::gpu_test_lock();
    let (scanner, backend, seed_chunks, _) = gpu_recovery_fixture();
    let chunks = std::sync::Arc::new(seed_chunks.into_iter().cycle().take(64).collect::<Vec<_>>());
    let expected = std::sync::Arc::new(
        scanner
            .scan_coalesced_with_backend(&chunks, crate::hw_probe::ScanBackend::CpuFallback)
            .expect("scalar concurrent-dispatch reference succeeds"),
    );
    scanner.clear_fragment_cache();
    let scanner = std::sync::Arc::new(scanner);
    let mut route = scanner.default_execution_route();
    route.gpu_pipeline_depth = 1;

    std::thread::scope(|scope| {
        let handles = (0..8)
            .map(|_| {
                let scanner = std::sync::Arc::clone(&scanner);
                let chunks = std::sync::Arc::clone(&chunks);
                let expected = std::sync::Arc::clone(&expected);
                scope.spawn(move || {
                    let matches = with_test_region_presence_byte_limit(64, || {
                        scanner.scan_coalesced_gpu_region_presence_recovering(
                            &chunks, backend, route, false, None,
                        )
                    })
                    .expect("concurrent direct dispatch must not exhaust another worker's slot")
                    .matches;
                    assert_eq!(matches, *expected);
                })
            })
            .collect::<Vec<_>>();
        for handle in handles {
            handle.join().expect("direct GPU worker remains healthy");
        }
    });
}

#[cfg(feature = "gpu")]
/// Proves phase-two recovery retains completed GPU shards while sharing no
/// fault-injection or adapter state with concurrent parity tests.
#[test]
fn automatic_phase2_gpu_recovery_preserves_completed_shards() {
    let _gpu_test_guard = crate::testing::gpu_test_lock();
    let (scanner, backend, chunks, expected) = gpu_recovery_fixture();

    let outcome = with_test_region_presence_byte_limit(64, || {
        crate::engine::gpu_region_dispatch_helpers::with_test_phase2_dispatch_failure(1, || {
            scanner
                .scan_coalesced_gpu_region_presence_recovering(
                    &chunks,
                    backend,
                    scanner.default_execution_route(),
                    true,
                    None,
                )
                .expect("automatic route must recover phase-two admission ranges")
        })
    });

    assert_eq!(outcome.matches, expected);
    let recovery = outcome.recovery.expect("typed phase-two recovery receipt");
    assert_eq!(recovery.failed_backend, backend);
    assert_eq!(
        recovery.ranges,
        vec![
            crate::RecoveredInputRange::new(1, 0, chunks[1].data.len()),
            crate::RecoveredInputRange::new(2, 0, chunks[2].data.len()),
        ],
        "the completed phase-two shard must remain GPU-owned"
    );
}
#[test]
fn phase2_gpu_admission_workload_uses_original_slice_when_every_row_is_eligible() {
    let chunks = [
        keyhog_core::Chunk::from("phase-one-triggered"),
        keyhog_core::Chunk::from("no-phase-one-trigger"),
    ];

    let workload = build_phase2_gpu_admission_workload(&chunks);

    let Phase2GpuAdmissionWorkload::Full {
        chunks: selected_chunks,
    } = workload
    else {
        panic!("an all-eligible batch must retain the original chunk slice");
    };
    assert_eq!(selected_chunks.as_ptr(), chunks.as_ptr());
    assert_eq!(selected_chunks.len(), chunks.len());
}

#[test]
fn phase2_gpu_admission_workload_filter_keeps_eligible_triggered_and_untriggered_rows() {
    let chunks = [
        keyhog_core::Chunk::from("oversized-or-non-ascii"),
        keyhog_core::Chunk::from("eligible-triggered"),
        keyhog_core::Chunk::from("eligible-untriggered"),
        keyhog_core::Chunk::from("decode-only"),
    ];

    let workload =
        build_phase2_gpu_admission_workload_filtered(&chunks, |idx, _| matches!(idx, 1 | 2));

    let Phase2GpuAdmissionWorkload::Subset {
        indices,
        chunks: selected_chunks,
        full_len,
    } = workload
    else {
        panic!("mixed eligibility must build a mapped subset workload");
    };
    assert_eq!(full_len, 4);
    assert_eq!(indices, vec![1, 2]);
    assert_eq!(selected_chunks[0].data.as_ref(), "eligible-triggered");
    assert_eq!(selected_chunks[1].data.as_ref(), "eligible-untriggered");
}

#[test]
fn phase2_gpu_admission_workload_preserves_eligible_prefix_before_exclusion() {
    let chunks = [
        keyhog_core::Chunk::from("eligible-before"),
        keyhog_core::Chunk::from("excluded-after"),
    ];

    let workload = build_phase2_gpu_admission_workload_filtered(&chunks, |idx, _| idx == 0);

    let Phase2GpuAdmissionWorkload::Subset {
        indices,
        chunks: selected_chunks,
        full_len,
    } = workload
    else {
        panic!("an eligible prefix before an exclusion must remain in the mapped subset");
    };
    assert_eq!(full_len, chunks.len());
    assert_eq!(indices, vec![0]);
    assert_eq!(selected_chunks.len(), 1);
    assert_eq!(selected_chunks[0].data.as_ref(), "eligible-before");
}

#[test]
fn phase2_gpu_admission_workload_filter_is_empty_when_every_row_is_excluded() {
    let chunks = [
        keyhog_core::Chunk::from("decode-only-a"),
        keyhog_core::Chunk::from("decode-only-b"),
    ];
    let workload = build_phase2_gpu_admission_workload_filtered(&chunks, |_, _| false);

    let Phase2GpuAdmissionWorkload::Empty = workload else {
        panic!("an all-excluded batch must not dispatch phase-2 GPU admission");
    };
}

#[test]
fn phase2_gpu_trigger_row_mismatch_is_rejected() {
    let error = validate_phase2_gpu_trigger_rows(4, 3).expect_err("mismatched rows rejected");

    assert!(
        error
            .to_string()
            .contains("refusing to run mismatched phase-2 admission"),
        "trigger/chunk cardinality drift must be a loud GPU route failure"
    );
}

#[test]
fn phase2_gpu_admission_expands_subset_bits_to_original_batch() {
    let subset = Phase2GpuDfaAdmission {
        admitted: vec![true, false, true],
        complete: vec![true, true, true],
        matches_seen: 7,
        candidate_bits: vec![0x1, 0x2, 0x4],
        candidate_words_per_region: 1,
        candidate_phase2_indices: vec![7; 32],
    };

    let full = expand_phase2_gpu_admission(subset, &[1, 3, 4], 5);

    assert_eq!(full.admitted, vec![false, true, false, false, true]);
    assert_eq!(full.complete, vec![false, true, false, true, true]);
    assert_eq!(full.matches_seen, 7);
    assert_eq!(full.candidate_words_per_region, 1);
    assert_eq!(full.candidate_bits, vec![0, 0x1, 0, 0x2, 0x4]);
}

#[test]
fn phase2_gpu_admission_length_mismatch_marks_evidence_incomplete() {
    let subset = Phase2GpuDfaAdmission {
        admitted: vec![true],
        complete: vec![true],
        matches_seen: 1,
        candidate_bits: vec![0x1],
        candidate_words_per_region: 1,
        candidate_phase2_indices: vec![7; 32],
    };

    let full = expand_phase2_gpu_admission(subset, &[0, 2], 3);

    assert_eq!(full.admitted, vec![true, false, false]);
    assert!(
        full.complete.iter().all(|&complete| !complete),
        "mismatched subset evidence must not claim complete GPU admission coverage"
    );
    assert!(full.candidate_bits.is_empty());
    assert_eq!(full.candidate_words_per_region, 0);
    assert!(full.candidate_phase2_indices.is_empty());
}

#[test]
fn phase2_gpu_admission_out_of_range_index_marks_evidence_incomplete() {
    let subset = Phase2GpuDfaAdmission {
        admitted: vec![true],
        complete: vec![true],
        matches_seen: 1,
        candidate_bits: vec![0x1],
        candidate_words_per_region: 1,
        candidate_phase2_indices: vec![7; 32],
    };

    let full = expand_phase2_gpu_admission(subset, &[3], 3);

    assert_eq!(full.admitted, vec![false; 3]);
    assert_eq!(full.complete, vec![false; 3]);
    assert!(full.candidate_bits.is_empty());
    assert_eq!(full.candidate_words_per_region, 0);
    assert!(full.candidate_phase2_indices.is_empty());
}

#[cfg(feature = "simd")]
#[test]
fn complete_always_active_negative_preserves_triggered_row_keyword_phase2_findings() {
    let detector = keyhog_core::DetectorSpec {
        id: "triggered-row-phase2-keyword".into(),
        name: "Triggered Row Phase Two Keyword".into(),
        service: "fixture".into(),
        severity: keyhog_core::Severity::High,
        keywords: vec!["credential".into()],
        patterns: vec![keyhog_core::PatternSpec {
            regex: r"(?:^|[^A-Za-z0-9])([A-Za-z0-9]{32})(?:$|[^A-Za-z0-9])".into(),
            group: Some(1),
            ..Default::default()
        }],
        ..keyhog_scanner::testing::named_detector_fixture_defaults()
    };
    let scanner = CompiledScanner::compile(vec![detector]).expect("compile fixture detector");
    let chunk = keyhog_core::Chunk::from("credential = aB3dE5gH7jK9mN2pQ4sT6vW8xY1zC0fR");
    let keyword_idx = u32::try_from(
        scanner
            .route_classification
            .phase2_keyword_index
            .as_ref()
            .expect("phase-two keyword index")
            .find_iter("credential")
            .next()
            .expect("fixture keyword"),
    )
    .expect("fixture keyword index fits u32");
    let keyword_hints = [vec![keyword_idx]];
    let admitted = [false];
    let complete = [true];
    let anchors_present = [false];

    let results = scanner.scan_coalesced_phase2_with_admission(
        std::slice::from_ref(&chunk),
        vec![Some(vec![1])],
        Some(&admitted),
        Some(&complete),
        Some(&[]),
        0,
        Some(&[]),
        Some(&keyword_hints),
        Some(&anchors_present),
        None,
        None,
        None,
        None,
        crate::hw_probe::ScanBackend::CpuFallback,
        scanner.default_execution_route(),
    );
    let results = results.expect("always-active negative phase-two scan succeeds");

    let found = results[0]
        .iter()
        .find(|finding| finding.detector_id.as_ref() == "triggered-row-phase2-keyword")
        .expect("complete always-active absence must not suppress keyword-triggered phase two");
    assert_eq!(
        found.credential.as_ref(),
        "aB3dE5gH7jK9mN2pQ4sT6vW8xY1zC0fR"
    );
}

#[cfg(feature = "simd")]
#[test]
fn phase2_gpu_candidate_bits_drive_production_active_set() {
    let detector = keyhog_core::DetectorSpec {
        id: "gpu-candidate-active-set".into(),
        name: "GPU Candidate Active Set".into(),
        service: "fixture".into(),
        severity: keyhog_core::Severity::High,
        patterns: vec![keyhog_core::PatternSpec {
            regex: r"([A-Za-z0-9]{32})".into(),
            group: Some(1),
            ..Default::default()
        }],
        ..keyhog_scanner::testing::named_detector_fixture_defaults()
    };
    let scanner = CompiledScanner::compile(vec![detector]).expect("compile fixture detector");
    assert_eq!(scanner.phase2_patterns.len(), 1);
    let chunk = keyhog_core::Chunk::from("aB3dE5gH7jK9mN2pQ4sT6vW8xY1zC0fR");
    let triggers = || vec![Some(vec![0])];
    let admitted = [true];
    let complete = [true];
    let anchors_present = [false];
    let keyword_hints = [Vec::<u32>::new()];
    let mut candidate_map = vec![u32::MAX; u32::BITS as usize];
    candidate_map[0] = 0;

    let hit_bits = [1u32];
    let hit = scanner
        .scan_coalesced_phase2_with_admission(
            std::slice::from_ref(&chunk),
            triggers(),
            Some(&admitted),
            Some(&complete),
            Some(&hit_bits),
            1,
            Some(&candidate_map),
            Some(&keyword_hints),
            Some(&anchors_present),
            None,
            None,
            None,
            None,
            crate::hw_probe::ScanBackend::CpuFallback,
            scanner.default_execution_route(),
        )
        .expect("candidate-hit scan");
    assert!(hit[0]
        .iter()
        .any(|finding| finding.detector_id.as_ref() == "gpu-candidate-active-set"));

    let miss_bits = [0u32];
    let missed = scanner
        .scan_coalesced_phase2_with_admission(
            std::slice::from_ref(&chunk),
            triggers(),
            Some(&[false]),
            Some(&complete),
            Some(&miss_bits),
            1,
            Some(&candidate_map),
            Some(&keyword_hints),
            Some(&anchors_present),
            None,
            None,
            None,
            None,
            crate::hw_probe::ScanBackend::CpuFallback,
            scanner.default_execution_route(),
        )
        .expect("candidate-miss scan");
    assert!(
        missed[0].is_empty(),
        "a complete candidate miss must suppress the covered CPU admission path"
    );

    let malformed_map = vec![u32::MAX; u32::BITS as usize];
    let malformed = scanner
        .scan_coalesced_phase2_with_admission(
            std::slice::from_ref(&chunk),
            triggers(),
            Some(&admitted),
            Some(&complete),
            Some(&hit_bits),
            1,
            Some(&malformed_map),
            Some(&keyword_hints),
            Some(&anchors_present),
            None,
            None,
            None,
            None,
            crate::hw_probe::ScanBackend::CpuFallback,
            scanner.default_execution_route(),
        )
        .expect("malformed candidate evidence falls back to CPU");
    assert!(malformed[0]
        .iter()
        .any(|finding| finding.detector_id.as_ref() == "gpu-candidate-active-set"));

    let omitted = scanner
        .scan_coalesced_phase2_with_admission(
            std::slice::from_ref(&chunk),
            vec![None],
            Some(&[false]),
            Some(&complete),
            Some(&[]),
            0,
            Some(&[]),
            Some(&keyword_hints),
            Some(&anchors_present),
            None,
            None,
            None,
            None,
            crate::hw_probe::ScanBackend::CpuFallback,
            scanner.default_execution_route(),
        )
        .expect("omitted candidate coverage falls back to CPU");
    assert!(
        omitted[0]
            .iter()
            .any(|finding| finding.detector_id.as_ref() == "gpu-candidate-active-set"),
        "complete evidence cannot omit a compatible prefixless pattern"
    );
}

#[cfg(feature = "simd")]
#[test]
fn normalized_triggered_rows_discard_raw_gpu_evidence_and_recompute_admission() {
    let detectors = vec![
        keyhog_core::DetectorSpec {
            id: "raw-trigger-fixture".into(),
            name: "Raw trigger fixture".into(),
            service: "fixture".into(),
            severity: keyhog_core::Severity::High,
            patterns: vec![keyhog_core::PatternSpec {
                regex: r"(rawhit_[A-Z]{4})".into(),
                group: Some(1),
                ..Default::default()
            }],
            ..keyhog_scanner::testing::named_detector_fixture_defaults()
        },
        keyhog_core::DetectorSpec {
            id: "normalized-required-fixture".into(),
            name: "Normalized required fixture".into(),
            service: "fixture".into(),
            severity: keyhog_core::Severity::High,
            patterns: vec![keyhog_core::PatternSpec {
                regex: r"([a-f0-9]{8}:fx)".into(),
                group: Some(1),
                required_literals: vec![":fx".into()],
                ..Default::default()
            }],
            ..keyhog_scanner::testing::named_detector_fixture_defaults()
        },
        keyhog_core::DetectorSpec {
            id: "normalized-phase2-keyword-fixture".into(),
            name: "Normalized phase two keyword fixture".into(),
            service: "fixture".into(),
            severity: keyhog_core::Severity::High,
            keywords: vec!["credential".into()],
            patterns: vec![keyhog_core::PatternSpec {
                regex: r"(?:^|[^A-Za-z0-9])([A-Za-z0-9]{32})(?:$|[^A-Za-z0-9])".into(),
                group: Some(1),
                ..Default::default()
            }],
            ..keyhog_scanner::testing::named_detector_fixture_defaults()
        },
    ];
    let simd_scanner = CompiledScanner::compile_for_backend(
        detectors.clone(),
        crate::hw_probe::ScanBackend::SimdCpu,
    )
    .expect("compile normalization fixtures for SIMD");
    let scanner =
        CompiledScanner::compile_for_backend(detectors, crate::hw_probe::ScanBackend::CpuFallback)
            .expect("compile normalization fixtures for scalar phase two");
    let chunk = keyhog_core::Chunk::from(concat!(
        "rawhit_ABCD\n",
        "required=0123abcd:\u{ff46}\u{ff58}\n",
        "\u{ff43}\u{ff52}\u{ff45}\u{ff44}\u{ff45}\u{ff4e}\u{ff54}\u{ff49}\u{ff41}\u{ff4c}",
        " = aB3dE5gH7jK9mN2pQ4sT6vW8xY1zC0fR\n"
    ));
    let raw_triggers = simd_scanner
        .collect_triggered_patterns_for_backend(&chunk.data, crate::hw_probe::ScanBackend::SimdCpu)
        .expect("SIMD trigger collection succeeds");
    assert!(raw_triggers.iter().any(|&word| word != 0));
    let raw_keyword_hints = [Vec::<u32>::new()];
    let admitted = [false];
    let complete = [true];
    let anchors_present = [false];

    let results = scanner.scan_coalesced_phase2_with_admission(
        std::slice::from_ref(&chunk),
        vec![Some(raw_triggers)],
        Some(&admitted),
        Some(&complete),
        Some(&[]),
        0,
        Some(&[]),
        Some(&raw_keyword_hints),
        Some(&anchors_present),
        None,
        None,
        None,
        None,
        crate::hw_probe::ScanBackend::SimdCpu,
        scanner.default_execution_route(),
    );
    let results = results.expect("normalized phase-two scan succeeds");
    let by_detector = |detector: &str| {
        results[0]
            .iter()
            .find(|finding| finding.detector_id.as_ref() == detector)
            .unwrap_or_else(|| panic!("missing normalized finding for {detector}"))
    };

    assert_eq!(
        by_detector("normalized-required-fixture")
            .credential
            .as_ref(),
        "0123abcd:fx"
    );
    assert_eq!(
        by_detector("normalized-phase2-keyword-fixture")
            .credential
            .as_ref(),
        "aB3dE5gH7jK9mN2pQ4sT6vW8xY1zC0fR"
    );
}