fuel-dispatch 0.58.3

Dispatch infrastructure for fuel: KernelBindingTable, per-backend registration wrappers, CompiledNode + compile_node, ExecutionPlan + compile_plan + resolve_kernel, FusedKernelRegistry, PipelinedExecutor. The layer that takes a graph and runs it against registered backends. Extracted from fuel-memory 2026-05-31.
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
// SPDX-License-Identifier: MIT OR Apache-2.0
//! CapturedRun 4b-resume Step 3 — empirical seeding of the CUDA verification
//! ledger.
//!
//! The CUDA analogue of Task 4.5b's [`super::seed_cpu_ledger`]. Every CUDA
//! kernel contract in `fuel-dispatch/kernel-contracts/cuda/*.fkc.md` declares
//! `bit_stable_on_same_hardware: true`, but the V-FKC-9 import gate
//! ([`super::gate_precision`], wired at `register.rs:363`) downgrades any such
//! claim lacking a matching `pass` entry in the git-checked-in
//! `fuel-dispatch/kernel-contracts/fkc-verified-ledger.json` to
//! `PrecisionGuarantee::UNAUDITED`. An unaudited CUDA candidate then loses its
//! placement to the (Task-4.5b-seeded, audited) CPU alternative under
//! [`crate::ranker::filters::AccuracyPreferenceFilter`] (an unaudited candidate has no accuracy claim and is not bit-stable), so the decode runs on
//! CPU and never enters a CapturedRun capture scope. This harness earns the
//! CUDA `bit_stable_on_same_hardware` ledger entries so the decode-path CUDA
//! kernels are audited and win their placements.
//!
//! Mechanism (mirrors [`super::harness`], generalized from the single
//! rope-apply contract to the WHOLE production CUDA binding table): register
//! every CUDA kernel via `register` (the caller passes `fuel_cuda_dispatch::register_baracuda_cuda_kernels`),
//! iterate `table.iter_entries()`, synthesize a per-`OpKind` probe, drive
//! [`super::verify_bit_stability`] through a real [`super::CudaInvoker`] for
//! `ITERS` repeat calls, and `upsert` a `pass`/`fail` record keyed on the
//! entry's `kernel_revision_hash`. `upsert` (not `push`) keeps re-seeding
//! idempotent — the `include_str!`-embedded ledger recompiles after the first
//! write, so a naive `push` re-run would append duplicates.
//!
//! Never fabricates a pass: an op with no probe recipe, a kernel `Err`, or a
//! panic (caught via `catch_unwind`) contributes NO ledger entry and is logged
//! as skipped/failed. `#[cfg(feature = "cuda")]` throughout — needs a live
//! `CudaDevice`; its seeding test is `#[ignore]`'d.

use std::panic::{AssertUnwindSafe, catch_unwind};

use fuel_cuda_backend::CudaDevice;
use fuel_ir::DType;
use fuel_ir::dispatch::OpKind;
use fuel_ir::probe::BackendId;

use super::{
    CpuInvoker, CudaInvoker, HostTensor, KernelInvoker, LedgerRecord, ProbeInputs,
    VerificationLedger, VerifyError, VerifyOutcome, fill_deterministic, verify_bit_stability,
};
use crate::kernel::{KernelBindingTable, MatmulM, OpParams};

/// CUDA ops whose contract declares a numeric `max_ulp` bound (only
/// `indexing.fkc.md` today — exact copies, bound 0). The V-FKC-9 gate collapses
/// the WHOLE guarantee if ANY declared machine-checkable claim is unbacked, so
/// these need a `max_ulp` ledger entry IN ADDITION to `bit_stable`. Verified
/// CUDA-candidate-vs-CPU-reference (0 ULP = byte-identical for an exact copy).
const MAX_ULP_OPS: &[(OpKind, u32)] = &[
    (OpKind::IndexSelect, 0),
    (OpKind::Gather, 0),
    (OpKind::MaskedFill, 0),
];

/// `true` iff every `f32` element of `cand` is within `bound` ULP of `refr`
/// (mirrors `verify_precision_bound`'s `MaxUlp` arm). `Err` on a length/align
/// mismatch rather than a panic.
fn max_ulp_ok(cand: &[u8], refr: &[u8], bound: u32) -> std::result::Result<bool, String> {
    if cand.len() % 4 != 0 || refr.len() != cand.len() {
        return Err(format!(
            "output length/align mismatch (cand {} ref {})",
            cand.len(),
            refr.len()
        ));
    }
    let a: &[f32] = bytemuck::cast_slice(cand);
    let b: &[f32] = bytemuck::cast_slice(refr);
    for (x, y) in a.iter().zip(b.iter()) {
        // Shared total-order ULP distance — correct across the sign/zero
        // boundary; never drifts from `verify_precision_bound`'s `MaxUlp` arm.
        if super::ulp::ulp_distance(*x, *y) > bound as u64 {
            return Ok(false);
        }
    }
    Ok(true)
}

/// Repeat-call count per probe for `bit_stable_on_same_hardware` (≥16 floor,
/// same as the CPU seeder + the rope-apply harness).
const ITERS: usize = 16;

/// The verified claim this harness earns. CUDA contracts also carry
/// `max_ulp`/`max_relative`/`max_absolute` slots, but the decode-path
/// contracts leave them `~` (null → not gated); only `indexing` sets
/// `max_ulp: 0` (handled as a follow-on, needs a CPU-reference ULP check).
const CLAIM: &str = "bit_stable_on_same_hardware";

/// A synthesized, safe, valid probe for one `(OpKind, dtypes)` CUDA
/// registration: real inputs the kernel runs on without crashing, the
/// `OpParams` it needs, and the output dtype/shape `CudaInvoker` allocates.
#[derive(Debug)]
struct Probe {
    inputs: ProbeInputs,
    params: OpParams,
    out_dtype: DType,
    out_shape: Vec<usize>,
}

/// Which recipe answered for an `(op, dtypes)` registration (GAP-383).
///
/// This harness's OWN recipes (`build_cuda_probe`) always win, so every record it already earned
/// re-seeds from the identical probe. Only where it has none does the SHARED backend-agnostic
/// recipe set the CPU and Vulkan seeders use (`probe_recipes::build_primitive_probe`) answer: it
/// covers 114 ops against this harness's ~42, and a second copy is the divergence its own header
/// warns about.
#[derive(Debug)]
enum ProbeChoice {
    /// This harness's own recipe.
    Own(Probe),
    /// The shared recipe.
    Shared(Probe),
    /// The shared recipe needs a seeded output (the in-place family: the target arrives as
    /// `outputs[0]`) and `CudaInvoker` cannot seed one; running it on a zeroed buffer would earn
    /// a pass that measures nothing (GAP-222), so the entry is skipped.
    NeedsSeededOutput,
    /// No recipe anywhere.
    None,
}

fn choose_probe(op: OpKind, dtypes: &[DType], seed: u64) -> ProbeChoice {
    if let Some(p) = build_cuda_probe(op, dtypes, seed) {
        return ProbeChoice::Own(p);
    }
    match super::probe_recipes::build_primitive_probe(op, dtypes, seed) {
        Some(shared) if shared.out_seed.is_some() => ProbeChoice::NeedsSeededOutput,
        Some(shared) => ProbeChoice::Shared(Probe {
            inputs: shared.inputs,
            params: shared.params,
            out_dtype: shared.out_dtype,
            out_shape: shared.out_shape,
        }),
        None => ProbeChoice::None,
    }
}

/// Encode `vals` into `dt`'s byte representation (float dtypes only — the
/// decode path is F32; other float widths fan the same recipes). `None` for a
/// dtype this harness can't encode (integer index dtypes, quantized, etc.),
/// so the caller skips rather than guesses.
fn to_bytes(dt: DType, vals: &[f32]) -> Option<Vec<u8>> {
    Some(match dt {
        DType::F32 => bytemuck::cast_slice(vals).to_vec(),
        DType::F64 => {
            bytemuck::cast_slice(&vals.iter().map(|&x| x as f64).collect::<Vec<_>>()).to_vec()
        }
        DType::BF16 => bytemuck::cast_slice(
            &vals
                .iter()
                .map(|&x| half::bf16::from_f32(x))
                .collect::<Vec<_>>(),
        )
        .to_vec(),
        DType::F16 => bytemuck::cast_slice(
            &vals
                .iter()
                .map(|&x| half::f16::from_f32(x))
                .collect::<Vec<_>>(),
        )
        .to_vec(),
        _ => return None,
    })
}

fn ht(dt: DType, shape: Vec<usize>, vals: &[f32]) -> Option<HostTensor> {
    Some(HostTensor {
        dtype: dt,
        shape,
        bytes: to_bytes(dt, vals)?,
    })
}

/// Build a real, valid probe for a CUDA primitive `op` at the registered
/// `dtypes`. `None` ⇒ this harness has no recipe for that op yet (logged +
/// skipped, never a fabricated entry). The recipe (inputs + `OpParams`) is
/// backend-agnostic — the same shapes the CPU wrappers accept — because the
/// CUDA wrappers pull identical `OpParams` (verified by reading
/// `baracuda_dispatch.rs`'s wrapper macros).
fn build_cuda_probe(op: OpKind, dtypes: &[DType], seed: u64) -> Option<Probe> {
    let dt = *dtypes.first()?;
    // Only recipes over encodable float dtypes; integer/quant fan-outs skip.
    to_bytes(dt, &[0.0])?;

    match op {
        // --- Binary elementwise (2 inputs, params ignored) -----------------
        OpKind::AddElementwise
        | OpKind::SubElementwise
        | OpKind::MulElementwise
        | OpKind::DivElementwise
        | OpKind::MaximumElementwise
        | OpKind::MinimumElementwise
        // Pow / Rem share the binary calling convention; the claim is byte-identity across
        // repeats, so a NaN with a stable payload (pow of a negative base) is stable. Absent
        // only because nobody listed them: without a pass their F32 entries could not carry
        // the numeric claim (row 39).
        | OpKind::PowElementwise
        | OpKind::RemElementwise => {
            let a = ht(dt, vec![4], &fill_deterministic(4, seed))?;
            let b = ht(dt, vec![4], &fill_deterministic(4, seed ^ 0x9E37_79B9))?;
            Some(Probe {
                inputs: vec![a, b],
                params: OpParams::None,
                out_dtype: dt,
                out_shape: vec![4],
            })
        }

        // --- Per-axis reduce (1 input -> reduced output of the same dtype) --
        // Absent until row 39: without a pass their F32 entries could not carry the numeric
        // claim. Wide enough that the reduction spans many threads of a block.
        OpKind::SumReduce | OpKind::MaxReduce | OpKind::MinReduce | OpKind::MeanReduce => {
            let (outer, last) = (8usize, 2048usize);
            let x = ht(
                dt,
                vec![outer, last],
                &fill_deterministic(outer * last, seed),
            )?;
            Some(Probe {
                inputs: vec![x],
                params: OpParams::Reduce {
                    dims: vec![1],
                    keepdim: false,
                },
                out_dtype: dt,
                out_shape: vec![outer],
            })
        }

        // --- Unary elementwise (1 input, params ignored) -------------------
        OpKind::NegElementwise
        | OpKind::ReluElementwise
        | OpKind::SqrElementwise
        | OpKind::SqrtElementwise
        | OpKind::RecipElementwise
        | OpKind::RsqrtElementwise
        | OpKind::AbsElementwise
        | OpKind::TanhElementwise
        | OpKind::ExpElementwise
        | OpKind::LogElementwise
        | OpKind::SinElementwise
        | OpKind::CosElementwise
        | OpKind::SigmoidElementwise
        | OpKind::SiluElementwise
        | OpKind::GeluTanhElementwise
        | OpKind::GeluElementwise
        | OpKind::ErfElementwise
        | OpKind::StepElementwise
        | OpKind::SignElementwise
        | OpKind::FloorElementwise
        | OpKind::CeilElementwise
        | OpKind::RoundElementwise => {
            let x = ht(dt, vec![4], &fill_deterministic(4, seed))?;
            Some(Probe {
                inputs: vec![x],
                params: OpParams::None,
                out_dtype: dt,
                out_shape: vec![4],
            })
        }

        // --- MatMul (2 inputs) ---------------------------------------------
        OpKind::MatMul => {
            let (m, n, k) = (2usize, 2usize, 2usize);
            let lhs = ht(dt, vec![m * k], &fill_deterministic(m * k, seed))?;
            let rhs = ht(dt, vec![k * n], &fill_deterministic(k * n, seed ^ 0x1234))?;
            Some(Probe {
                inputs: vec![lhs, rhs],
                params: OpParams::Matmul {
                    lhs_batch_dims: vec![],
                    rhs_batch_dims: vec![],
                    m,
                    n,
                    k,
                    m_compute: MatmulM::All,
                },
                out_dtype: dt,
                out_shape: vec![m * n],
            })
        }

        // --- RmsNorm / LayerNorm last-dim (1 input) ------------------------
        OpKind::RmsNormLastDim | OpKind::LayerNormLastDim => {
            let (outer, last) = (2usize, 4usize);
            let x = ht(
                dt,
                vec![outer * last],
                &fill_deterministic(outer * last, seed),
            )?;
            Some(Probe {
                inputs: vec![x],
                params: OpParams::NormLastDim {
                    outer_count: outer,
                    last_dim: last,
                    eps: 1e-5,
                },
                out_dtype: dt,
                out_shape: vec![outer * last],
            })
        }

        // --- Softmax / LogSoftmax last-dim (1 input) -----------------------
        OpKind::SoftmaxLastDim | OpKind::LogSoftmaxLastDim => {
            let (outer, last) = (2usize, 4usize);
            let x = ht(
                dt,
                vec![outer * last],
                &fill_deterministic(outer * last, seed),
            )?;
            Some(Probe {
                inputs: vec![x],
                params: OpParams::SoftmaxLastDim {
                    outer_count: outer,
                    last_dim: last,
                },
                out_dtype: dt,
                out_shape: vec![outer * last],
            })
        }

        // --- Affine y = mul*x + add (1 input) ------------------------------
        OpKind::Affine => {
            let x = ht(dt, vec![4], &fill_deterministic(4, seed))?;
            Some(Probe {
                inputs: vec![x],
                params: OpParams::Affine { mul: 2.0, add: 1.0 },
                out_dtype: dt,
                out_shape: vec![4],
            })
        }

        // --- IndexSelect (embed): src[outer, source_dim, inner] + U32 idx --
        OpKind::IndexSelect => {
            let (outer, source_dim, n_idx, inner) = (1usize, 4usize, 2usize, 3usize);
            let src = ht(
                dt,
                vec![outer * source_dim * inner],
                &fill_deterministic(outer * source_dim * inner, seed),
            )?;
            // Indices are ALWAYS U32 (the CUDA wrapper hard-requires it); 0,1
            // are in-bounds for source_dim=4.
            let indices = HostTensor {
                dtype: DType::U32,
                shape: vec![n_idx],
                bytes: bytemuck::cast_slice(&[0u32, 1u32]).to_vec(),
            };
            Some(Probe {
                inputs: vec![src, indices],
                params: OpParams::IndexSelect {
                    outer_count: outer,
                    source_dim_size: source_dim,
                    n_indices: n_idx,
                    inner_count: inner,
                },
                out_dtype: dt,
                out_shape: vec![outer * n_idx * inner],
            })
        }

        // --- Concat along a single axis (2 inputs) — rope decompose --------
        OpKind::Concat => {
            let a = ht(dt, vec![2], &fill_deterministic(2, seed))?;
            let b = ht(dt, vec![2], &fill_deterministic(2, seed ^ 0x5555))?;
            Some(Probe {
                inputs: vec![a, b],
                params: OpParams::Concat {
                    outer_count: 1,
                    input_dim_sizes: vec![2, 2],
                    inner_count: 1,
                    axis: 0,
                },
                out_dtype: dt,
                out_shape: vec![4],
            })
        }

        _ => None,
    }
}

/// One attempt outcome, kept even for skips/failures so the report shows
/// exactly what did and didn't verify — never silently.
#[derive(Debug)]
pub struct CudaSeedAttempt {
    pub op: String,
    pub dtypes: Vec<DType>,
    pub kernel_revision_hash: u64,
    pub outcome: String,
}

/// `epoch:<unix seconds>` — dependency-free timestamp (house convention).
fn verified_at_string() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    format!("epoch:{secs}")
}

/// Empirically verify every CUDA primitive registration this harness has a
/// probe recipe for, and return a ledger seeded from the EMBEDDED (checked-in)
/// records plus any freshly-earned CUDA `pass` entries (never discards prior
/// entries — the CPU 4.5b records + the rope-apply record survive), together
/// with a full attempt log (every skip/failure) for the report.
///
/// `only` restricts to a subset of `OpKind`s (e.g. the decode-path set); pass
/// `None` to sweep every registered CUDA kernel. Requires a live CUDA device.
pub fn run_cuda_verification(
    register: fn(&mut KernelBindingTable),
    only: Option<&[OpKind]>,
    force: bool,
) -> std::result::Result<(VerificationLedger, Vec<CudaSeedAttempt>), VerifyError> {
    let mut table = KernelBindingTable::new();
    register(&mut table);

    let mut ledger =
        VerificationLedger::from_records(VerificationLedger::embedded().records().to_vec());
    let device =
        CudaDevice::new(0).map_err(|e| VerifyError::Backend(format!("no CUDA device: {e}")))?;
    let mut log = Vec::new();

    for (op, dtypes, backend, entry) in table.iter_entries() {
        if backend != BackendId::Cuda {
            continue;
        }
        if let Some(set) = only {
            if !set.contains(&op) {
                continue;
            }
        }
        let dtypes_vec = dtypes.to_vec();
        let rev = entry.kernel_revision_hash;

        if !force && ledger.has_pass(BackendId::Cuda, dtypes, rev, CLAIM) {
            log.push(CudaSeedAttempt {
                op: format!("{op:?}"),
                dtypes: dtypes_vec,
                kernel_revision_hash: rev,
                outcome: "skip: already has a pass for this revision".to_string(),
            });
            continue;
        }

        // Deterministic per-(op,dtype) seed so a re-run is byte-identical.
        let seed = 0x2545_F491_4F6C_DD1D_u64
            ^ (op as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
            ^ (dtypes.len() as u64).wrapping_mul(0xD1B5_4A32_D192_ED03);
        let probe = match choose_probe(op, dtypes, seed) {
            ProbeChoice::Own(p) | ProbeChoice::Shared(p) => p,
            ProbeChoice::NeedsSeededOutput => {
                log.push(CudaSeedAttempt {
                    op: format!("{op:?}"),
                    dtypes: dtypes_vec,
                    kernel_revision_hash: rev,
                    outcome: "skip: probe needs a seeded output, CudaInvoker cannot seed"
                        .to_string(),
                });
                continue;
            }
            ProbeChoice::None => {
                log.push(CudaSeedAttempt {
                    op: format!("{op:?}"),
                    dtypes: dtypes_vec,
                    kernel_revision_hash: rev,
                    outcome: "skip: no probe recipe for this op/dtype".to_string(),
                });
                continue;
            }
        };

        let inv = CudaInvoker::new(device.clone(), probe.out_dtype, probe.out_shape.clone())
            .with_params(probe.params.clone());
        let inputs = probe.inputs.clone();
        let attempt = catch_unwind(AssertUnwindSafe(|| {
            verify_bit_stability(&inv, entry, std::slice::from_ref(&inputs), ITERS)
        }));

        let (result, outcome, evidence) = match attempt {
            Ok(Ok(VerifyOutcome::Pass)) => (
                Some("pass"),
                "pass".to_string(),
                serde_json::json!({ "repeat_calls": ITERS, "harness": "capturedrun-4b/seed_cuda_ledger" }),
            ),
            Ok(Ok(VerifyOutcome::Fail { detail })) => (
                Some("fail"),
                format!("fail: {detail}"),
                serde_json::json!({ "detail": detail }),
            ),
            Ok(Ok(VerifyOutcome::NoReference)) => (
                None,
                "skip: no reference".to_string(),
                serde_json::Value::Null,
            ),
            Ok(Err(e)) => (
                Some("fail"),
                format!("fail: invoke error {e:?}"),
                serde_json::json!({ "invoke_error": format!("{e:?}") }),
            ),
            Err(_) => (
                Some("fail"),
                "fail: kernel invocation panicked".to_string(),
                serde_json::json!({ "panic": true }),
            ),
        };

        if let Some(result) = result {
            ledger.upsert(LedgerRecord {
                kernel_ref: entry.kernel_source.to_string(),
                backend: "Cuda".to_string(),
                dtypes: dtypes.iter().map(|d| format!("{d:?}")).collect(),
                kernel_revision_hash: rev,
                claim: CLAIM.to_string(),
                result: result.to_string(),
                verified_at: verified_at_string(),
                protocol_version: 1,
                evidence,
            });
        }
        log.push(CudaSeedAttempt {
            op: format!("{op:?}"),
            dtypes: dtypes_vec,
            kernel_revision_hash: rev,
            outcome,
        });
    }

    // ---- Second pass: max_ulp claims (CUDA candidate vs CPU reference) ----
    // The gate needs these for the few ops declaring a numeric bound (only the
    // exact-copy indexing family). Reference is the registered CPU kernel for
    // the SAME (op, dtypes); 0 ULP means byte-identical.
    let mut cpu_table = KernelBindingTable::new();
    crate::dispatch::register_cpu_kernels(&mut cpu_table);
    for (op, dtypes, backend, cuda_entry) in table.iter_entries() {
        if backend != BackendId::Cuda {
            continue;
        }
        if let Some(set) = only {
            if !set.contains(&op) {
                continue;
            }
        }
        let Some(&(_, bound)) = MAX_ULP_OPS.iter().find(|(o, _)| *o == op) else {
            continue;
        };
        let dtypes_vec = dtypes.to_vec();
        let rev = cuda_entry.kernel_revision_hash;
        if !force && ledger.has_pass(BackendId::Cuda, dtypes, rev, "max_ulp") {
            continue;
        }
        let seed = 0x2545_F491_4F6C_DD1D_u64
            ^ (op as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
            ^ (dtypes.len() as u64).wrapping_mul(0xD1B5_4A32_D192_ED03);
        let probe = match choose_probe(op, dtypes, seed) {
            ProbeChoice::Own(p) | ProbeChoice::Shared(p) => p,
            ProbeChoice::NeedsSeededOutput | ProbeChoice::None => {
                log.push(CudaSeedAttempt {
                    op: format!("{op:?}"),
                    dtypes: dtypes_vec,
                    kernel_revision_hash: rev,
                    outcome: "max_ulp skip: no probe recipe".to_string(),
                });
                continue;
            }
        };
        let cpu_entry = cpu_table
            .iter_entries()
            .find(|(o, d, b, _)| *o == op && *d == dtypes && *b == BackendId::Cpu)
            .map(|(_, _, _, e)| e);
        let Some(cpu_entry) = cpu_entry else {
            log.push(CudaSeedAttempt {
                op: format!("{op:?}"),
                dtypes: dtypes_vec,
                kernel_revision_hash: rev,
                outcome: "max_ulp skip: no CPU reference entry".to_string(),
            });
            continue;
        };

        let cand = CudaInvoker::new(device.clone(), probe.out_dtype, probe.out_shape.clone())
            .with_params(probe.params.clone());
        let refr = CpuInvoker::new(probe.out_dtype, probe.out_shape.clone())
            .with_params(probe.params.clone());
        let inputs = probe.inputs.clone();
        let attempt = catch_unwind(AssertUnwindSafe(
            || -> std::result::Result<String, VerifyError> {
                let a = cand.invoke(cuda_entry, &inputs)?;
                let b = refr.invoke(cpu_entry, &inputs)?;
                Ok(match max_ulp_ok(&a.bytes, &b.bytes, bound) {
                    Ok(true) => "pass".to_string(),
                    Ok(false) => format!("fail: exceeds max_ulp {bound}"),
                    Err(e) => format!("fail: {e}"),
                })
            },
        ));

        let (result, outcome) = match attempt {
            Ok(Ok(s)) if s == "pass" => (Some("pass"), "max_ulp pass".to_string()),
            Ok(Ok(s)) => (Some("fail"), format!("max_ulp {s}")),
            Ok(Err(e)) => (Some("fail"), format!("max_ulp invoke error {e:?}")),
            Err(_) => (Some("fail"), "max_ulp panicked".to_string()),
        };
        if let Some(result) = result {
            ledger.upsert(LedgerRecord {
                kernel_ref: cuda_entry.kernel_source.to_string(),
                backend: "Cuda".to_string(),
                dtypes: dtypes.iter().map(|d| format!("{d:?}")).collect(),
                kernel_revision_hash: rev,
                claim: "max_ulp".to_string(),
                result: result.to_string(),
                verified_at: verified_at_string(),
                protocol_version: 1,
                evidence: serde_json::json!({ "bound": bound, "reference": "cpu", "harness": "capturedrun-4b/seed_cuda_ledger" }),
            });
        }
        log.push(CudaSeedAttempt {
            op: format!("{op:?}"),
            dtypes: dtypes_vec,
            kernel_revision_hash: rev,
            outcome,
        });
    }

    Ok((ledger, log))
}

#[cfg_attr(
    not(feature = "dev-tools"),
    allow(
        dead_code,
        reason = "called only by the dev-tools seeding entry point; unit-tested without it"
    )
)]
/// The `OpKind`s of `table_ops` whose `Debug` name appears in the comma-separated `names`
/// (`FUEL_SEED_CUDA_OPS`), in table order, once each. An unknown name matches nothing.
pub(crate) fn ops_named(table_ops: &[OpKind], names: &str) -> Vec<OpKind> {
    let wanted: Vec<&str> = names
        .split(',')
        .map(str::trim)
        .filter(|n| !n.is_empty())
        .collect();
    let mut out: Vec<OpKind> = Vec::new();
    for op in table_ops {
        if wanted.contains(&format!("{op:?}").as_str()) && !out.contains(op) {
            out.push(*op);
        }
    }
    out
}

#[cfg(feature = "dev-tools")]
/// CapturedRun 4b-resume Step 3 — sweep the production CUDA binding table,
/// empirically verify `bit_stable_on_same_hardware` for every op this
/// harness has a recipe for, and WRITE the merged ledger back to the
/// git-checked-in `fuel-dispatch/kernel-contracts/fkc-verified-ledger.json`.
///
/// Requires a live CUDA device (a maintenance tool, not a test). Run:
///   `cargo run -p fuel-dispatch --features dev-tools --bin fuel-dev-tools -- seed-cuda (with --features cuda)`
pub(crate) fn run_seed_cuda_ledger(register: fn(&mut KernelBindingTable)) {
    // Optional subset (a batch): `FUEL_SEED_CUDA_OPS=Cast,MaskedFill,...`. Unset or empty = every
    // probe-able CUDA entry, exactly as before.
    let only: Option<Vec<OpKind>> = std::env::var("FUEL_SEED_CUDA_OPS")
        .ok()
        .filter(|s| !s.trim().is_empty())
        .map(|names| {
            let mut t = KernelBindingTable::new();
            register(&mut t);
            let ops: Vec<OpKind> = t.iter_entries().map(|(op, _, _, _)| op).collect();
            let picked = ops_named(&ops, &names);
            println!(
                "[step3] FUEL_SEED_CUDA_OPS={names:?} -> {} op(s): {picked:?}",
                picked.len()
            );
            picked
        });
    let (ledger, log) =
        run_cuda_verification(register, only.as_deref(), true).expect("cuda seeding runs");
    for a in &log {
        println!(
            "[step3] {} {:?} (rev={}): {}",
            a.op, a.dtypes, a.kernel_revision_hash, a.outcome
        );
    }
    let passed = log.iter().filter(|a| a.outcome == "pass").count();
    let failed = log.iter().filter(|a| a.outcome.starts_with("fail")).count();
    let skipped = log.iter().filter(|a| a.outcome.starts_with("skip")).count();
    println!(
        "[step3] {passed} passed, {failed} failed, {skipped} skipped, {} attempts",
        log.len()
    );
    assert!(
        passed > 0,
        "expected at least one CUDA kernel to verify bit-stable; got 0 — see log"
    );

    let cuda_passes = ledger
        .records()
        .iter()
        .filter(|r| r.backend == "Cuda" && r.claim == CLAIM && r.result == "pass")
        .count();
    println!("[step3] ledger now holds {cuda_passes} CUDA bit-stable pass records");

    // Route through the ONE merging writer (GAP-210): three seeders
    // share this file and no backend may truncate another's records.
    // `ledger` already carries the embedded set, so the merge is a
    // no-op here — routing through it is what keeps that true.
    let summary = super::ledger::write_merged_ledger(ledger.records());
    println!(
        "[step3] merged {} record(s) into {} existing -> {} total, written to {}",
        summary.fresh,
        summary.before,
        summary.after,
        summary.path.display(),
    );
}

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

    /// Representative ops this harness already has its OWN recipes for (taken from `build_cuda_probe`'s
    /// match arms): binary and unary elementwise, reductions, norms, softmax, matmul, indexing.
    const OWN_OPS: &[OpKind] = &[
        OpKind::AddElementwise,
        OpKind::SubElementwise,
        OpKind::MulElementwise,
        OpKind::DivElementwise,
        OpKind::MaximumElementwise,
        OpKind::MinimumElementwise,
        OpKind::PowElementwise,
        OpKind::RemElementwise,
        OpKind::SumReduce,
        OpKind::MaxReduce,
        OpKind::MinReduce,
        OpKind::MeanReduce,
        OpKind::NegElementwise,
        OpKind::ReluElementwise,
        OpKind::SqrElementwise,
        OpKind::SqrtElementwise,
        OpKind::RecipElementwise,
        OpKind::RsqrtElementwise,
        OpKind::AbsElementwise,
        OpKind::TanhElementwise,
        OpKind::SigmoidElementwise,
        OpKind::SiluElementwise,
        OpKind::GeluElementwise,
        OpKind::ExpElementwise,
        OpKind::LogElementwise,
        OpKind::SinElementwise,
        OpKind::CosElementwise,
        OpKind::SoftmaxLastDim,
        OpKind::RmsNormLastDim,
        OpKind::LayerNormLastDim,
        OpKind::MatMul,
        OpKind::IndexSelect,
        OpKind::Concat,
    ];

    fn fingerprint(p: &Probe) -> String {
        format!("{p:?}")
    }

    #[test]
    fn an_op_with_its_own_recipe_never_reaches_the_shared_one() {
        // The invariant behind "existing records re-seed identically": wherever this harness's own
        // recipe answers, `choose_probe` returns EXACTLY that probe (same inputs, params, output).
        let seed = 0x2545_F491_4F6C_DD1D_u64;
        let mut own_answers = 0usize;
        for &op in OWN_OPS {
            for dt in [DType::F32, DType::F16, DType::BF16, DType::F64] {
                for dtypes in [vec![dt, dt], vec![dt, dt, dt], vec![dt, DType::U32, dt]] {
                    if let Some(own) = build_cuda_probe(op, &dtypes, seed) {
                        own_answers += 1;
                        match choose_probe(op, &dtypes, seed) {
                            ProbeChoice::Own(chosen) => assert_eq!(
                                fingerprint(&chosen),
                                fingerprint(&own),
                                "{op:?} {dtypes:?}: the chosen probe differs from the harness's own"
                            ),
                            other => {
                                panic!("{op:?} {dtypes:?}: own recipe exists but got {other:?}")
                            }
                        }
                    }
                }
            }
        }
        // CONTROL: the sweep must see real own-recipe answers, or the assertion above is vacuous.
        assert!(
            own_answers > 40,
            "CONTROL: only {own_answers} own-recipe answers seen"
        );
    }

    #[test]
    fn ops_the_harness_lacks_fall_back_to_the_shared_recipe() {
        // The three measured recipe pairs of GAP-383.
        for (op, dtypes) in [
            (OpKind::Cast, vec![DType::U32, DType::F32]),
            (
                OpKind::GreaterEqualElementwise,
                vec![DType::F32, DType::F32, DType::Bool],
            ),
            (
                OpKind::MaskedFill,
                vec![DType::F32, DType::Bool, DType::F32],
            ),
        ] {
            assert!(
                build_cuda_probe(op, &dtypes, 7).is_none(),
                "PRECONDITION: the harness's own recipes do not cover {op:?} {dtypes:?}"
            );
            assert!(
                matches!(choose_probe(op, &dtypes, 7), ProbeChoice::Shared(_)),
                "{op:?} {dtypes:?} should fall back to the shared recipe"
            );
        }
    }

    #[test]
    fn an_in_place_probe_is_skipped_rather_than_run_on_a_zeroed_output() {
        // Sabotage sibling of the fallback: the shared recipe for an in-place op carries `out_seed`;
        // ignoring it would earn a pass on an all-zero buffer (GAP-222).
        assert!(matches!(
            choose_probe(OpKind::AbsInplace, &[DType::F32, DType::F32], 7),
            ProbeChoice::NeedsSeededOutput
        ));
    }

    #[test]
    fn an_op_with_no_recipe_anywhere_is_none() {
        assert!(matches!(
            choose_probe(OpKind::QMatMul, &[DType::F32, DType::U32, DType::F32], 7),
            ProbeChoice::None
        ));
    }

    #[test]
    fn ops_named_picks_each_requested_op_once_and_ignores_unknown_names() {
        let table = [
            OpKind::Cast,
            OpKind::Cast,
            OpKind::MaskedFill,
            OpKind::AddElementwise,
        ];
        assert_eq!(
            ops_named(&table, " Cast, MaskedFill ,Nope,,"),
            vec![OpKind::Cast, OpKind::MaskedFill]
        );
        assert!(ops_named(&table, "").is_empty());
    }
}