fuel-ir 0.20.14

Core types and traits for the fuel ML framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
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
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
// SPDX-License-Identifier: MIT OR Apache-2.0
//! TDD for the FDX validators (V1..V21). For EVERY validator there is a test
//! that PASSES on a valid input and a test that FAILS with the EXPECTED
//! `FdxValidationError` variant on a crafted invalid input. Structs are built
//! directly. Tests run under `--features dlpack`.

use super::*;
use crate::dlpack::abi::{DLDataType, DLDevice, dtype_code};
use crate::dlpack::sidecar::{
    FDXAffine, FDXAffineTerm, FDXBlockTable, FDXBufferRef, FDXDTypeExt, FDXExtent,
    FDXIndexedResidency, FDXOutputView, FDXQuant, FDXResidency, FDXStorage, FDXSymBinding,
    FDXSymEnv, FDXTiling,
};
use core::ffi::c_void;

// ─────────────────────────────────────────────────────────────────────────────
// Builders
// ─────────────────────────────────────────────────────────────────────────────

fn uint8_dtype() -> DLDataType {
    DLDataType {
        code: dtype_code::K_DL_UINT,
        bits: 8,
        lanes: 1,
    }
}

fn f16_dtype() -> DLDataType {
    DLDataType {
        code: dtype_code::K_DL_FLOAT,
        bits: 16,
        lanes: 1,
    }
}

fn dtype_ext_none() -> FDXDTypeExt {
    FDXDTypeExt {
        logical_dtype: FDX_DTYPE_NONE,
        bit_width: 0,
        packing: 0,
        lanes: 0,
        sub_byte_bit_order: 0,
        _pad: 0,
        reserved: [0; 2],
    }
}

fn quant_none() -> FDXQuant {
    FDXQuant {
        family: FDX_QUANT_NONE,
        ggml_dtype: FDX_DTYPE_NONE,
        block_ndim: 0,
        _pad0: [0; 3],
        block_shape: [0; 4],
        block_axes: [-1; 4],
        pack_order: 0,
        _pad1: [0; 3],
        scale_present: 0,
        scale_dtype: FDX_DTYPE_NONE,
        scale_placement: 0,
        scale_granularity: 0,
        _pad2: [0; 3],
        scale_buffer: FDX_BUFFER_INLINE,
        zp_present: 0,
        zp_dtype: FDX_DTYPE_NONE,
        _pad3: 0,
        zp_buffer: FDX_BUFFER_INLINE,
        scale_pair_act: 0,
        scale_pair_weight: 0,
        role: 0,
        _pad4: 0,
        reserved: [0; 6],
    }
}

fn tiling_none() -> FDXTiling {
    FDXTiling {
        alignment_bytes: 0,
        access_granularity_bits: 0,
        tile_ndim: 0,
        _pad: [0; 7],
        tile_shape: [0; 4],
        reserved: [0; 4],
    }
}

fn residency_none() -> FDXResidency {
    FDXResidency {
        tier: 0,
        substrate: 0,
        backend_id: 0,
        _pad: 0,
        device_index: 0,
        is_mmap_view: 0,
        _pad2: [0; 7],
        reserved: [0; 4],
    }
}

fn storage_none() -> FDXStorage {
    FDXStorage {
        class: 0,
        _pad: [0; 3],
        _pad_align: 0,
        session_id: 0,
        reserved: [0; 4],
    }
}

fn gather_none() -> FDXIndexedResidency {
    FDXIndexedResidency {
        kind: FDX_GATHER_NONE as u8,
        _pad0: [0; 3],
        num_blocks: 0,
        block_size: 0,
        pool_buffer: 0,
        _pad1: 0,
        physical_ndim: 0,
        _pad2: [0; 7],
        physical_shape: [0; 6],
        physical_strides: [0; 6],
        element_dtype: FDX_DTYPE_NONE,
        _pad3: [0; 2],
        block_table: FDXBlockTable {
            table_buffer: 0,
            id_dtype: FDX_DTYPE_NONE,
            _pad0: 0,
            max_blocks_per_seq: 0,
            unmapped_sentinel: FDX_BLOCK_UNMAPPED,
            layout_flags: 0,
            reserved: [0; 4],
        },
        num_sequences: 0,
        max_seq_capacity: 0,
        logical_ndim: 0,
        seq_axis: 0xFF,
        _pad4: [0; 6],
        logical_shape: [0; 6],
        logical_extents_count: 0,
        _pad5: [0; 7],
        logical_extents: [scalar_ext(0); 6],
        context_lens_buffer: FDX_BUFFER_NONE,
        context_len_sym: FDX_SYM_NONE,
        context_len_scope: 0,
        _pad6: [0; 3],
        reserved: [0; 6],
    }
}

fn affine_zero() -> FDXAffine {
    FDXAffine {
        c0: 0,
        term_count: 0,
        _pad: [0; 7],
        terms: [FDXAffineTerm {
            coeff: 0,
            sym_id: FDX_SYM_NONE,
            _pad: 0,
        }; FDX_AFFINE_MAX_TERMS],
    }
}

fn scalar_ext(v: u64) -> FDXExtent {
    FDXExtent {
        kind: FDX_EXTENT_SCALAR as u8,
        _pad: [0; 3],
        min: v,
        capacity: v,
        sym_id: FDX_SYM_NONE,
        sym_scope: 0,
        _pad2: [0; 3],
        cap_kind: FDX_CAP_KIND_EXPLICIT as u8,
        _pad3: [0; 3],
        _pad4: 0,
        affine: affine_zero(),
        reserved: [0; 2],
    }
}

fn range_ext(min: u64, capacity: u64, sym_id: u32) -> FDXExtent {
    FDXExtent {
        kind: FDX_EXTENT_RANGE as u8,
        _pad: [0; 3],
        min,
        capacity,
        sym_id,
        sym_scope: 0,
        _pad2: [0; 3],
        cap_kind: FDX_CAP_KIND_EXPLICIT as u8,
        _pad3: [0; 3],
        _pad4: 0,
        affine: affine_zero(),
        reserved: [0; 2],
    }
}

fn affine_ext(min: u64, capacity: u64, c0: i64, terms: &[(i64, u32)]) -> FDXExtent {
    let mut a = affine_zero();
    a.c0 = c0;
    a.term_count = terms.len() as u8;
    for (i, &(coeff, sym_id)) in terms.iter().enumerate() {
        a.terms[i] = FDXAffineTerm {
            coeff,
            sym_id,
            _pad: 0,
        };
    }
    FDXExtent {
        kind: FDX_EXTENT_AFFINE as u8,
        _pad: [0; 3],
        min,
        capacity,
        sym_id: FDX_SYM_NONE,
        sym_scope: 0,
        _pad2: [0; 3],
        cap_kind: FDX_CAP_KIND_EXPLICIT as u8,
        _pad3: [0; 3],
        _pad4: 0,
        affine: a,
        reserved: [0; 2],
    }
}

fn data_buffer(size_bytes: u64) -> FDXBufferRef {
    FDXBufferRef {
        role: FDX_BUFFER_ROLE_DATA,
        _pad: [0; 1],
        dtype: FDX_DTYPE_U8,
        _pad2: 0,
        data: core::ptr::null_mut(),
        device: DLDevice {
            device_type: 1,
            device_id: 0,
        },
        byte_offset: 0,
        size_bytes,
        ndim: 1,
        _pad3: 0,
        shape: [size_bytes, 0, 0, 0, 0, 0],
        strides: [1, 0, 0, 0, 0, 0],
        reserved: [0; 4],
    }
}

/// A minimal valid sidecar for a meaning-bearing tensor (flags supplied).
fn sidecar(flags: u32) -> FDXSidecar {
    FDXSidecar {
        magic: FDX_MAGIC,
        version: FDX_VERSION_1,
        struct_bytes: core::mem::size_of::<FDXSidecar>() as u32,
        flags,
        dtype_ext: dtype_ext_none(),
        quant: quant_none(),
        extents_count: 0,
        _pad0: 0,
        extents: core::ptr::null(),
        tiling: tiling_none(),
        residency: residency_none(),
        storage: storage_none(),
        buffers_count: 0,
        _pad1: 0,
        buffers: core::ptr::null(),
        views_count: 0,
        _pad2: 0,
        views: core::ptr::null(),
        gather: gather_none(),
        reserved: [0; 2],
    }
}

/// Base honesty-uint8 1-D byte tensor of `n_bytes`.
fn base_uint8(n_bytes: i64, shape: &mut [i64; 1], strides: &mut [i64; 1]) -> DLTensor {
    shape[0] = n_bytes;
    strides[0] = 1;
    DLTensor {
        data: core::ptr::null_mut(),
        device: DLDevice {
            device_type: 1,
            device_id: 0,
        },
        ndim: 1,
        dtype: uint8_dtype(),
        shape: shape.as_mut_ptr(),
        strides: strides.as_mut_ptr(),
        byte_offset: 0,
    }
}

fn env(bindings: &[FDXSymBinding]) -> FDXSymEnv {
    FDXSymEnv {
        count: bindings.len() as u32,
        _pad: 0,
        bindings: bindings.as_ptr(),
    }
}

fn bind(sym_id: u32, value: u64) -> FDXSymBinding {
    FDXSymBinding {
        sym_id,
        _pad: 0,
        value,
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// V1 — header
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v1_pass() {
    let sc = sidecar(0);
    assert!(check_v1_header(&sc).is_ok());
}

#[test]
fn v1_fail_bad_magic() {
    let mut sc = sidecar(0);
    sc.magic = 0xDEAD_BEEF;
    assert!(matches!(
        check_v1_header(&sc),
        Err(FdxValidationError::BadMagic { .. })
    ));
}

/// Version `0` is rejected. `0` is not a version -- the format starts at 1.
///
/// THIS TEST DID NOT EXIST UNTIL 2026-09-06, AND ITS ABSENCE IS THE POINT.
/// `check_v1_header` has always rejected `0`, but nothing asserted it and the
/// doc comment did not mention it, so the lower bound was defended by nothing.
/// A refactor collapsing `version == 0 || version > MAX` to `version > MAX`
/// would have been SILENT: the doc endorsed the shorter form, and the only
/// version test plants `FDX_VERSION_MAX + 1` -- the HIGH side alone.
///
/// That is the same test asymmetry GAP-292 found in FKC, in a file whose CODE
/// was already correct: THE GATE HAD TWO SIDES AND THE TEST SET INHERITED ONLY
/// ONE. Born-red verified: deleting `version == 0 ||` makes this fail while
/// `v1_fail_unsupported_version` keeps passing. See GAP-298.
#[test]
fn v1_fail_version_zero() {
    let mut sc = sidecar(0);
    sc.version = 0;
    assert!(matches!(
        check_v1_header(&sc),
        Err(FdxValidationError::UnsupportedVersion { .. })
    ));
}
#[test]
fn v1_fail_unsupported_version() {
    let mut sc = sidecar(0);
    sc.version = FDX_VERSION_MAX + 1;
    assert!(matches!(
        check_v1_header(&sc),
        Err(FdxValidationError::UnsupportedVersion { .. })
    ));
}

#[test]
fn v1_fail_struct_bytes_too_small() {
    let mut sc = sidecar(0);
    sc.struct_bytes = 4;
    assert!(matches!(
        check_v1_header(&sc),
        Err(FdxValidationError::StructBytesTooSmall { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V2 — flag/field coherence
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v2_pass() {
    let sc = sidecar(0); // no flags, no blocks
    assert!(check_v2_flag_coherence(&sc).is_ok());
}

#[test]
fn v2_fail_quant_flag_without_block() {
    let mut sc = sidecar(FDX_FLAG_HAS_QUANT); // flag set, quant.family == NONE
    sc.quant.family = FDX_QUANT_NONE;
    assert!(matches!(
        check_v2_flag_coherence(&sc),
        Err(FdxValidationError::FlagFieldIncoherent { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V3 — honesty (dtype)
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v3_pass() {
    let sc = sidecar(FDX_FLAG_MEANING_REQUIRES_EXT);
    let mut sh = [0i64; 1];
    let mut st = [0i64; 1];
    let base = base_uint8(16, &mut sh, &mut st);
    assert!(check_v3_honesty_dtype(&sc, &base).is_ok());
}

#[test]
fn v3_fail_dishonest_dtype() {
    let sc = sidecar(FDX_FLAG_MEANING_REQUIRES_EXT);
    let mut sh = [4i64; 1];
    let mut st = [1i64; 1];
    let base = DLTensor {
        data: core::ptr::null_mut(),
        device: DLDevice {
            device_type: 1,
            device_id: 0,
        },
        ndim: 1,
        dtype: f16_dtype(), // dishonest: meaning-bearing but not uint8
        shape: sh.as_mut_ptr(),
        strides: st.as_mut_ptr(),
        byte_offset: 0,
    };
    assert!(matches!(
        check_v3_honesty_dtype(&sc, &base),
        Err(FdxValidationError::DishonestBase { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V4 — sub-byte sizing
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v4_pass() {
    let mut sc = sidecar(FDX_FLAG_HAS_DTYPE_EXT);
    sc.dtype_ext = FDXDTypeExt {
        logical_dtype: FDX_DTYPE_F4,
        bit_width: 4,
        packing: 1, // DENSE_SUBBYTE
        lanes: 1,
        sub_byte_bit_order: 0,
        _pad: 0,
        reserved: [0; 2],
    };
    assert!(check_v4_sub_byte(&sc).is_ok());
}

#[test]
fn v4_fail_zero_bit_width() {
    let mut sc = sidecar(FDX_FLAG_HAS_DTYPE_EXT);
    sc.dtype_ext.logical_dtype = FDX_DTYPE_F4;
    sc.dtype_ext.bit_width = 0;
    assert!(matches!(
        check_v4_sub_byte(&sc),
        Err(FdxValidationError::BadSubByte { .. })
    ));
}

#[test]
fn v4_fail_dense_subbyte_full_byte() {
    let mut sc = sidecar(FDX_FLAG_HAS_DTYPE_EXT);
    sc.dtype_ext.logical_dtype = FDX_DTYPE_U8;
    sc.dtype_ext.bit_width = 8;
    sc.dtype_ext.packing = 1; // DENSE_SUBBYTE but bit_width >= 8
    assert!(matches!(
        check_v4_sub_byte(&sc),
        Err(FdxValidationError::BadSubByte { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V5 — quant coherence
// ─────────────────────────────────────────────────────────────────────────────

fn ggml_quant() -> FDXQuant {
    let mut q = quant_none();
    q.family = FDX_QUANT_GGML_BLOCK;
    q.ggml_dtype = 12; // Q4K
    q.block_ndim = 1;
    q.block_shape = [256, 0, 0, 0];
    q.block_axes = [1, -1, -1, -1];
    q.scale_present = 1;
    q.scale_placement = FDX_SCALE_PLACEMENT_INLINE;
    q.scale_buffer = FDX_BUFFER_INLINE;
    q.scale_granularity = FDX_SCALE_GRAN_PER_TENSOR;
    q
}

fn mx_quant() -> FDXQuant {
    let mut q = quant_none();
    q.family = FDX_QUANT_MX;
    q.block_ndim = 1;
    q.block_shape = [32, 0, 0, 0];
    q.block_axes = [1, -1, -1, -1];
    q.scale_present = 1;
    q.scale_dtype = FDX_DTYPE_F8E8M0;
    q.scale_placement = FDX_SCALE_PLACEMENT_SEPARATE_BUFFER;
    q.scale_granularity = FDX_SCALE_GRAN_PER_BLOCK;
    q.scale_buffer = 1;
    q
}

fn affine_block_quant() -> FDXQuant {
    let mut q = quant_none();
    q.family = FDX_QUANT_AFFINE_BLOCK;
    q.block_ndim = 1;
    q.block_shape = [64, 0, 0, 0];
    q.block_axes = [0, -1, -1, -1];
    q.scale_present = 1;
    q.scale_dtype = FDX_DTYPE_F32;
    q.scale_placement = FDX_SCALE_PLACEMENT_SEPARATE_BUFFER;
    q.scale_buffer = 1;
    q.scale_granularity = FDX_SCALE_GRAN_PER_TENSOR;
    q
}

#[test]
fn v5_pass_ggml() {
    let mut sc = sidecar(FDX_FLAG_HAS_QUANT);
    sc.quant = ggml_quant();
    assert!(check_v5_quant(&sc).is_ok());
}

#[test]
fn v5_pass_mx() {
    let mut sc = sidecar(FDX_FLAG_HAS_QUANT);
    sc.quant = mx_quant();
    assert!(check_v5_quant(&sc).is_ok());
}

#[test]
fn v5_pass_affine_block() {
    let mut sc = sidecar(FDX_FLAG_HAS_QUANT);
    sc.quant = affine_block_quant();
    assert!(check_v5_quant(&sc).is_ok());
}

#[test]
fn v5_fail_ggml_with_perblock() {
    let mut sc = sidecar(FDX_FLAG_HAS_QUANT);
    let mut q = ggml_quant();
    q.scale_granularity = FDX_SCALE_GRAN_PER_BLOCK; // PerBlock under GGML
    sc.quant = q;
    assert!(matches!(
        check_v5_quant(&sc),
        Err(FdxValidationError::QuantRegimeViolation { .. })
    ));
}

#[test]
fn v5_fail_ggml_with_separate_buffer() {
    let mut sc = sidecar(FDX_FLAG_HAS_QUANT);
    let mut q = ggml_quant();
    q.scale_placement = FDX_SCALE_PLACEMENT_SEPARATE_BUFFER;
    q.scale_buffer = 1;
    sc.quant = q;
    assert!(matches!(
        check_v5_quant(&sc),
        Err(FdxValidationError::QuantRegimeViolation { .. })
    ));
}

#[test]
fn v5_fail_mx_wrong_scale_dtype() {
    let mut sc = sidecar(FDX_FLAG_HAS_QUANT);
    let mut q = mx_quant();
    q.scale_dtype = FDX_DTYPE_F32; // MX requires F8E8M0
    sc.quant = q;
    assert!(matches!(
        check_v5_quant(&sc),
        Err(FdxValidationError::QuantRegimeViolation { .. })
    ));
}

#[test]
fn v5_fail_affine_block_inline_scale() {
    let mut sc = sidecar(FDX_FLAG_HAS_QUANT);
    let mut q = affine_block_quant();
    q.scale_buffer = FDX_BUFFER_INLINE; // must be a real index
    sc.quant = q;
    assert!(matches!(
        check_v5_quant(&sc),
        Err(FdxValidationError::QuantRegimeViolation { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V6 — scale shape vs block geometry
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v6_pass_affine_block_scale_count() {
    // base logical axis 0 length 128, block 64 ⇒ 2 blocks ⇒ scale shape [2].
    let mut sc = sidecar(FDX_FLAG_HAS_QUANT);
    let mut q = affine_block_quant();
    q.block_axes = [0, -1, -1, -1];
    q.block_shape = [64, 0, 0, 0];
    sc.quant = q;
    let mut sh = [128i64; 1];
    let mut st = [1i64; 1];
    let base = base_uint8(128, &mut sh, &mut st);
    let mut scale = data_buffer(8);
    scale.role = FDX_BUFFER_ROLE_SCALE;
    scale.dtype = FDX_DTYPE_F32;
    scale.ndim = 1;
    scale.shape = [2, 0, 0, 0, 0, 0]; // 2 blocks
    let buffers = vec![data_buffer(64), scale];
    assert!(check_v6_scale_shape(&sc, &base, &buffers).is_ok());
}

#[test]
fn v6_affine_block_subbyte_logical_count() {
    // NF4 (spec §6.2 / §13.5a): the honest base is the PACKED uint8 byte buffer
    // (2 nibbles/byte), but the block count is over the base LOGICAL element shape.
    // 64 packed bytes @ bit_width 4 ⇒ 128 logical F4 elements; block 64 ⇒ 2 blocks
    // ⇒ scale shape [2]. V6 must convert the byte extent to logical via bit_width
    // (a byte-only `ceil(64/64)=1` would wrongly reject the spec's own example).
    let mut sc = sidecar(FDX_FLAG_HAS_QUANT | FDX_FLAG_HAS_DTYPE_EXT);
    sc.dtype_ext = FDXDTypeExt {
        logical_dtype: FDX_DTYPE_F4,
        bit_width: 4,
        packing: 1, // DENSE_SUBBYTE
        lanes: 1,
        sub_byte_bit_order: 0,
        _pad: 0,
        reserved: [0; 2],
    };
    let mut q = affine_block_quant();
    q.block_axes = [0, -1, -1, -1];
    q.block_shape = [64, 0, 0, 0];
    sc.quant = q;
    let mut sh = [64i64; 1]; // 64 PACKED bytes
    let mut st = [1i64; 1];
    let base = base_uint8(64, &mut sh, &mut st);
    let mut scale = data_buffer(8);
    scale.role = FDX_BUFFER_ROLE_SCALE;
    scale.dtype = FDX_DTYPE_F32;
    scale.ndim = 1;
    scale.shape = [2, 0, 0, 0, 0, 0]; // 128 logical / 64 = 2 blocks
    let buffers = vec![data_buffer(64), scale];
    assert!(
        check_v6_scale_shape(&sc, &base, &buffers).is_ok(),
        "sub-byte AFFINE_BLOCK block count must be over LOGICAL elements (bytes*8/bit_width)"
    );
}

#[test]
fn v6_fail_block_scale_count_mismatch() {
    let mut sc = sidecar(FDX_FLAG_HAS_QUANT);
    let mut q = affine_block_quant();
    q.block_axes = [0, -1, -1, -1];
    q.block_shape = [64, 0, 0, 0];
    sc.quant = q;
    let mut sh = [128i64; 1];
    let mut st = [1i64; 1];
    let base = base_uint8(128, &mut sh, &mut st);
    let mut scale = data_buffer(8);
    scale.role = FDX_BUFFER_ROLE_SCALE;
    scale.dtype = FDX_DTYPE_F32;
    scale.ndim = 1;
    scale.shape = [5, 0, 0, 0, 0, 0]; // wrong: should be 2
    let buffers = vec![data_buffer(64), scale];
    assert!(matches!(
        check_v6_scale_shape(&sc, &base, &buffers),
        Err(FdxValidationError::ScaleShapeMismatch { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V7 — extents
// ─────────────────────────────────────────────────────────────────────────────

fn base_3d(shape: &mut [i64; 3], strides: &mut [i64; 3]) -> DLTensor {
    // [32, 4096, 128] capacity F16, dense strides keyed to capacity.
    shape.copy_from_slice(&[32, 4096, 128]);
    strides.copy_from_slice(&[4096 * 128, 128, 1]);
    DLTensor {
        data: core::ptr::null_mut(),
        device: DLDevice {
            device_type: 2,
            device_id: 0,
        },
        ndim: 3,
        dtype: f16_dtype(),
        shape: shape.as_mut_ptr(),
        strides: strides.as_mut_ptr(),
        byte_offset: 0,
    }
}

#[test]
fn v7_pass_kv_extents() {
    let exts = [scalar_ext(32), range_ext(1, 4096, 7), scalar_ext(128)];
    let mut sc = sidecar(FDX_FLAG_HAS_SYMBOLIC);
    sc.extents_count = 3;
    sc.extents = exts.as_ptr();
    let mut sh = [0i64; 3];
    let mut st = [0i64; 3];
    let base = base_3d(&mut sh, &mut st);
    assert!(check_v7_extents(&sc, &base).is_ok());
}

#[test]
fn v7_fail_capacity_mismatch() {
    // axis 1 capacity 9999 != base.shape[1] 4096
    let exts = [scalar_ext(32), range_ext(1, 9999, 7), scalar_ext(128)];
    let mut sc = sidecar(FDX_FLAG_HAS_SYMBOLIC);
    sc.extents_count = 3;
    sc.extents = exts.as_ptr();
    let mut sh = [0i64; 3];
    let mut st = [0i64; 3];
    let base = base_3d(&mut sh, &mut st);
    assert!(matches!(
        check_v7_extents(&sc, &base),
        Err(FdxValidationError::ExtentMismatch { axis: 1, .. })
    ));
}

#[test]
fn v7_fail_cap_kind_poisoned() {
    let mut bad = scalar_ext(32);
    bad.cap_kind = 1; // AFFINE_MAX poisoning on a Scalar
    let exts = [bad, range_ext(1, 4096, 7), scalar_ext(128)];
    let mut sc = sidecar(FDX_FLAG_HAS_SYMBOLIC);
    sc.extents_count = 3;
    sc.extents = exts.as_ptr();
    let mut sh = [0i64; 3];
    let mut st = [0i64; 3];
    let base = base_3d(&mut sh, &mut st);
    assert!(matches!(
        check_v7_extents(&sc, &base),
        Err(FdxValidationError::ExtentMismatch { axis: 0, .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V8 — capacity backing
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v8_pass_full_backing() {
    let sc = sidecar(FDX_FLAG_HAS_SYMBOLIC);
    let mut sh = [0i64; 3];
    let mut st = [0i64; 3];
    let base = base_3d(&mut sh, &mut st);
    let buffers = vec![data_buffer(32 * 4096 * 128 * 2)];
    assert!(check_v8_capacity_backing(&sc, &base, &buffers).is_ok());
}

#[test]
fn v8_fail_under_backed_without_flag() {
    let sc = sidecar(FDX_FLAG_HAS_SYMBOLIC); // MEANING_REQUIRES_EXT clear
    let mut sh = [0i64; 3];
    let mut st = [0i64; 3];
    let base = base_3d(&mut sh, &mut st);
    let buffers = vec![data_buffer(1024)]; // far too small
    assert!(matches!(
        check_v8_capacity_backing(&sc, &base, &buffers),
        Err(FdxValidationError::CapacityNotBacked { .. })
    ));
}

#[test]
fn v8_pass_under_backed_with_meaning_flag() {
    let sc = sidecar(FDX_FLAG_HAS_SYMBOLIC | FDX_FLAG_MEANING_REQUIRES_EXT);
    let mut sh = [0i64; 3];
    let mut st = [0i64; 3];
    let base = base_3d(&mut sh, &mut st);
    let buffers = vec![data_buffer(1024)];
    assert!(check_v8_capacity_backing(&sc, &base, &buffers).is_ok());
}

// ─────────────────────────────────────────────────────────────────────────────
// V9 — buffer refs
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v9_pass() {
    let mut sc = sidecar(0);
    sc.buffers_count = 1;
    let buffers = vec![data_buffer(16)];
    assert!(check_v9_buffer_refs(&sc, &buffers).is_ok());
}

#[test]
fn v9_fail_scale_buffer_oob() {
    let mut sc = sidecar(FDX_FLAG_HAS_QUANT);
    sc.quant = mx_quant();
    sc.quant.scale_buffer = 7; // out of range
    sc.buffers_count = 1;
    let buffers = vec![data_buffer(16)];
    assert!(matches!(
        check_v9_buffer_refs(&sc, &buffers),
        Err(FdxValidationError::BufferRefOutOfRange { index: 7, .. })
    ));
}

#[test]
fn v9_fail_index0_not_data() {
    let mut sc = sidecar(0);
    sc.buffers_count = 1;
    let mut b = data_buffer(16);
    b.role = FDX_BUFFER_ROLE_SCALE; // index 0 must be Data
    let buffers = vec![b];
    assert!(matches!(
        check_v9_buffer_refs(&sc, &buffers),
        Err(FdxValidationError::FlagFieldIncoherent { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V10 — bundle
// ─────────────────────────────────────────────────────────────────────────────

fn view(byte_offset: u64, len_elements: u64, dtype: u16) -> FDXOutputView {
    FDXOutputView {
        byte_offset,
        len_elements,
        dtype,
        _pad: [0; 2],
        ndim: 1,
        shape: [len_elements, 0, 0, 0, 0, 0],
        strides: [1, 0, 0, 0, 0, 0],
        name_hash: 0,
        reserved: [0; 4],
    }
}

#[test]
fn v10_pass() {
    // bundle: F32 [0..B*V*4), I64 [B*V*4 ..]
    let b = 4u64;
    let v = 8u64;
    let total = b * v * 4 + b * 8;
    let views = [
        view(0, b * v, FDX_DTYPE_F32),
        view(b * v * 4, b, FDX_DTYPE_I64),
    ];
    let mut sc = sidecar(FDX_FLAG_IS_BUNDLE);
    sc.views_count = 2;
    sc.views = views.as_ptr();
    let buffers = vec![data_buffer(total)];
    assert!(check_v10_bundle(&sc, &buffers).is_ok());
}

#[test]
fn v10_fail_overlap() {
    let views = [view(0, 8, FDX_DTYPE_F32), view(4, 8, FDX_DTYPE_F32)]; // overlap
    let mut sc = sidecar(FDX_FLAG_IS_BUNDLE);
    sc.views_count = 2;
    sc.views = views.as_ptr();
    let buffers = vec![data_buffer(1024)];
    assert!(matches!(
        check_v10_bundle(&sc, &buffers),
        Err(FdxValidationError::BundleOverlap { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V11 — explicit strides
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v11_pass() {
    let mut sh = [0i64; 1];
    let mut st = [0i64; 1];
    let base = base_uint8(16, &mut sh, &mut st);
    assert!(check_v11_explicit_strides(&base).is_ok());
}

#[test]
fn v11_fail_null_strides() {
    let mut sh = [4i64; 1];
    let base = DLTensor {
        data: core::ptr::null_mut(),
        device: DLDevice {
            device_type: 1,
            device_id: 0,
        },
        ndim: 1,
        dtype: f16_dtype(),
        shape: sh.as_mut_ptr(),
        strides: core::ptr::null_mut(), // NULL strides, ndim != 0
        byte_offset: 0,
    };
    assert!(matches!(
        check_v11_explicit_strides(&base),
        Err(FdxValidationError::NullStrides { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V12 — 256-byte alignment (boundary b)
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v12_pass_aligned() {
    // 256-aligned pointer (fabricated; not dereferenced).
    let aligned = 0x1_0000usize as *mut c_void;
    let mut sh = [0i64; 1];
    let mut st = [0i64; 1];
    let mut base = base_uint8(16, &mut sh, &mut st);
    base.data = aligned;
    let mut buf = data_buffer(16);
    buf.data = aligned;
    let buffers = vec![buf];
    assert!(check_v12_alignment_boundary_b(&base, &buffers).is_ok());
}

#[test]
fn v12_fail_misaligned() {
    let misaligned = 0x1_0001usize as *mut c_void;
    let mut sh = [0i64; 1];
    let mut st = [0i64; 1];
    let mut base = base_uint8(16, &mut sh, &mut st);
    base.data = misaligned;
    let buffers = vec![data_buffer(16)];
    assert!(matches!(
        check_v12_alignment_boundary_b(&base, &buffers),
        Err(FdxValidationError::Misaligned { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V13 — signed-stride OOB range
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v13_pass_positive_strides() {
    // [4,4] F32, strides [4,1], size 64 bytes (4*4*4).
    assert!(check_v13_signed_stride_oob(&[4, 4], &[4, 1], 0, 4, 64, "t").is_ok());
}

#[test]
fn v13_pass_negative_strides_first_class() {
    // Reversed last axis: strides [4, -1], byte_offset points at iteration-first
    // element so start_offset stays non-negative. [4,4] F32 64 bytes.
    // For row r col c: addr = bo + r*4 + c*(-1). Window: lo at c=3 ⇒ -3;
    // byte_offset must absorb that. Put byte_offset at 3 elems = 12 bytes.
    assert!(check_v13_signed_stride_oob(&[4, 4], &[4, -1], 12, 4, 64, "t").is_ok());
}

#[test]
fn v13_fail_out_of_bounds() {
    // stride too large: [4] with stride 100, size 64 bytes ⇒ touches way past.
    assert!(matches!(
        check_v13_signed_stride_oob(&[4], &[100], 0, 4, 64, "t"),
        Err(FdxValidationError::StrideRangeOutOfBounds { .. })
    ));
}

#[test]
fn v13_fail_negative_escapes_below_zero() {
    // negative stride with insufficient byte_offset ⇒ window dips below 0.
    assert!(matches!(
        check_v13_signed_stride_oob(&[4], &[-1], 0, 4, 64, "t"),
        Err(FdxValidationError::StrideRangeOutOfBounds { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V14 — realize-time symbol bounds
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v14_pass_range_in_bounds() {
    let ext = range_ext(1, 4096, 7);
    let b = [bind(7, 2048)];
    let e = env(&b);
    assert_eq!(check_v14_extent_bounds(&ext, 1, &e).unwrap(), 2048);
}

#[test]
fn v14_fail_range_over_capacity() {
    let ext = range_ext(1, 4096, 7);
    let b = [bind(7, 5000)]; // > capacity
    let e = env(&b);
    assert!(matches!(
        check_v14_extent_bounds(&ext, 1, &e),
        Err(FdxValidationError::ExtentOutOfRange { .. })
    ));
}

#[test]
fn v14_fail_unbound_symbol() {
    let ext = range_ext(1, 4096, 7);
    let b: [FDXSymBinding; 0] = [];
    let e = env(&b);
    assert!(matches!(
        check_v14_extent_bounds(&ext, 1, &e),
        Err(FdxValidationError::UnboundSymbol { sym_id: 7, .. })
    ));
}

#[test]
fn v14_pass_affine_decode() {
    // k_len = cached_len(7) + new_tokens(8); cap 4096, min 1.
    let ext = affine_ext(1, 4096, 0, &[(1, 7), (1, 8)]);
    let b = [bind(7, 2000), bind(8, 1)];
    let e = env(&b);
    assert_eq!(check_v14_extent_bounds(&ext, 1, &e).unwrap(), 2001);
}

#[test]
fn v14_fail_affine_over_capacity() {
    let ext = affine_ext(1, 4096, 0, &[(1, 7), (1, 8)]);
    let b = [bind(7, 4096), bind(8, 1)]; // 4097 > 4096
    let e = env(&b);
    assert!(matches!(
        check_v14_extent_bounds(&ext, 1, &e),
        Err(FdxValidationError::ExtentOutOfRange { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V15 — no raw pointers in serialized form
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v15_pass_serialized() {
    let sc = sidecar(0); // all array pointers null
    let buffers = vec![data_buffer(16)]; // data null
    assert!(check_v15_no_serialized_pointers(&sc, &buffers).is_ok());
}

#[test]
fn v15_fail_pointer_present() {
    let mut sc = sidecar(0);
    let exts = [scalar_ext(1)];
    sc.extents = exts.as_ptr(); // non-null array pointer in "serialized" form
    sc.extents_count = 1;
    let buffers = vec![data_buffer(16)];
    assert!(matches!(
        check_v15_no_serialized_pointers(&sc, &buffers),
        Err(FdxValidationError::PointerInSerializedForm { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V16 — affine well-formedness
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v16_pass() {
    let ext = affine_ext(1, 4096, 0, &[(1, 7), (1, 8)]);
    assert!(check_v16_affine(&ext, 1).is_ok());
}

#[test]
fn v16_fail_degenerate_range() {
    // term_count==1, c0==0, coeff==1 ⇒ must be Range.
    let ext = affine_ext(0, 4096, 0, &[(1, 7)]);
    assert!(matches!(
        check_v16_affine(&ext, 1),
        Err(FdxValidationError::AffineDegenerate { .. })
    ));
}

#[test]
fn v16_fail_duplicate_sym() {
    let ext = affine_ext(1, 4096, 0, &[(1, 7), (1, 7)]); // dup sym 7
    assert!(matches!(
        check_v16_affine(&ext, 1),
        Err(FdxValidationError::AffineMalformed { .. })
    ));
}

#[test]
fn v16_fail_too_many_terms() {
    // craft term_count > MAX by hand.
    let mut ext = affine_ext(1, 4096, 0, &[(1, 1), (1, 2), (1, 3), (1, 4)]);
    ext.affine.term_count = (FDX_AFFINE_MAX_TERMS + 1) as u8;
    assert!(matches!(
        check_v16_affine(&ext, 1),
        Err(FdxValidationError::AffineTooManyTerms { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V17 — affine evaluation safety
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v17_pass() {
    let ext = affine_ext(1, 4096, 5, &[(1, 7)]); // c0=5 ⇒ legal affine
    let b = [bind(7, 100)];
    let e = env(&b);
    assert_eq!(check_v17_affine_eval(&ext, 1, &e).unwrap(), 105);
}

#[test]
fn v17_fail_overflow() {
    // coeff * sym overflows i128 accumulation.
    let ext = affine_ext(0, u64::MAX, 0, &[(i64::MAX, 7), (i64::MAX, 8)]);
    let b = [bind(7, u64::MAX), bind(8, u64::MAX)];
    let e = env(&b);
    assert!(matches!(
        check_v17_affine_eval(&ext, 1, &e),
        Err(FdxValidationError::AffineOverflow { .. })
    ));
}

#[test]
fn v17_fail_negative_result() {
    // c0 large-negative dominates ⇒ negative result rejected before narrowing.
    let ext = affine_ext(0, 4096, -1000, &[(1, 7)]);
    let b = [bind(7, 1)]; // -999
    let e = env(&b);
    assert!(matches!(
        check_v17_affine_eval(&ext, 1, &e),
        Err(FdxValidationError::ExtentOutOfRange { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// Gather builders
// ─────────────────────────────────────────────────────────────────────────────

/// A valid §13.8-style paged gather sidecar + base + buffers.
fn gather_fixture() -> (FDXSidecar, DLTensor, Vec<FDXBufferRef>, [i64; 1], [i64; 1]) {
    let num_blocks = 256u64;
    let block_size = 16u64;
    let hkv = 8u64;
    let d = 128u64;
    let elem = 2u64; // F16
    let per_block = block_size * hkv * d; // 16384 typed elements
    let pool_bytes = per_block * num_blocks * elem; // 8,388,608
    let max_blocks_per_seq = 64u32;
    let max_seq_cap = max_blocks_per_seq as u64 * block_size; // 1024
    let num_seq = 4u64;

    let mut g = gather_none();
    g.kind = FDX_GATHER_PAGED_BLOCKS as u8;
    g.num_blocks = num_blocks;
    g.block_size = block_size;
    g.pool_buffer = 0;
    g.physical_ndim = 4;
    g.physical_shape = [num_blocks, block_size, hkv, d, 0, 0];
    g.physical_strides = [
        (block_size * hkv * d) as i64,
        (hkv * d) as i64,
        d as i64,
        1,
        0,
        0,
    ];
    g.element_dtype = FDX_DTYPE_F16;
    g.block_table = FDXBlockTable {
        table_buffer: 1,
        id_dtype: FDX_DTYPE_U32,
        _pad0: 0,
        max_blocks_per_seq,
        unmapped_sentinel: FDX_BLOCK_UNMAPPED,
        layout_flags: 0,
        reserved: [0; 4],
    };
    g.num_sequences = num_seq;
    g.max_seq_capacity = max_seq_cap;
    g.logical_ndim = 3;
    g.seq_axis = 1;
    g.logical_shape = [hkv, max_seq_cap, d, 0, 0, 0];
    g.logical_extents_count = 3;
    g.logical_extents = [
        scalar_ext(hkv),
        range_ext(0, max_seq_cap, 11),
        scalar_ext(d),
        scalar_ext(0),
        scalar_ext(0),
        scalar_ext(0),
    ];
    g.context_lens_buffer = 2;
    g.context_len_sym = 11;
    g.context_len_scope = 0;

    let mut sc =
        sidecar(FDX_FLAG_HAS_GATHER | FDX_FLAG_HAS_SYMBOLIC | FDX_FLAG_MEANING_REQUIRES_EXT);
    sc.gather = g;
    // base extents: 1-D byte pool, Scalar(pool_bytes).
    sc.buffers_count = 3;

    let mut sh = [0i64; 1];
    let mut st = [0i64; 1];
    let base = base_uint8(pool_bytes as i64, &mut sh, &mut st);

    let mut pool = data_buffer(pool_bytes);
    pool.role = FDX_BUFFER_ROLE_POOL;
    pool.dtype = FDX_DTYPE_F16;
    pool.ndim = 4;
    pool.shape = [num_blocks, block_size, hkv, d, 0, 0];
    pool.strides = [
        (block_size * hkv * d) as i64,
        (hkv * d) as i64,
        d as i64,
        1,
        0,
        0,
    ];

    let mut bt = data_buffer(num_seq * max_blocks_per_seq as u64 * 4);
    bt.role = FDX_BUFFER_ROLE_BLOCK_TABLE;
    bt.dtype = FDX_DTYPE_U32;
    bt.ndim = 2;
    bt.shape = [num_seq, max_blocks_per_seq as u64, 0, 0, 0, 0];
    bt.strides = [max_blocks_per_seq as i64, 1, 0, 0, 0, 0];

    let mut cl = data_buffer(num_seq * 4);
    cl.role = FDX_BUFFER_ROLE_CONTEXT_LENS;
    cl.dtype = FDX_DTYPE_U32;
    cl.ndim = 1;
    cl.shape = [num_seq, 0, 0, 0, 0, 0];
    cl.strides = [1, 0, 0, 0, 0, 0];

    let buffers = vec![pool, bt, cl];
    (sc, base, buffers, sh, st)
}

// ─────────────────────────────────────────────────────────────────────────────
// V18 — gather coherence
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v18_pass() {
    let (sc, _b, _buf, _sh, _st) = gather_fixture();
    assert!(check_v18_gather_coherence(&sc).is_ok());
}

#[test]
fn v18_fail_block_size_zero() {
    let (mut sc, _b, _buf, _sh, _st) = gather_fixture();
    sc.gather.block_size = 0;
    assert!(matches!(
        check_v18_gather_coherence(&sc),
        Err(FdxValidationError::GatherIncoherent { .. })
    ));
}

#[test]
fn v18_fail_bad_capacity_product() {
    let (mut sc, _b, _buf, _sh, _st) = gather_fixture();
    sc.gather.max_seq_capacity = 999; // != 64*16
    assert!(matches!(
        check_v18_gather_coherence(&sc),
        Err(FdxValidationError::GatherIncoherent { .. })
    ));
}

#[test]
fn v18_fail_unsupported_kind() {
    let (mut sc, _b, _buf, _sh, _st) = gather_fixture();
    sc.gather.kind = 9; // unknown
    assert!(matches!(
        check_v18_gather_coherence(&sc),
        Err(FdxValidationError::UnsupportedGatherKind { kind: 9 })
    ));
}

#[test]
fn v18_fail_sentinel_below_num_blocks() {
    let (mut sc, _b, _buf, _sh, _st) = gather_fixture();
    sc.gather.block_table.unmapped_sentinel = 100; // < num_blocks 256
    assert!(matches!(
        check_v18_gather_coherence(&sc),
        Err(FdxValidationError::GatherIncoherent { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V19 — meaning + base honesty
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v19_pass() {
    let (sc, base, _buf, _sh, _st) = gather_fixture();
    assert!(check_v19_gather_meaning_and_honesty(&sc, &base).is_ok());
}

#[test]
fn v19_fail_missing_meaning_flag() {
    let (mut sc, base, _buf, _sh, _st) = gather_fixture();
    sc.flags &= !FDX_FLAG_MEANING_REQUIRES_EXT;
    assert!(matches!(
        check_v19_gather_meaning_and_honesty(&sc, &base),
        Err(FdxValidationError::DishonestBase { .. })
    ));
}

#[test]
fn v19_fail_base_byte_cover_mismatch() {
    let (sc, _base, _buf, mut sh, mut st) = gather_fixture();
    // base byte length wrong (half the pool).
    let base = base_uint8(4_194_304, &mut sh, &mut st);
    assert!(matches!(
        check_v19_gather_meaning_and_honesty(&sc, &base),
        Err(FdxValidationError::DishonestBase { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V20 — pool backing
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v20_pass() {
    let (sc, _b, buffers, _sh, _st) = gather_fixture();
    assert!(check_v20_pool_backing(&sc, &buffers).is_ok());
}

#[test]
fn v20_fail_pool_under_backed() {
    let (sc, _b, mut buffers, _sh, _st) = gather_fixture();
    buffers[0].size_bytes = 1024; // far too small
    assert!(matches!(
        check_v20_pool_backing(&sc, &buffers),
        Err(FdxValidationError::CapacityNotBacked { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V21(a) — gather buffers
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v21a_pass() {
    let (sc, _b, buffers, _sh, _st) = gather_fixture();
    assert!(check_v21a_gather_buffers(&sc, &buffers).is_ok());
}

#[test]
fn v21a_fail_block_table_shape() {
    let (sc, _b, mut buffers, _sh, _st) = gather_fixture();
    buffers[1].shape = [4, 99, 0, 0, 0, 0]; // wrong max_blocks_per_seq
    assert!(matches!(
        check_v21a_gather_buffers(&sc, &buffers),
        Err(FdxValidationError::GatherIncoherent { .. })
    ));
}

#[test]
fn v21a_fail_table_buffer_oob() {
    let (mut sc, _b, buffers, _sh, _st) = gather_fixture();
    sc.gather.block_table.table_buffer = 9; // out of range
    assert!(matches!(
        check_v21a_gather_buffers(&sc, &buffers),
        Err(FdxValidationError::BufferRefOutOfRange { index: 9, .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V21(c) — block table full-table scan
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v21c_pass() {
    let (sc, _b, _buf, _sh, _st) = gather_fixture();
    // valid ids plus sentinel tail.
    let ids = vec![0u32, 1, 2, 255, FDX_BLOCK_UNMAPPED, FDX_BLOCK_UNMAPPED];
    assert!(check_v21c_block_table_scan(&sc, &ids).is_ok());
}

#[test]
fn v21c_fail_id_out_of_range() {
    let (sc, _b, _buf, _sh, _st) = gather_fixture();
    let ids = vec![0u32, 256, 1]; // 256 >= num_blocks 256
    assert!(matches!(
        check_v21c_block_table_scan(&sc, &ids),
        Err(FdxValidationError::BlockIdOutOfRange { id: 256, .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V21(d) — seq live length
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v21d_pass_normal_and_empty() {
    let (sc, _b, _buf, _sh, _st) = gather_fixture();
    assert!(check_v21d_seq_live_length(&sc, 0, 512).is_ok());
    // L == 0 is legal (finished/evicted sequence).
    assert!(check_v21d_seq_live_length(&sc, 1, 0).is_ok());
    // exactly capacity is legal.
    assert!(check_v21d_seq_live_length(&sc, 2, 1024).is_ok());
}

#[test]
fn v21d_fail_over_capacity() {
    let (sc, _b, _buf, _sh, _st) = gather_fixture();
    assert!(matches!(
        check_v21d_seq_live_length(&sc, 0, 2000), // > max_seq_capacity 1024
        Err(FdxValidationError::ExtentOutOfRange { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// V21(e) — logical extents
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn v21e_pass() {
    let (sc, _b, _buf, _sh, _st) = gather_fixture();
    assert!(check_v21e_logical_extents(&sc).is_ok());
}

#[test]
fn v21e_fail_seq_extent_min_nonzero() {
    let (mut sc, _b, _buf, _sh, _st) = gather_fixture();
    sc.gather.logical_extents[1].min = 1; // must be 0 for a paged batch
    assert!(matches!(
        check_v21e_logical_extents(&sc),
        Err(FdxValidationError::GatherIncoherent { .. })
    ));
}

#[test]
fn v21e_fail_seq_sym_mismatch() {
    let (mut sc, _b, _buf, _sh, _st) = gather_fixture();
    sc.gather.logical_extents[1].sym_id = 99; // != context_len_sym 11
    assert!(matches!(
        check_v21e_logical_extents(&sc),
        Err(FdxValidationError::GatherIncoherent { .. })
    ));
}

// ─────────────────────────────────────────────────────────────────────────────
// Top-level surfaces
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn validate_pass_dense_kv() {
    let exts = [scalar_ext(32), range_ext(1, 4096, 7), scalar_ext(128)];
    let mut sc = sidecar(FDX_FLAG_HAS_SYMBOLIC);
    sc.extents_count = 3;
    sc.extents = exts.as_ptr();
    sc.buffers_count = 1;
    let mut sh = [0i64; 3];
    let mut st = [0i64; 3];
    let base = base_3d(&mut sh, &mut st);
    let buffers = vec![data_buffer(32 * 4096 * 128 * 2)];
    assert!(validate(&sc, &base, &buffers).is_ok());
}

#[test]
fn validate_pass_full_gather() {
    let (sc, base, buffers, _sh, _st) = gather_fixture();
    assert!(validate(&sc, &base, &buffers).is_ok());
}

#[test]
fn validate_realize_pass_gather() {
    let (sc, base, buffers, _sh, _st) = gather_fixture();
    let b = [bind(11, 512)];
    let e = env(&b);
    assert!(validate_realize(&sc, &base, &buffers, &e).is_ok());
}

#[test]
fn validate_realize_fail_over_capacity() {
    let (sc, base, buffers, _sh, _st) = gather_fixture();
    let b = [bind(11, 99999)]; // > max_seq_capacity
    let e = env(&b);
    assert!(validate_realize(&sc, &base, &buffers, &e).is_err());
}

#[test]
fn validate_realize_pass_affine_decode() {
    // [32, 4096, 128] KV with affine live axis 1.
    let exts = [
        scalar_ext(32),
        affine_ext(1, 4096, 0, &[(1, 7), (1, 8)]),
        scalar_ext(128),
    ];
    let mut sc = sidecar(FDX_FLAG_HAS_SYMBOLIC | FDX_FLAG_HAS_AFFINE_EXTENT);
    sc.extents_count = 3;
    sc.extents = exts.as_ptr();
    sc.buffers_count = 1;
    let mut sh = [0i64; 3];
    let mut st = [0i64; 3];
    let base = base_3d(&mut sh, &mut st);
    let buffers = vec![data_buffer(32 * 4096 * 128 * 2)];
    let b = [bind(7, 2000), bind(8, 1)];
    let e = env(&b);
    assert!(validate_realize(&sc, &base, &buffers, &e).is_ok());
}

// ─────────────────────────────────────────────────────────────────────────────
// meaning-bearing ⇒ MEANING_REQUIRES_EXT (generalises V19's mandatory clause)
//
// The v1 meaning-bearing set already implies the flag — measured: no valid v1
// sidecar sets a meaning-bearing flag without MEANING_REQUIRES_EXT. (The per-check
// tests DO build HAS_QUANT/HAS_DTYPE_EXT sidecars, but they call check_v4/v5/v6
// DIRECTLY and never reach validate(), so they never exercise this arm — the call
// path, not the fixture, is what determines membership.) The arm's real job is a
// FUTURE flag, so a SYNTHETIC bit with no other validator attached is the only
// construction where ONLY this arm can reject: a real member like
// HAS_QUANT-without-implication is caught by V2/V5 first and would redden a
// born-red on the wrong guard.
//
// Sabotage-proven (2026-09-08):
//   * arm body replaced with `Ok(())` reddens `meaning_bearing_flag_without_ext_is_rejected`
//     and `every_real_meaning_bearing_flag_requires_ext`.
//   * arm rejecting ANY set flag (ignoring the `meaning_bearing` param) reddens
//     `non_meaning_bearing_flag_is_not_required_to_set_ext`.
// ─────────────────────────────────────────────────────────────────────────────

/// A synthetic FUTURE meaning-bearing flag in the reserved range (bit 30). No
/// other validator knows this bit, so only the new arm can act on it — which is
/// what keeps the born-red from passing on some other guard.
const SYNTHETIC_MB_FLAG: u32 = 1 << 30;
/// A synthetic flag deliberately kept OUT of the meaning-bearing set (bit 29).
const SYNTHETIC_NON_MB_FLAG: u32 = 1 << 29;

#[test]
fn meaning_bearing_flag_without_ext_is_rejected() {
    // synthetic meaning-bearing flag set, MEANING_REQUIRES_EXT CLEAR -> reject.
    let sc = sidecar(SYNTHETIC_MB_FLAG);
    assert!(matches!(
        check_v22_meaning_bearing_implies_ext(&sc, &[SYNTHETIC_MB_FLAG]),
        Err(FdxValidationError::FlagFieldIncoherent { .. })
    ));
}

#[test]
fn meaning_bearing_flag_with_ext_is_accepted() {
    // same flag, MEANING_REQUIRES_EXT SET -> the implication is satisfied.
    let sc = sidecar(SYNTHETIC_MB_FLAG | FDX_FLAG_MEANING_REQUIRES_EXT);
    assert!(check_v22_meaning_bearing_implies_ext(&sc, &[SYNTHETIC_MB_FLAG]).is_ok());
}

#[test]
fn non_meaning_bearing_flag_is_not_required_to_set_ext() {
    // A flag NOT in the injected set, MEANING_REQUIRES_EXT clear -> must NOT
    // reject: proves the arm checks set MEMBERSHIP, not mere presence (i.e. it is
    // not just rejecting everything with MEANING_REQUIRES_EXT clear).
    let sc = sidecar(SYNTHETIC_NON_MB_FLAG);
    assert!(check_v22_meaning_bearing_implies_ext(&sc, &[SYNTHETIC_MB_FLAG]).is_ok());
    // And a REAL non-meaning-bearing flag against the REAL production set:
    let sc2 = sidecar(FDX_FLAG_HAS_TILING);
    assert!(check_v22_meaning_bearing_implies_ext(&sc2, FDX_FLAG_MEANING_BEARING).is_ok());
}

#[test]
fn every_real_meaning_bearing_flag_requires_ext() {
    // Foundation check on the guard itself: the production set is non-empty (an
    // empty set would make the arm a silent no-op — the "which number moves if it
    // became a no-op" check), and each real member, set alone with
    // MEANING_REQUIRES_EXT clear, is rejected by the real arm.
    assert!(
        !FDX_FLAG_MEANING_BEARING.is_empty(),
        "empty meaning-bearing set = the arm is a no-op"
    );
    for &m in FDX_FLAG_MEANING_BEARING {
        let sc = sidecar(m);
        assert!(
            matches!(
                check_v22_meaning_bearing_implies_ext(&sc, FDX_FLAG_MEANING_BEARING),
                Err(FdxValidationError::FlagFieldIncoherent { .. })
            ),
            "meaning-bearing flag {m:#x} must require MEANING_REQUIRES_EXT"
        );
    }
}

#[test]
fn v22_flag_partition_is_exhaustive() {
    // The §8.22 exhaustiveness claim as a RULE, given a falsifier: every flag in
    // FDX_FLAG_ALL is in exactly one of three groups — the meaning-bearing set,
    // the five V22 does not constrain, or MEANING_REQUIRES_EXT itself. A future
    // flag appended to FDX_FLAG_ALL without being classified reddens this, at the
    // moment someone must decide which side it falls on. Without it the §8.22
    // "constrains the whole flag space" sentence is an assertion nobody can break.
    use std::collections::BTreeSet;
    let mb: BTreeSet<u32> = FDX_FLAG_MEANING_BEARING.iter().copied().collect();
    let excluded: BTreeSet<u32> = [
        FDX_FLAG_HAS_SYMBOLIC,
        FDX_FLAG_HAS_TILING,
        FDX_FLAG_IS_BUNDLE,
        FDX_FLAG_READ_ONLY,
        FDX_FLAG_HAS_AFFINE_EXTENT,
    ]
    .into_iter()
    .collect();
    let consequent: BTreeSet<u32> = [FDX_FLAG_MEANING_REQUIRES_EXT].into_iter().collect();

    // Pairwise disjoint — no flag is classified two ways.
    assert!(
        mb.is_disjoint(&excluded),
        "meaning-bearing set overlaps the five V22 does not constrain"
    );
    assert!(
        mb.is_disjoint(&consequent),
        "meaning-bearing set contains MEANING_REQUIRES_EXT (it is the target of the implication, not a member)"
    );
    assert!(
        excluded.is_disjoint(&consequent),
        "the five V22 does not constrain contain MEANING_REQUIRES_EXT"
    );

    // Covering — the union is exactly FDX_FLAG_ALL.
    let mut union: BTreeSet<u32> = BTreeSet::new();
    union.extend(&mb);
    union.extend(&excluded);
    union.extend(&consequent);
    let all: BTreeSet<u32> = FDX_FLAG_ALL.iter().copied().collect();
    assert_eq!(
        union, all,
        "the V22 partition (meaning-bearing ∪ the five ∪ MEANING_REQUIRES_EXT) does not equal \
         FDX_FLAG_ALL — a flag was added to the spec without being classified into one of the \
         three §8.22 groups"
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// FULL-validate() coverage for meaning-bearing sidecars.
//
// GAP: quant / sub-byte sidecars were tested ONLY per-check — HAS_QUANT and
// HAS_DTYPE_EXT fixtures exist, but they all call check_v4/v5/v6 DIRECTLY, so
// the ORCHESTRATOR's quant/sub-byte path was uncovered end-to-end. A census
// keyed on "do quant sidecars appear in the tests" reads green; the gap is the
// CALL PATH, not the fixture. These take a coherent sidecar through validate().
//
// NON-VACUITY: each positive fixture is paired with an incoherent sibling that
// validate() MUST reject. The pair is the born-red: if the orchestrator did not
// reach the quant/sub-byte path, the incoherent case would pass too. (The
// per-check tests already pass and say nothing about the orchestrator.)
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn validate_pass_ggml_quant_sidecar() {
    let mut sc = sidecar(FDX_FLAG_HAS_QUANT | FDX_FLAG_MEANING_REQUIRES_EXT);
    sc.quant.family = FDX_QUANT_GGML_BLOCK;
    sc.quant.ggml_dtype = FDX_GGML_Q4_0;
    sc.buffers_count = 1;
    let mut sh = [0i64; 1];
    let mut st = [0i64; 1];
    let base = base_uint8(64, &mut sh, &mut st);
    let buffers = vec![data_buffer(64)];
    assert!(
        validate(&sc, &base, &buffers).is_ok(),
        "a coherent GGML_BLOCK quant sidecar must pass the full validate()"
    );
}

#[test]
fn validate_rejects_incoherent_ggml_quant() {
    // Same sidecar, but ggml_dtype cleared to NONE — V5 must reject it THROUGH
    // validate(). Non-vacuity proof for the positive above.
    let mut sc = sidecar(FDX_FLAG_HAS_QUANT | FDX_FLAG_MEANING_REQUIRES_EXT);
    sc.quant.family = FDX_QUANT_GGML_BLOCK;
    sc.quant.ggml_dtype = FDX_DTYPE_NONE;
    sc.buffers_count = 1;
    let mut sh = [0i64; 1];
    let mut st = [0i64; 1];
    let base = base_uint8(64, &mut sh, &mut st);
    let buffers = vec![data_buffer(64)];
    assert!(
        matches!(
            validate(&sc, &base, &buffers),
            Err(FdxValidationError::QuantIncoherent { .. })
        ),
        "an incoherent GGML_BLOCK quant sidecar must be rejected by validate() (proves the quant path is reached)"
    );
}

#[test]
fn validate_pass_sub_byte_sidecar() {
    let mut sc = sidecar(FDX_FLAG_HAS_DTYPE_EXT | FDX_FLAG_MEANING_REQUIRES_EXT);
    sc.dtype_ext.logical_dtype = FDX_DTYPE_I4;
    sc.dtype_ext.bit_width = 4;
    sc.dtype_ext.packing = FDX_PACKING_DENSE_SUBBYTE;
    // `lanes: 1` is what the field's own doc calls a scalar dtype. ⚠️ IT CHANGES
    // NO ASSERTION TODAY -- `validate()` never reads `dtype_ext.lanes` (measured:
    // 0 reads in validate.rs; control: it reads `logical_dtype` and `bit_width`
    // there). It is set so the fixture MATCHES ITS NAME, because a fixture named
    // coherent is what the next author copies as the template for a well-formed
    // sub-byte sidecar. See GAP-286: the field having no validator arm is a
    // separate defect and is NOT fixed here.
    sc.dtype_ext.lanes = 1;
    sc.buffers_count = 1;
    let mut sh = [0i64; 1];
    let mut st = [0i64; 1];
    let base = base_uint8(64, &mut sh, &mut st);
    let buffers = vec![data_buffer(64)];
    assert!(
        validate(&sc, &base, &buffers).is_ok(),
        "a coherent sub-byte (HAS_DTYPE_EXT) sidecar must pass the full validate()"
    );
}

#[test]
fn validate_rejects_incoherent_sub_byte() {
    // Same sidecar, bit_width cleared to 0 — V4 must reject it THROUGH validate().
    // Non-vacuity proof for the positive above.
    let mut sc = sidecar(FDX_FLAG_HAS_DTYPE_EXT | FDX_FLAG_MEANING_REQUIRES_EXT);
    sc.dtype_ext.logical_dtype = FDX_DTYPE_I4;
    sc.dtype_ext.bit_width = 0;
    sc.dtype_ext.packing = FDX_PACKING_DENSE_SUBBYTE;
    sc.dtype_ext.lanes = 1;
    sc.buffers_count = 1;
    let mut sh = [0i64; 1];
    let mut st = [0i64; 1];
    let base = base_uint8(64, &mut sh, &mut st);
    let buffers = vec![data_buffer(64)];
    assert!(
        matches!(
            validate(&sc, &base, &buffers),
            Err(FdxValidationError::BadSubByte { .. })
        ),
        "an incoherent sub-byte sidecar (bit_width 0) must be rejected by validate() (proves V4 is reached)"
    );
}