Skip to main content

fuel_dispatch/fkc/
mod.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! # FKC kernel-contract importer (`fkc`)
3//!
4//! The Fuel Kernel Contract (FKC) importer: parse a provider's markdown
5//! contract file(s) and (eventually) auto-register every described kernel onto
6//! Fuel's dispatch surface (`KernelBindingTable` / `FusedKernelRegistry`) with
7//! zero hand-written registration glue.
8//!
9//! This module is unconditional production infrastructure (`pub mod fkc` in
10//! lib.rs, no feature gate; the `fkc` feature was removed in bd757464).
11//!
12//! ## Status — first slice
13//!
14//! Implemented here: the module skeleton, the [`FkcError`] type, the serde
15//! schema structs mirroring FKC §3.1 / §3.2 / §3.3, and the markdown +
16//! restricted-YAML parser ([`parse_file`] / [`parse_path`]) that:
17//! - splits the file-level `---` front-matter (§3.1),
18//! - extracts each `## ` section's single ` ```fkc ` block (§3.1),
19//! - enforces the §3.8 restricted YAML subset (tabs / anchors / aliases /
20//!   merge keys / the Norway problem) BEFORE deserializing, then
21//! - deserializes each block into the schema and assembles an [`FkcFile`].
22//!
23//! Also implemented: lowering to dispatch types (`lower.rs`), caps/cost/
24//! precision projection, the `LinkRegistry`, the revision hash, and — this
25//! slice — the END-TO-END registration path (`register.rs`):
26//! [`import_bundle_str`] / [`import_bundle`] / [`import_glob`] →
27//! [`ImportedProvider`] → [`ImportedProvider::register_into`] populating
28//! both the `KernelBindingTable` (primitives) and the
29//! `FusedKernelRegistry` (fused ops), with the duplicate-detection
30//! `finalize` gate surfaced as [`FkcError::DuplicateKernelRef`].
31//!
32//! NOT yet implemented (later slices of the plan): the cost trampoline /
33//! global cost-table (imported costs use the Judge-bootstrapped sentinel
34//! `CostFn` for now), the full `V-FKC-*` validators, and the CI lint.
35//!
36//! ## Authoritative references
37//!
38//! - Format spec: `docs/specs/kernel-contract-format.md`.
39//! - Adoption plan: `docs/session-prompts/kernel-contract-adoption-plan.md`.
40//! - Authored corpus (valid instances): `fuel-dispatch/kernel-contracts/**/*.fkc.md`.
41
42mod caps_map;
43pub(crate) mod cost_compile;
44pub(crate) mod cost_expr;
45mod cpu_link;
46mod error;
47mod lower;
48mod parse;
49mod precision;
50mod register;
51mod return_check;
52mod revhash;
53mod schema;
54mod shape_constraint;
55// pub: the §6.20 shape-expression wire codec + evaluator is public interop
56// surface (byte-matches the KISS reference, golden-verified) — its decoder is
57// the reserved-tag decline point / future extension-registry activation point,
58// live API rather than crate-internal plumbing.
59pub mod shape_expr;
60pub(crate) mod shape_expr_parse;
61mod validate;
62// pub(crate): jit_ingest.rs (outside this module tree) reaches LedgerRecord
63// via crate::fkc::verify::LedgerRecord for RejectionReport::ledger_record.
64pub(crate) mod verify;
65// Contract-maintenance tooling for the `audited:` attestation (GAP-228).
66// OUTSIDE `verify/` on purpose: it writes `.fkc.md` files, and `verify/`'s
67// single-writer gate scans that directory for any write call. See its docs.
68// Tests exercise its guards; the `dev-tools` binary drives its two GAP-228 tools.
69#[cfg(any(test, feature = "dev-tools"))]
70pub(crate) mod contract_audit_flip;
71mod warn;
72
73pub use caps_map::{ResolvedLayout, Tri, is_generic_contract};
74pub use cost_expr::{
75    CompiledCostExpr, CostEvalError, CostNode, bind_cost_symbols, cost_estimate, eval as eval_cost,
76};
77pub use cpu_link::{
78    CPU_AFFINE_CLAMP_POWI_ENTRY_POINTS, CPU_ATTENTION_ENTRY_POINTS, CPU_BINARY_ENTRY_POINTS,
79    CPU_COMPARE_ENTRY_POINTS, CPU_CONV_ENTRY_POINTS, CPU_FUSED_CONV_ROPE_ENTRY_POINTS,
80    CPU_FUSED_LINEAR_QUANT_ENTRY_POINTS, CPU_FUSED_NORM_ENTRY_POINTS, CPU_INPLACE_ENTRY_POINTS,
81    CPU_MATMUL_ENTRY_POINTS, CPU_NORM_BACKWARD_ENTRY_POINTS, CPU_NORM_ENTRY_POINTS,
82    CPU_PADDING_ENTRY_POINTS, CPU_REDUCE_ENTRY_POINTS, CPU_REDUCE_TO_ENTRY_POINTS,
83    CPU_ROPE_ENTRY_POINTS, CPU_SHAPE_OPS_ENTRY_POINTS, CPU_SSM_ENTRY_POINTS,
84    CPU_UNARY_ENTRY_POINTS, CPU_WHERE_ENTRY_POINTS, CpuLinkRegistry,
85};
86pub use error::FkcError;
87pub use lower::{LinkRegistry, Resolved, ResolvedFused, ResolvedPrimitive, lower_file};
88pub use parse::{parse_file, parse_path};
89pub use register::{
90    ImportedProvider, fused_unknown_cost, import_bundle, import_bundle_str, import_glob,
91};
92pub use revhash::compute_revision;
93pub use schema::{
94    AcceptBlock, CapsBlock, CostBlock, CostMemory, FdxSpec, FkcFile, FkcFrontMatter, FkcKernel,
95    FkcProvider, GatherSpec, LayoutSpec, OpParamFieldSpec, OpParamsSchema, OutputDesc,
96    PrecisionBlock, QuantSpec, ReturnBlock, TensorDesc,
97};
98pub use shape_constraint::{
99    AxisIndex, ProbeCombo, RankSpec, ShapeAtom, ShapeConstraint, parse_rank_spec,
100    parse_shape_constraint, solve_probe_shapes,
101};
102pub use validate::{FKC_SUPPORTED_VERSIONS, validate_file, validate_kernel};
103pub use warn::ImportWarning;
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    // ----- Real-contract corpus paths (load-bearing schema-match test) -----
110
111    /// `elementwise-binary.fkc.md` — the simplest authored CPU contract.
112    const ELEMENTWISE_BINARY: &str =
113        include_str!("../../kernel-contracts/cpu/elementwise-binary.fkc.md");
114    /// `quant-matmul.fkc.md` — a more complex authored CPU contract (GGML quant
115    /// weight matmuls + NF4 with a separate scale operand, gemm cost class,
116    /// fdx.quant blocks).
117    const QUANT_MATMUL: &str = include_str!("../../kernel-contracts/cpu/quant-matmul.fkc.md");
118    /// `rope-apply.fkc.md` (Task 4.6) — baracuda's `rope_apply_<dt>_run`,
119    /// shipped but never wired into any dispatch path before this task. Its
120    /// `entry_point` names raw baracuda FFI symbols resolved only by a
121    /// harness-local `LinkRegistry` (`fuel-dispatch/src/fkc/verify/
122    /// harness.rs`, `#[cfg(feature = "cuda")]`), so it can only be
123    /// `import_bundle_str`'d for real under `--features cuda`. What CAN run
124    /// here, in the default build: parse + validate + lower against a STUB
125    /// registry (below) that resolves only the four EXACT expected
126    /// symbols — proof the contract is structurally well-formed (dtype-fan,
127    /// entry_point suffixing, per-operand fixed-vs-varying dtypes) without
128    /// touching any real CUDA code.
129    const ROPE_APPLY: &str = include_str!("../../kernel-contracts/cuda/rope-apply.fkc.md");
130
131    // =====================================================================
132    // PARSE A REAL CONTRACT — the key correctness test (§3.1/§3.3 schema match)
133    // =====================================================================
134
135    #[test]
136    fn parses_real_elementwise_binary_contract() {
137        let file =
138            parse_file(ELEMENTWISE_BINARY).expect("authored elementwise-binary.fkc.md must parse");
139
140        // Front-matter.
141        assert_eq!(file.front_matter.fkc_version, 1);
142        assert_eq!(file.front_matter.provider.name, "fuel-cpu-backend");
143        assert_eq!(file.front_matter.provider.backend, "Cpu");
144        assert_eq!(file.front_matter.provider.kernel_source, "portable-cpu");
145        assert_eq!(
146            file.front_matter.provider.link_registry.as_deref(),
147            Some("fuel_cpu_backend::fkc::ENTRY_POINTS")
148        );
149
150        // Non-empty kernels.
151        assert!(
152            !file.kernels.is_empty(),
153            "elementwise-binary must yield kernels"
154        );
155
156        // The umbrella `binary` chassis section + per-(op, dtype) thunks.
157        let names: Vec<&str> = file.kernels.iter().map(|k| k.kernel.as_str()).collect();
158        assert!(
159            names.contains(&"binary"),
160            "expected the `binary` chassis section; got {names:?}"
161        );
162        assert!(
163            names.contains(&"add_f32"),
164            "expected `add_f32`; got {names:?}"
165        );
166
167        // op_kind round-trips as a string; fused_op absent for these primitives.
168        let add_f32 = file
169            .kernels
170            .iter()
171            .find(|k| k.kernel == "add_f32")
172            .expect("add_f32 present");
173        assert_eq!(add_f32.op_kind.as_deref(), Some("AddElementwise"));
174        assert!(add_f32.fused_op.is_none());
175
176        // Accept block: two inputs (lhs, rhs), dtypes parsed as strings.
177        let accept = add_f32.accept.as_ref().expect("add_f32 has accept");
178        assert_eq!(accept.inputs.len(), 2);
179        assert_eq!(accept.inputs[0].name.as_deref(), Some("lhs"));
180        assert_eq!(accept.inputs[0].dtypes, vec!["F32".to_string()]);
181        // Layout five-flag set parsed.
182        let layout = accept.inputs[0].layout.as_ref().expect("lhs has layout");
183        assert_eq!(layout.contiguous.as_deref(), Some("required"));
184        assert_eq!(layout.strided.as_deref(), Some("rejected"));
185
186        // Return block: one output with rules carried as strings.
187        let ret = add_f32.return_.as_ref().expect("add_f32 has return");
188        assert_eq!(ret.outputs.len(), 1);
189        assert_eq!(
190            ret.outputs[0].dtype_rule.as_deref(),
191            Some("passthrough(lhs)")
192        );
193
194        // Cost: provenance + expression strings carried verbatim.
195        let cost = add_f32.cost.as_ref().expect("add_f32 has cost");
196        assert_eq!(cost.provenance.as_deref(), Some("judge_measured"));
197        assert_eq!(cost.flops.as_deref(), Some("n"));
198        assert_eq!(cost.bytes_moved.as_deref(), Some("3 * n * 4"));
199
200        // Determinism token.
201        assert_eq!(
202            add_f32.determinism.as_deref(),
203            Some("same_hardware_bitwise")
204        );
205    }
206
207    #[test]
208    fn parses_real_quant_matmul_contract() {
209        let file = parse_file(QUANT_MATMUL).expect("authored quant-matmul.fkc.md must parse");
210
211        assert_eq!(file.front_matter.provider.name, "fuel-cpu-backend");
212        assert!(!file.kernels.is_empty());
213
214        let names: Vec<&str> = file.kernels.iter().map(|k| k.kernel.as_str()).collect();
215        assert!(
216            names.contains(&"qmatmul_q4_0_f32"),
217            "expected qmatmul_q4_0_f32; got {names:?}"
218        );
219        assert!(
220            names.contains(&"nf4_matmul_f32"),
221            "expected nf4_matmul_f32; got {names:?}"
222        );
223
224        // A GGML quant weight operand: family/ggml_dtype parsed as strings,
225        // scale_operand stays None (INLINE single-place rule).
226        let q40 = file
227            .kernels
228            .iter()
229            .find(|k| k.kernel == "qmatmul_q4_0_f32")
230            .unwrap();
231        assert_eq!(q40.op_kind.as_deref(), Some("QMatMul"));
232        let weight = q40
233            .accept
234            .as_ref()
235            .unwrap()
236            .inputs
237            .iter()
238            .find(|d| d.name.as_deref() == Some("weight"))
239            .expect("q4_0 has a weight operand");
240        let quant = weight
241            .fdx
242            .as_ref()
243            .unwrap()
244            .quant
245            .as_ref()
246            .expect("weight has fdx.quant");
247        assert_eq!(quant.family.as_deref(), Some("GGML_BLOCK"));
248        assert_eq!(quant.ggml_dtype.as_deref(), Some("Q4_0"));
249        assert_eq!(quant.role.as_deref(), Some("weight"));
250        assert!(
251            quant.scale_operand.is_none(),
252            "INLINE scale: no separate operand"
253        );
254
255        // op_params variant + a field with a constraint string.
256        let op_params = q40.accept.as_ref().unwrap().op_params.as_ref().unwrap();
257        assert_eq!(op_params.variant.as_deref(), Some("QMatMul"));
258        assert!(op_params.fields.contains_key("k"));
259
260        // NF4: the absmax is a SEPARATE scale operand (single-place rule).
261        let nf4 = file
262            .kernels
263            .iter()
264            .find(|k| k.kernel == "nf4_matmul_f32")
265            .unwrap();
266        let nf4_inputs = &nf4.accept.as_ref().unwrap().inputs;
267        assert!(
268            nf4_inputs
269                .iter()
270                .any(|d| d.name.as_deref() == Some("absmax")),
271            "NF4 has a separate absmax operand"
272        );
273        let w_packed = nf4_inputs
274            .iter()
275            .find(|d| d.name.as_deref() == Some("w_packed"))
276            .unwrap();
277        let nf4_quant = w_packed.fdx.as_ref().unwrap().quant.as_ref().unwrap();
278        assert_eq!(nf4_quant.family.as_deref(), Some("AFFINE_BLOCK"));
279        assert_eq!(nf4_quant.scale_operand.as_deref(), Some("absmax"));
280    }
281
282    /// Task 4.6 — the rope-apply CUDA acceptance-kernel contract must
283    /// parse, pass the `V-FKC-*` validators, and LOWER structurally
284    /// correctly, all WITHOUT the `cuda` feature (a stub registry stands
285    /// in for the real link, matching `lower.rs`'s own `StubLink`
286    /// precedent). This is the default-feature verification the Task 4.6
287    /// brief explicitly permits in lieu of a real `--features cuda` import.
288    #[test]
289    fn parses_and_lowers_real_rope_apply_contract() {
290        use fuel_ir::DType;
291        use fuel_ir::dispatch::OpKind;
292        use fuel_ir::probe::BackendId;
293
294        let file = parse_file(ROPE_APPLY).expect("rope-apply.fkc.md must parse");
295        validate_file(&file).expect("rope-apply.fkc.md must pass the V-FKC-* validators");
296
297        assert_eq!(file.front_matter.provider.name, "fuel-cuda-backend");
298        assert_eq!(file.front_matter.provider.backend, "Cuda");
299        assert_eq!(file.front_matter.provider.kernel_source, "baracuda");
300
301        let names: Vec<&str> = file.kernels.iter().map(|k| k.kernel.as_str()).collect();
302        assert!(
303            names.contains(&"rope_apply"),
304            "expected a `rope_apply` section; got {names:?}"
305        );
306
307        let kernel = file
308            .kernels
309            .iter()
310            .find(|k| k.kernel == "rope_apply")
311            .unwrap();
312        assert_eq!(kernel.op_kind.as_deref(), Some("Rope"));
313        assert!(
314            kernel.fused_op.is_none(),
315            "rope_apply is a primitive op_kind contract, not fused"
316        );
317
318        // Three inputs: x (fans over the 4 dtypes), cos + sin (fixed F32 each,
319        // per baracuda's ABI — see the contract's front-matter note).
320        let accept = kernel.accept.as_ref().expect("rope_apply has accept");
321        assert_eq!(accept.inputs.len(), 3);
322        assert_eq!(accept.inputs[0].name.as_deref(), Some("x"));
323        assert_eq!(
324            accept.inputs[0].dtypes,
325            vec![
326                "F32".to_string(),
327                "F16".to_string(),
328                "BF16".to_string(),
329                "F64".to_string()
330            ],
331        );
332        assert_eq!(accept.inputs[1].name.as_deref(), Some("cos"));
333        assert_eq!(accept.inputs[1].dtypes, vec!["F32".to_string()]);
334        assert_eq!(accept.inputs[2].name.as_deref(), Some("sin"));
335        assert_eq!(accept.inputs[2].dtypes, vec!["F32".to_string()]);
336
337        // Lower against a stub that resolves ONLY the four raw baracuda symbols
338        // this contract's base entry_point ("baracuda_kernels_rope_apply") fans
339        // into — a wrong suffix, or a missing/extra variant, fails this.
340        fn dummy_kernel(
341            _inputs: &[std::sync::Arc<std::sync::RwLock<fuel_memory::Storage>>],
342            _outputs: &mut [std::sync::Arc<std::sync::RwLock<fuel_memory::Storage>>],
343            _layouts: &[fuel_ir::Layout],
344            _params: &crate::kernel::OpParams,
345        ) -> fuel_ir::Result<()> {
346            Ok(())
347        }
348        struct StubRopeApplyLink;
349        impl LinkRegistry for StubRopeApplyLink {
350            fn resolve_primitive(&self, symbol: &str) -> Option<crate::kernel::KernelRef> {
351                const KNOWN: &[&str] = &[
352                    "baracuda_kernels_rope_apply_f32",
353                    "baracuda_kernels_rope_apply_f16",
354                    "baracuda_kernels_rope_apply_bf16",
355                    "baracuda_kernels_rope_apply_f64",
356                ];
357                if KNOWN.contains(&symbol) {
358                    Some(dummy_kernel)
359                } else {
360                    None
361                }
362            }
363            fn resolve_fused(&self, _symbol: &str) -> Option<crate::kernel::KernelRef> {
364                None
365            }
366        }
367
368        let mut warnings = Vec::new();
369        let resolved = lower_file(&file, &StubRopeApplyLink, &mut warnings)
370            .expect("rope-apply.fkc.md must lower against a registry resolving its 4 real symbols");
371        let primitives: Vec<_> = resolved
372            .iter()
373            .filter_map(|r| match r {
374                Resolved::Primitive(p) => Some(p),
375                Resolved::Fused(_) => None,
376            })
377            .collect();
378        assert_eq!(
379            primitives.len(),
380            4,
381            "expected 4 dtype variants (F32/F16/BF16/F64); got {}",
382            primitives.len(),
383        );
384        for p in &primitives {
385            assert_eq!(p.op, OpKind::Rope);
386            assert_eq!(p.backend, BackendId::Cuda);
387            // Per-variant key: [x_dt, F32(cos), F32(sin), x_dt(out, passthrough)].
388            assert_eq!(
389                p.dtypes.len(),
390                4,
391                "expected [x, cos, sin, out] key; got {:?}",
392                p.dtypes
393            );
394            assert_eq!(p.dtypes[1], DType::F32, "cos is always F32");
395            assert_eq!(p.dtypes[2], DType::F32, "sin is always F32");
396            assert_eq!(
397                p.dtypes[0], p.dtypes[3],
398                "output passthrough(x) must match x's dtype"
399            );
400        }
401        let x_dtypes: std::collections::HashSet<DType> =
402            primitives.iter().map(|p| p.dtypes[0]).collect();
403        assert_eq!(
404            x_dtypes,
405            [DType::F32, DType::F16, DType::BF16, DType::F64]
406                .into_iter()
407                .collect(),
408            "expected exactly the F32/F16/BF16/F64 fan",
409        );
410    }
411
412    // =====================================================================
413    // §3.8 NEGATIVES
414    // =====================================================================
415
416    const VALID_MINIMAL: &str = "\
417---
418fkc_version: 1
419provider:
420  name: test-provider
421  backend: Cpu
422  kernel_source: \"test-cpu\"
423---
424
425# test bundle
426
427## demo
428
429A blurb.
430
431```fkc
432kernel: demo
433op_kind: AddElementwise
434blurb: \"demo\"
435entry_point: \"x::y\"
436```
437";
438
439    #[test]
440    fn valid_minimal_parses() {
441        let file = parse_file(VALID_MINIMAL).expect("minimal valid file parses");
442        assert_eq!(file.kernels.len(), 1);
443        assert_eq!(file.kernels[0].kernel, "demo");
444    }
445
446    #[test]
447    fn tab_indentation_in_block_is_rejected() {
448        // A tab-indented line inside the fkc block.
449        let src = "\
450---
451fkc_version: 1
452provider:
453  name: p
454  backend: Cpu
455  kernel_source: \"c\"
456---
457
458## demo
459
460b
461
462```fkc
463kernel: demo
464accept:
465\tinputs: []
466```
467";
468        let err = parse_file(src).expect_err("tab must be rejected");
469        assert!(
470            matches!(err, FkcError::TabIndentation { .. }),
471            "got {err:?}"
472        );
473    }
474
475    #[test]
476    fn anchor_is_rejected() {
477        let src = "\
478---
479fkc_version: 1
480provider:
481  name: p
482  backend: Cpu
483  kernel_source: \"c\"
484---
485
486## demo
487
488b
489
490```fkc
491kernel: &base demo
492op_kind: AddElementwise
493```
494";
495        let err = parse_file(src).expect_err("anchor must be rejected");
496        assert!(
497            matches!(err, FkcError::AnchorDisallowed { .. }),
498            "got {err:?}"
499        );
500    }
501
502    #[test]
503    fn alias_is_rejected() {
504        let src = "\
505---
506fkc_version: 1
507provider:
508  name: p
509  backend: Cpu
510  kernel_source: \"c\"
511---
512
513## demo
514
515b
516
517```fkc
518kernel: demo
519blurb: *base
520```
521";
522        let err = parse_file(src).expect_err("alias must be rejected");
523        assert!(
524            matches!(err, FkcError::AliasDisallowed { .. }),
525            "got {err:?}"
526        );
527    }
528
529    #[test]
530    fn merge_key_is_rejected() {
531        let src = "\
532---
533fkc_version: 1
534provider:
535  name: p
536  backend: Cpu
537  kernel_source: \"c\"
538---
539
540## demo
541
542b
543
544```fkc
545kernel: demo
546caps:
547  <<: defaults
548```
549";
550        let err = parse_file(src).expect_err("merge key must be rejected");
551        assert!(
552            matches!(err, FkcError::MergeKeyDisallowed { .. }),
553            "got {err:?}"
554        );
555    }
556
557    #[test]
558    fn unquoted_norway_token_is_rejected() {
559        // `family: no` unquoted, in a value position — must be flagged, never
560        // silently coerced to a bool.
561        let src = "\
562---
563fkc_version: 1
564provider:
565  name: p
566  backend: Cpu
567  kernel_source: \"c\"
568---
569
570## demo
571
572b
573
574```fkc
575kernel: demo
576family: no
577```
578";
579        let err = parse_file(src).expect_err("unquoted Norway token must be rejected");
580        assert!(
581            matches!(err, FkcError::NorwayToken { ref token, .. } if token == "no"),
582            "got {err:?}"
583        );
584    }
585
586    #[test]
587    fn quoted_norway_token_is_accepted_as_string() {
588        // `family: "none"` (quoted) must NOT trip the Norway check and must
589        // deserialize to the string "none".
590        let src = "\
591---
592fkc_version: 1
593provider:
594  name: p
595  backend: Cpu
596  kernel_source: \"c\"
597---
598
599## demo
600
601b
602
603```fkc
604kernel: demo
605accept:
606  inputs:
607    - name: lhs
608      dtypes: [F32]
609      fdx:
610        quant:
611          family: \"none\"
612```
613";
614        let file = parse_file(src).expect("quoted token parses");
615        let fam = file.kernels[0].accept.as_ref().unwrap().inputs[0]
616            .fdx
617            .as_ref()
618            .unwrap()
619            .quant
620            .as_ref()
621            .unwrap()
622            .family
623            .as_deref();
624        assert_eq!(fam, Some("none"));
625    }
626
627    // =====================================================================
628    // §3.1 fenced-block anatomy
629    // =====================================================================
630
631    #[test]
632    fn missing_fkc_block_is_rejected() {
633        let src = "\
634---
635fkc_version: 1
636provider:
637  name: p
638  backend: Cpu
639  kernel_source: \"c\"
640---
641
642## demo
643
644Just prose, no fkc block.
645";
646        let err = parse_file(src).expect_err("section with no fkc block must error");
647        assert!(
648            matches!(err, FkcError::MissingFkcBlock { ref section } if section == "demo"),
649            "got {err:?}"
650        );
651    }
652
653    #[test]
654    fn duplicate_fkc_block_is_rejected() {
655        let src = "\
656---
657fkc_version: 1
658provider:
659  name: p
660  backend: Cpu
661  kernel_source: \"c\"
662---
663
664## demo
665
666b
667
668```fkc
669kernel: demo
670```
671
672more prose
673
674```fkc
675kernel: demo2
676```
677";
678        let err = parse_file(src).expect_err("section with two fkc blocks must error");
679        assert!(
680            matches!(err, FkcError::MultipleFkcBlocks { ref section, count } if section == "demo" && count == 2),
681            "got {err:?}"
682        );
683    }
684
685    #[test]
686    fn missing_front_matter_is_rejected() {
687        let src = "## demo\n\n```fkc\nkernel: demo\n```\n";
688        let err = parse_file(src).expect_err("file without front-matter must error");
689        assert!(
690            matches!(err, FkcError::MalformedFrontMatter(_)),
691            "got {err:?}"
692        );
693    }
694
695    // =====================================================================
696    // §3.1 orphan ```fkc block (outside any `## ` section) — a silent no-op
697    // import bug: `split_sections` drops everything before the first `## `
698    // heading, so a block placed there vanished with `Ok(FkcFile { kernels:
699    // [] })` instead of a typed error.
700    // =====================================================================
701
702    #[test]
703    fn orphan_fkc_block_outside_a_section_is_rejected() {
704        // A fkc block under only an H1, no `## ` heading — today silently dropped.
705        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";
706        let err = parse_file(src).expect_err(
707            "an fkc block outside any `## ` section must be rejected, not silently dropped",
708        );
709        assert!(
710            matches!(err, FkcError::OrphanFkcBlock { .. }),
711            "got {err:?}"
712        );
713    }
714
715    #[test]
716    fn fkc_block_with_no_sections_at_all_is_rejected() {
717        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";
718        assert!(matches!(
719            parse_file(src).unwrap_err(),
720            FkcError::OrphanFkcBlock { .. }
721        ));
722    }
723
724    #[test]
725    fn non_fkc_fence_before_first_heading_is_not_flagged() {
726        // A yaml doc example in the intro prose must NOT trigger the orphan check.
727        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";
728        parse_file(src).expect("a non-fkc intro fence + a real section parses fine");
729    }
730
731    #[test]
732    fn indented_pseudo_heading_does_not_hide_a_following_orphan_fkc_block() {
733        // An indented `  ## foo` is NOT a real heading to split_sections (column-0
734        // only), so a ```fkc block after it is still an orphan and must be rejected —
735        // the detector must not treat the indented line as "a section started".
736        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";
737        let err = parse_file(src)
738            .expect_err("an indented pseudo-heading must not hide a following orphan fkc block");
739        assert!(
740            matches!(err, FkcError::OrphanFkcBlock { .. }),
741            "got {err:?}"
742        );
743    }
744}