fuel-dispatch 0.20.0

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
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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
// SPDX-License-Identifier: MIT OR Apache-2.0
//! §5 return-contract validation: cross-check a fused contract's declared
//! shape/dtype rules against the real registered FusedOpEntry fns.
use crate::fkc::ImportWarning;
use crate::fkc::error::FkcError;
use crate::fkc::lower::lower_dtype;
use crate::fkc::schema::FkcKernel;
use crate::fkc::shape_constraint::solve_probe_shapes;
use fuel_graph::registry::{FusedOpId, FusedOpParams, default_registry};
use fuel_ir::{DType, Shape};

pub type ProbeComboRef<'a> = &'a [(String, Shape, DType)];

fn role<'a>(combo: ProbeComboRef<'a>, name: &str) -> Option<&'a (String, Shape, DType)> {
    combo.iter().find(|(r, _, _)| r == name)
}
fn inner<'a>(rule: &'a str, head: &str) -> Option<&'a str> {
    rule.trim()
        .strip_prefix(head)?
        .strip_suffix(')')
        .map(str::trim)
}

/// §5.1: `fixed(D)` and `passthrough(role)` are evaluable; every other token is
/// `Ok(None)` = not-evaluable (skip, never a false reject). `fixed(<bad dtype>)`
/// is a hard error (a real authoring bug).
pub fn eval_dtype_rule(
    rule: &str,
    combo: ProbeComboRef,
    section: &str,
) -> Result<Option<DType>, FkcError> {
    if let Some(tok) = inner(rule, "fixed(") {
        return Ok(Some(lower_dtype(tok, section, "return")?));
    }
    if let Some(r) = inner(rule, "passthrough(") {
        return Ok(role(combo, r).map(|(_, _, d)| *d));
    }
    Ok(None)
}
/// §5.2: `same_as(role)` yields the operand's whole shape; a `DimExpr` string
/// (`extent(role,axis)` / `const(N)` / `param(N)` / `add|sub|mul|div(a,b)`) evaluates to a
/// single-dim shape via the shape-expr oracle (§6.20). `params` carries the op's
/// flattened param values for `param(N)` — index order pinned to
/// `FusedOpParams::key().ints` (the C-4 threading convention); an EMPTY slice
/// declines every `param(N)` rule (`ParamOutOfRange` → skip), preserving the
/// pre-threading behavior for callers with no synthesized values. Every other
/// token, a surfaced gap, or a decline on a recognized DimExpr → `Ok(None)`
/// (not-evaluable; never a false reject).
pub fn eval_shape_rule(
    rule: &str,
    combo: ProbeComboRef,
    params: &[i64],
    _section: &str,
) -> Result<Option<Shape>, FkcError> {
    let rule = rule.trim();
    if let Some(r) = inner(rule, "same_as(") {
        return Ok(role(combo, r).map(|(_, s, _)| s.clone()));
    }
    // §6.20-0008 role-woven `matmul(role_a, role_b)`: a WHOLE-shape rule (the
    // contraction output is multi-dim, so it returns a `Shape` directly — NOT the
    // single-dim `DimExpr` path). Resolve the two roles to operand shapes and
    // derive `[..batch, M, N]` via the shipped shape-expr oracle. §4 guardrail:
    // computed from the operand shapes + M/N/K role structure, never from decompose.
    if rule.starts_with("matmul(") {
        let Some((lhs, rhs)) = crate::fkc::shape_expr_parse::parse_matmul_operands(rule, combo)
        else {
            return Ok(None);
        };
        // Never-panic + §4 guard: `matmul_shape` indexes `lhs[r-2]` and `rhs[r-1]`
        // (r = lhs rank), so require both operands rank >= 2 with EQUAL rank (the
        // `fused_linear` same-rank contract). A degenerate rank or a symbolic /
        // negative extent → skip (Ok(None), never a false reject).
        if lhs.len() < 2
            || rhs.len() < 2
            || lhs.len() != rhs.len()
            || lhs.iter().chain(rhs.iter()).any(|&d| d < 0)
        {
            return Ok(None);
        }
        let out = crate::fkc::shape_expr::matmul_shape(&lhs, &rhs);
        let dims: Vec<usize> = out.iter().map(|&d| d as usize).collect();
        return Ok(Some(Shape::from_dims(&dims)));
    }
    // A DimExpr form: parse (role names → positional AST), then evaluate over the
    // combo + the caller's flattened param values (C-4 T1 threading).
    if is_dimexpr_head(rule) {
        let Some(dim) = crate::fkc::shape_expr_parse::parse_dim(rule, combo) else {
            return Ok(None);
        };
        let operands: Vec<Vec<i64>> = combo.iter().map(|(_, s, _)| shape_to_i64(s)).collect();
        return match crate::fkc::shape_expr::eval_dim(&dim, &operands, params) {
            // A DimExpr denotes a single dimension → a rank-1 output shape (d ≥ 0).
            Ok(crate::fkc::shape_expr::DimValue::Concrete(d)) if d >= 0 => {
                Ok(Some(Shape::from_dims(&[d as usize])))
            }
            // Negative dim (not a valid shape), a surfaced Gap, or a decline → skip; never a false reject.
            Ok(_) | Err(_) => Ok(None),
        };
    }
    Ok(None)
}

/// Invoke a registry rule fn (`shape_rule` / `dtype_rule` / `output_views`),
/// catching a `debug_assert`/panic so a corpus contract can never CRASH the
/// importer (never-panic on the import path). Some registry fns `debug_assert`
/// a specific input arity (e.g. `flash_attn`'s "4 or 5 inputs"); a fused
/// contract elsewhere in the corpus that declares a different operand count
/// (e.g. `metal/matmul-attn.fkc.md`'s 3-input `FLASH_ATTN`) would otherwise
/// panic when the cross-check hands the real fn a probe combo of that arity.
///
/// A caught panic is NO LONGER a SILENT skip (review Finding 1): it pushes an
/// [`ImportWarning`] naming the skipped differential, so a coverage hole is
/// visible to the importer rather than vanishing. Returns `None` (skip this
/// differential for this combo) on a caught panic; `Some(value)` otherwise.
/// Mirrors the `catch_unwind` guard in `verify::harness`.
///
/// **Debug-vs-release residual (documented, review Finding 1).** `catch_unwind`
/// only ever fires in a DEBUG build, where the fn's `debug_assert!` is live; in
/// RELEASE that assert is stripped and the fn instead reads operand 0 and
/// returns a value, so a *panic-driven* skip is inherently build-mode-dependent
/// — a drifted contract could then pass `cargo test` yet raise a mismatch under
/// `cargo build --release`. The [`expected_min_inputs`] arity pre-check in
/// [`cross_check_fused_section`] closes that split for the listed cases (an
/// under-arity attention or Conv2D contract) by skipping BEFORE the call in BOTH
/// build modes; this guard stays the never-panic backstop for any other unforeseen
/// panic (whose skip remains debug-only — the residual this note preserves).
fn guard_rule<T>(
    warnings: &mut Vec<ImportWarning>,
    section: &str,
    what: &str,
    f: impl FnOnce() -> T,
) -> Option<T> {
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
        Ok(v) => Some(v),
        Err(_) => {
            warnings.push(ImportWarning {
                section: section.into(),
                message: format!(
                    "return cross-check: the registered {what} fn panicked on the probe combo \
                     (likely an input-arity mismatch); differential skipped for this combo \
                     (never-panic backstop — see the debug-vs-release note on guard_rule)"
                ),
            });
            None
        }
    }
}

/// The minimum input arity the registry rule fn for a synth-supported `variant`
/// requires before it safely indexes its operands. The attention family:
/// `flash_attn` / `flash_attn_backward` `debug_assert!(len == 4 || 5)` and
/// `paged_attn` `debug_assert!(len == 5 || 6)`, and a leaner corpus contract
/// can under-declare them (metal `matmul-attn.fkc.md`'s 3-input `FLASH_ATTN`
/// declares only q/k/v). C-4 T3 adds `Conv2D` (min 2): its rule fns read
/// `input_shapes[1]` (the weight) and `debug_assert!` 2-or-3 inputs, its dtype
/// differential is now params-live, and real 2-input CONV2D fused sections
/// exist (`vulkan/conv-attn-rope.fkc.md`) — so an under-declaring sibling is a
/// live authoring risk, not a hypothetical. For every other synth variant the
/// corpus contracts match the fn's arity, so no under-arity split exists today
/// and `None` leaves the `guard_rule` catch-and-warn backstop in charge. The
/// policy: an entry is added when a REAL corpus family could under-declare it —
/// kept deliberately small + co-located with the synth fns (do NOT reach into
/// `fuel-graph/src/registry` for the arities — mirror its documented asserts).
fn expected_min_inputs(variant: Option<&str>) -> Option<usize> {
    match variant {
        Some("FlashAttn") | Some("FlashAttnBackward") => Some(4),
        Some("PagedAttn") => Some(5),
        Some("Conv2D") => Some(2),
        _ => None,
    }
}

/// Make twin-rank operands observably distinct for the bundle differential
/// (review Finding 3): the §3.5 solver seeds same-rank operands identically
/// (e.g. `selective_scan`'s `u [B,L,dim]` and `b [B,L,dstate]` both seed to the
/// same probe shape), so a slot rule that drifts to a DIFFERENT same-rank
/// operand (`same_as(b)` for `same_as(u)`) would evaluate EQUAL to the
/// `output_views` oracle and import clean. Bump each operand's leading axis by
/// its position (operand 0 unchanged) so twin-rank operands diverge. dim0 is the
/// batch axis for every bundle-bearing fused op (`selective_scan` /
/// `ssd_chunk_scan`) and is passed straight through to each output slot, so
/// distinguishing operands here never perturbs the oracle's slot geometry — it
/// only lets an operand-role drift in a slot rule diverge from the reference.
fn distinct_role_probe(combo: ProbeComboRef) -> Vec<(String, Shape, DType)> {
    combo
        .iter()
        .enumerate()
        .map(|(i, (role, shape, dt))| {
            let mut dims: Vec<usize> = shape.dims().to_vec();
            if let Some(d0) = dims.first_mut() {
                *d0 += i; // operand 0 unchanged; each later operand distinct on dim0
            }
            (role.clone(), Shape::from_dims(&dims), *dt)
        })
        .collect()
}

/// True iff `variant` is one of the params-DEPENDENT variants
/// [`synth_probe_param_points`] knows how to synthesize — kept in lockstep
/// with its match arms (pinned by
/// `synth_param_points_distinguish_every_ints_slot_pair`, which iterates the
/// same list). Used by the cross-check to distinguish "no points because the
/// variant is out of synth scope" (a documented skip — e.g. Nf4Matmul,
/// double-gated on FDX AFFINE_BLOCK) from "no points because the probe combo
/// was unreadable by the shape-coupled derivation" — the latter is a
/// coverage hole that must WARN, not vanish (review fix; the same
/// no-silent-skip norm `guard_rule` follows).
fn is_params_dependent_synth_variant(variant: Option<&str>) -> bool {
    matches!(
        variant,
        Some(
            "Conv2D" | "ConvTranspose2D" | "QMatMul" | "FusedSoftmaxCrossEntropy" | "CausalConv1d"
        )
    )
}

/// True iff `rule` starts with a recognized `DimExpr` constructor head.
fn is_dimexpr_head(rule: &str) -> bool {
    const HEADS: &[&str] = &[
        "extent(", "const(", "param(", "add(", "sub(", "mul(", "div(",
    ];
    HEADS.iter().any(|h| rule.starts_with(h))
}

/// Widen a `fuel_ir::Shape`'s concrete `usize` extents to `i64` for the evaluator. Probe
/// shapes are concrete (no symbolic sentinel arises on this path — see the C-1 Task-4 note).
fn shape_to_i64(s: &Shape) -> Vec<i64> {
    s.dims().iter().map(|&d| d as i64).collect()
}

/// Synthesize the `FusedOpParams` variant NAMED by the contract's
/// `op_params.variant` (§3.7), with placeholder field values, for the
/// params-INDEPENDENT fused ops (their rule fns ignore the field values).
/// The ONLY correctness requirement is that the returned variant matches the
/// name so the real registered `shape_rule` fn never hits its wrong-params
/// panic (`qmatmul.rs:63`, `conv2d.rs:86`). Division of labor (C-4): a
/// params-DEPENDENT variant (Conv2D / ConvTranspose2D / QMatMul / FSCE /
/// CausalConv1d) returns `None` HERE — its real, per-combo param POINTS come
/// from [`synth_probe_param_points`] instead, and the cross-check loops over
/// those. An op in NEITHER synth fn (e.g. Nf4Matmul, double-gated on FDX
/// AFFINE_BLOCK) is a skipped differential — never a foreign variant, never
/// a panic.
pub fn synth_probe_params(variant: Option<&str>) -> Result<Option<FusedOpParams>, FkcError> {
    const EPS: f64 = 1e-5;
    Ok(match variant {
        Some("SoftmaxLastDim") => Some(FusedOpParams::SoftmaxLastDim),
        Some("SoftmaxLastDimBackward") => Some(FusedOpParams::SoftmaxLastDimBackward),
        Some("RmsNormLastDim") => Some(FusedOpParams::RmsNormLastDim { eps: EPS }),
        Some("LayerNormLastDim") => Some(FusedOpParams::LayerNormLastDim { eps: EPS }),
        Some("RmsNormLastDimBackward") => Some(FusedOpParams::RmsNormLastDimBackward { eps: EPS }),
        Some("LayerNormLastDimBackward") => {
            Some(FusedOpParams::LayerNormLastDimBackward { eps: EPS })
        }
        Some("ReduceMaxToBackward") => Some(FusedOpParams::ReduceMaxToBackward),
        Some("PowIBackward") => Some(FusedOpParams::PowIBackward { exp: 2 }),
        Some("Rope") => Some(FusedOpParams::Rope),
        Some("FusedLinear") => Some(FusedOpParams::FusedLinear),
        // Convergence-C C-3: widen synth so the shape-oracle cross-check fires
        // for the expressible attention / affine / scan fused ops. Every variant
        // added here has a params-INDEPENDENT shape rule (`same_as`/`matmul`
        // returning `input_shapes[0/1/2]`, or a bundle whose slot-0 shape is a
        // plain passthrough), so the placeholder field values below never reach a
        // params-dependent branch and the wrong-params panic stays unreachable
        // (the never-panic invariant). Field values are arbitrary valid
        // placeholders — the shape rules ignore them.
        Some("InplaceAffine") => Some(FusedOpParams::InplaceAffine { mul: 1.0, add: 0.0 }),
        Some("FlashAttn") => Some(FusedOpParams::FlashAttn {
            softmax_scale: 1.0,
            causal: false,
            window_size_left: None,
            window_size_right: None,
            softcap: None,
            k_len: None,
        }),
        Some("PagedAttn") => Some(FusedOpParams::PagedAttn {
            softmax_scale: 1.0,
            block_size: 16,
            softcap: None,
        }),
        // FLASH_ATTN_BACKWARD_{Q,K,V} share ONE `FlashAttnBackward` variant
        // (the FusedOpId distinguishes dQ/dK/dV); a single arm covers all three.
        Some("FlashAttnBackward") => Some(FusedOpParams::FlashAttnBackward {
            softmax_scale: 1.0,
            causal: false,
            window_size_left: None,
            window_size_right: None,
            softcap: None,
        }),
        Some("SelectiveScan") => Some(FusedOpParams::SelectiveScan {
            delta_softplus: false,
        }),
        Some("SsdChunkScan") => Some(FusedOpParams::SsdChunkScan { chunk_size: 1 }),
        _ => None,
    })
}

/// C-4 T2: synthesize per-variant, per-combo param POINTS for the
/// params-DEPENDENT fused ops — the variants [`synth_probe_params`]
/// deliberately returns `None` for. Each point is `(FusedOpParams, ints)`
/// where `ints` IS the params' [`FusedOpParams::key()`]`.ints` flattening
/// (by construction — the same encoding CSE keys on), so the declared-rule
/// evaluator (`param(N)` indexes `ints[N]`) and the real registry fn (which
/// receives the `FusedOpParams`) always see IDENTICAL values — consistency
/// by construction. Per-variant index tables (pinned by test + corpus prose):
///
/// - `Conv2D`                   → `[sh, sw, ph, pw, groups]` (2 points)
/// - `ConvTranspose2D`          → `[sh, sw, ph, pw, oph, opw, dh, dw, groups]` (2 points)
/// - `QMatMul`                  → `[quant_type_key, k, n]` (1 point, combo-derived)
/// - `FusedSoftmaxCrossEntropy` → `[reduction_key, ignore_index]` (2 points: None, Mean)
/// - `CausalConv1d`             → `[use_silu]` (1 point)
///
/// **Shape-coupled derivation:** fields the contract couples to operand
/// shapes derive FROM the combo — QMatMul `k = a.dims[last]`,
/// `n = w_q_bytes.dims[0]` (linear-quant.fkc.md §op_params constraints);
/// Conv2D padding derives from the weight's kernel extents so the real fn's
/// usize `(H + 2·ph − Kh)` arithmetic can never underflow (a debug-build
/// panic) — valid by construction, for ANY rank-4 probe with nonzero
/// extents. Variants with a free field get ≥ 2 DISTINCT points (the
/// sabotage-calibration norm applied to params: one point could false-green
/// a declared rule that ignores the param). The points are also
/// ORDER-ASYMMETRIC (review fix): for every pair of `key().ints` slots, at
/// least one point assigns them different values — so a length-preserving
/// slot reorder of the flattening in `fuel-graph/src/registry.rs`, or a
/// `param(i)`/`param(j)` confusion in a declared rule, cannot evaluate
/// identically at every point (pinned by
/// `synth_param_points_distinguish_every_ints_slot_pair`).
///
/// **Never-panic pin** (extends the `synth_probe_params` matching-variant
/// pin): an unknown variant, or a combo the derivation can't safely read
/// (missing operand / wrong rank / zero extent), returns EMPTY — a skipped
/// differential, never a foreign variant, never a panic.
pub fn synth_probe_param_points(
    variant: Option<&str>,
    combo: ProbeComboRef,
) -> Vec<(FusedOpParams, Vec<i64>)> {
    use fuel_graph::registry::Reduction;
    /// Pair each params value with its own `key().ints` flattening.
    fn points(params: Vec<FusedOpParams>) -> Vec<(FusedOpParams, Vec<i64>)> {
        params
            .into_iter()
            .map(|p| {
                let ints = p.key().ints;
                (p, ints)
            })
            .collect()
    }
    match variant {
        Some("Conv2D") => {
            // Positional read mirrors the real fn (`input_shapes[0]` = x,
            // `[1]` = weight; conv2d.rs shape_rule).
            let (Some((_, x, _)), Some((_, w, _))) = (combo.first(), combo.get(1)) else {
                return Vec::new();
            };
            let (xd, wd) = (x.dims(), w.dims());
            if xd.len() != 4 || wd.len() != 4 {
                return Vec::new();
            }
            let (h, w_in, kh, kw) = (xd[2], xd[3], wd[2], wd[3]);
            if h == 0 || w_in == 0 || kh == 0 || kw == 0 {
                return Vec::new();
            }
            // Padding stays SHAPE-COUPLED: any ph ≥ kh/2 keeps
            // `h + 2·ph − kh` ≥ h−1 ≥ 0 for any h ≥ 1 (larger padding only
            // grows the sum), so the real fn's usize arithmetic can never
            // underflow — valid even when the kernel exceeds the spatial
            // input. Order-asymmetry (review fix): the old points had
            // stride == padding at BOTH points ([1,1,1,1,1]/[2,2,2,2,1]), so
            // a stride<->padding reorder of the `key().ints` flattening — or
            // a param(i)/param(j) confusion in a future declared rule — was
            // invisible at every point. Point 2's ints are now pairwise
            // DISTINCT for the common odd/even kernels (e.g. 3x3 →
            // [3,4,6,7,2]), so every slot transposition is observable, and
            // the two points still differ in EVERY free field. groups is
            // unread by the real shape/dtype fns (conv2d.rs), so 1-vs-2 is
            // purely an order-asymmetry probe.
            points(vec![
                FusedOpParams::Conv2D {
                    stride: (1, 2),
                    padding: (kh / 2, kw / 2 + 3),
                    groups: 1,
                },
                FusedOpParams::Conv2D {
                    stride: (3, 4),
                    padding: (kh / 2 + 5, kw / 2 + 6),
                    groups: 2,
                },
            ])
        }
        Some("ConvTranspose2D") => points(vec![
            // Not shape-coupled: the real fn saturates (conv_transpose_2d.rs),
            // so every value is panic-safe; `output_padding < stride` holds at
            // both points (the standard validity relation). Order-asymmetry
            // (review fix): the old points had padding == output_padding and
            // dilation == groups == 1 at BOTH points, so those slot reorders
            // (and the matching param(N) confusions) were invisible. The 9
            // ints are now chosen so every slot PAIR differs at one point or
            // the other ([2,3,0,1,1,2,4,5,1] / [5,4,3,2,4,0,2,6,3]), and the
            // two points differ in EVERY field. groups only multiplies
            // `w.dims[1]` in the real shape fn — any value is panic-safe.
            FusedOpParams::ConvTranspose2D {
                stride: (2, 3),
                padding: (0, 1),
                output_padding: (1, 2),
                dilation: (4, 5),
                groups: 1,
            },
            FusedOpParams::ConvTranspose2D {
                stride: (5, 4),
                padding: (3, 2),
                output_padding: (4, 0),
                dilation: (2, 6),
                groups: 3,
            },
        ]),
        Some("QMatMul") => {
            // Combo-derived per the contract couplings (`k == a.dim[-1]`,
            // `n == w_q_bytes.dim[0]`) — consistency by construction. Q4_0
            // matches the contract's declared `ggml_dtype`. One point: every
            // field is shape- or format-coupled, so no free field exists to
            // vary a second point on.
            let (Some((_, a, _)), Some((_, w, _))) = (combo.first(), combo.get(1)) else {
                return Vec::new();
            };
            let (Some(&k), Some(&n)) = (a.dims().last(), w.dims().first()) else {
                return Vec::new();
            };
            points(vec![FusedOpParams::QMatMul {
                quant_type: fuel_graph::QuantType::Q4_0,
                k,
                n,
            }])
        }
        Some("FusedSoftmaxCrossEntropy") => points(vec![
            // The reduction-CONDITIONAL shape rule (None → targets.shape,
            // Mean/Sum → []) makes both branches mandatory; ignore_index is
            // the conventional -100 sentinel at both points.
            FusedOpParams::FusedSoftmaxCrossEntropy {
                reduction: Reduction::None,
                ignore_index: -100,
            },
            FusedOpParams::FusedSoftmaxCrossEntropy {
                reduction: Reduction::Mean,
                ignore_index: -100,
            },
        ]),
        Some("CausalConv1d") => points(vec![
            // Shape/dtype rules ignore `use_silu` (causal_conv1d.rs); one
            // point suffices.
            FusedOpParams::CausalConv1d { use_silu: false },
        ]),
        _ => Vec::new(),
    }
}

/// §5 (Finding 5.1): cross-check a `fused_op` section's DECLARED §5.1/§5.2
/// return rules against the REAL registered [`fuel_graph::registry::FusedOpEntry`]
/// `shape_rule`/`dtype_rule` fn pointers, at every probe combo `solve_probe_shapes`
/// produces. Runs inside `lower_fused` (the only site holding both the parsed
/// [`FkcKernel`] and the resolved [`FusedOpId`]) — BEFORE registration, so a
/// disagreement fails the import rather than silently drifting from the graph's
/// single source of truth.
///
/// Invariant (never-panic guard): the real `shape_rule`/`dtype_rule` fns for
/// some fused ops (e.g. qmatmul, conv2d) `panic!` on a mismatched
/// `FusedOpParams` variant. C-4 T3 RETIRES the C-3 coincidence this fn used
/// to lean on ("evaluable ⇒ params-independent, so the real fn is never
/// called with a synthless variant"): params-DEPENDENT variants now get real
/// synthesized values too ([`synth_probe_param_points`]), so their
/// `passthrough`/`fixed` dtype rules are genuinely cross-checked. The
/// never-panic mechanism is structural, not coincidental:
/// - **matching-variant synth**: both synth fns only ever build the variant
///   NAMED by the contract (or nothing), so the wrong-params panic is
///   unreachable by construction;
/// - **value validity**: params-dependent points are shape-coupled to the
///   probe combo (Conv2D padding derives from the weight kernel; QMatMul k/n
///   from a/w), so the real fn's arithmetic cannot underflow on any probe;
/// - **arity pre-check**: [`expected_min_inputs`] (attention family + Conv2D)
///   skips an under-declared contract consistently in debug AND release,
///   with a warning;
/// - **backstop**: [`guard_rule`] (catch_unwind + warn) stays the last-resort
///   never-panic guard for anything unforeseen.
///
/// A real fn is still invoked ONLY when the contract's declared rule is
/// EVALUABLE (`eval_dtype_rule`/`eval_shape_rule` returned `Some`) and a
/// param point exists for the variant.
pub fn cross_check_fused_section(
    kernel: &FkcKernel,
    id: FusedOpId,
    warnings: &mut Vec<ImportWarning>,
) -> Result<(), FkcError> {
    let section = kernel.kernel.as_str();
    let Some(entry) = default_registry().entry(id) else {
        return Ok(());
    };
    let Some(accept) = kernel.accept.as_ref() else {
        return Ok(());
    };
    let Some(ret) = kernel.return_.as_ref() else {
        return Ok(());
    };
    let variant = accept.op_params.as_ref().and_then(|s| s.variant.as_deref());

    // Soft-catch solver errors (e.g. a malformed-vocabulary shape_constraint):
    // skip the cross-check + warn rather than fail the whole import. This
    // protects the currently-green norm-softmax live-kernel test, whose
    // `same_as=out` output-role refs + free-text prose constraints soft-degrade
    // to warnings today — a future hard solver error must not regress that.
    let combos = match solve_probe_shapes(&accept.inputs, section, warnings) {
        Ok(c) => c,
        Err(e) => {
            warnings.push(ImportWarning {
                section: section.into(),
                message: format!("return cross-check skipped: {e}"),
            });
            return Ok(());
        }
    };
    // Single synthesized params for the params-INDEPENDENT variants; the
    // params-DEPENDENT variants synthesize per-combo POINTS inside the loop.
    let single = synth_probe_params(variant)?;

    // Finding 1 (arity pre-check — closes the debug-vs-release split). The
    // attention-family registry rule fns `debug_assert!` a minimum input arity
    // (flash_attn / flash_attn_backward: 4-or-5; paged_attn: 5-or-6). A leaner
    // corpus contract that under-declares (the metal `matmul-attn.fkc.md`
    // 3-input FLASH_ATTN) would make that assert PANIC in a DEBUG build (caught
    // + skipped by `guard_rule`) but be STRIPPED in RELEASE (the fn reads
    // operand 0 and the differential runs) — so a drifted contract could pass
    // `cargo test` yet fail `cargo build --release`. Pre-check the probe arity
    // (= `accept.inputs.len()`, constant across every combo) so BOTH build modes
    // reach the SAME skip decision, and surface a warning instead of a silent
    // (debug-only) skip.
    let probe_arity = accept.inputs.len();
    let arity_ok = match expected_min_inputs(variant) {
        Some(min) if probe_arity < min => {
            warnings.push(ImportWarning {
                section: section.into(),
                message: format!(
                    "return cross-check: fused variant {} declares {probe_arity} input(s) but its \
                     registered rule fn requires >= {min}; the shape/dtype differential is skipped \
                     (consistently in debug and release — the fn's arity debug_assert fires only in debug)",
                    variant.unwrap_or("<unknown>"),
                ),
            });
            false
        }
        _ => true,
    };

    for combo in &combos {
        // Skip the primary-output differential when the probe arity can't
        // satisfy the registry fn (Finding 1): the same decision in debug and
        // release. The bundle differential below is independent (its ops declare
        // no minimum via `expected_min_inputs`).
        if !arity_ok {
            break;
        }
        let in_shapes: Vec<Shape> = combo.iter().map(|(_, s, _)| s.clone()).collect();
        let in_dtypes: Vec<DType> = combo.iter().map(|(_, _, d)| *d).collect();
        // FusedOpEntry::shape_rule/dtype_rule describe the PRIMARY output (slot 0) only
        // (registry.rs doc-invariant). Additional bundle slots are validated against
        // output_views in Task 3.4 — do NOT compare non-primary outputs against these fns,
        // or a valid multi-output contract whose slot-N rule differs from slot-0 would be
        // spuriously rejected.
        let Some(out) = ret.outputs.first() else {
            continue;
        };
        let role_name = out.name.as_deref().unwrap_or("out");
        // C-4 T3: the param POINTS for this combo. A params-independent
        // variant contributes its ONE synthesized params, paired with its
        // `key().ints` flattening (the same encoding `param(N)` indexes —
        // one convention for every variant); a params-dependent variant
        // contributes the per-combo shape-coupled points (>= 2 wherever a
        // free field exists, so a rule that ignores the param can't
        // false-green on a single point). EMPTY points ⇒ every differential
        // for this combo is skipped — never a foreign variant, never a
        // panic. Out-of-synth-scope variants (e.g. Nf4Matmul) stay documented
        // skips; a params-DEPENDENT variant whose combo the derivation can't
        // read WARNS (review fix — no silent coverage hole).
        let points: Vec<(FusedOpParams, Vec<i64>)> = match single.as_ref() {
            Some(p) => vec![(p.clone(), p.key().ints)],
            None => {
                let pts = synth_probe_param_points(variant, combo);
                if pts.is_empty() && is_params_dependent_synth_variant(variant) {
                    warnings.push(ImportWarning {
                        section: section.into(),
                        message: format!(
                            "return cross-check: no param point could be synthesized for \
                             params-dependent variant {} from this probe combo (operand shapes \
                             unreadable by the shape-coupled derivation); shape/dtype \
                             differentials skipped for this combo",
                            variant.unwrap_or("<unknown>"),
                        ),
                    });
                }
                pts
            }
        };
        for (p, ints) in &points {
            // dtype_rule: the real fn is called only with a matching-variant
            // point (never an `unwrap_or` fallback — a params-matching
            // dtype_rule may read its fields).
            if let Some(rule) = out.dtype_rule.as_deref()
                && let Some(declared) = eval_dtype_rule(rule, combo, section)?
            {
                // Never-panic guard: a registry fn that `debug_assert`s an
                // arity the probe combo doesn't satisfy → warn + skip this
                // point (see `guard_rule`; the arity pre-check above already
                // skips the known under-arity cases in BOTH build modes).
                let Some(real) = guard_rule(warnings, section, "dtype_rule", || {
                    (entry.dtype_rule)(&in_dtypes, p)
                }) else {
                    continue;
                };
                if declared != real {
                    return Err(FkcError::ShapeRuleMismatch {
                        section: section.into(),
                        role: role_name.into(),
                        expected: format!("dtype {declared:?}"),
                        actual: format!("dtype {real:?}"),
                    });
                }
            }
            if let Some(rule) = out.shape_rule.as_deref() {
                // C-4 T3: the SAME point feeds both sides — `ints` to the
                // declared-rule evaluator (`param(N)` indexes it) and `p` to
                // the real registry fn — consistency by construction.
                if let Some(declared) = eval_shape_rule(rule, combo, ints, section)? {
                    let Some(real) = guard_rule(warnings, section, "shape_rule", || {
                        (entry.shape_rule)(&in_shapes, p)
                    }) else {
                        continue;
                    };
                    if declared != real {
                        return Err(FkcError::ShapeRuleMismatch {
                            section: section.into(),
                            role: role_name.into(),
                            expected: format!("shape {declared:?}"),
                            actual: format!("shape {real:?}"),
                        });
                    }
                }
            }
        }
    }
    // §5.5 (Finding 5.2): a `return.bundle` declares its slot count as a YAML
    // sequence; that count must agree with the real registered
    // `FusedOpEntry::output_views` arity, or a multi-output contract could
    // silently under/over-declare slots relative to what the graph actually
    // allocates. Same never-panic guard as shape_rule/dtype_rule above:
    // `output_views` also takes `&FusedOpParams`, so it's only invoked when
    // `synth_probe_params` produced `Some(params)` for this variant.
    //
    // Convergence-C C-3: the only bundle-bearing fused ops (SELECTIVE_SCAN,
    // SSD_CHUNK_SCAN) are now synth-supported (`synth_probe_params` returns
    // `Some`), so this bundle check is corpus-LIVE — it validates the declared
    // `return.bundle` slot count against the real `output_views` arity and
    // rank-checks each evaluable slot. `output_views` is guarded by `guard_rule`
    // (never-panic) exactly like `shape_rule`/`dtype_rule`.
    if let (Some(bundle), Some(output_views), Some(p)) =
        (ret.bundle.as_ref(), entry.output_views, single.as_ref())
        && let Some(combo) = combos.first()
    {
        // Finding 3: run the bundle differential over a ROLE-DISTINCT probe so
        // a same-rank operand-role drift in a slot rule (`same_as(b)` for
        // `same_as(u)`) diverges from the `output_views` oracle instead of
        // evaluating equal (twin-rank operands seed identically). Both the
        // oracle (`output_views(in_shapes, ..)`) and the declared slot eval
        // read the SAME distinct probe, so the UNMUTATED contract still
        // matches (declared slot 0 == the u-derived view), while a drift is
        // caught. Still §4: the reference is `output_views` (role/vocab-
        // derived), never `entry.decompose`.
        let distinct = distinct_role_probe(combo);
        let in_shapes: Vec<Shape> = distinct.iter().map(|(_, s, _)| s.clone()).collect();
        let in_dtypes: Vec<DType> = distinct.iter().map(|(_, _, d)| *d).collect();
        // Never-panic guard (see `guard_rule`): an `output_views` fn that
        // asserts an arity the probe doesn't satisfy → warn + skip the bundle checks.
        if let Some(views) = guard_rule(warnings, section, "output_views", || {
            output_views(&in_shapes, &in_dtypes, p)
        }) {
            check_bundle_arity(section, views.len(), bundle)?;
            // Rule 13 (Finding 5.3): rank-check every bundle slot whose
            // `shape_rule` is EVALUABLE against this probe combo. The static
            // `shape:`-literal branch is already rank-checked pre-registration
            // in `validate.rs::check_bundle_ranks`; this covers the DERIVED
            // case that check never could (no statically-knowable rank for a
            // `shape_rule` string without evaluating it against a real probe).
            if let serde_yaml_ng::Value::Sequence(slots) = bundle {
                for (i, slot) in slots.iter().enumerate() {
                    let serde_yaml_ng::Value::Mapping(map) = slot else {
                        continue;
                    };
                    let slot_name = map
                        .get(serde_yaml_ng::Value::String("name".into()))
                        .and_then(|v| v.as_str())
                        .map(str::to_string)
                        .unwrap_or_else(|| format!("slot{i}"));
                    if let Some(rule) = map
                        .get(serde_yaml_ng::Value::String("shape_rule".into()))
                        .and_then(|v| v.as_str())
                    {
                        // C-4 T3: bundle slot rules see the same `key().ints`
                        // flattening as the primary output (one `param(N)`
                        // convention). Both bundle-bearing ops are
                        // params-independent (single-synth), so `p` is the
                        // one point for the whole bundle differential.
                        if let Some(shape) =
                            eval_shape_rule(rule, &distinct, &p.key().ints, section)?
                        {
                            check_slot_rank(section, &slot_name, &shape)?;
                            // Finding 3: differentially compare the evaluated slot
                            // shape to the `output_views` oracle for the SAME slot
                            // (mirrors the primary-output differential above). A
                            // slot whose `shape_rule` is not evaluable (e.g.
                            // `from_params(last_state)`) yields `None` and stays a
                            // documented skip; only an evaluable, mismatching slot
                            // is rejected.
                            if let Some(view) = views.get(i)
                                && shape != view.shape
                            {
                                return Err(FkcError::ShapeRuleMismatch {
                                    section: section.into(),
                                    role: slot_name.clone(),
                                    expected: format!("shape {:?}", view.shape),
                                    actual: format!("shape {shape:?}"),
                                });
                            }
                        }
                    }
                }
            }
        }
    }
    Ok(())
}

/// Rule 13 (Finding 5.3): a bundle slot's shape rank must be ≤ 6, whether the
/// slot's shape came from a static `shape:` literal (checked in
/// `validate.rs::check_bundle_ranks`, pre-registration) or was DERIVED from a
/// `shape_rule` and evaluated here against a real probe shape. The serialized
/// `FDXOutputView` (`[u64; 6]`) cannot represent rank > 6 either way.
pub fn check_slot_rank(section: &str, slot: &str, shape: &Shape) -> Result<(), FkcError> {
    let rank = shape.rank();
    if rank > 6 {
        return Err(FkcError::BundleSlotRankExceeded {
            section: section.into(),
            slot: slot.into(),
            rank,
        });
    }
    Ok(())
}

/// Finding 5.4 (FKC side, Task 3.6): extract a `return.bundle`'s per-slot
/// NAMES, in declared order. `Vec::new()` when `ret` is `None`, or `ret`'s
/// `bundle` is `None`/not a `Sequence`, or a slot is not a `Mapping` — never
/// a false reject; the FDX bundle-arity check (`check_bundle_arity`) is the
/// authority on WHETHER the slot count is right, this fn only reads names.
/// A slot with no `name:` key falls back to `slot{i}` (mirrors the same
/// fallback in `cross_check_fused_section`'s rank-check loop, §5.5).
pub fn bundle_slot_names(ret: &Option<crate::fkc::schema::ReturnBlock>) -> Vec<String> {
    let Some(ret) = ret.as_ref() else {
        return Vec::new();
    };
    let Some(bundle) = ret.bundle.as_ref() else {
        return Vec::new();
    };
    let serde_yaml_ng::Value::Sequence(slots) = bundle else {
        return Vec::new();
    };
    slots
        .iter()
        .enumerate()
        .map(|(i, slot)| {
            let serde_yaml_ng::Value::Mapping(map) = slot else {
                return format!("slot{i}");
            };
            map.get(serde_yaml_ng::Value::String("name".into()))
                .and_then(|v| v.as_str())
                .map(str::to_string)
                .unwrap_or_else(|| format!("slot{i}"))
        })
        .collect()
}

/// §5.5: the declared slot count of a `return.bundle` — a YAML `Sequence`,
/// one entry per output slot. `None` for a malformed (non-sequence) bundle;
/// callers treat that as not-evaluable, never a false reject.
pub fn bundle_slot_count(bundle: &serde_yaml_ng::Value) -> Option<usize> {
    match bundle {
        serde_yaml_ng::Value::Sequence(s) => Some(s.len()),
        _ => None,
    }
}

/// §5.5 (Finding 5.2): the declared `return.bundle` slot count must agree
/// with the real registered `FusedOpEntry::output_views` arity.
pub fn check_bundle_arity(
    section: &str,
    output_views_arity: usize,
    bundle: &serde_yaml_ng::Value,
) -> Result<(), FkcError> {
    if let Some(declared) = bundle_slot_count(bundle)
        && declared != output_views_arity
    {
        return Err(FkcError::BundleArityMismatch {
            section: section.into(),
            expected: output_views_arity,
            actual: declared,
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use fuel_ir::{DType, Shape};

    #[test]
    fn synth_probe_params_builds_the_matching_variant_or_none() {
        use fuel_graph::registry::FusedOpParams;
        assert!(matches!(
            synth_probe_params(Some("SoftmaxLastDim")).unwrap(),
            Some(FusedOpParams::SoftmaxLastDim)
        ));
        assert!(matches!(
            synth_probe_params(Some("RmsNormLastDim")).unwrap(),
            Some(FusedOpParams::RmsNormLastDim { .. })
        ));
        // Convergence-C C-3: the newly-widened arms return their matching variant.
        assert!(matches!(
            synth_probe_params(Some("InplaceAffine")).unwrap(),
            Some(FusedOpParams::InplaceAffine { .. })
        ));
        assert!(matches!(
            synth_probe_params(Some("FlashAttn")).unwrap(),
            Some(FusedOpParams::FlashAttn { .. })
        ));
        assert!(matches!(
            synth_probe_params(Some("PagedAttn")).unwrap(),
            Some(FusedOpParams::PagedAttn { .. })
        ));
        assert!(matches!(
            synth_probe_params(Some("FlashAttnBackward")).unwrap(),
            Some(FusedOpParams::FlashAttnBackward { .. })
        ));
        assert!(matches!(
            synth_probe_params(Some("SelectiveScan")).unwrap(),
            Some(FusedOpParams::SelectiveScan { .. })
        ));
        assert!(matches!(
            synth_probe_params(Some("SsdChunkScan")).unwrap(),
            Some(FusedOpParams::SsdChunkScan { .. })
        ));
        // C-4 T3 division-of-labor pin (the old ":534" flip): Conv2D is NO
        // LONGER an unsupported skip — it is params-DEPENDENT, so the single
        // path must stay None (a placeholder here would feed the real fn
        // params the shape rule actually READS) while the POINTS path
        // synthesizes its real per-combo values. Both halves pinned:
        assert!(synth_probe_params(Some("Conv2D")).unwrap().is_none());
        let conv_combo: Vec<(String, Shape, DType)> = vec![
            ("x".into(), Shape::from_dims(&[2, 3, 8, 8]), DType::F32),
            ("weight".into(), Shape::from_dims(&[4, 3, 3, 3]), DType::F32),
        ];
        assert!(
            !synth_probe_param_points(Some("Conv2D"), &conv_combo).is_empty(),
            "Conv2D synth is no longer None — the points path covers it",
        );
        // The absent case stays None.
        assert!(synth_probe_params(None).unwrap().is_none());
        // never-panic invariant: QMatMul synth is EITHER QMatMul OR None, never a foreign variant.
        match synth_probe_params(Some("QMatMul")).unwrap() {
            None => {}
            Some(p) => assert!(matches!(p, FusedOpParams::QMatMul { .. })),
        }
    }

    #[test]
    fn bundle_slot_count_disagreeing_with_output_views_arity_is_rejected() {
        let two_slots: serde_yaml_ng::Value = serde_yaml_ng::from_str(
            "- { name: y, shape_rule: same_as(u) }\n- { name: last_state, shape_rule: from_params(state) }").unwrap();
        assert_eq!(bundle_slot_count(&two_slots), Some(2));
        let err = check_bundle_arity("selective_scan", 3, &two_slots)
            .expect_err("declared 2 vs 3 real output_views slots must be rejected");
        assert!(
            matches!(
                err,
                FkcError::BundleArityMismatch {
                    expected: 3,
                    actual: 2,
                    ..
                }
            ),
            "got {err:?}"
        );
        assert!(check_bundle_arity("selective_scan", 2, &two_slots).is_ok());
    }

    #[test]
    fn shape_rule_derived_bundle_slot_over_rank6_is_rejected() {
        use fuel_ir::Shape;
        let rank7 = Shape::from_dims(&[2, 2, 2, 2, 2, 2, 2]);
        let err = check_slot_rank("s", "big_slot", &rank7).expect_err("rank 7 must be rejected");
        assert!(
            matches!(err, FkcError::BundleSlotRankExceeded { rank: 7, .. }),
            "got {err:?}"
        );
        assert!(check_slot_rank("s", "ok_slot", &Shape::from_dims(&[1, 1, 1, 1, 1, 1])).is_ok());
    }

    #[test]
    fn interpreter_evaluates_supported_vocab_and_skips_the_rest() {
        let combo: Vec<(String, Shape, DType)> = vec![
            ("x".into(), Shape::from_dims(&[2, 3]), DType::F32),
            ("upstream".into(), Shape::from_dims(&[4, 5]), DType::F16),
        ];
        let c: ProbeComboRef = &combo;
        assert_eq!(
            eval_dtype_rule("fixed(F16)", c, "k").unwrap(),
            Some(DType::F16)
        );
        assert_eq!(
            eval_dtype_rule("passthrough(x)", c, "k").unwrap(),
            Some(DType::F32)
        );
        assert_eq!(eval_dtype_rule("dequant(w)", c, "k").unwrap(), None);
        assert_eq!(
            eval_shape_rule("same_as(upstream)", c, &[], "k").unwrap(),
            Some(Shape::from_dims(&[4, 5]))
        );
        assert_eq!(
            eval_shape_rule("from_params(q)", c, &[], "k").unwrap(),
            None
        );
        // `matmul(a, b)` over a combo that has NO `a`/`b` roles → unknown-role skip.
        assert_eq!(eval_shape_rule("matmul(a, b)", c, &[], "k").unwrap(), None);
        assert_eq!(
            eval_shape_rule("same_as(does_not_exist)", c, &[], "k").unwrap(),
            None
        );

        // Convergence-C: DimExpr rules evaluate to a single-dim shape via the §6.20 oracle.
        // combo "x" = [2, 3].
        assert_eq!(
            eval_shape_rule("extent(x, 0)", c, &[], "k").unwrap(),
            Some(Shape::from_dims(&[2]))
        );
        assert_eq!(
            eval_shape_rule("const(9)", c, &[], "k").unwrap(),
            Some(Shape::from_dims(&[9]))
        );
        // div(extent(x, last), const(2)) on x=[2,3]: floor(3/2) = 1.
        assert_eq!(
            eval_shape_rule("div(extent(x, last), const(2))", c, &[], "k").unwrap(),
            Some(Shape::from_dims(&[1]))
        );
        // mul(extent(x, 0)=2, const(3)=3) = 6.
        assert_eq!(
            eval_shape_rule("mul(extent(x, 0), const(3))", c, &[], "k").unwrap(),
            Some(Shape::from_dims(&[6]))
        );
        // Unknown role, a param rule with EMPTY params (`&[]` → ParamOutOfRange
        // decline; C-4 T1 pin — values thread via the params slice now, but no
        // values still means skip), a ÷0 decline, and a negative result all
        // surface as not-evaluable → None (never a false reject).
        assert_eq!(
            eval_shape_rule("extent(nope, 0)", c, &[], "k").unwrap(),
            None
        );
        assert_eq!(eval_shape_rule("param(0)", c, &[], "k").unwrap(), None);
        assert_eq!(
            eval_shape_rule("div(extent(x, last), const(0))", c, &[], "k").unwrap(),
            None
        );
        assert_eq!(
            eval_shape_rule("sub(const(2), extent(x, 1))", c, &[], "k").unwrap(),
            None
        ); // 2 − 3 = −1
    }

    /// C-4 T1: `eval_shape_rule` threads its params slice through to the §6.20
    /// `eval_dim` oracle, so a `param(N)` rule evaluates against synthesized
    /// values instead of unconditionally declining. Index order is the
    /// `FusedOpParams::key().ints` flattening (pinned per-variant in T2). An
    /// EMPTY slice still declines every `param(N)` rule (`ParamOutOfRange` →
    /// skip) — the pre-threading pin stays the default for value-less callers.
    #[test]
    fn eval_shape_rule_threads_param_values_through_the_oracle() {
        let combo: Vec<(String, Shape, DType)> =
            vec![("x".into(), Shape::from_dims(&[2, 3]), DType::F32)];
        let c: ProbeComboRef = &combo;
        // param(0) with values [7] → single-dim Shape [7].
        assert_eq!(
            eval_shape_rule("param(0)", c, &[7], "k").unwrap(),
            Some(Shape::from_dims(&[7]))
        );
        // Composite: mul(extent(x,0)=2, param(1)=5) = 10 — params and extents mix.
        assert_eq!(
            eval_shape_rule("mul(extent(x, 0), param(1))", c, &[7, 5], "k").unwrap(),
            Some(Shape::from_dims(&[10])),
        );
        // Out-of-range index (param(2) with 2 values) → ParamOutOfRange decline → skip.
        assert_eq!(eval_shape_rule("param(2)", c, &[7, 5], "k").unwrap(), None);
        // A negative param value is not a valid dim → skip (the d >= 0 guard).
        assert_eq!(eval_shape_rule("param(0)", c, &[-3], "k").unwrap(), None);
        // No values (&[]) — every param(N) rule still declines to skip.
        assert_eq!(eval_shape_rule("param(0)", c, &[], "k").unwrap(), None);
    }

    /// Convergence-C C-3 (Tier 3): the whole-shape `matmul(role_a, role_b)` rule
    /// resolves its two roles to operand shapes and returns the contraction
    /// `[..batch, M, N]` via the shipped `shape_expr::matmul_shape` — byte-for-byte
    /// the registry `fused_linear::matmul_output_shape`. Degenerate ranks skip.
    #[test]
    fn eval_shape_rule_matmul_resolves_roles_to_contraction_shape() {
        let combo: Vec<(String, Shape, DType)> = vec![
            ("a".into(), Shape::from_dims(&[8, 4096]), DType::F32),
            ("b".into(), Shape::from_dims(&[4096, 1024]), DType::F32),
            ("bias".into(), Shape::from_dims(&[1024]), DType::F32),
        ];
        let c: ProbeComboRef = &combo;
        // a=[8,4096] · b=[4096,1024] → [8,1024].
        assert_eq!(
            eval_shape_rule("matmul(a, b)", c, &[], "k").unwrap(),
            Some(Shape::from_dims(&[8, 1024]))
        );
        // Whitespace-insensitive (mirrors parse_dim).
        assert_eq!(
            eval_shape_rule("matmul(a,b)", c, &[], "k").unwrap(),
            Some(Shape::from_dims(&[8, 1024]))
        );

        // Batched: [4,8,16] · [4,16,32] → [4,8,32].
        let batched: Vec<(String, Shape, DType)> = vec![
            ("a".into(), Shape::from_dims(&[4, 8, 16]), DType::F32),
            ("b".into(), Shape::from_dims(&[4, 16, 32]), DType::F32),
        ];
        assert_eq!(
            eval_shape_rule("matmul(a, b)", &batched, &[], "k").unwrap(),
            Some(Shape::from_dims(&[4, 8, 32])),
        );

        // Guards → skip (Ok(None), never a false reject / never a panic):
        // unknown role, a rank-1 operand, and a rank-mismatch.
        assert_eq!(
            eval_shape_rule("matmul(a, nope)", c, &[], "k").unwrap(),
            None
        );
        let rank1: Vec<(String, Shape, DType)> = vec![
            ("a".into(), Shape::from_dims(&[8]), DType::F32),
            ("b".into(), Shape::from_dims(&[8]), DType::F32),
        ];
        assert_eq!(
            eval_shape_rule("matmul(a, b)", &rank1, &[], "k").unwrap(),
            None
        );
        let rank_mismatch: Vec<(String, Shape, DType)> = vec![
            ("a".into(), Shape::from_dims(&[4, 8, 16]), DType::F32),
            ("b".into(), Shape::from_dims(&[16, 32]), DType::F32),
        ];
        assert_eq!(
            eval_shape_rule("matmul(a, b)", &rank_mismatch, &[], "k").unwrap(),
            None
        );
    }

    /// Finding 5.4 deliverable (Task 3.6 coverage gap): the extractor must
    /// actually PULL the right names out of a real `ReturnBlock`, not merely
    /// avoid panicking. Mirrors the real corpus shape
    /// (`docs/kernel-contracts/fused/conv-rope.fkc.md`'s `SELECTIVE_SCAN`
    /// bundle: `y` / `last_state`). Bare `y` is a YAML-1.1 "Norway problem"
    /// candidate (`y`/`yes`/`on` historically coerce to bool `true`), but the
    /// slot names live inside a `serde_yaml_ng::Value` (untyped) tree here, and
    /// `serde_yaml_ng` 0.0.12 keeps bare `y` as the plain string `"y"` — pinned by
    /// this assertion, not just asserted in prose.
    /// Finding 1 (warn-not-silent-skip): a caught panic in a registry rule fn
    /// must now push an `ImportWarning` naming the skipped differential, not
    /// vanish silently. Previously `guard_rule` returned `catch_unwind(..).ok()`
    /// — a caught panic became `None` with NO diagnostic, so a coverage hole
    /// (e.g. the metal 3-input FLASH_ATTN differential going inert in a debug
    /// build) left no trace. This proves the warning is recorded.
    #[test]
    fn guard_rule_warns_on_a_caught_panic_instead_of_silently_skipping() {
        let mut warnings: Vec<ImportWarning> = Vec::new();
        // Suppress the default panic hook's stderr print for this deliberate panic.
        let prev = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let caught: Option<i32> = guard_rule(&mut warnings, "sec", "shape_rule", || {
            panic!("simulated debug_assert arity panic");
        });
        std::panic::set_hook(prev);
        assert!(
            caught.is_none(),
            "a caught panic yields None (skip this differential)"
        );
        assert_eq!(
            warnings.len(),
            1,
            "the caught panic must surface exactly one warning"
        );
        assert_eq!(warnings[0].section, "sec");
        assert!(
            warnings[0].message.contains("shape_rule") && warnings[0].message.contains("panicked"),
            "the warning names the skipped differential + the panic: {:?}",
            warnings[0].message,
        );
        // The happy path (no panic) returns Some and adds NO warning.
        let ok: Option<i32> = guard_rule(&mut warnings, "sec", "dtype_rule", || 7);
        assert_eq!(ok, Some(7));
        assert_eq!(warnings.len(), 1, "a successful call adds no warning");
    }

    /// Finding 1 (arity pre-check): the attention-family fns declare a minimum
    /// input arity that a leaner corpus contract can under-declare — and C-4 T3
    /// adds Conv2D (its rule fns read `input_shapes[1]` and assert 2-or-3
    /// inputs, and real 2-input CONV2D fused sections exist in
    /// `vulkan/conv-attn-rope.fkc.md`, so the under-declaration risk is live
    /// now that Conv2D's dtype differential runs). Every other synth variant
    /// has no declared minimum (the `guard_rule` backstop covers them). This
    /// pins the small, deliberately-local arity table.
    #[test]
    fn expected_min_inputs_covers_attention_family_and_conv2d() {
        assert_eq!(expected_min_inputs(Some("FlashAttn")), Some(4));
        assert_eq!(expected_min_inputs(Some("FlashAttnBackward")), Some(4));
        assert_eq!(expected_min_inputs(Some("PagedAttn")), Some(5));
        // C-4 T3: Conv2D's differentials are params-live; pre-check its arity.
        assert_eq!(expected_min_inputs(Some("Conv2D")), Some(2));
        // Other synth variants (and the absent case) declare no minimum.
        assert_eq!(expected_min_inputs(Some("SelectiveScan")), None);
        assert_eq!(expected_min_inputs(Some("InplaceAffine")), None);
        assert_eq!(expected_min_inputs(None), None);
    }

    /// Finding 3 helper: `distinct_role_probe` leaves operand 0 untouched and
    /// bumps each later operand's leading (dim0/batch) axis by its position, so
    /// twin-rank operands become observably distinct while the oracle's slot
    /// geometry (which flows dim0 straight through) is preserved.
    #[test]
    fn distinct_role_probe_bumps_dim0_by_position_leaving_operand0() {
        let combo: Vec<(String, Shape, DType)> = vec![
            ("u".into(), Shape::from_dims(&[2, 3, 4]), DType::F32),
            ("b".into(), Shape::from_dims(&[2, 3, 4]), DType::F32),
            ("c".into(), Shape::from_dims(&[2, 3, 4]), DType::F32),
        ];
        let d = distinct_role_probe(&combo);
        assert_eq!(d[0].1, Shape::from_dims(&[2, 3, 4]), "operand 0 unchanged");
        assert_eq!(d[1].1, Shape::from_dims(&[3, 3, 4]), "operand 1 dim0 +1");
        assert_eq!(d[2].1, Shape::from_dims(&[4, 3, 4]), "operand 2 dim0 +2");
        // The twin-rank u/b/c are now distinct on dim0 — an operand-role swap in
        // a slot rule (same_as(u) -> same_as(b)) evaluates to a different shape.
        assert_ne!(d[0].1, d[1].1);
    }

    /// C-4 T2: `synth_probe_param_points` synthesizes per-variant, per-combo
    /// param POINTS for the params-DEPENDENT fused ops. Each point's ints are
    /// the `FusedOpParams::key().ints` flattening (the `param(N)` indexing
    /// convention pinned in the plan §3): Conv2D `[sh,sw,ph,pw,groups]`,
    /// ConvTranspose2D 9 slots, QMatMul `[quant_type_key,k,n]`, FSCE
    /// `[reduction_key,ignore_index]`, CausalConv1d `[use_silu]`. Params-
    /// dependent ops with a free field get >= 2 DISTINCT points (the
    /// sabotage-calibration norm applied to params: a single point could
    /// false-green a rule that ignores the param).
    #[test]
    fn synth_probe_param_points_pins_per_variant_tables_and_key_ints_flattening() {
        use fuel_graph::registry::Reduction;
        let conv: Vec<(String, Shape, DType)> = vec![
            ("x".into(), Shape::from_dims(&[2, 3, 8, 8]), DType::F32),
            ("weight".into(), Shape::from_dims(&[4, 3, 3, 3]), DType::F32),
        ];
        // Conv2D — 2 points; padding is SHAPE-COUPLED to the weight kernel
        // (kh/2 = 1 for the 3x3 kernel) so the real fn's usize
        // `(H + 2p − K)` arithmetic can never underflow. Point 2's ints are
        // pairwise DISTINCT (order-asymmetry, review fix): any slot reorder
        // of the flattening — stride<->padding included — changes the vector.
        let pts = synth_probe_param_points(Some("Conv2D"), &conv);
        assert_eq!(
            pts.len(),
            2,
            "Conv2D needs >= 2 points (no single-point false-green)"
        );
        assert!(
            matches!(
                pts[0].0,
                FusedOpParams::Conv2D {
                    stride: (1, 2),
                    padding: (1, 4),
                    groups: 1
                }
            ),
            "got {:?}",
            pts[0].0,
        );
        assert_eq!(pts[0].1, vec![1, 2, 1, 4, 1]);
        assert!(
            matches!(
                pts[1].0,
                FusedOpParams::Conv2D {
                    stride: (3, 4),
                    padding: (6, 7),
                    groups: 2
                }
            ),
            "got {:?}",
            pts[1].0,
        );
        assert_eq!(pts[1].1, vec![3, 4, 6, 7, 2]);
        assert_ne!(
            pts[0].1, pts[1].1,
            "the two points must differ (param-dependence observable)"
        );

        // ConvTranspose2D — 2 points, ints = [sh,sw,ph,pw,oph,opw,dh,dw,groups]
        // (registry.rs tag-11 flattening). output_padding < stride at both
        // points (the standard validity relation); the real fn saturates, so
        // no shape coupling is needed. Every slot PAIR differs at one point
        // or the other (order-asymmetry, review fix): padding<->output_padding
        // and dilation<->groups reorders — invisible in the old all-0/all-1
        // values — now change an asserted vector.
        let pts = synth_probe_param_points(Some("ConvTranspose2D"), &conv);
        assert_eq!(pts.len(), 2, "ConvTranspose2D needs >= 2 points");
        assert!(
            matches!(pts[0].0, FusedOpParams::ConvTranspose2D { .. }),
            "got {:?}",
            pts[0].0
        );
        assert_eq!(pts[0].1, vec![2, 3, 0, 1, 1, 2, 4, 5, 1]);
        assert!(
            matches!(pts[1].0, FusedOpParams::ConvTranspose2D { .. }),
            "got {:?}",
            pts[1].0
        );
        assert_eq!(pts[1].1, vec![5, 4, 3, 2, 4, 0, 2, 6, 3]);

        // QMatMul — 1 point, COMBO-DERIVED per the contract couplings
        // (`k == a.dim[-1]`, `n == w_q_bytes.dim[0]`; linear-quant.fkc.md
        // §op_params) — consistency by construction. Q4_0 (key 1) matches the
        // contract's declared ggml_dtype.
        let qm: Vec<(String, Shape, DType)> = vec![
            ("a".into(), Shape::from_dims(&[8, 4096]), DType::F32),
            (
                "w_q_bytes".into(),
                Shape::from_dims(&[1024, 128]),
                DType::U32,
            ),
        ];
        let pts = synth_probe_param_points(Some("QMatMul"), &qm);
        assert_eq!(pts.len(), 1);
        assert!(
            matches!(
                pts[0].0,
                FusedOpParams::QMatMul {
                    k: 4096,
                    n: 1024,
                    ..
                }
            ),
            "k/n must derive from the combo; got {:?}",
            pts[0].0,
        );
        assert_eq!(pts[0].1, vec![1, 4096, 1024]);

        // FusedSoftmaxCrossEntropy — 2 points (None then Mean: the shape rule
        // is reduction-CONDITIONAL, so both branches need a point);
        // ignore_index is the conventional -100 sentinel at both.
        let fsce: Vec<(String, Shape, DType)> = vec![
            ("logits".into(), Shape::from_dims(&[8, 32000]), DType::F32),
            ("targets".into(), Shape::from_dims(&[8]), DType::I64),
        ];
        let pts = synth_probe_param_points(Some("FusedSoftmaxCrossEntropy"), &fsce);
        assert_eq!(pts.len(), 2, "FSCE needs both reduction branches covered");
        assert!(
            matches!(
                pts[0].0,
                FusedOpParams::FusedSoftmaxCrossEntropy {
                    reduction: Reduction::None,
                    ignore_index: -100
                }
            ),
            "got {:?}",
            pts[0].0
        );
        assert_eq!(pts[0].1, vec![2, -100], "Reduction::None.key() = 2");
        assert!(
            matches!(
                pts[1].0,
                FusedOpParams::FusedSoftmaxCrossEntropy {
                    reduction: Reduction::Mean,
                    ignore_index: -100
                }
            ),
            "got {:?}",
            pts[1].0
        );
        assert_eq!(pts[1].1, vec![0, -100], "Reduction::Mean.key() = 0");

        // CausalConv1d — 1 point (shape/dtype rules ignore use_silu).
        let cc: Vec<(String, Shape, DType)> = vec![
            ("x".into(), Shape::from_dims(&[2, 4, 19]), DType::F32),
            ("weight".into(), Shape::from_dims(&[4, 1, 4]), DType::F32),
            ("bias".into(), Shape::from_dims(&[4]), DType::F32),
        ];
        let pts = synth_probe_param_points(Some("CausalConv1d"), &cc);
        assert_eq!(pts.len(), 1);
        assert!(
            matches!(pts[0].0, FusedOpParams::CausalConv1d { use_silu: false }),
            "got {:?}",
            pts[0].0
        );
        assert_eq!(pts[0].1, vec![0]);
    }

    /// Review fix (order-degeneracy): for every params-dependent variant,
    /// every PAIR of `key().ints` slots must be distinguished by at least one
    /// synth point (`ints[i] != ints[j]` at that point). Otherwise a
    /// length-preserving reorder of the `key().ints` flattening in
    /// `fuel-graph/src/registry.rs` (stride<->padding for Conv2D;
    /// padding<->output_padding or dilation<->groups for ConvTranspose2D)
    /// passes every exact-ints pin while the corpus doc tables go silently
    /// wrong — and, once whole-shape `param(N)` rules land, a
    /// `param(i)`/`param(j)` confusion in a declared rule would evaluate
    /// identically at EVERY point and false-green: exactly the failure the
    /// ">= 2 points" norm claims to prevent.
    #[test]
    fn synth_param_points_distinguish_every_ints_slot_pair() {
        let combo: Vec<(String, Shape, DType)> = vec![
            ("x".into(), Shape::from_dims(&[2, 3, 8, 8]), DType::F32),
            ("weight".into(), Shape::from_dims(&[4, 3, 3, 3]), DType::F32),
        ];
        for v in [
            "Conv2D",
            "ConvTranspose2D",
            "QMatMul",
            "FusedSoftmaxCrossEntropy",
            "CausalConv1d",
        ] {
            let pts = synth_probe_param_points(Some(v), &combo);
            assert!(!pts.is_empty(), "{v} must synthesize points");
            let len = pts[0].1.len();
            for i in 0..len {
                for j in (i + 1)..len {
                    assert!(
                        pts.iter().any(|(_, ints)| ints[i] != ints[j]),
                        "{v}: ints slots {i} and {j} are equal at EVERY synth point \
                         (order-degenerate: a slot reorder in the key().ints flattening, \
                         or a param({i})/param({j}) confusion in a declared rule, would \
                         false-green)",
                    );
                }
            }
        }
    }

    /// C-4 T2 (flattening differential): every returned point's ints ARE its
    /// own `FusedOpParams::key().ints` — the ONE flattening `param(N)`
    /// indexes, shared with CSE keying. Guards against a hand-rolled ints
    /// table drifting from `key()` if either side changes.
    #[test]
    fn synth_probe_param_points_ints_equal_key_ints_for_every_point() {
        // One rank-4 combo readable by every derivation (Conv2D reads
        // x/weight rank-4; QMatMul reads a.last=8, w.dim0=4).
        let combo: Vec<(String, Shape, DType)> = vec![
            ("x".into(), Shape::from_dims(&[2, 3, 8, 8]), DType::F32),
            ("weight".into(), Shape::from_dims(&[4, 3, 3, 3]), DType::F32),
        ];
        for v in [
            "Conv2D",
            "ConvTranspose2D",
            "QMatMul",
            "FusedSoftmaxCrossEntropy",
            "CausalConv1d",
        ] {
            let pts = synth_probe_param_points(Some(v), &combo);
            assert!(!pts.is_empty(), "{v} must synthesize at least one point");
            for (p, ints) in &pts {
                assert_eq!(
                    ints,
                    &p.key().ints,
                    "{v}: ints must be the key().ints flattening"
                );
            }
        }
    }

    /// C-4 T2 (never-a-foreign-variant pin, extending the `synth_probe_params`
    /// pin above): an unknown/params-independent variant synthesizes NOTHING
    /// (those stay `synth_probe_params`' job), and a combo the shape-coupled
    /// derivation can't safely read (missing operand, wrong rank, zero
    /// extent) declines to EMPTY — a skip, never a panic, never a guess.
    #[test]
    fn synth_probe_param_points_declines_unknown_variants_and_unreadable_combos() {
        let conv_ok: Vec<(String, Shape, DType)> = vec![
            ("x".into(), Shape::from_dims(&[2, 3, 8, 8]), DType::F32),
            ("weight".into(), Shape::from_dims(&[4, 3, 3, 3]), DType::F32),
        ];
        // Unknown + params-independent variants → empty.
        assert!(synth_probe_param_points(None, &conv_ok).is_empty());
        assert!(synth_probe_param_points(Some("SoftmaxLastDim"), &conv_ok).is_empty());
        assert!(synth_probe_param_points(Some("Bogus"), &conv_ok).is_empty());
        // Conv2D guards: missing weight operand / rank-3 x / zero spatial extent.
        assert!(synth_probe_param_points(Some("Conv2D"), &conv_ok[..1]).is_empty());
        let rank3: Vec<(String, Shape, DType)> = vec![
            ("x".into(), Shape::from_dims(&[3, 8, 8]), DType::F32),
            ("weight".into(), Shape::from_dims(&[4, 3, 3, 3]), DType::F32),
        ];
        assert!(synth_probe_param_points(Some("Conv2D"), &rank3).is_empty());
        let zero_h: Vec<(String, Shape, DType)> = vec![
            ("x".into(), Shape::from_dims(&[2, 3, 0, 8]), DType::F32),
            ("weight".into(), Shape::from_dims(&[4, 3, 3, 3]), DType::F32),
        ];
        assert!(synth_probe_param_points(Some("Conv2D"), &zero_h).is_empty());
        // QMatMul guards: missing operand / scalar (rank-0) activations.
        let qm: Vec<(String, Shape, DType)> = vec![
            ("a".into(), Shape::from_dims(&[8, 4096]), DType::F32),
            (
                "w_q_bytes".into(),
                Shape::from_dims(&[1024, 128]),
                DType::U32,
            ),
        ];
        assert!(synth_probe_param_points(Some("QMatMul"), &qm[..1]).is_empty());
        let scalar_a: Vec<(String, Shape, DType)> = vec![
            ("a".into(), Shape::from_dims(&[]), DType::F32),
            (
                "w_q_bytes".into(),
                Shape::from_dims(&[1024, 128]),
                DType::U32,
            ),
        ];
        assert!(synth_probe_param_points(Some("QMatMul"), &scalar_a).is_empty());
    }

    /// C-4 T2 (synth-value validity, the adversarial-review item): both
    /// Conv2D points must be VALID for the real registered shape fn on every
    /// probe — including a kernel LARGER than the spatial input (kh=5 > h=1),
    /// exactly where naive fixed padding would underflow the fn's usize
    /// `h + 2·ph − kh` (a debug-build panic). The shape-coupled padding
    /// (derived from the weight kernel) keeps the arithmetic non-negative by
    /// construction; a panic here fails the test.
    #[test]
    fn synth_conv2d_points_are_valid_for_the_real_registry_shape_fn() {
        use fuel_graph::registry::FusedOps;
        let entry = default_registry()
            .entry(FusedOps::CONV2D)
            .expect("CONV2D registered");
        let cases = [
            // (x, weight): kernel > input; odd kernel; even kernel.
            (
                Shape::from_dims(&[1, 1, 1, 7]),
                Shape::from_dims(&[1, 1, 5, 5]),
            ),
            (
                Shape::from_dims(&[2, 3, 8, 8]),
                Shape::from_dims(&[4, 3, 3, 3]),
            ),
            (
                Shape::from_dims(&[2, 3, 8, 8]),
                Shape::from_dims(&[4, 3, 4, 4]),
            ),
        ];
        for (x, w) in cases {
            let combo: Vec<(String, Shape, DType)> = vec![
                ("x".into(), x.clone(), DType::F32),
                ("weight".into(), w.clone(), DType::F32),
            ];
            let pts = synth_probe_param_points(Some("Conv2D"), &combo);
            assert_eq!(pts.len(), 2, "x={x:?} w={w:?}");
            for (p, _) in &pts {
                let out = (entry.shape_rule)(&[x.clone(), w.clone()], p);
                assert_eq!(out.rank(), 4, "x={x:?} w={w:?} params={p:?}");
            }
        }
    }

    #[test]
    fn bundle_slot_names_extracts_names_from_a_real_return_block() {
        let ret: crate::fkc::schema::ReturnBlock = serde_yaml_ng::from_str(
            "outputs: []\nbundle:\n  - { name: y, shape_rule: same_as(u) }\n  - { name: last_state, shape_rule: from_params(state) }",
        )
        .expect("parses");
        assert_eq!(
            bundle_slot_names(&Some(ret)),
            vec!["y".to_string(), "last_state".to_string()]
        );
        assert_eq!(bundle_slot_names(&None), Vec::<String>::new());
    }

    /// C-4 T5 (doc-vs-code drift is a defect): the fused corpus prose pins a
    /// per-variant `param(N)` index table — the `FusedOpParams::key().ints`
    /// flattening the T1–T3 threading indexes. This test compiles the corpus
    /// files in (`include_str!`, so a doc edit forces a recompile) and checks,
    /// for every ints-bearing variant contracted in those two files, that its
    /// table row exists, pins EVERY index `param(0)..param(len-1)`, and pins
    /// none beyond `key().ints`' actual length — so renumbering the flattening
    /// in `fuel-graph/src/registry.rs` without updating the docs (or vice
    /// versa) fails here, not silently.
    #[test]
    fn corpus_prose_pins_param_index_tables_matching_key_ints() {
        use fuel_graph::registry::Reduction;
        const CONV_ROPE: &str =
            include_str!("../../../docs/kernel-contracts/fused/conv-rope.fkc.md");
        const LINEAR_QUANT: &str =
            include_str!("../../../docs/kernel-contracts/fused/linear-quant.fkc.md");

        fn table_row<'a>(doc: &'a str, doc_name: &str, variant: &str) -> &'a str {
            let marker = format!("| `{variant}` |");
            doc.lines()
                .find(|l| l.contains(&marker))
                .unwrap_or_else(|| {
                    panic!("{doc_name} prose is missing the `{variant}` param-index table row")
                })
        }
        fn assert_row_pins(doc: &str, doc_name: &str, variant: &str, params: &FusedOpParams) {
            let ints = params.key().ints;
            let row = table_row(doc, doc_name, variant);
            for i in 0..ints.len() {
                assert!(
                    row.contains(&format!("param({i})=")),
                    "{doc_name}: `{variant}` row must pin param({i}) (key().ints has {} slots)",
                    ints.len(),
                );
            }
            assert!(
                !row.contains(&format!("param({})", ints.len())),
                "{doc_name}: `{variant}` row pins more slots than key().ints carries ({})",
                ints.len(),
            );
        }

        // conv-rope.fkc.md — Conv2D / ConvTranspose2D / CausalConv1d /
        // SelectiveScan / SsdChunkScan (Rope carries no fields → no row).
        assert_row_pins(
            CONV_ROPE,
            "conv-rope.fkc.md",
            "Conv2D",
            &FusedOpParams::Conv2D {
                stride: (1, 1),
                padding: (0, 0),
                groups: 1,
            },
        );
        assert_row_pins(
            CONV_ROPE,
            "conv-rope.fkc.md",
            "ConvTranspose2D",
            &FusedOpParams::ConvTranspose2D {
                stride: (1, 1),
                padding: (0, 0),
                output_padding: (0, 0),
                dilation: (1, 1),
                groups: 1,
            },
        );
        assert_row_pins(
            CONV_ROPE,
            "conv-rope.fkc.md",
            "CausalConv1d",
            &FusedOpParams::CausalConv1d { use_silu: false },
        );
        assert_row_pins(
            CONV_ROPE,
            "conv-rope.fkc.md",
            "SelectiveScan",
            &FusedOpParams::SelectiveScan {
                delta_softplus: false,
            },
        );
        assert_row_pins(
            CONV_ROPE,
            "conv-rope.fkc.md",
            "SsdChunkScan",
            &FusedOpParams::SsdChunkScan { chunk_size: 256 },
        );

        // linear-quant.fkc.md — QMatMul / FusedSoftmaxCrossEntropy / Nf4Matmul
        // (FusedLinear has no fields; InplaceAffine's f64 fields ride
        // `key().bits`, NOT `ints` — no `param(N)` slot exists for either).
        assert_row_pins(
            LINEAR_QUANT,
            "linear-quant.fkc.md",
            "QMatMul",
            &FusedOpParams::QMatMul {
                quant_type: fuel_graph::QuantType::Q4_0,
                k: 32,
                n: 4,
            },
        );
        assert_row_pins(
            LINEAR_QUANT,
            "linear-quant.fkc.md",
            "FusedSoftmaxCrossEntropy",
            &FusedOpParams::FusedSoftmaxCrossEntropy {
                reduction: Reduction::Mean,
                ignore_index: -100,
            },
        );
        assert_row_pins(
            LINEAR_QUANT,
            "linear-quant.fkc.md",
            "Nf4Matmul",
            &FusedOpParams::Nf4Matmul { block_size: 64 },
        );

        // The threading note itself (the convention sentence) must be present
        // in BOTH files: `param(N)` indexes the key().ints flattening.
        for (doc, doc_name) in [
            (CONV_ROPE, "conv-rope.fkc.md"),
            (LINEAR_QUANT, "linear-quant.fkc.md"),
        ] {
            assert!(
                doc.contains("`param(N)` indexes the `FusedOpParams::key().ints` flattening"),
                "{doc_name} must carry the C-4 param-threading convention note",
            );
        }
    }
}