fuel-dispatch 0.19.1

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.
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
// SPDX-License-Identifier: MIT OR Apache-2.0
//! # FKC kernel-contract importer (`fkc`)
//!
//! The Fuel Kernel Contract (FKC) importer: parse a provider's markdown
//! contract file(s) and (eventually) auto-register every described kernel onto
//! Fuel's dispatch surface (`KernelBindingTable` / `FusedKernelRegistry`) with
//! zero hand-written registration glue.
//!
//! This module is unconditional production infrastructure (`pub mod fkc` in
//! lib.rs, no feature gate; the `fkc` feature was removed in bd757464).
//!
//! ## Status — first slice
//!
//! Implemented here: the module skeleton, the [`FkcError`] type, the serde
//! schema structs mirroring FKC §3.1 / §3.2 / §3.3, and the markdown +
//! restricted-YAML parser ([`parse_file`] / [`parse_path`]) that:
//! - splits the file-level `---` front-matter (§3.1),
//! - extracts each `## ` section's single ` ```fkc ` block (§3.1),
//! - enforces the §3.8 restricted YAML subset (tabs / anchors / aliases /
//!   merge keys / the Norway problem) BEFORE deserializing, then
//! - deserializes each block into the schema and assembles an [`FkcFile`].
//!
//! Also implemented: lowering to dispatch types (`lower.rs`), caps/cost/
//! precision projection, the `LinkRegistry`, the revision hash, and — this
//! slice — the END-TO-END registration path (`register.rs`):
//! [`import_bundle_str`] / [`import_bundle`] / [`import_glob`] →
//! [`ImportedProvider`] → [`ImportedProvider::register_into`] populating
//! both the `KernelBindingTable` (primitives) and the
//! `FusedKernelRegistry` (fused ops), with the duplicate-detection
//! `finalize` gate surfaced as [`FkcError::DuplicateKernelRef`].
//!
//! NOT yet implemented (later slices of the plan): the cost trampoline /
//! global cost-table (imported costs use the Judge-bootstrapped sentinel
//! `CostFn` for now), the full `V-FKC-*` validators, and the CI lint.
//!
//! ## Authoritative references
//!
//! - Format spec: `docs/specs/kernel-contract-format.md`.
//! - Adoption plan: `docs/session-prompts/kernel-contract-adoption-plan.md`.
//! - Authored corpus (valid instances): `docs/kernel-contracts/**/*.fkc.md`.

mod caps_map;
pub(crate) mod cost_compile;
pub(crate) mod cost_expr;
mod cpu_link;
#[cfg(feature = "cuda")]
mod cuda_link;
mod error;
mod lower;
mod parse;
mod precision;
mod register;
mod return_check;
mod revhash;
mod schema;
mod shape_constraint;
// pub: the §6.20 shape-expression wire codec + evaluator is public interop
// surface (byte-matches the KISS reference, golden-verified) — its decoder is
// the reserved-tag decline point / future extension-registry activation point,
// live API rather than crate-internal plumbing.
pub mod shape_expr;
pub(crate) mod shape_expr_parse;
mod validate;
// pub(crate): jit_ingest.rs (outside this module tree) reaches LedgerRecord
// via crate::fkc::verify::LedgerRecord for RejectionReport::ledger_record.
pub(crate) mod verify;
// Contract-maintenance tooling for the `audited:` attestation (GAP-228).
// OUTSIDE `verify/` on purpose: it writes `.fkc.md` files, and `verify/`'s
// single-writer gate scans that directory for any write call. See its docs.
#[cfg(test)]
mod contract_audit_flip;
#[cfg(feature = "vulkan")]
mod vulkan_link;
mod warn;

pub use caps_map::{ResolvedLayout, Tri, is_generic_contract};
pub use cost_expr::{
    CompiledCostExpr, CostEvalError, CostNode, bind_cost_symbols, cost_estimate, eval as eval_cost,
};
pub use cpu_link::{
    CPU_AFFINE_CLAMP_POWI_ENTRY_POINTS, CPU_ATTENTION_ENTRY_POINTS, CPU_BINARY_ENTRY_POINTS,
    CPU_COMPARE_ENTRY_POINTS, CPU_CONV_ENTRY_POINTS, CPU_FUSED_CONV_ROPE_ENTRY_POINTS,
    CPU_FUSED_LINEAR_QUANT_ENTRY_POINTS, CPU_FUSED_NORM_ENTRY_POINTS, CPU_INPLACE_ENTRY_POINTS,
    CPU_MATMUL_ENTRY_POINTS, CPU_NORM_BACKWARD_ENTRY_POINTS, CPU_NORM_ENTRY_POINTS,
    CPU_PADDING_ENTRY_POINTS, CPU_REDUCE_ENTRY_POINTS, CPU_REDUCE_TO_ENTRY_POINTS,
    CPU_ROPE_ENTRY_POINTS, CPU_SHAPE_OPS_ENTRY_POINTS, CPU_SSM_ENTRY_POINTS,
    CPU_UNARY_ENTRY_POINTS, CPU_WHERE_ENTRY_POINTS, CpuLinkRegistry,
};
#[cfg(feature = "cuda")]
pub use cuda_link::{
    CUDA_AFFINE_ENTRY_POINTS, CUDA_ARG_REDUCE_ENTRY_POINTS, CUDA_BINARY_ENTRY_POINTS,
    CUDA_CAST_ENTRY_POINTS, CUDA_CAUSAL_CONV1D_ENTRY_POINTS, CUDA_CLAMP_ENTRY_POINTS,
    CUDA_CLAMP_INPLACE_ENTRY_POINTS, CUDA_CONCAT_ENTRY_POINTS, CUDA_COST_FNS,
    CUDA_CUMSUM_ENTRY_POINTS, CUDA_FLASH_DECODING_ENTRY_POINTS, CUDA_FLIP_ENTRY_POINTS,
    CUDA_GEMM_DENSE_ENTRY_POINTS, CUDA_GEMM_INT_ENTRY_POINTS, CUDA_INDEXING_ENTRY_POINTS,
    CUDA_INPLACE_AFFINE_ENTRY_POINTS, CUDA_INPLACE_UNARY_ENTRY_POINTS, CUDA_NORM_ENTRY_POINTS,
    CUDA_PAD_BACKWARD_ENTRY_POINTS, CUDA_PAD_ENTRY_POINTS, CUDA_POWI_BACKWARD_ENTRY_POINTS,
    CUDA_POWI_ENTRY_POINTS, CUDA_POWI_INPLACE_ENTRY_POINTS, CUDA_REDUCE_ENTRY_POINTS,
    CUDA_REDUCE_TO_ENTRY_POINTS, CUDA_ROLL_ENTRY_POINTS, CUDA_ROPE_ENTRY_POINTS,
    CUDA_SOFTMAX_ENTRY_POINTS, CUDA_TRIANGULAR_ENTRY_POINTS, CUDA_UNARY_ENTRY_POINTS,
    CUDA_WRITE_SLICE_ENTRY_POINTS, CUDA_WRITE_SLICE_ROTATING_ENTRY_POINTS, CudaLinkRegistry,
};
pub use error::FkcError;
pub use lower::{LinkRegistry, Resolved, ResolvedFused, ResolvedPrimitive, lower_file};
pub use parse::{parse_file, parse_path};
pub use register::{
    ImportedProvider, fused_unknown_cost, import_bundle, import_bundle_str, import_glob,
};
pub use revhash::compute_revision;
pub use schema::{
    AcceptBlock, CapsBlock, CostBlock, CostMemory, FdxSpec, FkcFile, FkcFrontMatter, FkcKernel,
    FkcProvider, GatherSpec, LayoutSpec, OpParamFieldSpec, OpParamsSchema, OutputDesc,
    PrecisionBlock, QuantSpec, ReturnBlock, TensorDesc,
};
pub use shape_constraint::{
    AxisIndex, ProbeCombo, RankSpec, ShapeAtom, ShapeConstraint, parse_rank_spec,
    parse_shape_constraint, solve_probe_shapes,
};
pub use validate::{FKC_SUPPORTED_VERSIONS, validate_file, validate_kernel};
#[cfg(feature = "vulkan")]
pub use vulkan_link::{
    VULKAN_CAST_ENTRY_POINTS, VULKAN_ELEMENTWISE_ENTRY_POINTS, VulkanLinkRegistry,
};
pub use warn::ImportWarning;

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

    // ----- Real-contract corpus paths (load-bearing schema-match test) -----

    /// `elementwise-binary.fkc.md` — the simplest authored CPU contract.
    const ELEMENTWISE_BINARY: &str =
        include_str!("../../../docs/kernel-contracts/cpu/elementwise-binary.fkc.md");
    /// `quant-matmul.fkc.md` — a more complex authored CPU contract (GGML quant
    /// weight matmuls + NF4 with a separate scale operand, gemm cost class,
    /// fdx.quant blocks).
    const QUANT_MATMUL: &str =
        include_str!("../../../docs/kernel-contracts/cpu/quant-matmul.fkc.md");
    /// `rope-apply.fkc.md` (Task 4.6) — baracuda's `rope_apply_<dt>_run`,
    /// shipped but never wired into any dispatch path before this task. Its
    /// `entry_point` names raw baracuda FFI symbols resolved only by a
    /// harness-local `LinkRegistry` (`fuel-dispatch/src/fkc/verify/
    /// harness.rs`, `#[cfg(feature = "cuda")]`), so it can only be
    /// `import_bundle_str`'d for real under `--features cuda`. What CAN run
    /// here, in the default build: parse + validate + lower against a STUB
    /// registry (below) that resolves only the four EXACT expected
    /// symbols — proof the contract is structurally well-formed (dtype-fan,
    /// entry_point suffixing, per-operand fixed-vs-varying dtypes) without
    /// touching any real CUDA code.
    const ROPE_APPLY: &str = include_str!("../../../docs/kernel-contracts/cuda/rope-apply.fkc.md");

    // =====================================================================
    // PARSE A REAL CONTRACT — the key correctness test (§3.1/§3.3 schema match)
    // =====================================================================

    #[test]
    fn parses_real_elementwise_binary_contract() {
        let file =
            parse_file(ELEMENTWISE_BINARY).expect("authored elementwise-binary.fkc.md must parse");

        // Front-matter.
        assert_eq!(file.front_matter.fkc_version, 1);
        assert_eq!(file.front_matter.provider.name, "fuel-cpu-backend");
        assert_eq!(file.front_matter.provider.backend, "Cpu");
        assert_eq!(file.front_matter.provider.kernel_source, "portable-cpu");
        assert_eq!(
            file.front_matter.provider.link_registry.as_deref(),
            Some("fuel_cpu_backend::fkc::ENTRY_POINTS")
        );

        // Non-empty kernels.
        assert!(
            !file.kernels.is_empty(),
            "elementwise-binary must yield kernels"
        );

        // The umbrella `binary` chassis section + per-(op, dtype) thunks.
        let names: Vec<&str> = file.kernels.iter().map(|k| k.kernel.as_str()).collect();
        assert!(
            names.contains(&"binary"),
            "expected the `binary` chassis section; got {names:?}"
        );
        assert!(
            names.contains(&"add_f32"),
            "expected `add_f32`; got {names:?}"
        );

        // op_kind round-trips as a string; fused_op absent for these primitives.
        let add_f32 = file
            .kernels
            .iter()
            .find(|k| k.kernel == "add_f32")
            .expect("add_f32 present");
        assert_eq!(add_f32.op_kind.as_deref(), Some("AddElementwise"));
        assert!(add_f32.fused_op.is_none());

        // Accept block: two inputs (lhs, rhs), dtypes parsed as strings.
        let accept = add_f32.accept.as_ref().expect("add_f32 has accept");
        assert_eq!(accept.inputs.len(), 2);
        assert_eq!(accept.inputs[0].name.as_deref(), Some("lhs"));
        assert_eq!(accept.inputs[0].dtypes, vec!["F32".to_string()]);
        // Layout five-flag set parsed.
        let layout = accept.inputs[0].layout.as_ref().expect("lhs has layout");
        assert_eq!(layout.contiguous.as_deref(), Some("required"));
        assert_eq!(layout.strided.as_deref(), Some("rejected"));

        // Return block: one output with rules carried as strings.
        let ret = add_f32.return_.as_ref().expect("add_f32 has return");
        assert_eq!(ret.outputs.len(), 1);
        assert_eq!(
            ret.outputs[0].dtype_rule.as_deref(),
            Some("passthrough(lhs)")
        );

        // Cost: provenance + expression strings carried verbatim.
        let cost = add_f32.cost.as_ref().expect("add_f32 has cost");
        assert_eq!(cost.provenance.as_deref(), Some("judge_measured"));
        assert_eq!(cost.flops.as_deref(), Some("n"));
        assert_eq!(cost.bytes_moved.as_deref(), Some("3 * n * 4"));

        // Determinism token.
        assert_eq!(
            add_f32.determinism.as_deref(),
            Some("same_hardware_bitwise")
        );
    }

    #[test]
    fn parses_real_quant_matmul_contract() {
        let file = parse_file(QUANT_MATMUL).expect("authored quant-matmul.fkc.md must parse");

        assert_eq!(file.front_matter.provider.name, "fuel-cpu-backend");
        assert!(!file.kernels.is_empty());

        let names: Vec<&str> = file.kernels.iter().map(|k| k.kernel.as_str()).collect();
        assert!(
            names.contains(&"qmatmul_q4_0_f32"),
            "expected qmatmul_q4_0_f32; got {names:?}"
        );
        assert!(
            names.contains(&"nf4_matmul_f32"),
            "expected nf4_matmul_f32; got {names:?}"
        );

        // A GGML quant weight operand: family/ggml_dtype parsed as strings,
        // scale_operand stays None (INLINE single-place rule).
        let q40 = file
            .kernels
            .iter()
            .find(|k| k.kernel == "qmatmul_q4_0_f32")
            .unwrap();
        assert_eq!(q40.op_kind.as_deref(), Some("QMatMul"));
        let weight = q40
            .accept
            .as_ref()
            .unwrap()
            .inputs
            .iter()
            .find(|d| d.name.as_deref() == Some("weight"))
            .expect("q4_0 has a weight operand");
        let quant = weight
            .fdx
            .as_ref()
            .unwrap()
            .quant
            .as_ref()
            .expect("weight has fdx.quant");
        assert_eq!(quant.family.as_deref(), Some("GGML_BLOCK"));
        assert_eq!(quant.ggml_dtype.as_deref(), Some("Q4_0"));
        assert_eq!(quant.role.as_deref(), Some("weight"));
        assert!(
            quant.scale_operand.is_none(),
            "INLINE scale: no separate operand"
        );

        // op_params variant + a field with a constraint string.
        let op_params = q40.accept.as_ref().unwrap().op_params.as_ref().unwrap();
        assert_eq!(op_params.variant.as_deref(), Some("QMatMul"));
        assert!(op_params.fields.contains_key("k"));

        // NF4: the absmax is a SEPARATE scale operand (single-place rule).
        let nf4 = file
            .kernels
            .iter()
            .find(|k| k.kernel == "nf4_matmul_f32")
            .unwrap();
        let nf4_inputs = &nf4.accept.as_ref().unwrap().inputs;
        assert!(
            nf4_inputs
                .iter()
                .any(|d| d.name.as_deref() == Some("absmax")),
            "NF4 has a separate absmax operand"
        );
        let w_packed = nf4_inputs
            .iter()
            .find(|d| d.name.as_deref() == Some("w_packed"))
            .unwrap();
        let nf4_quant = w_packed.fdx.as_ref().unwrap().quant.as_ref().unwrap();
        assert_eq!(nf4_quant.family.as_deref(), Some("AFFINE_BLOCK"));
        assert_eq!(nf4_quant.scale_operand.as_deref(), Some("absmax"));
    }

    /// Task 4.6 — the rope-apply CUDA acceptance-kernel contract must
    /// parse, pass the `V-FKC-*` validators, and LOWER structurally
    /// correctly, all WITHOUT the `cuda` feature (a stub registry stands
    /// in for the real link, matching `lower.rs`'s own `StubLink`
    /// precedent). This is the default-feature verification the Task 4.6
    /// brief explicitly permits in lieu of a real `--features cuda` import.
    #[test]
    fn parses_and_lowers_real_rope_apply_contract() {
        use fuel_ir::DType;
        use fuel_ir::dispatch::OpKind;
        use fuel_ir::probe::BackendId;

        let file = parse_file(ROPE_APPLY).expect("rope-apply.fkc.md must parse");
        validate_file(&file).expect("rope-apply.fkc.md must pass the V-FKC-* validators");

        assert_eq!(file.front_matter.provider.name, "fuel-cuda-backend");
        assert_eq!(file.front_matter.provider.backend, "Cuda");
        assert_eq!(file.front_matter.provider.kernel_source, "baracuda");

        let names: Vec<&str> = file.kernels.iter().map(|k| k.kernel.as_str()).collect();
        assert!(
            names.contains(&"rope_apply"),
            "expected a `rope_apply` section; got {names:?}"
        );

        let kernel = file
            .kernels
            .iter()
            .find(|k| k.kernel == "rope_apply")
            .unwrap();
        assert_eq!(kernel.op_kind.as_deref(), Some("Rope"));
        assert!(
            kernel.fused_op.is_none(),
            "rope_apply is a primitive op_kind contract, not fused"
        );

        // Three inputs: x (fans over the 4 dtypes), cos + sin (fixed F32 each,
        // per baracuda's ABI — see the contract's front-matter note).
        let accept = kernel.accept.as_ref().expect("rope_apply has accept");
        assert_eq!(accept.inputs.len(), 3);
        assert_eq!(accept.inputs[0].name.as_deref(), Some("x"));
        assert_eq!(
            accept.inputs[0].dtypes,
            vec![
                "F32".to_string(),
                "F16".to_string(),
                "BF16".to_string(),
                "F64".to_string()
            ],
        );
        assert_eq!(accept.inputs[1].name.as_deref(), Some("cos"));
        assert_eq!(accept.inputs[1].dtypes, vec!["F32".to_string()]);
        assert_eq!(accept.inputs[2].name.as_deref(), Some("sin"));
        assert_eq!(accept.inputs[2].dtypes, vec!["F32".to_string()]);

        // Lower against a stub that resolves ONLY the four raw baracuda symbols
        // this contract's base entry_point ("baracuda_kernels_rope_apply") fans
        // into — a wrong suffix, or a missing/extra variant, fails this.
        fn dummy_kernel(
            _inputs: &[std::sync::Arc<std::sync::RwLock<fuel_memory::Storage>>],
            _outputs: &mut [std::sync::Arc<std::sync::RwLock<fuel_memory::Storage>>],
            _layouts: &[fuel_ir::Layout],
            _params: &crate::kernel::OpParams,
        ) -> fuel_ir::Result<()> {
            Ok(())
        }
        struct StubRopeApplyLink;
        impl LinkRegistry for StubRopeApplyLink {
            fn resolve_primitive(&self, symbol: &str) -> Option<crate::kernel::KernelRef> {
                const KNOWN: &[&str] = &[
                    "baracuda_kernels_rope_apply_f32",
                    "baracuda_kernels_rope_apply_f16",
                    "baracuda_kernels_rope_apply_bf16",
                    "baracuda_kernels_rope_apply_f64",
                ];
                if KNOWN.contains(&symbol) {
                    Some(dummy_kernel)
                } else {
                    None
                }
            }
            fn resolve_fused(&self, _symbol: &str) -> Option<crate::kernel::KernelRef> {
                None
            }
        }

        let mut warnings = Vec::new();
        let resolved = lower_file(&file, &StubRopeApplyLink, &mut warnings)
            .expect("rope-apply.fkc.md must lower against a registry resolving its 4 real symbols");
        let primitives: Vec<_> = resolved
            .iter()
            .filter_map(|r| match r {
                Resolved::Primitive(p) => Some(p),
                Resolved::Fused(_) => None,
            })
            .collect();
        assert_eq!(
            primitives.len(),
            4,
            "expected 4 dtype variants (F32/F16/BF16/F64); got {}",
            primitives.len(),
        );
        for p in &primitives {
            assert_eq!(p.op, OpKind::Rope);
            assert_eq!(p.backend, BackendId::Cuda);
            // Per-variant key: [x_dt, F32(cos), F32(sin), x_dt(out, passthrough)].
            assert_eq!(
                p.dtypes.len(),
                4,
                "expected [x, cos, sin, out] key; got {:?}",
                p.dtypes
            );
            assert_eq!(p.dtypes[1], DType::F32, "cos is always F32");
            assert_eq!(p.dtypes[2], DType::F32, "sin is always F32");
            assert_eq!(
                p.dtypes[0], p.dtypes[3],
                "output passthrough(x) must match x's dtype"
            );
        }
        let x_dtypes: std::collections::HashSet<DType> =
            primitives.iter().map(|p| p.dtypes[0]).collect();
        assert_eq!(
            x_dtypes,
            [DType::F32, DType::F16, DType::BF16, DType::F64]
                .into_iter()
                .collect(),
            "expected exactly the F32/F16/BF16/F64 fan",
        );
    }

    // =====================================================================
    // §3.8 NEGATIVES
    // =====================================================================

    const VALID_MINIMAL: &str = "\
---
fkc_version: 1
provider:
  name: test-provider
  backend: Cpu
  kernel_source: \"test-cpu\"
---

# test bundle

## demo

A blurb.

```fkc
kernel: demo
op_kind: AddElementwise
blurb: \"demo\"
entry_point: \"x::y\"
```
";

    #[test]
    fn valid_minimal_parses() {
        let file = parse_file(VALID_MINIMAL).expect("minimal valid file parses");
        assert_eq!(file.kernels.len(), 1);
        assert_eq!(file.kernels[0].kernel, "demo");
    }

    #[test]
    fn tab_indentation_in_block_is_rejected() {
        // A tab-indented line inside the fkc block.
        let src = "\
---
fkc_version: 1
provider:
  name: p
  backend: Cpu
  kernel_source: \"c\"
---

## demo

b

```fkc
kernel: demo
accept:
\tinputs: []
```
";
        let err = parse_file(src).expect_err("tab must be rejected");
        assert!(
            matches!(err, FkcError::TabIndentation { .. }),
            "got {err:?}"
        );
    }

    #[test]
    fn anchor_is_rejected() {
        let src = "\
---
fkc_version: 1
provider:
  name: p
  backend: Cpu
  kernel_source: \"c\"
---

## demo

b

```fkc
kernel: &base demo
op_kind: AddElementwise
```
";
        let err = parse_file(src).expect_err("anchor must be rejected");
        assert!(
            matches!(err, FkcError::AnchorDisallowed { .. }),
            "got {err:?}"
        );
    }

    #[test]
    fn alias_is_rejected() {
        let src = "\
---
fkc_version: 1
provider:
  name: p
  backend: Cpu
  kernel_source: \"c\"
---

## demo

b

```fkc
kernel: demo
blurb: *base
```
";
        let err = parse_file(src).expect_err("alias must be rejected");
        assert!(
            matches!(err, FkcError::AliasDisallowed { .. }),
            "got {err:?}"
        );
    }

    #[test]
    fn merge_key_is_rejected() {
        let src = "\
---
fkc_version: 1
provider:
  name: p
  backend: Cpu
  kernel_source: \"c\"
---

## demo

b

```fkc
kernel: demo
caps:
  <<: defaults
```
";
        let err = parse_file(src).expect_err("merge key must be rejected");
        assert!(
            matches!(err, FkcError::MergeKeyDisallowed { .. }),
            "got {err:?}"
        );
    }

    #[test]
    fn unquoted_norway_token_is_rejected() {
        // `family: no` unquoted, in a value position — must be flagged, never
        // silently coerced to a bool.
        let src = "\
---
fkc_version: 1
provider:
  name: p
  backend: Cpu
  kernel_source: \"c\"
---

## demo

b

```fkc
kernel: demo
family: no
```
";
        let err = parse_file(src).expect_err("unquoted Norway token must be rejected");
        assert!(
            matches!(err, FkcError::NorwayToken { ref token, .. } if token == "no"),
            "got {err:?}"
        );
    }

    #[test]
    fn quoted_norway_token_is_accepted_as_string() {
        // `family: "none"` (quoted) must NOT trip the Norway check and must
        // deserialize to the string "none".
        let src = "\
---
fkc_version: 1
provider:
  name: p
  backend: Cpu
  kernel_source: \"c\"
---

## demo

b

```fkc
kernel: demo
accept:
  inputs:
    - name: lhs
      dtypes: [F32]
      fdx:
        quant:
          family: \"none\"
```
";
        let file = parse_file(src).expect("quoted token parses");
        let fam = file.kernels[0].accept.as_ref().unwrap().inputs[0]
            .fdx
            .as_ref()
            .unwrap()
            .quant
            .as_ref()
            .unwrap()
            .family
            .as_deref();
        assert_eq!(fam, Some("none"));
    }

    // =====================================================================
    // §3.1 fenced-block anatomy
    // =====================================================================

    #[test]
    fn missing_fkc_block_is_rejected() {
        let src = "\
---
fkc_version: 1
provider:
  name: p
  backend: Cpu
  kernel_source: \"c\"
---

## demo

Just prose, no fkc block.
";
        let err = parse_file(src).expect_err("section with no fkc block must error");
        assert!(
            matches!(err, FkcError::MissingFkcBlock { ref section } if section == "demo"),
            "got {err:?}"
        );
    }

    #[test]
    fn duplicate_fkc_block_is_rejected() {
        let src = "\
---
fkc_version: 1
provider:
  name: p
  backend: Cpu
  kernel_source: \"c\"
---

## demo

b

```fkc
kernel: demo
```

more prose

```fkc
kernel: demo2
```
";
        let err = parse_file(src).expect_err("section with two fkc blocks must error");
        assert!(
            matches!(err, FkcError::MultipleFkcBlocks { ref section, count } if section == "demo" && count == 2),
            "got {err:?}"
        );
    }

    #[test]
    fn missing_front_matter_is_rejected() {
        let src = "## demo\n\n```fkc\nkernel: demo\n```\n";
        let err = parse_file(src).expect_err("file without front-matter must error");
        assert!(
            matches!(err, FkcError::MalformedFrontMatter(_)),
            "got {err:?}"
        );
    }

    // =====================================================================
    // §3.1 orphan ```fkc block (outside any `## ` section) — a silent no-op
    // import bug: `split_sections` drops everything before the first `## `
    // heading, so a block placed there vanished with `Ok(FkcFile { kernels:
    // [] })` instead of a typed error.
    // =====================================================================

    #[test]
    fn orphan_fkc_block_outside_a_section_is_rejected() {
        // A fkc block under only an H1, no `## ` heading — today silently dropped.
        let src = "---\nfkc_version: 1\nprovider:\n  name: p\n  backend: Cpu\n  kernel_source: \"ks\"\n---\n\n# Title\n\n```fkc\nkernel: add_f32\nop_kind: AddElementwise\n```\n";
        let err = parse_file(src).expect_err(
            "an fkc block outside any `## ` section must be rejected, not silently dropped",
        );
        assert!(
            matches!(err, FkcError::OrphanFkcBlock { .. }),
            "got {err:?}"
        );
    }

    #[test]
    fn fkc_block_with_no_sections_at_all_is_rejected() {
        let src = "---\nfkc_version: 1\nprovider:\n  name: p\n  backend: Cpu\n  kernel_source: \"ks\"\n---\n\n```fkc\nkernel: add_f32\nop_kind: AddElementwise\n```\n";
        assert!(matches!(
            parse_file(src).unwrap_err(),
            FkcError::OrphanFkcBlock { .. }
        ));
    }

    #[test]
    fn non_fkc_fence_before_first_heading_is_not_flagged() {
        // A yaml doc example in the intro prose must NOT trigger the orphan check.
        let src = "---\nfkc_version: 1\nprovider:\n  name: p\n  backend: Cpu\n  kernel_source: \"ks\"\n---\n\n# Title\n\n```yaml\nexample: true\n```\n\n## add_f32\n\n```fkc\nkernel: add_f32\nop_kind: AddElementwise\n```\n";
        parse_file(src).expect("a non-fkc intro fence + a real section parses fine");
    }

    #[test]
    fn indented_pseudo_heading_does_not_hide_a_following_orphan_fkc_block() {
        // An indented `  ## foo` is NOT a real heading to split_sections (column-0
        // only), so a ```fkc block after it is still an orphan and must be rejected —
        // the detector must not treat the indented line as "a section started".
        let src = "---\nfkc_version: 1\nprovider:\n  name: p\n  backend: Cpu\n  kernel_source: \"ks\"\n---\n\n# Title\n\n  ## not-a-real-heading (indented)\n\n```fkc\nkernel: add_f32\nop_kind: AddElementwise\n```\n";
        let err = parse_file(src)
            .expect_err("an indented pseudo-heading must not hide a following orphan fkc block");
        assert!(
            matches!(err, FkcError::OrphanFkcBlock { .. }),
            "got {err:?}"
        );
    }
}