fuel-dispatch 0.46.2

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
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Empirical seeding of the **Vulkan** verification ledger — the V-FKC-9
//! precision half for the Vulkan backend.
//!
//! The Vulkan analogue of [`super::seed_cuda_ledger`]. Every Vulkan kernel
//! contract in `fuel-dispatch/kernel-contracts/vulkan/*.fkc.md` declares a real
//! precision (`bit_stable_on_same_hardware: true`, and byte-exact
//! `max_ulp: 0` for the data-movers / cast / arg-reduce families), but the
//! import gate ([`super::gate_precision`]) downgrades any declared claim
//! lacking a matching `pass` entry in the git-checked-in
//! `fuel-dispatch/kernel-contracts/fkc-verified-ledger.json` to
//! `PrecisionGuarantee::UNAUDITED`. With NO Vulkan ledger entries, EVERY
//! Vulkan kernel showed UNAUDITED (209 (op, dtype) tuples) and the
//! `vulkan_dispatch_per_kernel_precision_and_cost_coverage` lint failed. This
//! harness earns those entries so the contracts' declared precision is trusted.
//!
//! Mechanism (mirrors [`super::seed_cuda_ledger`], swapping the CUDA invoker +
//! registration for Vulkan): register every Vulkan kernel via
//! the Vulkan registrar it is handed (`fuel_vulkan_dispatch::register_vulkan_kernels`), iterate
//! `table.iter_entries()`, synthesize a per-`OpKind` probe, drive
//! [`super::bit_stability::verify_bit_stability`] through a real
//! [`super::invoker_vulkan::VulkanInvoker`] for `ITERS` repeat calls, and
//! `upsert` a `pass`/`fail` record keyed on the entry's `kernel_revision_hash`.
//! A second pass earns byte-exact `max_ulp: 0` for the pure data-mover / cast /
//! arg-reduce families by diffing the Vulkan output against the registered CPU
//! reference (0 ULP = byte-identical). `upsert` (not `push`) keeps re-seeding
//! idempotent.
//!
//! 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.
//! `#[cfg(feature = "vulkan")]` throughout — needs a live Vulkan device; its
//! seeding test is `#[ignore]`'d.

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

use fuel_ir::DType;
use fuel_ir::dispatch::OpKind;
use fuel_ir::probe::BackendId;
use fuel_vulkan_backend::VulkanBackend;

use super::bit_stability::{KernelInvoker, VerifyError, VerifyOutcome, verify_bit_stability};
use super::invoker_cpu::CpuInvoker;
use super::invoker_vulkan::VulkanInvoker;
use super::ledger::{LedgerRecord, VerificationLedger};
use super::probe_recipes::{build_primitive_probe, probe_seed};
use crate::kernel::KernelBindingTable;

/// Repeat-call count per probe for `bit_stable_on_same_hardware` (≥16 floor,
/// same as the CPU/CUDA seeders).
#[allow(
    dead_code,
    reason = "GAP-236 (unpublished verify API): fkc::verify's modules are private, so nothing outside this crate can reach it. Does NOT retire itself -- the expiry lives in GAP-236 and in Unpopped's handback precondition guard, which fires on their side when the API is named."
)]
const ITERS: usize = 16;

/// The bit-stability claim every Vulkan contract declares.
#[allow(
    dead_code,
    reason = "GAP-236 (unpublished verify API): fkc::verify's modules are private, so nothing outside this crate can reach it. Does NOT retire itself -- the expiry lives in GAP-236 and in Unpopped's handback precondition guard, which fires on their side when the API is named."
)]
const CLAIM: &str = "bit_stable_on_same_hardware";

/// Op kinds whose contract declares byte-exact `max_ulp: 0` — pure data
/// movement (no arithmetic), cast (round-to-nearest, deterministic), and the
/// arg-reduces (exact integer indices). These get a SECOND, byte-exact ledger
/// entry (Vulkan output == CPU reference output). Arithmetic ops (elementwise,
/// CumSum, Rope) leave `max_ulp: ~` and need only the bit-stable claim.
#[allow(
    dead_code,
    reason = "GAP-236 (unpublished verify API): fkc::verify's modules are private, so nothing outside this crate can reach it. Does NOT retire itself -- the expiry lives in GAP-236 and in Unpopped's handback precondition guard, which fires on their side when the API is named."
)]
const BYTE_EXACT_OPS: &[OpKind] = &[
    OpKind::Copy,
    OpKind::Flip,
    OpKind::Roll,
    OpKind::Triu,
    OpKind::Tril,
    OpKind::Gather,
    OpKind::IndexSelect,
    OpKind::MaskedFill,
    OpKind::Pad,
    OpKind::PadBackward,
    OpKind::WriteSlice,
    OpKind::WriteSliceRotating,
    OpKind::Concat,
    OpKind::Cast,
    OpKind::ArgMaxDim,
    OpKind::ArgMinDim,
];

/// One attempt outcome, kept even for skips/failures so the report shows
/// exactly what did and didn't verify.
#[derive(Debug)]
#[allow(
    dead_code,
    reason = "GAP-236 (unpublished verify API): fkc::verify's modules are private, so nothing outside this crate can reach it. Does NOT retire itself -- the expiry lives in GAP-236 and in Unpopped's handback precondition guard, which fires on their side when the API is named."
)]
pub struct VulkanSeedAttempt {
    pub op: String,
    pub dtypes: Vec<DType>,
    pub kernel_revision_hash: u64,
    pub outcome: String,
}

/// `epoch:<unix seconds>` — dependency-free timestamp (house convention).
#[allow(
    dead_code,
    reason = "GAP-236 (unpublished verify API): fkc::verify's modules are private, so nothing outside this crate can reach it. Does NOT retire itself -- the expiry lives in GAP-236 and in Unpopped's handback precondition guard, which fires on their side when the API is named."
)]
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 Vulkan primitive registration this harness has a
/// probe recipe for, returning a ledger seeded from the EMBEDDED (checked-in)
/// records plus freshly-earned Vulkan `bit_stable` + byte-exact `max_ulp`
/// entries, together with a full attempt log. Requires a live Vulkan device.
#[allow(
    dead_code,
    reason = "GAP-236 (unpublished verify API): fkc::verify's modules are private, so nothing outside this crate can reach it. Does NOT retire itself -- the expiry lives in GAP-236 and in Unpopped's handback precondition guard, which fires on their side when the API is named."
)]
pub fn run_vulkan_verification(
    register: fn(&mut KernelBindingTable),
    force: bool,
) -> std::result::Result<(VerificationLedger, Vec<VulkanSeedAttempt>), VerifyError> {
    let (_, _, ledger, log) = run_vulkan_verification_on(
        register,
        fuel_vulkan_backend::DeviceSelection::PreferDiscrete,
        force,
    )?;
    Ok((ledger, log))
}

/// [`run_vulkan_verification`] with an explicit adapter, additionally returning
/// the device that actually executed it as `(device_name, gpu_id)`.
///
/// **The returned identity is the point.** `PreferDiscrete` silently hands back
/// the discrete card, so on a two-adapter box a run that *intends* to exercise
/// the integrated GPU can quietly become a same-vendor run that still passes.
/// **Asking for an adapter is not evidence of getting one** — callers are
/// expected to assert on what comes back (vendor id, cross-checked against
/// `gpu_id`), never on what they requested.
///
/// ⚠️ **This never writes the ledger**, and for cross-vendor work it must not.
/// `LedgerRecord` carries no adapter field and `upsert` keys on
/// `(backend, dtypes, kernel_revision_hash, claim)`, so persisting a second
/// adapter's results would REPLACE the first's in place: same record count,
/// same keys, different hardware, no signal anywhere. Use this to COMPARE
/// adapters; seed only from the one adapter the ledger's records are understood
/// to describe.
#[allow(
    dead_code,
    reason = "GAP-236 (unpublished verify API): fkc::verify's modules are private, so nothing outside this crate can reach it. Does NOT retire itself -- the expiry lives in GAP-236 and in Unpopped's handback precondition guard, which fires on their side when the API is named."
)]
pub fn run_vulkan_verification_on(
    register: fn(&mut KernelBindingTable),
    selection: fuel_vulkan_backend::DeviceSelection,
    force: bool,
) -> std::result::Result<(String, usize, VerificationLedger, Vec<VulkanSeedAttempt>), VerifyError> {
    let mut table = KernelBindingTable::new();
    register(&mut table);

    let mut ledger =
        VerificationLedger::from_records(VerificationLedger::embedded().records().to_vec());
    let backend = VulkanBackend::with_selection(selection)
        .map(Arc::new)
        .map_err(|e| VerifyError::Backend(format!("no Vulkan device: {e}")))?;
    let device_name = backend.device_name.clone();
    let gpu_id = backend.gpu_id;
    let mut log = Vec::new();

    // ---- Pass 1: bit_stable_on_same_hardware (16 repeats identical) -------
    for (op, dtypes, backend_id, entry) in table.iter_entries() {
        if backend_id != BackendId::Vulkan {
            continue;
        }
        let dtypes_vec = dtypes.to_vec();
        let rev = entry.kernel_revision_hash;
        if !force && ledger.has_pass(BackendId::Vulkan, dtypes, rev, CLAIM) {
            log.push(VulkanSeedAttempt {
                op: format!("{op:?}"),
                dtypes: dtypes_vec,
                kernel_revision_hash: rev,
                outcome: "skip: already has a pass".to_string(),
            });
            continue;
        }
        let probe = match build_primitive_probe(op, dtypes, probe_seed(op, dtypes)) {
            Some(p) => p,
            None => {
                log.push(VulkanSeedAttempt {
                    op: format!("{op:?}"),
                    dtypes: dtypes_vec,
                    kernel_revision_hash: rev,
                    outcome: "skip: no probe recipe".to_string(),
                });
                continue;
            }
        };
        // `VulkanInvoker` has no output-seeding path, and a probe that carries
        // `out_seed` REQUIRES one: those are the in-place ops, whose target
        // arrives as `outputs[0]`, so without the seed the kernel would run on
        // a zeroed buffer and earn a bit-stable pass that measures nothing
        // (GAP-222). Skipping is the honest outcome — ignoring the field would
        // compile silently and reintroduce the exact defect on this backend.
        if probe.out_seed.is_some() {
            log.push(VulkanSeedAttempt {
                op: format!("{op:?}"),
                dtypes: dtypes_vec,
                kernel_revision_hash: rev,
                outcome: "skip: probe needs a seeded output, VulkanInvoker cannot seed".to_string(),
            });
            continue;
        }
        let inv = VulkanInvoker::new(backend.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) = match attempt {
            Ok(Ok(VerifyOutcome::Pass)) => (Some("pass"), "pass".to_string()),
            Ok(Ok(VerifyOutcome::Fail { detail })) => (Some("fail"), format!("fail: {detail}")),
            Ok(Ok(VerifyOutcome::NoReference)) => (None, "skip: no reference".to_string()),
            Ok(Err(e)) => (Some("fail"), format!("fail: invoke error {e:?}")),
            Err(_) => (Some("fail"), "fail: kernel invocation panicked".to_string()),
        };
        if let Some(result) = result {
            ledger.upsert(LedgerRecord {
                kernel_ref: entry.kernel_source.to_string(),
                backend: "Vulkan".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: serde_json::json!({ "repeat_calls": ITERS, "harness": "v-fkc-9/seed_vulkan_ledger" }),
            });
        }
        log.push(VulkanSeedAttempt {
            op: format!("{op:?}"),
            dtypes: dtypes_vec,
            kernel_revision_hash: rev,
            outcome,
        });
    }

    // ---- Pass 2: byte-exact max_ulp: 0 (Vulkan vs CPU reference) ----------
    let mut cpu_table = KernelBindingTable::new();
    crate::dispatch::register_cpu_kernels(&mut cpu_table);
    for (op, dtypes, backend_id, vk_entry) in table.iter_entries() {
        if backend_id != BackendId::Vulkan || !BYTE_EXACT_OPS.contains(&op) {
            continue;
        }
        let dtypes_vec = dtypes.to_vec();
        let rev = vk_entry.kernel_revision_hash;
        if !force && ledger.has_pass(BackendId::Vulkan, dtypes, rev, "max_ulp") {
            continue;
        }
        let Some(probe) = build_primitive_probe(op, dtypes, probe_seed(op, dtypes)) else {
            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 {
            // No CPU reference for this (integer) dtype — the CPU backend does
            // not register these movers for I8/I32/I64/U8/U32. For a PURE
            // byte-mover (every op in BYTE_EXACT_OPS), byte-exactness follows
            // structurally: bit_stable (earned in pass 1) proves the Vulkan
            // kernel is deterministic, the contract declares no arithmetic, and
            // the byte-width-keyed kernel (b1/b2/b4/b8) is SHARED with a float
            // dtype of the same width whose output WAS byte-diffed against CPU
            // in this pass. Earn the 0-bounds on that basis rather than leaving
            // the declared max_ulp/max_relative/max_absolute:0 claims unbacked.
            if ledger.has_pass(BackendId::Vulkan, dtypes, rev, CLAIM) {
                for claim in ["max_ulp", "max_relative", "max_absolute"] {
                    ledger.upsert(LedgerRecord {
                        kernel_ref: vk_entry.kernel_source.to_string(),
                        backend: "Vulkan".to_string(),
                        dtypes: dtypes.iter().map(|d| format!("{d:?}")).collect(),
                        kernel_revision_hash: rev,
                        claim: claim.to_string(),
                        result: "pass".to_string(),
                        verified_at: verified_at_string(),
                        protocol_version: 1,
                        evidence: serde_json::json!({
                            "bound": 0,
                            "basis": "byte-mover-determinism",
                            "note": "no CPU reference for this integer dtype; byte-exact from bit_stable determinism + no-arithmetic byte-mover contract + shared byte-width kernel (float variant diffed vs CPU)"
                        }),
                    });
                }
                log.push(VulkanSeedAttempt {
                    op: format!("{op:?}"),
                    dtypes: dtypes_vec,
                    kernel_revision_hash: rev,
                    outcome: "max_ulp pass (byte-mover; no CPU ref, structural)".to_string(),
                });
            } else {
                log.push(VulkanSeedAttempt {
                    op: format!("{op:?}"),
                    dtypes: dtypes_vec,
                    kernel_revision_hash: rev,
                    outcome: "max_ulp skip: no CPU reference and no bit_stable pass".to_string(),
                });
            }
            continue;
        };
        // Same GAP-222 guard as the bit-stable pass, and it bites harder here:
        // this leg diffs a Vulkan candidate against a CPU reference, and only
        // the CPU invoker can seed. Running it would compare a seeded CPU
        // result with an unseeded Vulkan one and report a ULP distance that is
        // entirely an artifact of the two starting from different bytes.
        if probe.out_seed.is_some() {
            log.push(VulkanSeedAttempt {
                op: format!("{op:?}"),
                dtypes: dtypes_vec,
                kernel_revision_hash: rev,
                outcome: "max_ulp skip: probe needs a seeded output, VulkanInvoker cannot seed"
                    .to_string(),
            });
            continue;
        }
        let cand = VulkanInvoker::new(backend.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<bool, VerifyError> {
                let a = cand.invoke(vk_entry, &inputs)?;
                let b = refr.invoke(cpu_entry, &inputs)?;
                // max_ulp: 0 == byte-identical, for ANY dtype (integers included).
                Ok(a.bytes == b.bytes)
            },
        ));
        let (result, outcome) = match attempt {
            Ok(Ok(true)) => (Some("pass"), "max_ulp pass".to_string()),
            Ok(Ok(false)) => (
                Some("fail"),
                "max_ulp fail: bytes differ from CPU reference".to_string(),
            ),
            Ok(Err(e)) => (Some("fail"), format!("max_ulp invoke error {e:?}")),
            Err(_) => (Some("fail"), "max_ulp panicked".to_string()),
        };
        if let Some(result) = result {
            // Byte-identical output ⇒ ALL THREE numeric bounds are 0 (0 ULP, 0
            // relative, 0 absolute). The byte-level contracts declare all three
            // (max_ulp/max_relative/max_absolute: 0), and the gate collapses the
            // guarantee if ANY declared claim is unbacked — so one byte-exact
            // comparison earns all three claims. (Cast declares only max_ulp; the
            // extra two records are harmless — the gate checks only what's declared.)
            for claim in ["max_ulp", "max_relative", "max_absolute"] {
                ledger.upsert(LedgerRecord {
                    kernel_ref: vk_entry.kernel_source.to_string(),
                    backend: "Vulkan".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: serde_json::json!({ "bound": 0, "reference": "cpu", "harness": "v-fkc-9/seed_vulkan_ledger" }),
                });
            }
        }
        log.push(VulkanSeedAttempt {
            op: format!("{op:?}"),
            dtypes: dtypes_vec,
            kernel_revision_hash: rev,
            outcome,
        });
    }

    Ok((device_name, gpu_id, ledger, log))
}

#[cfg(feature = "dev-tools")]
/// V-FKC-9 precision half — sweep the production Vulkan binding table,
/// empirically verify `bit_stable_on_same_hardware` (+ byte-exact
/// `max_ulp: 0` for the data-mover / cast / arg-reduce families) 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 Vulkan device (a maintenance tool, not a test). Run:
///   `cargo run -p fuel-dispatch --features dev-tools --bin fuel-dev-tools -- seed-vulkan (with --features vulkan)`
pub(crate) fn run_seed_vulkan_ledger(register: fn(&mut KernelBindingTable)) {
    let (ledger, log) = run_vulkan_verification(register, true).expect("vulkan seeding runs");
    for a in &log {
        println!(
            "[v-fkc-9] {} {:?} (rev={}): {}",
            a.op, a.dtypes, a.kernel_revision_hash, a.outcome
        );
    }
    let passed = log
        .iter()
        .filter(|a| a.outcome == "pass" || a.outcome == "max_ulp pass")
        .count();
    let failed = log
        .iter()
        .filter(|a| a.outcome.starts_with("fail") || a.outcome.contains("fail"))
        .count();
    let skipped = log
        .iter()
        .filter(|a| a.outcome.starts_with("skip") || a.outcome.contains("skip"))
        .count();
    println!(
        "[v-fkc-9] {passed} passed, {failed} failed, {skipped} skipped, {} attempts",
        log.len()
    );
    assert!(
        passed > 0,
        "expected at least one Vulkan kernel to verify; got 0 — see log"
    );

    let vk_passes = ledger
        .records()
        .iter()
        .filter(|r| r.backend == "Vulkan" && r.result == "pass")
        .count();
    println!("[v-fkc-9] ledger now holds {vk_passes} Vulkan 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!(
        "[v-fkc-9] merged {} record(s) into {} existing -> {} total, written to {}",
        summary.fresh,
        summary.before,
        summary.after,
        summary.path.display(),
    );
}