tensogram 0.22.0

Fast binary N-tensor message format for scientific data — encode, decode, file I/O, streaming
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
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
// (C) Copyright 2026- ECMWF and individual contributors.
//
// This software is licensed under the terms of the Apache Licence Version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation nor
// does it submit to any jurisdiction.

use std::collections::BTreeMap;

use crate::dtype::Dtype;
use crate::error::{Result, TensogramError};
use crate::framing::{self, EncodedObject};
use crate::metadata::RESERVED_KEY;
use crate::substitute_and_mask::{self, MaskSet};
use crate::types::{DataObjectDescriptor, GlobalMetadata, MaskDescriptor, MasksMetadata};
pub use tensogram_encodings::bitmask::MaskMethod;
#[cfg(feature = "blosc2")]
use tensogram_encodings::pipeline::Blosc2Codec;
#[cfg(feature = "sz3")]
use tensogram_encodings::pipeline::Sz3ErrorBound;
#[cfg(feature = "zfp")]
use tensogram_encodings::pipeline::ZfpMode;
use tensogram_encodings::pipeline::{
    self, ByteOrder, CompressionType, EncodingType, FilterType, PipelineConfig,
};
use tensogram_encodings::simple_packing::{self, SimplePackingParams};

/// Options for encoding.
#[derive(Debug, Clone)]
pub struct EncodeOptions {
    /// Whether to compute frame-body integrity hashes (xxh3-64).
    ///
    /// `true` (the default) populates the inline hash slot of every
    /// frame and sets the message-wide `HASHES_PRESENT` preamble flag.
    /// `false` writes zero into every slot and leaves `HASHES_PRESENT`
    /// clear; readers skip integrity verification.
    ///
    /// v3 has exactly one hash algorithm — xxh3-64 — so this is a
    /// `bool` rather than an `Option<HashAlgorithm>` (Wave 2.1
    /// collapse).  When a second algorithm is added the field will
    /// become an enum again as a deliberate signal at every call site.
    /// The wire-format string identifier is
    /// [`crate::hash::HASH_ALGORITHM_NAME`].
    pub hashing: bool,
    /// Which backend to use for szip / zstd when both FFI and pure-Rust
    /// implementations are compiled in.
    ///
    /// Defaults to `Ffi` on native (faster, battle-tested) and `Pure` on
    /// `wasm32` (FFI cannot exist).  Override with
    /// `TENSOGRAM_COMPRESSION_BACKEND=pure` env variable, or set this
    /// field explicitly.
    pub compression_backend: pipeline::CompressionBackend,
    /// Thread budget for the multi-threaded coding pipeline.
    ///
    /// - `0` (default) — sequential (current behaviour).  Can be
    ///   overridden at runtime via `TENSOGRAM_THREADS=N`.
    /// - `1` — explicit single-threaded execution (bypasses env).
    /// - `N ≥ 2` — scoped pool of `N` workers.  Output bytes are
    ///   byte-identical to the sequential path regardless of `N`.
    ///
    /// When more than one data object is being encoded the budget is
    /// spent axis-B-first (intra-codec parallelism) — this codebase
    /// tends to have a small number of very large messages.  See the
    /// [multi-threaded pipeline guide](../../docs/src/guide/multi-threaded-pipeline.md)
    /// for the full policy.
    ///
    /// Ignored with a one-time `tracing::warn!` when the `threads`
    /// cargo feature is disabled.
    pub threads: u32,
    /// Minimum total payload bytes below which the parallel path is
    /// skipped even when `threads > 0`.
    ///
    /// `None` uses [`crate::DEFAULT_PARALLEL_THRESHOLD_BYTES`] (64 KiB).
    /// Set to `Some(0)` to force the parallel path for testing; set to
    /// `Some(usize::MAX)` to force sequential.
    pub parallel_threshold_bytes: Option<usize>,
    /// When `true`, NaN values in float / complex payloads are
    /// substituted with `0.0` and recorded in a bitmask companion
    /// section of the data-object frame (wire type 9
    /// `NTensorFrame`, see `plans/WIRE_FORMAT.md` §6.5).  When
    /// `false` (the default) any NaN in the input is a hard encode
    /// error.
    pub allow_nan: bool,
    /// When `true`, `+Inf` AND `-Inf` values are substituted with
    /// `0.0` and recorded in per-sign bitmasks (see `allow_nan`).
    /// The flag is a single switch for both signs on purpose — callers
    /// who want only one sign must pre-process their data.  When
    /// `false` (the default), any `±Inf` in the input is a hard encode
    /// error.
    pub allow_inf: bool,
    /// Compression method for the NaN mask (see
    /// [`tensogram_encodings::bitmask::MaskMethod`]).  Default
    /// [`MaskMethod::Roaring`].  Only consulted when `allow_nan` is
    /// `true` AND the input actually contained at least one NaN
    /// element.
    pub nan_mask_method: MaskMethod,
    /// Compression method for the `+Inf` mask.  Default
    /// [`MaskMethod::Roaring`].
    pub pos_inf_mask_method: MaskMethod,
    /// Compression method for the `-Inf` mask.  Default
    /// [`MaskMethod::Roaring`].
    pub neg_inf_mask_method: MaskMethod,
    /// Uncompressed byte-count threshold below which mask blobs are
    /// written with [`MaskMethod::None`] (raw packed bytes) regardless
    /// of the requested method.  Default `128`.  Single threshold
    /// across all three masks.  Set to `0` to disable the auto-fallback
    /// and always use the requested method.
    pub small_mask_threshold_bytes: usize,
    /// Where (if anywhere) to emit the aggregate xxh3 hash frame.
    ///
    /// The aggregate is a CBOR-rendered list of every per-object inline
    /// hash slot, useful for tools that want to read all hashes at once
    /// without walking every frame.  See [`AggregateHashPolicy`] for
    /// the variant semantics — `Auto` is the right choice for almost
    /// every caller and adapts to buffered vs streaming mode.
    ///
    /// Ignored when `hash_algorithm` is `None`: if hashing is disabled
    /// there is nothing to aggregate.
    pub aggregate_hash: AggregateHashPolicy,
}

/// Where to place the aggregate hash frame inside a message.
///
/// The frame holds every per-object xxh3 digest as hex-encoded text;
/// it is a redundant copy of the per-frame inline hash slots that
/// makes integrity checks possible without walking the body.  The
/// per-frame inline slots are always authoritative — the aggregate
/// frame is a convenience for legacy tooling.
///
/// # Mode constraints
///
/// - **Buffered encode** ([`encode`]) accepts every variant.
/// - **Streaming encode** ([`crate::streaming::StreamingEncoder`])
///   accepts `Auto`, `None`, `Footer`.  `Header` and `Both` are
///   rejected at construction time with a clear error: header
///   frames are written before any data object, so the hashes are
///   not yet known.
///
/// `Auto` is the right choice for almost every caller — the encoder
/// picks the mode-appropriate placement.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AggregateHashPolicy {
    /// Encoder picks: buffered → `Header`, streaming → `Footer`.
    /// This is the default and is valid in every mode.
    #[default]
    Auto,
    /// No aggregate hash frame is emitted.  Per-frame inline hash
    /// slots are unaffected.
    None,
    /// Emit a `HeaderHash` frame.  **Buffered mode only**; rejected
    /// at construction in streaming mode.
    Header,
    /// Emit a `FooterHash` frame.  Valid in both modes.
    Footer,
    /// Emit BOTH a `HeaderHash` and a `FooterHash` frame, carrying
    /// identical hash lists.  **Buffered mode only**; rejected at
    /// construction in streaming mode.
    Both,
}

impl AggregateHashPolicy {
    /// Resolve `Auto` against a buffered-mode default of `Header`.
    /// Internal helper for the buffered encoder.
    pub(crate) fn resolved_buffered(self) -> Self {
        match self {
            AggregateHashPolicy::Auto => AggregateHashPolicy::Header,
            other => other,
        }
    }

    /// Resolve `Auto` against the streaming-mode default of `Footer`,
    /// rejecting variants that streaming cannot satisfy.  Used by
    /// [`crate::streaming::StreamingEncoder::new`].
    pub(crate) fn resolved_streaming(self) -> Result<Self> {
        match self {
            AggregateHashPolicy::Auto => Ok(AggregateHashPolicy::Footer),
            AggregateHashPolicy::None => Ok(AggregateHashPolicy::None),
            AggregateHashPolicy::Footer => Ok(AggregateHashPolicy::Footer),
            AggregateHashPolicy::Header => Err(TensogramError::Encoding(
                "AggregateHashPolicy::Header is not supported in streaming mode \
                 — the header is written before any data object, so per-object \
                 hashes are not yet known.  Use Auto (defaults to Footer in \
                 streaming) or Footer explicitly."
                    .to_string(),
            )),
            AggregateHashPolicy::Both => Err(TensogramError::Encoding(
                "AggregateHashPolicy::Both is not supported in streaming mode \
                 — the header is written before any data object, so per-object \
                 hashes are not yet known.  Use Auto (defaults to Footer in \
                 streaming) or Footer explicitly."
                    .to_string(),
            )),
        }
    }

    /// Whether this policy requests a HeaderHash frame in the output.
    /// Only meaningful after a [`Self::resolved_buffered`] /
    /// [`Self::resolved_streaming`] call has eliminated `Auto`.
    pub(crate) fn emits_header(self) -> bool {
        matches!(
            self,
            AggregateHashPolicy::Header | AggregateHashPolicy::Both
        )
    }

    /// Whether this policy requests a FooterHash frame in the output.
    /// Only meaningful after a [`Self::resolved_buffered`] /
    /// [`Self::resolved_streaming`] call has eliminated `Auto`.
    pub(crate) fn emits_footer(self) -> bool {
        matches!(
            self,
            AggregateHashPolicy::Footer | AggregateHashPolicy::Both
        )
    }
}

impl Default for EncodeOptions {
    fn default() -> Self {
        Self {
            hashing: true,
            compression_backend: pipeline::CompressionBackend::default(),
            threads: 0,
            parallel_threshold_bytes: None,
            allow_nan: false,
            allow_inf: false,
            nan_mask_method: MaskMethod::default(),
            pos_inf_mask_method: MaskMethod::default(),
            neg_inf_mask_method: MaskMethod::default(),
            small_mask_threshold_bytes: 128,
            aggregate_hash: AggregateHashPolicy::Auto,
        }
    }
}

pub(crate) fn validate_object(desc: &DataObjectDescriptor, data_len: usize) -> Result<()> {
    if desc.obj_type.is_empty() {
        return Err(TensogramError::Metadata(
            "obj_type must not be empty".to_string(),
        ));
    }
    if desc.ndim as usize != desc.shape.len() {
        return Err(TensogramError::Metadata(format!(
            "ndim {} does not match shape.len() {}",
            desc.ndim,
            desc.shape.len()
        )));
    }
    if desc.strides.len() != desc.shape.len() {
        return Err(TensogramError::Metadata(format!(
            "strides.len() {} does not match shape.len() {}",
            desc.strides.len(),
            desc.shape.len()
        )));
    }
    if desc.encoding == "none" {
        let product = desc
            .shape
            .iter()
            .try_fold(1u64, |acc, &x| acc.checked_mul(x))
            .ok_or_else(|| TensogramError::Metadata("shape product overflow".to_string()))?;
        if desc.dtype.byte_width() > 0 {
            let expected_bytes = product
                .checked_mul(desc.dtype.byte_width() as u64)
                .ok_or_else(|| TensogramError::Metadata("shape product overflow".to_string()))?;
            if expected_bytes != data_len as u64 {
                return Err(TensogramError::Metadata(format!(
                    "data_len {data_len} does not match expected {expected_bytes} bytes from shape and dtype"
                )));
            }
        } else if desc.dtype == crate::Dtype::Bitmask {
            // Bitmask: expected data length is ceil(shape_product / 8)
            let expected_bytes = product.div_ceil(8);
            if expected_bytes != data_len as u64 {
                return Err(TensogramError::Metadata(format!(
                    "data_len {data_len} does not match expected {expected_bytes} bytes for bitmask (ceil({product}/8))"
                )));
            }
        }
    }
    // Strict-input contract on mask descriptor sub-maps: when the
    // caller supplies a `masks` block, every present `MaskDescriptor`
    // must be internally consistent (`method` recognised, `params`
    // map populated only with keys the method actually understands).
    if let Some(masks) = &desc.masks {
        validate_mask_params(masks)?;
    }
    Ok(())
}

/// Per-method allow-list of legitimate `params` keys for a
/// [`MaskDescriptor`].  See `plans/WIRE_FORMAT.md` §6.5.1 for the
/// canonical schema.
///
/// Strict-input contract: a key not in the allow-list (typically a
/// typo or a stale param from a previous codec choice) is rejected
/// with a `MetadataError`.  Earlier versions silently round-tripped
/// the unknown key, which would surface later as a decode failure on
/// downstream consumers.
fn mask_method_allowed_params(method: &str) -> Option<&'static [&'static str]> {
    match method {
        "none" | "rle" | "roaring" | "lz4" => Some(&[]),
        "zstd" => Some(&["level"]),
        "blosc2" => Some(&["codec", "level"]),
        _ => None,
    }
}

fn validate_mask_descriptor(kind: &str, md: &MaskDescriptor) -> Result<()> {
    let allowed = mask_method_allowed_params(&md.method).ok_or_else(|| {
        TensogramError::Metadata(format!(
            "mask {kind} has unknown method {method:?}; \
             expected one of: none, rle, roaring, lz4, zstd, blosc2",
            kind = kind,
            method = md.method,
        ))
    })?;
    for k in md.params.keys() {
        if !allowed.contains(&k.as_str()) {
            return Err(TensogramError::Metadata(format!(
                "mask {kind} (method {method:?}) has unknown param {key:?}; \
                 allowed for this method: {allowed:?}",
                kind = kind,
                method = md.method,
                key = k,
                allowed = allowed,
            )));
        }
    }
    Ok(())
}

fn validate_mask_params(masks: &MasksMetadata) -> Result<()> {
    if let Some(md) = &masks.nan {
        validate_mask_descriptor("nan", md)?;
    }
    if let Some(md) = &masks.pos_inf {
        validate_mask_descriptor("inf+", md)?;
    }
    if let Some(md) = &masks.neg_inf {
        validate_mask_descriptor("inf-", md)?;
    }
    Ok(())
}

#[derive(Debug, Clone, Copy)]
enum EncodeMode {
    Raw,
    PreEncoded,
}

/// Encode a single object: run the pipeline (or validate pre-encoded
/// bytes), compute its hash, and return the `EncodedObject`.
///
/// `intra_codec_threads` is passed through to [`PipelineConfig`] and
/// honoured by axis-B-capable codecs (blosc2, zstd, simple_packing,
/// shuffle).  Pure functional — no shared state, safe to call from
/// multiple rayon workers in parallel.
fn encode_one_object(
    desc: &DataObjectDescriptor,
    data: &[u8],
    mode: EncodeMode,
    options: &EncodeOptions,
    intra_codec_threads: u32,
) -> Result<EncodedObject> {
    validate_object(desc, data.len())?;

    // Pre-pipeline substitute-and-mask stage (Raw mode only).  Two
    // flavours gated by the same call:
    //
    // - `allow_nan == false && allow_inf == false` — behaves like the
    //   0.17 default finite check: first NaN / Inf errors out.
    // - Either flag true — substitute non-finite values with the
    //   dtype-specific zero and collect per-kind bitmasks for the
    //   frame-writing stage.  See `plans/WIRE_FORMAT.md` §6.5 and
    //   `docs/src/guide/nan-inf-handling.md` for the user-facing
    //   semantics.
    //
    // Pre-encoded bytes are opaque: skip the stage.
    let (pipeline_input, mask_set) = if matches!(mode, EncodeMode::Raw) {
        let parallel = crate::parallel::should_parallelise(
            intra_codec_threads,
            data.len(),
            options.parallel_threshold_bytes,
        );
        let (cow, masks) = substitute_and_mask::substitute_and_mask(
            data,
            desc.dtype,
            desc.byte_order,
            options.allow_nan,
            options.allow_inf,
            parallel,
        )?;
        (cow, masks)
    } else {
        (std::borrow::Cow::Borrowed(data), MaskSet::empty(0))
    };

    let num_elements = desc.num_elements()?;
    let dtype = desc.dtype;

    // Build the descriptor we will emit on the wire.  For Raw mode this
    // includes the auto-compute step: when `encoding=simple_packing` and
    // the user left out `sp_reference_value` / `sp_binary_scale_factor`
    // we derive them from the data here so the final descriptor carries
    // the full explicit 4-key set.  `PreEncoded` skips this — the bytes
    // are opaque, the user must have supplied complete params.
    //
    // Use the ORIGINAL `data` (pre-substitute), not `pipeline_input`:
    // when `allow_nan` / `allow_inf` are on, NaN / Inf get replaced
    // with `0.0` and any auto-compute over the substituted bytes
    // would derive a `sp_reference_value` distorted by those zeros
    // (silent precision loss).  Using the original data makes
    // `simple_packing::compute_params` surface non-finite inputs as a
    // clear `PackingError`, telling the user to either supply explicit
    // params or pre-substitute their data.
    let mut final_desc = desc.clone();
    if matches!(mode, EncodeMode::Raw) {
        resolve_simple_packing_params(&mut final_desc, data)?;
    }

    let mut config = build_pipeline_config_with_backend(
        &final_desc,
        num_elements,
        dtype,
        options.compression_backend,
        intra_codec_threads,
    )?;

    // When xxh3 hashing is requested and we are running the pipeline
    // (Raw mode), ask the pipeline to compute it inline — this avoids
    // a second walk over the encoded payload.  The pipeline's inline
    // path is xxh3-specific; other `HashAlgorithm` variants and
    // `PreEncoded` mode fall back to `compute_hash` further down.
    //
    // v3 has a single hash algorithm (xxh3-64); the boolean
    // `options.hashing` selects between "hash" and "no hash".  When
    // a second algorithm is added this collapses back to a match on
    // an enum so that adding a variant forces a compile error at
    // every call site.
    let inline_hash_requested = matches!(mode, EncodeMode::Raw) && options.hashing;
    config.compute_hash = inline_hash_requested;

    let (encoded_payload, inline_hash) = match mode {
        EncodeMode::Raw => {
            // Run the full encoding pipeline on the (possibly
            // substituted) payload.  When substitution occurred the
            // `pipeline_input` is `Cow::Owned`; otherwise it's the
            // caller's bytes borrowed zero-cost.
            let result = pipeline::encode_pipeline(pipeline_input.as_ref(), &config)
                .map_err(|e| TensogramError::Encoding(e.to_string()))?;

            // Store szip block offsets if produced
            if let Some(offsets) = &result.block_offsets {
                final_desc.params.insert(
                    "szip_block_offsets".to_string(),
                    ciborium::Value::Array(
                        offsets
                            .iter()
                            .map(|&o| ciborium::Value::Integer(o.into()))
                            .collect(),
                    ),
                );
            }

            (result.encoded_bytes, result.hash)
        }
        EncodeMode::PreEncoded => {
            // Caller's bytes are already encoded — use them directly.
            // `build_pipeline_config_with_backend` was called above purely
            // for defence-in-depth validation of the declared
            // encoding/compression params.
            validate_no_szip_offsets_for_non_szip(desc)?;
            if desc.compression == "szip" && desc.params.contains_key("szip_block_offsets") {
                validate_szip_block_offsets(&desc.params, data.len())?;
            }
            (data.to_vec(), None)
        }
    };

    // ── Compose the payload region: [encoded_payload][mask_nan][mask_inf+][mask_inf-] ──
    //
    // When no masks were collected (the common case), the region is
    // just `encoded_payload` and the descriptor gets `masks = None`,
    // making the frame byte-identical to the legacy `NTensorFrame`
    // payload layout except for the frame-type number.
    //
    // When masks ARE present, each kind is compressed via the
    // user-specified `MaskMethod` (with auto-fallback to `None` for
    // tiny masks), appended to the payload region in the canonical
    // order `nan`, `inf+`, `inf-` (matching the CBOR key sort order),
    // and each kind's CBOR descriptor records its byte offset and
    // length relative to the region start.  See
    // `plans/WIRE_FORMAT.md` §6.5.
    let (payload_region, masks_metadata) = compose_payload_region(
        encoded_payload,
        mask_set,
        &options.nan_mask_method,
        &options.pos_inf_mask_method,
        &options.neg_inf_mask_method,
        options.small_mask_threshold_bytes,
    )?;
    if let Some(m) = masks_metadata {
        final_desc.masks = Some(m);
    }
    let encoded_payload = payload_region;

    // v3: the per-object hash is no longer written into the CBOR
    // descriptor.  It lives in the inline hash slot of the frame's
    // footer (see `plans/WIRE_FORMAT.md` §2.4), populated by
    // `encode_data_object_frame` at frame-build time.  The
    // aggregate HashFrame reads those slots back in
    // `framing::build_hash_frame_cbor` — no second pass here.
    //
    // `inline_hash` from the pipeline is redundant with the
    // inline slot (same digest, different storage) and is
    // intentionally unused on this path; keeping it in the return
    // tuple preserves the pipeline's hash-while-encoding
    // invariant for callers that want a digest without going
    // through the frame layer.
    let _ = (inline_hash, options);

    Ok(EncodedObject {
        descriptor: final_desc,
        encoded_payload,
    })
}

fn encode_inner(
    global_metadata: &GlobalMetadata,
    descriptors: &[(&DataObjectDescriptor, &[u8])],
    options: &EncodeOptions,
    mode: EncodeMode,
) -> Result<Vec<u8>> {
    // ── Thread-budget dispatch (axis-B-first policy) ────────────────────
    //
    // Resolve the effective thread budget (explicit option > env var),
    // decide if the workload is large enough to parallelise, and pick
    // axis A (par_iter across objects) vs axis B (sequential, codec
    // uses the budget internally).
    //
    // `resolve_budget` surfaces an unparseable `TENSOGRAM_THREADS`
    // value as a typed error — Wave 1.1 strict-input contract.
    let budget = crate::parallel::resolve_budget(options.threads)?;
    let total_bytes: usize = descriptors.iter().map(|(_, d)| d.len()).sum();
    let parallel =
        crate::parallel::should_parallelise(budget, total_bytes, options.parallel_threshold_bytes);

    let any_axis_b = descriptors
        .iter()
        .any(|(d, _)| crate::parallel::is_axis_b_friendly(&d.encoding, &d.filter, &d.compression));
    let use_axis_a = parallel && crate::parallel::use_axis_a(descriptors.len(), budget, any_axis_b);

    // Axis B gets the full budget; axis A keeps codecs sequential so
    // that the product of axis A and axis B threads never exceeds the
    // caller's ask.
    let intra_codec_threads = if parallel && !use_axis_a { budget } else { 0 };

    let encode_one = |(desc, data): &(&DataObjectDescriptor, &[u8])| {
        encode_one_object(desc, data, mode, options, intra_codec_threads)
    };

    let encoded_objects: Vec<EncodedObject> = if use_axis_a {
        // Axis A: par_iter across objects.  Requires the `threads`
        // feature; when it's off, the caller's budget silently falls
        // back to sequential (with a one-time warning from `with_pool`).
        #[cfg(feature = "threads")]
        {
            use rayon::prelude::*;
            crate::parallel::with_pool(budget, || {
                descriptors
                    .par_iter()
                    .map(&encode_one)
                    .collect::<Result<Vec<_>>>()
            })?
        }
        #[cfg(not(feature = "threads"))]
        {
            descriptors.iter().map(encode_one).collect::<Result<_>>()?
        }
    } else {
        // Axis B (or purely sequential): iterate objects in order.
        // Install the pool when there's an intra-codec budget so that
        // parallel primitives inside codec implementations (e.g.
        // `simple_packing` chunked par_iter) actually use it.
        crate::parallel::run_maybe_pooled(budget, parallel, intra_codec_threads, || {
            descriptors.iter().map(encode_one).collect::<Result<_>>()
        })?
    };

    // Validate that the caller hasn't written to _reserved_ at any level.
    validate_no_client_reserved(global_metadata)?;

    // Validate base/descriptor count: base may be shorter (auto-extended) or
    // equal, but having MORE base entries than descriptors is an error —
    // the extra entries would be silently discarded.
    if global_metadata.base.len() > descriptors.len() {
        return Err(TensogramError::Metadata(format!(
            "metadata base has {} entries but only {} descriptors provided; \
             extra base entries would be discarded",
            global_metadata.base.len(),
            descriptors.len()
        )));
    }

    // Populate per-object base entries with _reserved_.tensor (ndim/shape/strides/dtype).
    // Pre-existing application keys (e.g. "mars") are preserved.
    let mut enriched_meta = global_metadata.clone();
    populate_base_entries(&mut enriched_meta.base, &encoded_objects);
    populate_reserved_provenance(&mut enriched_meta.reserved);

    // Resolve the aggregate-hash policy for buffered mode.  `Auto`
    // expands to `Header` (the canonical buffered placement); the
    // explicit variants pass through unchanged.  Streaming uses a
    // separate resolver that rejects `Header` / `Both`.
    let resolved = options.aggregate_hash.resolved_buffered();
    let hash_policy = framing::HashFramePolicy {
        header: resolved.emits_header(),
        footer: resolved.emits_footer(),
    };
    framing::encode_message(
        &enriched_meta,
        &encoded_objects,
        options.hashing,
        hash_policy,
    )
}

/// Encode a complete Tensogram message.
///
/// `global_metadata` is the message-level metadata (version, MARS keys, etc.).
/// `descriptors` is a list of (DataObjectDescriptor, raw_data) pairs.
/// Returns the complete wire-format message.
#[tracing::instrument(skip(global_metadata, descriptors, options), fields(objects = descriptors.len()))]
pub fn encode(
    global_metadata: &GlobalMetadata,
    descriptors: &[(&DataObjectDescriptor, &[u8])],
    options: &EncodeOptions,
) -> Result<Vec<u8>> {
    encode_inner(global_metadata, descriptors, options, EncodeMode::Raw)
}

/// Encode a pre-encoded Tensogram message where callers supply already-encoded bytes.
///
/// Use this when the payload bytes have already been encoded/compressed by an external
/// pipeline. The library will:
/// - Validate object descriptors (shape, dtype, etc.)
/// - Validate encoding/compression params via `build_pipeline_config()` (defense-in-depth)
/// - Use the caller's bytes directly as the encoded payload (no pipeline call)
/// - Compute a fresh xxh3 hash over the caller's bytes (overwrites any caller-supplied hash)
/// - Preserve caller-supplied `szip_block_offsets` in descriptor params
///
/// Per-object preceder metadata is a streaming-mode concept
/// (`StreamingEncoder::write_preceder()`); the buffered
/// `encode_pre_encoded` path does not emit preceders.
///
/// Unlike `encode()`, this path does NOT run the finite-value check — the caller's
/// bytes are assumed to be already well-formed for the declared encoding and are
/// written as-is.  If the pre-encoded bytes decode to NaN / Inf, that round-trips
/// through the wire unchanged.
#[tracing::instrument(name = "encode_pre_encoded", skip_all, fields(num_objects = descriptors.len()))]
pub fn encode_pre_encoded(
    global_metadata: &GlobalMetadata,
    descriptors: &[(&DataObjectDescriptor, &[u8])],
    options: &EncodeOptions,
) -> Result<Vec<u8>> {
    encode_inner(
        global_metadata,
        descriptors,
        options,
        EncodeMode::PreEncoded,
    )
}

/// Validate that the caller hasn't written to `_reserved_` at any level.
///
/// The `_reserved_` namespace is library-managed.  Client code must not
/// set it in the message-level metadata or in any `base[i]` entry.
fn validate_no_client_reserved(meta: &GlobalMetadata) -> Result<()> {
    if !meta.reserved.is_empty() {
        return Err(TensogramError::Metadata(format!(
            "client code must not write to '{RESERVED_KEY}' at message level; \
             this field is populated by the library"
        )));
    }
    for (i, entry) in meta.base.iter().enumerate() {
        if entry.contains_key(RESERVED_KEY) {
            return Err(TensogramError::Metadata(format!(
                "client code must not write to '{RESERVED_KEY}' in base[{i}]; \
                 this field is populated by the library"
            )));
        }
    }
    Ok(())
}

/// Populate per-object base entries with tensor metadata under `_reserved_.tensor`.
///
/// Resizes `base` to match the object count, then inserts a `_reserved_`
/// map containing `tensor: {ndim, shape, strides, dtype}` into each entry.
/// Pre-existing application keys (e.g. `"mars"`) are preserved.
pub(crate) fn populate_base_entries(
    base: &mut Vec<BTreeMap<String, ciborium::Value>>,
    encoded_objects: &[crate::framing::EncodedObject],
) {
    use ciborium::Value;

    // Ensure base has exactly one entry per object.
    base.resize_with(encoded_objects.len(), BTreeMap::new);

    for (entry, obj) in base.iter_mut().zip(encoded_objects.iter()) {
        let desc = &obj.descriptor;

        let tensor_map = Value::Map(vec![
            (
                Value::Text("ndim".to_string()),
                Value::Integer(desc.ndim.into()),
            ),
            (
                Value::Text("shape".to_string()),
                Value::Array(
                    desc.shape
                        .iter()
                        .map(|&d| Value::Integer(d.into()))
                        .collect(),
                ),
            ),
            (
                Value::Text("strides".to_string()),
                Value::Array(
                    desc.strides
                        .iter()
                        .map(|&s| Value::Integer(s.into()))
                        .collect(),
                ),
            ),
            (
                Value::Text("dtype".to_string()),
                Value::Text(desc.dtype.to_string()),
            ),
        ]);

        let reserved_map = Value::Map(vec![(Value::Text("tensor".to_string()), tensor_map)]);

        entry.insert(RESERVED_KEY.to_string(), reserved_map);
    }
}

/// Populate the `reserved` section with provenance fields as specified in
/// `WIRE_FORMAT.md`:
///
/// - `encoder.name` — `"tensogram"`
/// - `encoder.version` — library version at encode time
/// - `time` — UTC ISO 8601 timestamp
/// - `uuid` — RFC 4122 v4 UUID
///
/// Pre-existing keys in `reserved` are preserved; only these four are
/// set (or overwritten).
pub(crate) fn populate_reserved_provenance(reserved: &mut BTreeMap<String, ciborium::Value>) {
    use ciborium::Value;
    #[cfg(not(target_arch = "wasm32"))]
    use std::time::SystemTime;

    // encoder.name + encoder.version
    let version_str = env!("CARGO_PKG_VERSION");
    let encoder_map = Value::Map(vec![
        (
            Value::Text("name".to_string()),
            Value::Text("tensogram".to_string()),
        ),
        (
            Value::Text("version".to_string()),
            Value::Text(version_str.to_string()),
        ),
    ]);
    reserved.insert("encoder".to_string(), encoder_map);

    // time — ISO 8601 UTC
    // On wasm32-unknown-unknown, SystemTime::now() panics. Skip the `time`
    // field entirely rather than encoding a misleading epoch-0 timestamp.
    // Callers can set a timestamp via `_extra_` if needed.
    #[cfg(not(target_arch = "wasm32"))]
    {
        let secs = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        // Simple UTC format: YYYY-MM-DDThh:mm:ssZ
        // We compute from epoch seconds to avoid adding a datetime crate.
        let days = secs / 86400;
        let day_secs = secs % 86400;
        let hours = day_secs / 3600;
        let minutes = (day_secs % 3600) / 60;
        let seconds = day_secs % 60;
        // Civil date from days since 1970-01-01 (Howard Hinnant algorithm)
        let (y, m, d) = civil_from_days(days as i64);
        let timestamp = format!("{y:04}-{m:02}-{d:02}T{hours:02}:{minutes:02}:{seconds:02}Z");
        reserved.insert("time".to_string(), Value::Text(timestamp));
    }

    // uuid — RFC 4122 v4
    let id = uuid::Uuid::new_v4();
    reserved.insert("uuid".to_string(), Value::Text(id.to_string()));
}

/// Convert days since 1970-01-01 to (year, month, day).
/// Howard Hinnant's algorithm (public domain).
#[cfg(not(target_arch = "wasm32"))]
fn civil_from_days(days: i64) -> (i64, u32, u32) {
    let z = days + 719468;
    let era = if z >= 0 { z } else { z - 146096 } / 146097;
    // doe (day of era) is guaranteed in [0, 146096] by the era computation,
    // so the u32 cast cannot truncate.
    let doe = (z - era * 146097) as u32;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe as i64 + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    (y, m, d)
}

pub(crate) fn build_pipeline_config(
    desc: &DataObjectDescriptor,
    num_values: usize,
    dtype: Dtype,
) -> Result<PipelineConfig> {
    build_pipeline_config_with_backend(
        desc,
        num_values,
        dtype,
        pipeline::CompressionBackend::default(),
        0,
    )
}

/// Resolve the encoding type from a descriptor.
fn resolve_encoding(desc: &DataObjectDescriptor, dtype: Dtype) -> Result<EncodingType> {
    match desc.encoding.as_str() {
        "none" => Ok(EncodingType::None),
        "simple_packing" => {
            // Strict float64 check.  A `byte_width() != 8` test would
            // also let `Int64` / `Uint64` / `Complex64` through, and
            // the pipeline would then re-interpret their bytes as
            // f64 and produce silently-wrong output.
            if dtype != Dtype::Float64 {
                return Err(TensogramError::Encoding(format!(
                    "simple_packing only supports float64 dtype; got {dtype:?}"
                )));
            }
            let params = extract_simple_packing_params(&desc.params)?;
            Ok(EncodingType::SimplePacking(params))
        }
        other => Err(TensogramError::Encoding(format!(
            "unknown encoding: {other}"
        ))),
    }
}

/// Resolve the filter type from a descriptor.
fn resolve_filter(desc: &DataObjectDescriptor) -> Result<FilterType> {
    match desc.filter.as_str() {
        "none" => Ok(FilterType::None),
        "shuffle" => {
            let element_size = usize::try_from(get_u64_param(
                &desc.params,
                "shuffle_element_size",
            )?)
            .map_err(|_| {
                TensogramError::Metadata("shuffle_element_size out of usize range".to_string())
            })?;
            Ok(FilterType::Shuffle { element_size })
        }
        other => Err(TensogramError::Encoding(format!("unknown filter: {other}"))),
    }
}

/// Resolve the compression type from a descriptor, using the resolved
/// encoding and filter for any codec that depends on them (szip bits_per_sample,
/// blosc2 typesize).
///
/// `encoding` and `filter` are consumed only by the feature-gated `szip` and
/// `blosc2` arms below.  With every codec that needs them disabled (e.g. a
/// `--no-default-features` build) they are genuinely unused, so the `allow`
/// is scoped precisely to that build configuration rather than applied
/// unconditionally.
#[cfg_attr(
    not(any(feature = "szip", feature = "szip-pure", feature = "blosc2")),
    allow(unused_variables)
)]
fn resolve_compression(
    desc: &DataObjectDescriptor,
    dtype: Dtype,
    encoding: &EncodingType,
    filter: &FilterType,
) -> Result<CompressionType> {
    match desc.compression.as_str() {
        "none" => Ok(CompressionType::None),
        #[cfg(any(feature = "szip", feature = "szip-pure"))]
        "szip" => {
            let rsi = u32::try_from(get_u64_param(&desc.params, "szip_rsi")?)
                .map_err(|_| TensogramError::Metadata("szip_rsi out of u32 range".to_string()))?;
            let block_size = u32::try_from(get_u64_param(&desc.params, "szip_block_size")?)
                .map_err(|_| {
                    TensogramError::Metadata("szip_block_size out of u32 range".to_string())
                })?;
            let flags = u32::try_from(get_u64_param(&desc.params, "szip_flags")?)
                .map_err(|_| TensogramError::Metadata("szip_flags out of u32 range".to_string()))?;
            let bits_per_sample = match (encoding, filter) {
                (EncodingType::SimplePacking(params), _) => params.bits_per_value,
                (EncodingType::None, FilterType::Shuffle { .. }) => 8,
                (EncodingType::None, FilterType::None) => (dtype.byte_width() * 8) as u32,
            };
            Ok(CompressionType::Szip {
                rsi,
                block_size,
                flags,
                bits_per_sample,
            })
        }
        #[cfg(any(feature = "zstd", feature = "zstd-pure"))]
        "zstd" => {
            // Strict-input contract: a present-but-wrong-type
            // `zstd_level` errors instead of silently defaulting to 3.
            // The `_or_default` accessor distinguishes "absent" (use
            // the default) from "wrong type" (reject).
            let level_i64 = get_i64_param_or_default(&desc.params, "zstd_level", 3)?;
            let level = i32::try_from(level_i64).map_err(|_| {
                TensogramError::Metadata(format!("zstd_level value {level_i64} out of i32 range"))
            })?;
            Ok(CompressionType::Zstd { level })
        }
        #[cfg(feature = "lz4")]
        "lz4" => Ok(CompressionType::Lz4),
        #[cfg(feature = "blosc2")]
        "blosc2" => {
            // Strict-input: present-but-non-text `blosc2_codec`
            // rejects (vs. previously silently falling back to
            // "lz4").
            let codec_str = get_text_param_or_default(&desc.params, "blosc2_codec", "lz4")?;
            let codec = match codec_str {
                "blosclz" => Blosc2Codec::Blosclz,
                "lz4" => Blosc2Codec::Lz4,
                "lz4hc" => Blosc2Codec::Lz4hc,
                "zlib" => Blosc2Codec::Zlib,
                "zstd" => Blosc2Codec::Zstd,
                other => {
                    return Err(TensogramError::Encoding(format!(
                        "unknown blosc2 codec: {other}"
                    )));
                }
            };
            // Strict-input: present-but-wrong-type `blosc2_clevel`
            // rejects instead of defaulting to 5.
            let clevel_i64 = get_i64_param_or_default(&desc.params, "blosc2_clevel", 5)?;
            let clevel = i32::try_from(clevel_i64).map_err(|_| {
                TensogramError::Metadata(format!(
                    "blosc2_clevel value {clevel_i64} out of i32 range"
                ))
            })?;
            let typesize = match (encoding, filter) {
                (EncodingType::SimplePacking(params), _) => {
                    (params.bits_per_value as usize).div_ceil(8)
                }
                (EncodingType::None, FilterType::Shuffle { .. }) => 1,
                (EncodingType::None, FilterType::None) => dtype.byte_width(),
            };
            Ok(CompressionType::Blosc2 {
                codec,
                clevel,
                typesize,
            })
        }
        #[cfg(feature = "zfp")]
        "zfp" => {
            let mode_str = match desc.params.get("zfp_mode") {
                Some(ciborium::Value::Text(s)) => s.clone(),
                _ => {
                    return Err(TensogramError::Metadata(
                        "missing required parameter: zfp_mode".to_string(),
                    ));
                }
            };
            let mode = match mode_str.as_str() {
                "fixed_rate" => {
                    let rate = get_f64_param(&desc.params, "zfp_rate")?;
                    ZfpMode::FixedRate { rate }
                }
                "fixed_precision" => {
                    let precision = u32::try_from(get_u64_param(&desc.params, "zfp_precision")?)
                        .map_err(|_| {
                            TensogramError::Metadata("zfp_precision out of u32 range".to_string())
                        })?;
                    ZfpMode::FixedPrecision { precision }
                }
                "fixed_accuracy" => {
                    let tolerance = get_f64_param(&desc.params, "zfp_tolerance")?;
                    ZfpMode::FixedAccuracy { tolerance }
                }
                other => {
                    return Err(TensogramError::Encoding(format!(
                        "unknown zfp_mode: {other}"
                    )));
                }
            };
            Ok(CompressionType::Zfp { mode })
        }
        #[cfg(feature = "sz3")]
        "sz3" => {
            let mode_str = match desc.params.get("sz3_error_bound_mode") {
                Some(ciborium::Value::Text(s)) => s.clone(),
                _ => {
                    return Err(TensogramError::Metadata(
                        "missing required parameter: sz3_error_bound_mode".to_string(),
                    ));
                }
            };
            let bound_val = get_f64_param(&desc.params, "sz3_error_bound")?;
            let error_bound = match mode_str.as_str() {
                "abs" => Sz3ErrorBound::Absolute(bound_val),
                "rel" => Sz3ErrorBound::Relative(bound_val),
                "psnr" => Sz3ErrorBound::Psnr(bound_val),
                other => {
                    return Err(TensogramError::Encoding(format!(
                        "unknown sz3_error_bound_mode: {other}"
                    )));
                }
            };
            Ok(CompressionType::Sz3 { error_bound })
        }
        "rle" => {
            // Bitmask-only codec — see `plans/WIRE_FORMAT.md` §8.
            if dtype != Dtype::Bitmask {
                return Err(TensogramError::Encoding(format!(
                    "compression \"rle\" only supports dtype=bitmask, got dtype={:?}",
                    dtype
                )));
            }
            Ok(CompressionType::Rle)
        }
        "roaring" => {
            // Bitmask-only codec — see `plans/WIRE_FORMAT.md` §8.
            if dtype != Dtype::Bitmask {
                return Err(TensogramError::Encoding(format!(
                    "compression \"roaring\" only supports dtype=bitmask, got dtype={:?}",
                    dtype
                )));
            }
            Ok(CompressionType::Roaring)
        }
        other => Err(TensogramError::Encoding(format!(
            "unknown compression: {other}"
        ))),
    }
}

/// Build a pipeline config with an explicit compression backend override
/// and an intra-codec thread budget.
///
/// `intra_codec_threads == 0` preserves the pre-threads behaviour and is
/// what direct pipeline callers (benchmarks, external code) should use.
pub(crate) fn build_pipeline_config_with_backend(
    desc: &DataObjectDescriptor,
    num_values: usize,
    dtype: Dtype,
    compression_backend: pipeline::CompressionBackend,
    intra_codec_threads: u32,
) -> Result<PipelineConfig> {
    let encoding = resolve_encoding(desc, dtype)?;
    let filter = resolve_filter(desc)?;
    let compression = resolve_compression(desc, dtype, &encoding, &filter)?;

    Ok(PipelineConfig {
        encoding,
        filter,
        compression,
        num_values,
        byte_order: desc.byte_order,
        dtype_byte_width: dtype.byte_width(),
        swap_unit_size: dtype.swap_unit_size(),
        compression_backend,
        intra_codec_threads,
        // `compute_hash` is not carried in the descriptor — the caller
        // (encode_one_object / streaming) flips it on when a hash is
        // requested.  Default off so direct pipeline callers pay nothing
        // for hashing unless they opt in.
        compute_hash: false,
    })
}

fn extract_simple_packing_params(
    params: &BTreeMap<String, ciborium::Value>,
) -> Result<SimplePackingParams> {
    let reference_value = get_f64_param(params, "sp_reference_value")?;
    if reference_value.is_nan() || reference_value.is_infinite() {
        return Err(TensogramError::Metadata(format!(
            "sp_reference_value must be finite, got {reference_value}"
        )));
    }
    Ok(SimplePackingParams {
        reference_value,
        binary_scale_factor: i32::try_from(get_i64_param(params, "sp_binary_scale_factor")?)
            .map_err(|_| {
                TensogramError::Metadata("sp_binary_scale_factor out of i32 range".to_string())
            })?,
        decimal_scale_factor: i32::try_from(get_i64_param(params, "sp_decimal_scale_factor")?)
            .map_err(|_| {
                TensogramError::Metadata("sp_decimal_scale_factor out of i32 range".to_string())
            })?,
        bits_per_value: u32::try_from(get_u64_param(params, "sp_bits_per_value")?).map_err(
            |_| TensogramError::Metadata("sp_bits_per_value out of u32 range".to_string()),
        )?,
    })
}

/// Auto-compute the reference / binary-scale params for a
/// `simple_packing` descriptor when they are absent.
///
/// When a caller writes (in any language):
///
/// ```text
/// desc = { encoding: "simple_packing", sp_bits_per_value: 16, ... }
/// ```
///
/// the four-key explicit form
/// (`sp_reference_value` + `sp_binary_scale_factor` + the two knob
/// keys) is derived from the input data on the fly.  The descriptor
/// is then stamped with all four so that the wire-format representation
/// stays self-describing.
///
/// Contract:
/// * No-op when `encoding != "simple_packing"`.
/// * No-op when both `sp_reference_value` and `sp_binary_scale_factor`
///   are already present — explicit user values win and are not
///   recomputed.  This supports advanced workflows that pin the
///   reference value across many objects (e.g. for time-series delta
///   encoding downstream).
/// * `sp_bits_per_value` is required on both the auto-compute and
///   explicit-params paths — error otherwise.
/// * `sp_decimal_scale_factor` defaults to `0` when absent.
/// * The data bytes are interpreted as float64 in the descriptor's
///   declared byte order — simple_packing is strictly `Dtype::Float64`
///   (other 8-byte dtypes such as `Int64`, `Uint64`, `Complex64` are
///   rejected up-front to avoid silent reinterpretation).  The pipeline
///   builder re-checks the same constraint for callers that bypass
///   this resolver.
pub(crate) fn resolve_simple_packing_params(
    desc: &mut DataObjectDescriptor,
    data_bytes: &[u8],
) -> Result<()> {
    if desc.encoding != "simple_packing" {
        return Ok(());
    }

    // simple_packing only supports float64.  Other 8-byte dtypes
    // (Int64 / Uint64 / Complex64) would pass a byte-width check but
    // re-interpreting their bytes as f64 produces garbage params.
    // Tighten to exact equality with `Dtype::Float64`.
    if desc.dtype != Dtype::Float64 {
        return Err(TensogramError::Encoding(format!(
            "simple_packing only supports float64 dtype; got {:?}",
            desc.dtype
        )));
    }

    // sp_bits_per_value is required regardless of which path we take —
    // the explicit 4-key form needs it for the bit-packing layout, and
    // the auto-compute form needs it for `compute_params`.  Check it
    // here so the error is consistent and points at the canonical
    // missing key, rather than failing later in the pipeline-config
    // builder with a less specific message.
    if !desc.params.contains_key("sp_bits_per_value") {
        return Err(TensogramError::Metadata(
            "simple_packing requires sp_bits_per_value (the encoder can \
             auto-compute sp_reference_value + sp_binary_scale_factor from \
             the data, but the bit-width and decimal scale are the user \
             knobs).  Provide at least sp_bits_per_value, or the full \
             explicit 4-key set."
                .to_string(),
        ));
    }

    // The two derived keys are an all-or-nothing pair.  Providing only
    // one would either silently get overwritten by auto-compute (if we
    // ran it) or produce a meaningless mix of user-supplied + derived
    // values.  Detecting this here gives the user a clear error
    // before any encoding work happens.
    let has_ref = desc.params.contains_key("sp_reference_value");
    let has_bsf = desc.params.contains_key("sp_binary_scale_factor");
    if has_ref ^ has_bsf {
        let (set, missing) = if has_ref {
            ("sp_reference_value", "sp_binary_scale_factor")
        } else {
            ("sp_binary_scale_factor", "sp_reference_value")
        };
        return Err(TensogramError::Metadata(format!(
            "simple_packing: descriptor sets {set} but not {missing}.  \
             Provide both for explicit-params encoding, or neither to \
             let the encoder auto-compute them from the data."
        )));
    }

    // Explicit computed params present — trust them, skip the
    // auto-compute work entirely.  We still default the
    // sp_decimal_scale_factor knob when absent so the pipeline's
    // extract_simple_packing_params doesn't fault on a missing key.
    if has_ref && has_bsf {
        desc.params
            .entry("sp_decimal_scale_factor".to_string())
            .or_insert(ciborium::Value::Integer(0i64.into()));
        return Ok(());
    }

    let bits_per_value = u32::try_from(get_u64_param(&desc.params, "sp_bits_per_value")?)
        .map_err(|_| TensogramError::Metadata("sp_bits_per_value out of u32 range".to_string()))?;
    // Strict-input: a present-but-non-integer `sp_decimal_scale_factor`
    // is rejected.  Absence falls back to `0` (the standard default
    // documented at the field level — use a non-zero value only when
    // your data needs decimal-tier scaling).
    let decimal_scale_factor = i32::try_from(get_i64_param_or_default(
        &desc.params,
        "sp_decimal_scale_factor",
        0,
    )?)
    .map_err(|_| {
        TensogramError::Metadata("sp_decimal_scale_factor out of i32 range".to_string())
    })?;

    let values = bytes_as_f64_vec(data_bytes, desc.byte_order)?;
    let params = simple_packing::compute_params(&values, bits_per_value, decimal_scale_factor)
        .map_err(|e| TensogramError::Encoding(e.to_string()))?;

    desc.params.insert(
        "sp_reference_value".to_string(),
        ciborium::Value::Float(params.reference_value),
    );
    desc.params.insert(
        "sp_binary_scale_factor".to_string(),
        ciborium::Value::Integer(i64::from(params.binary_scale_factor).into()),
    );
    desc.params.insert(
        "sp_decimal_scale_factor".to_string(),
        ciborium::Value::Integer(i64::from(params.decimal_scale_factor).into()),
    );
    desc.params.insert(
        "sp_bits_per_value".to_string(),
        ciborium::Value::Integer(i64::from(params.bits_per_value).into()),
    );
    Ok(())
}

/// Reinterpret raw bytes as float64 honouring the descriptor's
/// byte order.  Used by the simple_packing auto-compute path.
///
/// Uses fallible `try_reserve_exact` rather than `collect()` so that
/// allocation failure on very large inputs surfaces as a structured
/// `TensogramError` instead of aborting the process — matching the
/// pattern in `tensogram_encodings::pipeline::bytes_to_f64`.
fn bytes_as_f64_vec(bytes: &[u8], byte_order: ByteOrder) -> Result<Vec<f64>> {
    if !bytes.len().is_multiple_of(8) {
        return Err(TensogramError::Metadata(format!(
            "simple_packing: input byte length {} is not a multiple of 8 (float64)",
            bytes.len()
        )));
    }
    let n = bytes.len() / 8;
    let mut out: Vec<f64> = Vec::new();
    out.try_reserve_exact(n).map_err(|e| {
        TensogramError::Encoding(format!(
            "simple_packing: failed to reserve {} bytes for byte-to-f64 \
             conversion: {e}",
            n.saturating_mul(std::mem::size_of::<f64>()),
        ))
    })?;
    for chunk in bytes.chunks_exact(8) {
        let mut buf = [0u8; 8];
        buf.copy_from_slice(chunk);
        out.push(match byte_order {
            ByteOrder::Big => f64::from_be_bytes(buf),
            ByteOrder::Little => f64::from_le_bytes(buf),
        });
    }
    Ok(out)
}

/// Maximum integer absolutely representable in `f64` without loss of
/// precision (`2^53`).  Beyond this magnitude, the conversion `i64 as
/// f64` rounds to the nearest even — silent precision loss.
const F64_EXACT_INT_BOUND: i128 = 1 << 53;

pub(crate) fn get_f64_param(params: &BTreeMap<String, ciborium::Value>, key: &str) -> Result<f64> {
    match params.get(key) {
        Some(ciborium::Value::Float(f)) => Ok(*f),
        Some(ciborium::Value::Integer(i)) => {
            // Strict-input contract: integers outside `[-2^53, 2^53]`
            // cannot be represented exactly in f64; converting them
            // would silently round.  Reject so the caller is forced
            // to either supply a float literal or pick a different
            // codec parameter.
            let n: i128 = (*i).into();
            if n.abs() > F64_EXACT_INT_BOUND {
                return Err(TensogramError::Metadata(format!(
                    "{key}: integer value {n} is outside the f64 \
                     exact-representable range [-2^53, 2^53]; \
                     converting to f64 would silently lose precision. \
                     Supply a float literal or pick a parameter that \
                     accepts integers up to i64::MAX."
                )));
            }
            // Within the exact-representable range, `as f64` is
            // lossless on every supported target.
            Ok(n as f64)
        }
        Some(other) => Err(TensogramError::Metadata(format!(
            "expected number for {key}, got {kind}",
            kind = crate::metadata::cbor_value_kind(other),
        ))),
        None => Err(TensogramError::Metadata(format!(
            "missing required parameter: {key}"
        ))),
    }
}

pub(crate) fn get_i64_param(params: &BTreeMap<String, ciborium::Value>, key: &str) -> Result<i64> {
    match params.get(key) {
        Some(ciborium::Value::Integer(i)) => {
            let n: i128 = (*i).into();
            i64::try_from(n).map_err(|_| {
                TensogramError::Metadata(format!("integer value {n} out of i64 range for {key}"))
            })
        }
        Some(other) => Err(TensogramError::Metadata(format!(
            "expected integer for {key}, got {kind}",
            kind = crate::metadata::cbor_value_kind(other),
        ))),
        None => Err(TensogramError::Metadata(format!(
            "missing required parameter: {key}"
        ))),
    }
}

/// Optional integer parameter accessor.
///
/// Distinguishes "key absent" (returns `default`) from "key present
/// but wrong CBOR type" (returns `Err`).  Earlier code used
/// `get_i64_param(...).unwrap_or(default)` which collapsed both into
/// the default — a strict-input violation: a typo such as
/// `zstd_level: "high"` (string) silently fell back to the default
/// level instead of erroring.
///
/// Use this whenever a numeric codec parameter has a sensible default
/// for the absent case but should reject other CBOR shapes.
pub(crate) fn get_i64_param_or_default(
    params: &BTreeMap<String, ciborium::Value>,
    key: &str,
    default: i64,
) -> Result<i64> {
    match params.get(key) {
        Some(ciborium::Value::Integer(i)) => {
            let n: i128 = (*i).into();
            i64::try_from(n).map_err(|_| {
                TensogramError::Metadata(format!("integer value {n} out of i64 range for {key}"))
            })
        }
        Some(other) => Err(TensogramError::Metadata(format!(
            "expected integer for {key}, got {kind}; \
             if you meant to use the default ({default}), omit the key",
            kind = crate::metadata::cbor_value_kind(other),
        ))),
        None => Ok(default),
    }
}

pub(crate) fn get_u64_param(params: &BTreeMap<String, ciborium::Value>, key: &str) -> Result<u64> {
    match params.get(key) {
        Some(ciborium::Value::Integer(i)) => {
            let n: i128 = (*i).into();
            u64::try_from(n).map_err(|_| {
                TensogramError::Metadata(format!("integer value {n} out of u64 range for {key}"))
            })
        }
        Some(other) => Err(TensogramError::Metadata(format!(
            "expected integer for {key}, got {kind}",
            kind = crate::metadata::cbor_value_kind(other),
        ))),
        None => Err(TensogramError::Metadata(format!(
            "missing required parameter: {key}"
        ))),
    }
}

/// Optional text parameter accessor with strict type-checking.
///
/// Same shape as [`get_i64_param_or_default`]: returns `default` when
/// the key is absent, but rejects non-text CBOR values.  Used for
/// codec sub-codec selectors (e.g. `blosc2_codec`).
//
// Currently the only call site lives behind `#[cfg(feature = "blosc2")]`,
// so the function would be flagged as dead code in feature combinations
// that exclude blosc2 (notably the WASM build).  The helper is also
// exercised by unit tests, so we permit `test` builds too.
#[cfg(any(feature = "blosc2", test))]
pub(crate) fn get_text_param_or_default<'a>(
    params: &'a BTreeMap<String, ciborium::Value>,
    key: &str,
    default: &'a str,
) -> Result<&'a str> {
    match params.get(key) {
        Some(ciborium::Value::Text(s)) => Ok(s.as_str()),
        Some(other) => Err(TensogramError::Metadata(format!(
            "expected text for {key}, got {kind}; \
             if you meant to use the default ({default:?}), omit the key",
            kind = crate::metadata::cbor_value_kind(other),
        ))),
        None => Ok(default),
    }
}

pub(crate) fn validate_szip_block_offsets(
    params: &BTreeMap<String, ciborium::Value>,
    encoded_bytes_len: usize,
) -> Result<()> {
    let value = params.get("szip_block_offsets").ok_or_else(|| {
        TensogramError::Metadata(
            "missing required parameter: szip_block_offsets for szip compression".to_string(),
        )
    })?;

    let offsets = match value {
        ciborium::Value::Array(arr) => arr,
        other => {
            return Err(TensogramError::Metadata(format!(
                "szip_block_offsets must be an array, got {other:?}"
            )));
        }
    };

    if offsets.is_empty() {
        return Err(TensogramError::Metadata(
            "szip_block_offsets must not be empty; first offset must be 0".to_string(),
        ));
    }

    let bit_bound = encoded_bytes_len.checked_mul(8).ok_or_else(|| {
        TensogramError::Metadata(format!(
            "encoded byte length {encoded_bytes_len} overflows bit-bound calculation"
        ))
    })?;
    let bit_bound_u64 = u64::try_from(bit_bound).map_err(|_| {
        TensogramError::Metadata(format!(
            "bit-bound {bit_bound} derived from {encoded_bytes_len} bytes does not fit in u64"
        ))
    })?;

    let mut parsed_offsets = Vec::with_capacity(offsets.len());
    for (idx, item) in offsets.iter().enumerate() {
        let offset = match item {
            ciborium::Value::Integer(i) => {
                let n: i128 = (*i).into();
                u64::try_from(n).map_err(|_| {
                    TensogramError::Metadata(format!(
                        "szip_block_offsets[{idx}] = {n} out of u64 range"
                    ))
                })?
            }
            other => {
                return Err(TensogramError::Metadata(format!(
                    "szip_block_offsets[{idx}] must be an integer, got {other:?}"
                )));
            }
        };

        if offset > bit_bound_u64 {
            return Err(TensogramError::Metadata(format!(
                "szip_block_offsets[{idx}] = {offset} exceeds bit bound {bit_bound_u64} (encoded_bytes_len = {encoded_bytes_len} bytes, {bit_bound_u64} bits)"
            )));
        }

        if idx == 0 {
            if offset != 0 {
                return Err(TensogramError::Metadata(format!(
                    "szip_block_offsets[0] must be 0, got {offset}"
                )));
            }
        } else {
            let prev = parsed_offsets[idx - 1];
            if offset <= prev {
                return Err(TensogramError::Metadata(format!(
                    "szip_block_offsets must be strictly increasing: szip_block_offsets[{}] = {}, szip_block_offsets[{idx}] = {offset}",
                    idx - 1,
                    prev
                )));
            }
        }

        parsed_offsets.push(offset);
    }

    Ok(())
}

pub(crate) fn validate_no_szip_offsets_for_non_szip(desc: &DataObjectDescriptor) -> Result<()> {
    if desc.compression != "szip" && desc.params.contains_key("szip_block_offsets") {
        return Err(TensogramError::Metadata(format!(
            "szip_block_offsets provided but compression is '{}', not 'szip'",
            desc.compression
        )));
    }
    Ok(())
}

/// Compose the payload region for a data-object frame.
///
/// The layout emitted is
/// `[encoded_payload][mask_nan][mask_inf+][mask_inf-]`
/// where each mask section is present iff the corresponding
/// [`MaskSet`] field is `Some`.  The returned [`MasksMetadata`]
/// records each section's byte offset (relative to the start of the
/// region) and length.
///
/// When [`MaskSet::is_empty`], the returned region is the caller's
/// `encoded_payload` unchanged and the metadata is `None` — the
/// resulting frame is byte-identical to the legacy `NTensorFrame`
/// payload layout except for the frame-type number.
///
/// # Small-mask fallback
///
/// When a mask's uncompressed bit-packed byte count is
/// `≤ small_threshold` (default 128, configurable and set to `0` to
/// disable), the method is forced to [`MaskMethod::None`] regardless
/// of the caller's requested method.  The resulting
/// [`MaskDescriptor::method`] reflects what was actually written,
/// not the caller's request.
///
/// Takes the per-kind methods + threshold directly rather than an
/// [`EncodeOptions`] reference so `StreamingEncoder` can call it
/// from its field snapshot without borrowing a synthesised options
/// struct.
pub(crate) fn compose_payload_region(
    mut encoded_payload: Vec<u8>,
    masks: MaskSet,
    nan_method: &MaskMethod,
    pos_inf_method: &MaskMethod,
    neg_inf_method: &MaskMethod,
    small_threshold: usize,
) -> Result<(Vec<u8>, Option<MasksMetadata>)> {
    if masks.is_empty() {
        return Ok((encoded_payload, None));
    }

    let mut metadata = MasksMetadata::default();
    let mut region_cursor = encoded_payload.len() as u64;

    // Append each present mask to the payload region and record its
    // descriptor.  Canonical order matches the CBOR key sort —
    // nan < inf+ < inf- — so the mask region stays byte-stable
    // across identical inputs.
    let mut append_one =
        |bits_opt: Option<&Vec<bool>>, method: &MaskMethod| -> Result<Option<MaskDescriptor>> {
            let Some(bits) = bits_opt else {
                return Ok(None);
            };
            let (blob, used_method) = encode_one_mask(bits, method.clone(), small_threshold)?;
            let desc = MaskDescriptor {
                method: used_method.name().to_string(),
                offset: region_cursor,
                length: blob.len() as u64,
                params: mask_params_cbor(&used_method),
            };
            region_cursor += blob.len() as u64;
            encoded_payload.extend_from_slice(&blob);
            Ok(Some(desc))
        };
    metadata.nan = append_one(masks.nan.as_ref(), nan_method)?;
    metadata.pos_inf = append_one(masks.pos_inf.as_ref(), pos_inf_method)?;
    metadata.neg_inf = append_one(masks.neg_inf.as_ref(), neg_inf_method)?;

    Ok((encoded_payload, Some(metadata)))
}

/// Compress one mask using the caller's chosen method, with auto-
/// fallback to [`MaskMethod::None`] for small masks.  Returns the
/// serialised blob AND the method actually used (may differ from the
/// requested method due to the small-mask fallback — see
/// [`compose_payload_region`]).
fn encode_one_mask(
    bits: &[bool],
    requested: MaskMethod,
    small_threshold: usize,
) -> Result<(Vec<u8>, MaskMethod)> {
    use tensogram_encodings::bitmask;

    // Small-mask fallback: compare the raw bit-packed byte count
    // against the threshold.  When `small_threshold == 0` the
    // fallback is disabled and we always honour the requested method.
    let uncompressed_bytes = bits.len().div_ceil(8);
    let method = if small_threshold > 0 && uncompressed_bytes <= small_threshold {
        MaskMethod::None
    } else {
        requested
    };

    let blob = match &method {
        MaskMethod::None => bitmask::codecs::encode_none(bits)
            .map_err(|e| TensogramError::Encoding(format!("bitmask pack: {e}")))?,
        MaskMethod::Rle => bitmask::rle::encode(bits),
        MaskMethod::Roaring => bitmask::roaring::encode(bits)
            .map_err(|e| TensogramError::Encoding(format!("roaring mask encode: {e}")))?,
        MaskMethod::Lz4 => bitmask::codecs::encode_lz4(bits)
            .map_err(|e| TensogramError::Encoding(format!("lz4 mask encode: {e}")))?,
        MaskMethod::Zstd { level } => bitmask::codecs::encode_zstd(bits, *level)
            .map_err(|e| TensogramError::Encoding(format!("zstd mask encode: {e}")))?,
        #[cfg(feature = "blosc2")]
        MaskMethod::Blosc2 { codec, level } => bitmask::codecs::encode_blosc2(bits, *codec, *level)
            .map_err(|e| TensogramError::Encoding(format!("blosc2 mask encode: {e}")))?,
    };

    Ok((blob, method))
}

/// Build the `params` sub-map for a [`MaskDescriptor`] per
/// `plans/WIRE_FORMAT.md` §6.5.1.  Empty for the parameter-less
/// methods; populated for `zstd` / `blosc2`.
fn mask_params_cbor(method: &MaskMethod) -> BTreeMap<String, ciborium::Value> {
    let mut params = BTreeMap::new();
    match method {
        MaskMethod::None | MaskMethod::Rle | MaskMethod::Roaring | MaskMethod::Lz4 => {}
        MaskMethod::Zstd { level } => {
            if let Some(l) = level {
                params.insert(
                    "level".to_string(),
                    ciborium::Value::Integer((*l as i64).into()),
                );
            }
        }
        #[cfg(feature = "blosc2")]
        MaskMethod::Blosc2 { codec, level } => {
            let codec_str = match codec {
                Blosc2Codec::Blosclz => "blosclz",
                Blosc2Codec::Lz4 => "lz4",
                Blosc2Codec::Lz4hc => "lz4hc",
                Blosc2Codec::Zlib => "zlib",
                Blosc2Codec::Zstd => "zstd",
            };
            params.insert(
                "codec".to_string(),
                ciborium::Value::Text(codec_str.to_string()),
            );
            params.insert(
                "level".to_string(),
                ciborium::Value::Integer((*level as i64).into()),
            );
        }
    }
    params
}

// ── Edge case tests ─────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::decode::{DecodeOptions, decode};
    use crate::types::{ByteOrder, GlobalMetadata};
    use std::collections::BTreeMap;

    fn make_descriptor(shape: Vec<u64>) -> DataObjectDescriptor {
        let strides = {
            let mut s = vec![1u64; shape.len()];
            for i in (0..shape.len().saturating_sub(1)).rev() {
                s[i] = s[i + 1] * shape[i + 1];
            }
            s
        };
        DataObjectDescriptor {
            obj_type: "ntensor".to_string(),
            ndim: shape.len() as u64,
            shape,
            strides,
            dtype: Dtype::Float32,
            byte_order: ByteOrder::native(),
            encoding: "none".to_string(),
            filter: "none".to_string(),
            compression: "none".to_string(),
            params: BTreeMap::new(),
            masks: None,
        }
    }

    // ── Category 1: base array mismatches ────────────────────────────────

    #[test]
    fn test_base_more_entries_than_descriptors_rejected() {
        // base has 5 entries but only 2 descriptors — should error.
        let meta = GlobalMetadata {
            base: vec![
                BTreeMap::new(),
                BTreeMap::new(),
                BTreeMap::new(),
                BTreeMap::new(),
                BTreeMap::new(),
            ],
            ..Default::default()
        };
        let desc = make_descriptor(vec![4]);
        let data = vec![0u8; 16];
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        let result = encode(
            &meta,
            &[(&desc, data.as_slice()), (&desc, data.as_slice())],
            &options,
        );
        assert!(
            result.is_err(),
            "5 base entries with 2 descriptors should fail"
        );
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("5") && err.contains("2"),
            "error should mention counts: {err}"
        );
    }

    #[test]
    fn test_base_fewer_entries_than_descriptors_auto_extended() {
        // base has 0 entries but 3 descriptors — auto-extends, _reserved_ inserted.
        let meta = GlobalMetadata {
            base: vec![],
            ..Default::default()
        };
        let desc = make_descriptor(vec![2]);
        let data = vec![0u8; 8];
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        let msg = encode(
            &meta,
            &[
                (&desc, data.as_slice()),
                (&desc, data.as_slice()),
                (&desc, data.as_slice()),
            ],
            &options,
        )
        .unwrap();

        let (decoded, _) = decode(&msg, &DecodeOptions::default()).unwrap();
        assert_eq!(decoded.base.len(), 3);
        // Each entry should have _reserved_ with tensor info
        for entry in &decoded.base {
            assert!(
                entry.contains_key("_reserved_"),
                "auto-extended base entry should have _reserved_"
            );
        }
    }

    #[test]
    fn test_base_entry_with_top_level_key_names_no_collision() {
        // base[0] contains a key named "version" — no collision with top-level version.
        let mut entry = BTreeMap::new();
        entry.insert(
            "version".to_string(),
            ciborium::Value::Text("my-version".to_string()),
        );
        entry.insert(
            "base".to_string(),
            ciborium::Value::Text("not-the-real-base".to_string()),
        );
        let meta = GlobalMetadata {
            base: vec![entry],
            ..Default::default()
        };
        let desc = make_descriptor(vec![2]);
        let data = vec![0u8; 8];
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        let msg = encode(&meta, &[(&desc, data.as_slice())], &options).unwrap();
        let (decoded, _) = decode(&msg, &DecodeOptions::default()).unwrap();

        // `version` and `base` are just free-form keys inside a
        // per-object `base[0]` entry — they have no special meaning
        // there.  The wire-format version lives in the preamble
        // (see `plans/WIRE_FORMAT.md` §3), not in CBOR metadata.
        assert_eq!(
            decoded.base[0].get("version"),
            Some(&ciborium::Value::Text("my-version".to_string()))
        );
        assert_eq!(
            decoded.base[0].get("base"),
            Some(&ciborium::Value::Text("not-the-real-base".to_string()))
        );
    }

    #[test]
    fn test_base_entry_with_deeply_nested_reserved_allowed() {
        // Only top-level _reserved_ in base[i] should be rejected.
        // Deeply nested _reserved_ (like {"foo": {"_reserved_": ...}}) is fine.
        let nested = ciborium::Value::Map(vec![(
            ciborium::Value::Text("_reserved_".to_string()),
            ciborium::Value::Text("nested-is-ok".to_string()),
        )]);
        let mut entry = BTreeMap::new();
        entry.insert("foo".to_string(), nested);
        let meta = GlobalMetadata {
            base: vec![entry],
            ..Default::default()
        };
        let desc = make_descriptor(vec![2]);
        let data = vec![0u8; 8];
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        // Should succeed — only top-level _reserved_ is rejected
        let msg = encode(&meta, &[(&desc, data.as_slice())], &options).unwrap();
        let (decoded, _) = decode(&msg, &DecodeOptions::default()).unwrap();
        // The nested _reserved_ should survive
        let foo = decoded.base[0].get("foo").unwrap();
        if let ciborium::Value::Map(pairs) = foo {
            assert_eq!(pairs.len(), 1);
        } else {
            panic!("expected map for foo");
        }
    }

    // ── Category 2: _reserved_ edge cases ────────────────────────────────

    #[test]
    fn test_reserved_rejected_at_message_level() {
        let mut reserved = BTreeMap::new();
        reserved.insert(
            "rogue".to_string(),
            ciborium::Value::Text("bad".to_string()),
        );
        let meta = GlobalMetadata {
            reserved,
            ..Default::default()
        };
        let desc = make_descriptor(vec![2]);
        let data = vec![0u8; 8];
        let result = encode(
            &meta,
            &[(&desc, data.as_slice())],
            &EncodeOptions::default(),
        );
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("_reserved_") && err.contains("message level"),
            "error: {err}"
        );
    }

    #[test]
    fn test_reserved_rejected_in_base_entry() {
        let mut entry = BTreeMap::new();
        entry.insert("_reserved_".to_string(), ciborium::Value::Map(vec![]));
        let meta = GlobalMetadata {
            base: vec![entry],
            ..Default::default()
        };
        let desc = make_descriptor(vec![2]);
        let data = vec![0u8; 8];
        let result = encode(
            &meta,
            &[(&desc, data.as_slice())],
            &EncodeOptions::default(),
        );
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("_reserved_") && err.contains("base[0]"),
            "error: {err}"
        );
    }

    #[test]
    fn test_reserved_tensor_has_four_keys_after_encode() {
        let meta = GlobalMetadata::default();
        let desc = make_descriptor(vec![3, 4]);
        let data = vec![0u8; 3 * 4 * 4]; // 3*4 float32
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        let msg = encode(&meta, &[(&desc, data.as_slice())], &options).unwrap();
        let (decoded, _) = decode(&msg, &DecodeOptions::default()).unwrap();

        let reserved = decoded.base[0]
            .get("_reserved_")
            .expect("_reserved_ missing");
        if let ciborium::Value::Map(pairs) = reserved {
            // Should have "tensor" key
            let tensor_entry = pairs
                .iter()
                .find(|(k, _)| *k == ciborium::Value::Text("tensor".to_string()));
            assert!(tensor_entry.is_some(), "missing tensor key in _reserved_");
            if let Some((_, ciborium::Value::Map(tensor_pairs))) = tensor_entry {
                let keys: Vec<String> = tensor_pairs
                    .iter()
                    .filter_map(|(k, _)| {
                        if let ciborium::Value::Text(s) = k {
                            Some(s.clone())
                        } else {
                            None
                        }
                    })
                    .collect();
                assert_eq!(keys.len(), 4, "tensor should have 4 keys, got: {keys:?}");
                assert!(keys.contains(&"ndim".to_string()));
                assert!(keys.contains(&"shape".to_string()));
                assert!(keys.contains(&"strides".to_string()));
                assert!(keys.contains(&"dtype".to_string()));
            } else {
                panic!("tensor is not a map");
            }
        } else {
            panic!("_reserved_ is not a map");
        }
    }

    #[test]
    fn test_reserved_tensor_scalar_ndim_zero() {
        // Scalar: ndim=0, shape=[], strides=[]
        let desc = DataObjectDescriptor {
            obj_type: "ntensor".to_string(),
            ndim: 0,
            shape: vec![],
            strides: vec![],
            dtype: Dtype::Float32,
            byte_order: ByteOrder::native(),
            encoding: "none".to_string(),
            filter: "none".to_string(),
            compression: "none".to_string(),
            params: BTreeMap::new(),
            masks: None,
        };
        let data = vec![0u8; 4]; // 1 float32
        let meta = GlobalMetadata::default();
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        let msg = encode(&meta, &[(&desc, data.as_slice())], &options).unwrap();
        let (decoded, _) = decode(&msg, &DecodeOptions::default()).unwrap();

        let reserved = decoded.base[0]
            .get("_reserved_")
            .expect("_reserved_ missing");
        if let ciborium::Value::Map(pairs) = reserved {
            let tensor_entry = pairs
                .iter()
                .find(|(k, _)| *k == ciborium::Value::Text("tensor".to_string()));
            if let Some((_, ciborium::Value::Map(tensor_pairs))) = tensor_entry {
                // ndim should be 0
                let ndim = tensor_pairs
                    .iter()
                    .find(|(k, _)| *k == ciborium::Value::Text("ndim".to_string()));
                assert!(
                    matches!(ndim, Some((_, ciborium::Value::Integer(i))) if i128::from(*i) == 0),
                    "ndim should be 0 for scalar"
                );
                // shape should be empty array
                let shape = tensor_pairs
                    .iter()
                    .find(|(k, _)| *k == ciborium::Value::Text("shape".to_string()));
                assert!(
                    matches!(shape, Some((_, ciborium::Value::Array(a))) if a.is_empty()),
                    "shape should be [] for scalar"
                );
            } else {
                panic!("tensor missing or not a map");
            }
        } else {
            panic!("_reserved_ is not a map");
        }
    }

    // ── Category 3: _extra_ edge cases ───────────────────────────────────

    #[test]
    fn test_extra_with_keys_colliding_with_base_entry_keys() {
        // _extra_ has key "mars", base[0] also has key "mars" — different scopes, both survive
        let mut entry = BTreeMap::new();
        entry.insert(
            "mars".to_string(),
            ciborium::Value::Text("base-mars".to_string()),
        );
        let mut extra = BTreeMap::new();
        extra.insert(
            "mars".to_string(),
            ciborium::Value::Text("extra-mars".to_string()),
        );
        let meta = GlobalMetadata {
            base: vec![entry],
            extra,
            ..Default::default()
        };
        let desc = make_descriptor(vec![2]);
        let data = vec![0u8; 8];
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        let msg = encode(&meta, &[(&desc, data.as_slice())], &options).unwrap();
        let (decoded, _) = decode(&msg, &DecodeOptions::default()).unwrap();

        assert_eq!(
            decoded.base[0].get("mars"),
            Some(&ciborium::Value::Text("base-mars".to_string()))
        );
        assert_eq!(
            decoded.extra.get("mars"),
            Some(&ciborium::Value::Text("extra-mars".to_string()))
        );
    }

    #[test]
    fn test_empty_extra_omitted_from_cbor() {
        let meta = GlobalMetadata {
            extra: BTreeMap::new(),
            ..Default::default()
        };
        let desc = make_descriptor(vec![2]);
        let data = vec![0u8; 8];
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        let msg = encode(&meta, &[(&desc, data.as_slice())], &options).unwrap();
        let (decoded, _) = decode(&msg, &DecodeOptions::default()).unwrap();
        assert!(decoded.extra.is_empty());
    }

    #[test]
    fn test_extra_with_nested_maps_round_trips() {
        let nested = ciborium::Value::Map(vec![
            (
                ciborium::Value::Text("key1".to_string()),
                ciborium::Value::Integer(42.into()),
            ),
            (
                ciborium::Value::Text("key2".to_string()),
                ciborium::Value::Map(vec![(
                    ciborium::Value::Text("deep".to_string()),
                    ciborium::Value::Bool(true),
                )]),
            ),
        ]);
        let mut extra = BTreeMap::new();
        extra.insert("nested".to_string(), nested.clone());
        let meta = GlobalMetadata {
            extra,
            ..Default::default()
        };
        let desc = make_descriptor(vec![2]);
        let data = vec![0u8; 8];
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        let msg = encode(&meta, &[(&desc, data.as_slice())], &options).unwrap();
        let (decoded, _) = decode(&msg, &DecodeOptions::default()).unwrap();
        // Nested maps should round-trip
        assert!(decoded.extra.contains_key("nested"));
    }

    // ── Category 4: Serde deserialization ────────────────────────────────

    #[test]
    fn test_legacy_top_level_keys_routed_to_extra() {
        // Simulate a legacy v2-style message carrying `common` / `payload`
        // and a stray `version` top-level key.  Under the free-form rule
        // (see `plans/WIRE_FORMAT.md` §6.1), these unknown keys must flow
        // into `_extra_` rather than being silently dropped — the wire
        // version lives exclusively in the preamble (see [`crate::wire`]).
        use ciborium::Value;
        let cbor = Value::Map(vec![
            (Value::Text("common".to_string()), Value::Map(vec![])),
            (Value::Text("payload".to_string()), Value::Array(vec![])),
            (Value::Text("version".to_string()), Value::Integer(3.into())),
        ]);
        let mut bytes = Vec::new();
        ciborium::into_writer(&cbor, &mut bytes).unwrap();

        let decoded: GlobalMetadata = crate::metadata::cbor_to_global_metadata(&bytes).unwrap();
        assert!(decoded.base.is_empty());
        assert!(decoded.reserved.is_empty());
        assert!(decoded.extra.contains_key("common"));
        assert!(decoded.extra.contains_key("payload"));
        assert_eq!(
            decoded.extra.get("version"),
            Some(&Value::Integer(3.into()))
        );
    }

    #[test]
    fn test_old_reserved_key_name_routed_to_extra() {
        // "reserved" (unescaped, old v1 name) is NOT the library-managed
        // namespace — only the exact key `_reserved_` is.  Under the
        // free-form rule, `reserved` is just another top-level key and
        // flows into `_extra_` on decode.
        use ciborium::Value;
        let cbor = Value::Map(vec![(
            Value::Text("reserved".to_string()),
            Value::Map(vec![(
                Value::Text("rogue".to_string()),
                Value::Text("value".to_string()),
            )]),
        )]);
        let mut bytes = Vec::new();
        ciborium::into_writer(&cbor, &mut bytes).unwrap();

        let decoded: GlobalMetadata = crate::metadata::cbor_to_global_metadata(&bytes).unwrap();
        assert!(
            decoded.reserved.is_empty(),
            "legacy 'reserved' must NOT bleed into library-managed `_reserved_`"
        );
        assert!(
            decoded.extra.contains_key("reserved"),
            "legacy 'reserved' key must land in `_extra_`"
        );
    }

    // ── Category 4b: validate_no_client_reserved — multi-entry base ────

    #[test]
    fn test_reserved_rejected_in_second_base_entry_only() {
        // base[0] is clean, base[1] has _reserved_ → should fail, mentioning base[1]
        let mut entry0 = BTreeMap::new();
        entry0.insert("clean".to_string(), ciborium::Value::Text("ok".to_string()));
        let mut entry1 = BTreeMap::new();
        entry1.insert("_reserved_".to_string(), ciborium::Value::Map(vec![]));
        let meta = GlobalMetadata {
            base: vec![entry0, entry1],
            ..Default::default()
        };
        let desc = make_descriptor(vec![2]);
        let data = vec![0u8; 8];
        let result = encode(
            &meta,
            &[(&desc, data.as_slice()), (&desc, data.as_slice())],
            &EncodeOptions::default(),
        );
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("base[1]"),
            "error should mention base[1]: {err}"
        );
    }

    #[test]
    fn test_reserved_accepted_when_all_base_entries_clean() {
        // Multiple base entries, none have _reserved_ → should succeed
        let mut e0 = BTreeMap::new();
        e0.insert(
            "key0".to_string(),
            ciborium::Value::Text("val0".to_string()),
        );
        let mut e1 = BTreeMap::new();
        e1.insert(
            "key1".to_string(),
            ciborium::Value::Text("val1".to_string()),
        );
        let meta = GlobalMetadata {
            base: vec![e0, e1],
            ..Default::default()
        };
        let desc = make_descriptor(vec![2]);
        let data = vec![0u8; 8];
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        let msg = encode(
            &meta,
            &[(&desc, data.as_slice()), (&desc, data.as_slice())],
            &options,
        )
        .unwrap();
        let (decoded, _) = decode(&msg, &DecodeOptions::default()).unwrap();
        assert_eq!(decoded.base.len(), 2);
        assert!(decoded.base[0].contains_key("key0"));
        assert!(decoded.base[1].contains_key("key1"));
    }

    // ── Category 5: populate_base_entries — all dtypes ───────────────────

    #[test]
    fn test_reserved_tensor_dtype_strings_for_all_dtypes() {
        // Verify that _reserved_.tensor.dtype string is correct for every Dtype variant
        let dtypes_and_expected = [
            (Dtype::Float16, "float16"),
            (Dtype::Bfloat16, "bfloat16"),
            (Dtype::Float32, "float32"),
            (Dtype::Float64, "float64"),
            (Dtype::Complex64, "complex64"),
            (Dtype::Complex128, "complex128"),
            (Dtype::Int8, "int8"),
            (Dtype::Int16, "int16"),
            (Dtype::Int32, "int32"),
            (Dtype::Int64, "int64"),
            (Dtype::Uint8, "uint8"),
            (Dtype::Uint16, "uint16"),
            (Dtype::Uint32, "uint32"),
            (Dtype::Uint64, "uint64"),
        ];

        for (dtype, expected_str) in dtypes_and_expected {
            let byte_width = dtype.byte_width();
            let num_elements: u64 = 4;
            let data_len = num_elements as usize * byte_width;

            let desc = DataObjectDescriptor {
                obj_type: "ntensor".to_string(),
                ndim: 1,
                shape: vec![num_elements],
                strides: vec![1],
                dtype,
                byte_order: ByteOrder::native(),
                encoding: "none".to_string(),
                filter: "none".to_string(),
                compression: "none".to_string(),
                params: BTreeMap::new(),
                masks: None,
            };
            let data = vec![0u8; data_len];
            let meta = GlobalMetadata::default();
            let options = EncodeOptions {
                hashing: false,
                ..Default::default()
            };
            let msg = encode(&meta, &[(&desc, data.as_slice())], &options).unwrap();
            let (decoded, _) = decode(&msg, &DecodeOptions::default()).unwrap();

            let reserved = decoded.base[0]
                .get("_reserved_")
                .unwrap_or_else(|| panic!("_reserved_ missing for dtype {dtype}"));
            if let ciborium::Value::Map(pairs) = reserved {
                let tensor_entry = pairs
                    .iter()
                    .find(|(k, _)| *k == ciborium::Value::Text("tensor".to_string()));
                if let Some((_, ciborium::Value::Map(tensor_pairs))) = tensor_entry {
                    let dtype_val = tensor_pairs
                        .iter()
                        .find(|(k, _)| *k == ciborium::Value::Text("dtype".to_string()));
                    assert!(
                        matches!(
                            dtype_val,
                            Some((_, ciborium::Value::Text(s))) if s == expected_str
                        ),
                        "dtype for {dtype} should be '{expected_str}', got: {dtype_val:?}"
                    );
                } else {
                    panic!("tensor missing or not a map for dtype {dtype}");
                }
            } else {
                panic!("_reserved_ is not a map for dtype {dtype}");
            }
        }
    }

    // ── Category 6: GlobalMetadata serde with all fields ─────────────────

    #[test]
    fn test_global_metadata_serde_all_fields_populated() {
        // base + reserved + extra all populated — verify CBOR round-trip
        use ciborium::Value;

        let mut base_entry = BTreeMap::new();
        base_entry.insert("key".to_string(), Value::Text("base_val".to_string()));
        let mut reserved = BTreeMap::new();
        reserved.insert("encoder".to_string(), Value::Text("test".to_string()));
        let mut extra = BTreeMap::new();
        extra.insert("custom".to_string(), Value::Integer(42.into()));

        let meta = GlobalMetadata {
            base: vec![base_entry],
            reserved,
            extra,
        };

        // Serialize to CBOR and back
        let cbor_bytes = crate::metadata::global_metadata_to_cbor(&meta).unwrap();
        let decoded: GlobalMetadata =
            crate::metadata::cbor_to_global_metadata(&cbor_bytes).unwrap();
        assert_eq!(decoded.base.len(), 1);
        assert_eq!(
            decoded.base[0].get("key"),
            Some(&Value::Text("base_val".to_string()))
        );
        assert!(decoded.reserved.contains_key("encoder"));
        assert_eq!(
            decoded.extra.get("custom"),
            Some(&Value::Integer(42.into()))
        );
    }

    // ── Category 7: populate_reserved_provenance ─────────────────────────

    #[test]
    fn test_provenance_fields_present_after_encode() {
        let meta = GlobalMetadata::default();
        let desc = make_descriptor(vec![2]);
        let data = vec![0u8; 8];
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        let msg = encode(&meta, &[(&desc, data.as_slice())], &options).unwrap();
        let (decoded, _) = decode(&msg, &DecodeOptions::default()).unwrap();

        // Message-level reserved should have encoder, time, uuid
        assert!(decoded.reserved.contains_key("encoder"));
        assert!(decoded.reserved.contains_key("time"));
        assert!(decoded.reserved.contains_key("uuid"));

        // encoder should contain name and version
        if let ciborium::Value::Map(pairs) = decoded.reserved.get("encoder").unwrap() {
            let has_name = pairs
                .iter()
                .any(|(k, _)| *k == ciborium::Value::Text("name".to_string()));
            let has_version = pairs
                .iter()
                .any(|(k, _)| *k == ciborium::Value::Text("version".to_string()));
            assert!(has_name, "encoder map should have 'name' key");
            assert!(has_version, "encoder map should have 'version' key");
        } else {
            panic!("encoder should be a map");
        }

        // uuid should be a valid UUID string (36 chars with hyphens)
        if let ciborium::Value::Text(uuid_str) = decoded.reserved.get("uuid").unwrap() {
            assert_eq!(uuid_str.len(), 36, "UUID should be 36 chars: {uuid_str}");
            assert_eq!(
                uuid_str.chars().filter(|c| *c == '-').count(),
                4,
                "UUID should have 4 hyphens: {uuid_str}"
            );
        } else {
            panic!("uuid should be a text");
        }

        // time should be an ISO 8601 timestamp ending with Z
        if let ciborium::Value::Text(time_str) = decoded.reserved.get("time").unwrap() {
            assert!(
                time_str.ends_with('Z'),
                "time should end with Z: {time_str}"
            );
            assert!(
                time_str.contains('T'),
                "time should contain T separator: {time_str}"
            );
        } else {
            panic!("time should be a text");
        }
    }

    #[test]
    fn test_both_reserved_and_reserved_underscore_only_new_captured() {
        // Both "reserved" and "_reserved_" present — only "_reserved_" should be captured.
        use ciborium::Value;
        let cbor = Value::Map(vec![
            (
                Value::Text("_reserved_".to_string()),
                Value::Map(vec![(
                    Value::Text("encoder".to_string()),
                    Value::Text("tensogram".to_string()),
                )]),
            ),
            (
                Value::Text("reserved".to_string()),
                Value::Map(vec![(
                    Value::Text("old".to_string()),
                    Value::Text("ignored".to_string()),
                )]),
            ),
            (Value::Text("version".to_string()), Value::Integer(3.into())),
        ]);
        let mut bytes = Vec::new();
        ciborium::into_writer(&cbor, &mut bytes).unwrap();

        let decoded: GlobalMetadata = crate::metadata::cbor_to_global_metadata(&bytes).unwrap();
        assert!(decoded.reserved.contains_key("encoder"));
        assert!(!decoded.reserved.contains_key("old"));
    }

    // ── Category 8: encode_pre_encoded smoke tests ───────────────────────

    /// Roundtrip: encode raw bytes via encode(), then re-encode the exact same
    /// payload bytes via encode_pre_encoded(). Both decoded payloads must be
    /// byte-identical. We compare payload bytes, NOT raw wire messages (provenance
    /// UUIDs make raw message equality impossible).
    #[test]
    fn test_encode_pre_encoded_roundtrip_simple_packing() {
        // Use encoding="none" (raw float32) for maximum portability — no feature flags needed.
        let desc = make_descriptor(vec![4]);
        let raw_data: Vec<u8> = vec![0u8; 4 * 4]; // 4 float32 values, all-zero

        let meta = GlobalMetadata::default();
        let options = EncodeOptions::default();

        // Step 1: encode normally
        let msg1 = encode(&meta, &[(&desc, raw_data.as_slice())], &options).unwrap();

        // Step 2: decode to get the encoded payload bytes + descriptor
        let (_, objects1) = decode(&msg1, &DecodeOptions::default()).unwrap();
        let (decoded_desc1, decoded_payload1) = &objects1[0];

        // Step 3: re-encode the same bytes via encode_pre_encoded
        let msg2 = encode_pre_encoded(
            &meta,
            &[(&decoded_desc1.clone(), decoded_payload1.as_slice())],
            &options,
        )
        .unwrap();

        // Step 4: decode the second message
        let (_, objects2) = decode(&msg2, &DecodeOptions::default()).unwrap();
        let (_, decoded_payload2) = &objects2[0];

        // Payloads must be identical — same bytes, same encoding
        // (raw wire messages differ due to non-deterministic provenance UUIDs)
        assert_eq!(
            decoded_payload1, decoded_payload2,
            "decoded payloads should be equal after encode/re-encode roundtrip"
        );
    }

    // (Wave 2.4 removed the dead `EncodeOptions.emit_preceders` field.
    // Per-object preceder metadata in streaming mode flows through
    // `StreamingEncoder::write_preceder()` instead.)

    /// `encode_pre_encoded` populates each data-object frame's
    /// inline hash slot with the xxh3-64 of the frame body when
    /// `EncodeOptions.hash_algorithm` is `Some(Xxh3)` — same
    /// contract as `encode`.  v3 equivalent of the pre-v3
    /// "library overwrites caller-supplied descriptor hash" test
    /// (caller-supplied hashes are structurally impossible in v3
    /// because `DataObjectDescriptor.hash` is gone).
    #[test]
    fn test_encode_pre_encoded_populates_inline_hash_slot() {
        use crate::framing::{decode_message, scan};
        use crate::hash::verify_frame_hash;
        use crate::wire::{FrameHeader, MessageFlags, Preamble};

        let desc = make_descriptor(vec![2]);
        let data = vec![0xABu8; 8];
        let meta = GlobalMetadata::default();
        let options = EncodeOptions::default();

        let msg = encode_pre_encoded(&meta, &[(&desc, data.as_slice())], &options).unwrap();

        // Preamble HASHES_PRESENT must be set.
        let preamble = Preamble::read_from(&msg).unwrap();
        assert!(preamble.flags.has(MessageFlags::HASHES_PRESENT));

        // Every data-object frame's inline slot verifies.
        let messages = scan(&msg);
        assert_eq!(messages.len(), 1);
        let (offset, len) = messages[0];
        let only_msg = &msg[offset..offset + len];
        let decoded = decode_message(only_msg).unwrap();
        for (_, _, _, frame_offset) in &decoded.objects {
            let frame = &only_msg[*frame_offset..];
            let fh = FrameHeader::read_from(frame).unwrap();
            let frame_bytes = &frame[..fh.total_length as usize];
            verify_frame_hash(frame_bytes, fh.frame_type, None)
                .expect("inline hash slot must verify against body");
        }
    }

    #[test]
    fn test_validate_szip_block_offsets_happy_path() {
        let mut params = BTreeMap::new();
        params.insert(
            "szip_block_offsets".to_string(),
            ciborium::Value::Array(vec![0u64, 100, 200].into_iter().map(|n| n.into()).collect()),
        );

        assert!(validate_szip_block_offsets(&params, 100).is_ok());
    }

    #[test]
    fn test_validate_szip_block_offsets_missing_key() {
        let params = BTreeMap::new();

        let err = validate_szip_block_offsets(&params, 100)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("missing") && err.contains("szip_block_offsets"),
            "error: {err}"
        );
    }

    #[test]
    fn test_validate_szip_block_offsets_not_array() {
        let mut params = BTreeMap::new();
        params.insert(
            "szip_block_offsets".to_string(),
            ciborium::Value::Integer(0.into()),
        );

        let err = validate_szip_block_offsets(&params, 100)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("array") && err.contains("szip_block_offsets"),
            "error: {err}"
        );
    }

    #[test]
    fn test_validate_szip_block_offsets_non_integer_element() {
        let mut params = BTreeMap::new();
        params.insert(
            "szip_block_offsets".to_string(),
            ciborium::Value::Array(vec![
                ciborium::Value::Integer(0.into()),
                ciborium::Value::Text("x".to_string()),
            ]),
        );

        let err = validate_szip_block_offsets(&params, 100)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("integer") && err.contains("szip_block_offsets"),
            "error: {err}"
        );
    }

    #[test]
    fn test_validate_szip_block_offsets_nonzero_first() {
        let mut params = BTreeMap::new();
        params.insert(
            "szip_block_offsets".to_string(),
            ciborium::Value::Array(vec![5u64, 100, 200].into_iter().map(|n| n.into()).collect()),
        );

        let err = validate_szip_block_offsets(&params, 100)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("must be 0") && err.contains("got 5"),
            "error: {err}"
        );
    }

    #[test]
    fn test_validate_szip_block_offsets_non_monotonic() {
        let mut params = BTreeMap::new();
        params.insert(
            "szip_block_offsets".to_string(),
            ciborium::Value::Array(vec![0u64, 100, 50].into_iter().map(|n| n.into()).collect()),
        );

        let err = validate_szip_block_offsets(&params, 100)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("increasing") || err.contains("monotonic"),
            "error: {err}"
        );
    }

    #[test]
    fn test_validate_szip_block_offsets_offset_beyond_bound() {
        let mut params = BTreeMap::new();
        params.insert(
            "szip_block_offsets".to_string(),
            ciborium::Value::Array(vec![0u64, 100, 801].into_iter().map(|n| n.into()).collect()),
        );

        let err = validate_szip_block_offsets(&params, 100)
            .unwrap_err()
            .to_string();
        assert!(err.contains("800") && err.contains("801"), "error: {err}");
    }

    #[test]
    fn test_validate_no_szip_offsets_for_non_szip_rejects() {
        let mut params = BTreeMap::new();
        params.insert(
            "szip_block_offsets".to_string(),
            ciborium::Value::Array(vec![0u64, 1].into_iter().map(|n| n.into()).collect()),
        );
        let desc = DataObjectDescriptor {
            obj_type: "ntensor".to_string(),
            ndim: 1,
            shape: vec![2],
            strides: vec![1],
            dtype: Dtype::Float32,
            byte_order: ByteOrder::native(),
            encoding: "none".to_string(),
            filter: "none".to_string(),
            compression: "zstd".to_string(),
            params,
            masks: None,
        };

        let err = validate_no_szip_offsets_for_non_szip(&desc)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("szip_block_offsets") && err.contains("zstd"),
            "error: {err}"
        );
    }

    #[test]
    fn test_validate_no_szip_offsets_for_non_szip_allows_szip() {
        let mut params = BTreeMap::new();
        params.insert(
            "szip_block_offsets".to_string(),
            ciborium::Value::Array(vec![0u64, 1].into_iter().map(|n| n.into()).collect()),
        );
        let desc = DataObjectDescriptor {
            obj_type: "ntensor".to_string(),
            ndim: 1,
            shape: vec![2],
            strides: vec![1],
            dtype: Dtype::Float32,
            byte_order: ByteOrder::native(),
            encoding: "none".to_string(),
            filter: "none".to_string(),
            compression: "szip".to_string(),
            params,
            masks: None,
        };

        assert!(validate_no_szip_offsets_for_non_szip(&desc).is_ok());
    }

    // ── AggregateHashPolicy resolver tests ──────────────────────────

    #[test]
    fn aggregate_hash_policy_default_is_auto() {
        assert_eq!(AggregateHashPolicy::default(), AggregateHashPolicy::Auto);
    }

    #[test]
    fn aggregate_hash_policy_buffered_resolves_auto_to_header() {
        assert_eq!(
            AggregateHashPolicy::Auto.resolved_buffered(),
            AggregateHashPolicy::Header
        );
        // Other variants pass through unchanged.
        assert_eq!(
            AggregateHashPolicy::None.resolved_buffered(),
            AggregateHashPolicy::None
        );
        assert_eq!(
            AggregateHashPolicy::Footer.resolved_buffered(),
            AggregateHashPolicy::Footer
        );
        assert_eq!(
            AggregateHashPolicy::Both.resolved_buffered(),
            AggregateHashPolicy::Both
        );
    }

    #[test]
    fn aggregate_hash_policy_streaming_rejects_header() {
        let err = AggregateHashPolicy::Header
            .resolved_streaming()
            .unwrap_err();
        assert!(matches!(err, TensogramError::Encoding(_)));
    }

    #[test]
    fn aggregate_hash_policy_streaming_rejects_both() {
        let err = AggregateHashPolicy::Both.resolved_streaming().unwrap_err();
        assert!(matches!(err, TensogramError::Encoding(_)));
    }

    #[test]
    fn aggregate_hash_policy_streaming_resolves_auto_to_footer() {
        assert_eq!(
            AggregateHashPolicy::Auto.resolved_streaming().unwrap(),
            AggregateHashPolicy::Footer
        );
    }

    #[test]
    fn aggregate_hash_policy_streaming_accepts_explicit_footer_and_none() {
        assert_eq!(
            AggregateHashPolicy::Footer.resolved_streaming().unwrap(),
            AggregateHashPolicy::Footer
        );
        assert_eq!(
            AggregateHashPolicy::None.resolved_streaming().unwrap(),
            AggregateHashPolicy::None
        );
    }

    #[test]
    fn aggregate_hash_policy_emits_flags() {
        // emits_header / emits_footer reflect what the resolver produced.
        assert!(AggregateHashPolicy::Header.emits_header());
        assert!(!AggregateHashPolicy::Header.emits_footer());
        assert!(!AggregateHashPolicy::Footer.emits_header());
        assert!(AggregateHashPolicy::Footer.emits_footer());
        assert!(AggregateHashPolicy::Both.emits_header());
        assert!(AggregateHashPolicy::Both.emits_footer());
        assert!(!AggregateHashPolicy::None.emits_header());
        assert!(!AggregateHashPolicy::None.emits_footer());
    }

    // ── Strict optional-param accessor tests (Wave 1.7) ───────────────

    #[test]
    fn get_i64_param_or_default_returns_default_on_absent() {
        let params = BTreeMap::new();
        assert_eq!(
            get_i64_param_or_default(&params, "zstd_level", 3).unwrap(),
            3
        );
    }

    #[test]
    fn get_i64_param_or_default_returns_present_value() {
        let mut params = BTreeMap::new();
        params.insert(
            "zstd_level".to_string(),
            ciborium::Value::Integer(7i64.into()),
        );
        assert_eq!(
            get_i64_param_or_default(&params, "zstd_level", 3).unwrap(),
            7
        );
    }

    #[test]
    fn get_i64_param_or_default_rejects_wrong_type() {
        // Strict-input contract: a present-but-non-integer value is
        // rejected, NOT silently replaced by the default.  This is
        // the bug class the helper exists to prevent: a typo such
        // as `zstd_level: "high"` previously fell back to the default
        // level.
        let mut params = BTreeMap::new();
        params.insert(
            "zstd_level".to_string(),
            ciborium::Value::Text("high".to_string()),
        );
        let err = get_i64_param_or_default(&params, "zstd_level", 3).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("expected integer"), "msg: {msg}");
                assert!(msg.contains("zstd_level"), "msg: {msg}");
                assert!(msg.contains("default"), "msg: {msg}");
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn get_text_param_or_default_returns_default_on_absent() {
        let params = BTreeMap::new();
        assert_eq!(
            get_text_param_or_default(&params, "blosc2_codec", "lz4").unwrap(),
            "lz4"
        );
    }

    #[test]
    fn get_text_param_or_default_returns_present_value() {
        let mut params = BTreeMap::new();
        params.insert(
            "blosc2_codec".to_string(),
            ciborium::Value::Text("zstd".to_string()),
        );
        assert_eq!(
            get_text_param_or_default(&params, "blosc2_codec", "lz4").unwrap(),
            "zstd"
        );
    }

    #[test]
    fn get_text_param_or_default_rejects_wrong_type() {
        let mut params = BTreeMap::new();
        params.insert(
            "blosc2_codec".to_string(),
            ciborium::Value::Integer(5i64.into()),
        );
        let err = get_text_param_or_default(&params, "blosc2_codec", "lz4").unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("expected text"), "msg: {msg}");
                assert!(msg.contains("blosc2_codec"), "msg: {msg}");
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    // ── Mask params strict validation (Wave 1.14) ────────────────────

    fn make_mask_desc(method: &str, params: BTreeMap<String, ciborium::Value>) -> MaskDescriptor {
        MaskDescriptor {
            method: method.to_string(),
            offset: 0,
            length: 1,
            params,
        }
    }

    #[test]
    fn validate_mask_params_accepts_empty_for_paramless_methods() {
        for m in ["none", "rle", "roaring", "lz4"] {
            let masks = MasksMetadata {
                nan: Some(make_mask_desc(m, BTreeMap::new())),
                ..Default::default()
            };
            assert!(
                validate_mask_params(&masks).is_ok(),
                "method {m} must accept empty params"
            );
        }
    }

    #[test]
    fn validate_mask_params_accepts_zstd_level() {
        let mut params = BTreeMap::new();
        params.insert("level".to_string(), ciborium::Value::Integer(3i64.into()));
        let masks = MasksMetadata {
            nan: Some(make_mask_desc("zstd", params)),
            ..Default::default()
        };
        assert!(validate_mask_params(&masks).is_ok());
    }

    #[test]
    fn validate_mask_params_rejects_unknown_method() {
        let masks = MasksMetadata {
            nan: Some(make_mask_desc("snappy", BTreeMap::new())),
            ..Default::default()
        };
        let err = validate_mask_params(&masks).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("unknown method"), "msg: {msg}");
                assert!(msg.contains("snappy"), "msg: {msg}");
                assert!(msg.contains("expected one of"), "msg: {msg}");
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn validate_mask_params_rejects_unknown_param_for_paramless_method() {
        // RLE has no params; a `level` here is a stale leftover from
        // a different codec choice, almost certainly user error.
        let mut params = BTreeMap::new();
        params.insert("level".to_string(), ciborium::Value::Integer(5i64.into()));
        let masks = MasksMetadata {
            pos_inf: Some(make_mask_desc("rle", params)),
            ..Default::default()
        };
        let err = validate_mask_params(&masks).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("unknown param"), "msg: {msg}");
                assert!(msg.contains("level"), "msg: {msg}");
                assert!(msg.contains("rle"), "msg: {msg}");
                assert!(msg.contains("inf+"), "kind tag missing: {msg}");
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    // ── Strict integer→float bound (Wave 1.6) ────────────────────────

    #[test]
    fn get_f64_param_accepts_integer_within_exact_range() {
        let mut params = BTreeMap::new();
        // 2^53 is the boundary — must succeed (exact f64).
        params.insert(
            "tol".to_string(),
            ciborium::Value::Integer((1i64 << 53).into()),
        );
        assert_eq!(get_f64_param(&params, "tol").unwrap(), (1u64 << 53) as f64);
    }

    #[test]
    fn get_f64_param_rejects_integer_beyond_exact_range() {
        // 2^53 + 1 cannot be represented exactly in f64; reject.
        let mut params = BTreeMap::new();
        let too_big = i64::from((1u32 << 30) - 1) << 24; // safely beyond 2^53
        params.insert("tol".to_string(), ciborium::Value::Integer(too_big.into()));
        let err = get_f64_param(&params, "tol").unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("exact-representable"), "msg: {msg}");
                assert!(msg.contains("tol"), "msg: {msg}");
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn get_f64_param_accepts_negative_integer_within_range() {
        let mut params = BTreeMap::new();
        params.insert(
            "tol".to_string(),
            ciborium::Value::Integer((-(1i64 << 53)).into()),
        );
        assert_eq!(
            get_f64_param(&params, "tol").unwrap(),
            -((1u64 << 53) as f64)
        );
    }

    #[test]
    fn get_f64_param_rejects_large_negative_integer() {
        let mut params = BTreeMap::new();
        let too_neg = -(i64::from((1u32 << 30) - 1) << 24);
        params.insert("tol".to_string(), ciborium::Value::Integer(too_neg.into()));
        let err = get_f64_param(&params, "tol").unwrap_err();
        assert!(matches!(err, TensogramError::Metadata(_)));
    }

    #[test]
    fn validate_mask_params_rejects_typo_param() {
        // A typo on a known method (`levle` instead of `level` for
        // zstd) is rejected.
        let mut params = BTreeMap::new();
        params.insert("levle".to_string(), ciborium::Value::Integer(3i64.into()));
        let masks = MasksMetadata {
            neg_inf: Some(make_mask_desc("zstd", params)),
            ..Default::default()
        };
        let err = validate_mask_params(&masks).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("unknown param"), "msg: {msg}");
                assert!(msg.contains("levle"), "msg: {msg}");
                assert!(msg.contains("zstd"), "msg: {msg}");
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    // ── validate_object: bitmask data-length mismatch ─────────────────

    #[test]
    fn validate_object_bitmask_data_len_mismatch_rejected() {
        // Bitmask dtype: expected bytes = ceil(product / 8).  shape [20]
        // => ceil(20/8) = 3 bytes.  Supplying 2 bytes must error.
        let desc = DataObjectDescriptor {
            obj_type: "ntensor".to_string(),
            ndim: 1,
            shape: vec![20],
            strides: vec![1],
            dtype: Dtype::Bitmask,
            byte_order: ByteOrder::native(),
            encoding: "none".to_string(),
            filter: "none".to_string(),
            compression: "none".to_string(),
            params: BTreeMap::new(),
            masks: None,
        };
        let err = validate_object(&desc, 2).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("bitmask"), "msg: {msg}");
                assert!(msg.contains('3'), "expected ceil(20/8)=3: {msg}");
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn validate_object_bitmask_data_len_match_ok() {
        let desc = DataObjectDescriptor {
            obj_type: "ntensor".to_string(),
            ndim: 1,
            shape: vec![20],
            strides: vec![1],
            dtype: Dtype::Bitmask,
            byte_order: ByteOrder::native(),
            encoding: "none".to_string(),
            filter: "none".to_string(),
            compression: "none".to_string(),
            params: BTreeMap::new(),
            masks: None,
        };
        assert!(validate_object(&desc, 3).is_ok());
    }

    // ── validate_object: routes through validate_mask_params ─────────────

    #[test]
    fn validate_object_rejects_invalid_mask_descriptor() {
        // A `masks` block with an unknown method must be rejected by
        // validate_object via validate_mask_params.
        let masks = MasksMetadata {
            nan: Some(make_mask_desc("bogus", BTreeMap::new())),
            ..Default::default()
        };
        let desc = DataObjectDescriptor {
            obj_type: "ntensor".to_string(),
            ndim: 1,
            shape: vec![2],
            strides: vec![1],
            dtype: Dtype::Float32,
            byte_order: ByteOrder::native(),
            encoding: "none".to_string(),
            filter: "none".to_string(),
            compression: "none".to_string(),
            params: BTreeMap::new(),
            masks: Some(masks),
        };
        let err = validate_object(&desc, 8).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("unknown method"), "msg: {msg}");
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    // ── resolve_encoding error paths ─────────────────────────────────

    fn float64_desc(
        encoding: &str,
        params: BTreeMap<String, ciborium::Value>,
    ) -> DataObjectDescriptor {
        DataObjectDescriptor {
            obj_type: "ntensor".to_string(),
            ndim: 1,
            shape: vec![1],
            strides: vec![1],
            dtype: Dtype::Float64,
            byte_order: ByteOrder::native(),
            encoding: encoding.to_string(),
            filter: "none".to_string(),
            compression: "none".to_string(),
            params,
            masks: None,
        }
    }

    #[test]
    fn resolve_encoding_simple_packing_rejects_non_float64() {
        // simple_packing requires float64; float32 must error.
        let mut desc = float64_desc("simple_packing", BTreeMap::new());
        desc.dtype = Dtype::Float32;
        let err = resolve_encoding(&desc, Dtype::Float32).unwrap_err();
        match err {
            TensogramError::Encoding(msg) => {
                assert!(msg.contains("simple_packing"), "msg: {msg}");
                assert!(msg.contains("float64"), "msg: {msg}");
            }
            other => panic!("expected Encoding error, got: {other:?}"),
        }
    }

    #[test]
    fn resolve_encoding_rejects_unknown_encoding() {
        let desc = float64_desc("totally_unknown", BTreeMap::new());
        let err = resolve_encoding(&desc, Dtype::Float64).unwrap_err();
        match err {
            TensogramError::Encoding(msg) => {
                assert!(msg.contains("unknown encoding"), "msg: {msg}");
                assert!(msg.contains("totally_unknown"), "msg: {msg}");
            }
            other => panic!("expected Encoding error, got: {other:?}"),
        }
    }

    // ── resolve_filter error paths ───────────────────────────────────

    #[test]
    fn resolve_filter_rejects_unknown_filter() {
        let mut desc = float64_desc("none", BTreeMap::new());
        desc.filter = "rot13".to_string();
        let err = resolve_filter(&desc).unwrap_err();
        match err {
            TensogramError::Encoding(msg) => {
                assert!(msg.contains("unknown filter"), "msg: {msg}");
                assert!(msg.contains("rot13"), "msg: {msg}");
            }
            other => panic!("expected Encoding error, got: {other:?}"),
        }
    }

    #[test]
    fn resolve_filter_shuffle_missing_element_size_rejected() {
        // shuffle requires shuffle_element_size; absence errors.
        let mut desc = float64_desc("none", BTreeMap::new());
        desc.filter = "shuffle".to_string();
        let err = resolve_filter(&desc).unwrap_err();
        assert!(matches!(err, TensogramError::Metadata(_)));
    }

    #[test]
    fn resolve_filter_shuffle_happy_path() {
        let mut params = BTreeMap::new();
        params.insert(
            "shuffle_element_size".to_string(),
            ciborium::Value::Integer(4i64.into()),
        );
        let mut desc = float64_desc("none", params);
        desc.filter = "shuffle".to_string();
        let f = resolve_filter(&desc).unwrap();
        assert!(matches!(f, FilterType::Shuffle { element_size: 4 }));
    }

    // ── resolve_compression error paths ──────────────────────────────

    #[test]
    fn resolve_compression_rejects_unknown_compression() {
        let mut desc = float64_desc("none", BTreeMap::new());
        desc.compression = "magic".to_string();
        let enc = EncodingType::None;
        let filt = FilterType::None;
        let err = resolve_compression(&desc, Dtype::Float64, &enc, &filt).unwrap_err();
        match err {
            TensogramError::Encoding(msg) => {
                assert!(msg.contains("unknown compression"), "msg: {msg}");
                assert!(msg.contains("magic"), "msg: {msg}");
            }
            other => panic!("expected Encoding error, got: {other:?}"),
        }
    }

    #[test]
    fn resolve_compression_rle_rejects_non_bitmask() {
        let mut desc = float64_desc("none", BTreeMap::new());
        desc.compression = "rle".to_string();
        let err = resolve_compression(
            &desc,
            Dtype::Float64,
            &EncodingType::None,
            &FilterType::None,
        )
        .unwrap_err();
        match err {
            TensogramError::Encoding(msg) => {
                assert!(msg.contains("rle"), "msg: {msg}");
                assert!(msg.contains("bitmask"), "msg: {msg}");
            }
            other => panic!("expected Encoding error, got: {other:?}"),
        }
    }

    #[test]
    fn resolve_compression_roaring_rejects_non_bitmask() {
        let mut desc = float64_desc("none", BTreeMap::new());
        desc.compression = "roaring".to_string();
        let err = resolve_compression(
            &desc,
            Dtype::Float64,
            &EncodingType::None,
            &FilterType::None,
        )
        .unwrap_err();
        match err {
            TensogramError::Encoding(msg) => {
                assert!(msg.contains("roaring"), "msg: {msg}");
                assert!(msg.contains("bitmask"), "msg: {msg}");
            }
            other => panic!("expected Encoding error, got: {other:?}"),
        }
    }

    #[cfg(any(feature = "szip", feature = "szip-pure"))]
    #[test]
    fn resolve_compression_szip_rsi_out_of_u32_range() {
        // szip_rsi beyond u32::MAX must error.
        let mut params = BTreeMap::new();
        params.insert(
            "szip_rsi".to_string(),
            ciborium::Value::Integer((u64::from(u32::MAX) + 1).into()),
        );
        params.insert(
            "szip_block_size".to_string(),
            ciborium::Value::Integer(32i64.into()),
        );
        params.insert(
            "szip_flags".to_string(),
            ciborium::Value::Integer(0i64.into()),
        );
        let mut desc = float64_desc("none", params);
        desc.compression = "szip".to_string();
        let err = resolve_compression(
            &desc,
            Dtype::Float64,
            &EncodingType::None,
            &FilterType::None,
        )
        .unwrap_err();
        match err {
            TensogramError::Metadata(msg) => assert!(msg.contains("szip_rsi"), "msg: {msg}"),
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[cfg(any(feature = "szip", feature = "szip-pure"))]
    #[test]
    fn resolve_compression_szip_block_size_out_of_u32_range() {
        let mut params = BTreeMap::new();
        params.insert(
            "szip_rsi".to_string(),
            ciborium::Value::Integer(128i64.into()),
        );
        params.insert(
            "szip_block_size".to_string(),
            ciborium::Value::Integer((u64::from(u32::MAX) + 1).into()),
        );
        params.insert(
            "szip_flags".to_string(),
            ciborium::Value::Integer(0i64.into()),
        );
        let mut desc = float64_desc("none", params);
        desc.compression = "szip".to_string();
        let err = resolve_compression(
            &desc,
            Dtype::Float64,
            &EncodingType::None,
            &FilterType::None,
        )
        .unwrap_err();
        match err {
            TensogramError::Metadata(msg) => assert!(msg.contains("szip_block_size"), "msg: {msg}"),
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[cfg(any(feature = "szip", feature = "szip-pure"))]
    #[test]
    fn resolve_compression_szip_flags_out_of_u32_range() {
        let mut params = BTreeMap::new();
        params.insert(
            "szip_rsi".to_string(),
            ciborium::Value::Integer(128i64.into()),
        );
        params.insert(
            "szip_block_size".to_string(),
            ciborium::Value::Integer(32i64.into()),
        );
        params.insert(
            "szip_flags".to_string(),
            ciborium::Value::Integer((u64::from(u32::MAX) + 1).into()),
        );
        let mut desc = float64_desc("none", params);
        desc.compression = "szip".to_string();
        let err = resolve_compression(
            &desc,
            Dtype::Float64,
            &EncodingType::None,
            &FilterType::None,
        )
        .unwrap_err();
        match err {
            TensogramError::Metadata(msg) => assert!(msg.contains("szip_flags"), "msg: {msg}"),
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[cfg(any(feature = "zstd", feature = "zstd-pure"))]
    #[test]
    fn resolve_compression_zstd_level_out_of_i32_range() {
        let mut params = BTreeMap::new();
        params.insert(
            "zstd_level".to_string(),
            ciborium::Value::Integer((i64::from(i32::MAX) + 1).into()),
        );
        let mut desc = float64_desc("none", params);
        desc.compression = "zstd".to_string();
        let err = resolve_compression(
            &desc,
            Dtype::Float64,
            &EncodingType::None,
            &FilterType::None,
        )
        .unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("zstd_level"), "msg: {msg}");
                assert!(msg.contains("i32"), "msg: {msg}");
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[cfg(feature = "blosc2")]
    #[test]
    fn resolve_compression_blosc2_clevel_out_of_i32_range() {
        let mut params = BTreeMap::new();
        params.insert(
            "blosc2_codec".to_string(),
            ciborium::Value::Text("lz4".to_string()),
        );
        params.insert(
            "blosc2_clevel".to_string(),
            ciborium::Value::Integer((i64::from(i32::MAX) + 1).into()),
        );
        let mut desc = float64_desc("none", params);
        desc.compression = "blosc2".to_string();
        let err = resolve_compression(
            &desc,
            Dtype::Float64,
            &EncodingType::None,
            &FilterType::None,
        )
        .unwrap_err();
        match err {
            TensogramError::Metadata(msg) => assert!(msg.contains("blosc2_clevel"), "msg: {msg}"),
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[cfg(feature = "blosc2")]
    #[test]
    fn resolve_compression_blosc2_unknown_codec_rejected() {
        let mut params = BTreeMap::new();
        params.insert(
            "blosc2_codec".to_string(),
            ciborium::Value::Text("snappy".to_string()),
        );
        let mut desc = float64_desc("none", params);
        desc.compression = "blosc2".to_string();
        let err = resolve_compression(
            &desc,
            Dtype::Float64,
            &EncodingType::None,
            &FilterType::None,
        )
        .unwrap_err();
        match err {
            TensogramError::Encoding(msg) => {
                assert!(msg.contains("unknown blosc2 codec"), "msg: {msg}");
                assert!(msg.contains("snappy"), "msg: {msg}");
            }
            other => panic!("expected Encoding error, got: {other:?}"),
        }
    }

    #[cfg(feature = "zfp")]
    #[test]
    fn resolve_compression_zfp_missing_mode_rejected() {
        let mut desc = float64_desc("none", BTreeMap::new());
        desc.compression = "zfp".to_string();
        let err = resolve_compression(
            &desc,
            Dtype::Float64,
            &EncodingType::None,
            &FilterType::None,
        )
        .unwrap_err();
        match err {
            TensogramError::Metadata(msg) => assert!(msg.contains("zfp_mode"), "msg: {msg}"),
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[cfg(feature = "zfp")]
    #[test]
    fn resolve_compression_zfp_precision_out_of_u32_range() {
        let mut params = BTreeMap::new();
        params.insert(
            "zfp_mode".to_string(),
            ciborium::Value::Text("fixed_precision".to_string()),
        );
        params.insert(
            "zfp_precision".to_string(),
            ciborium::Value::Integer((u64::from(u32::MAX) + 1).into()),
        );
        let mut desc = float64_desc("none", params);
        desc.compression = "zfp".to_string();
        let err = resolve_compression(
            &desc,
            Dtype::Float64,
            &EncodingType::None,
            &FilterType::None,
        )
        .unwrap_err();
        match err {
            TensogramError::Metadata(msg) => assert!(msg.contains("zfp_precision"), "msg: {msg}"),
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[cfg(feature = "zfp")]
    #[test]
    fn resolve_compression_zfp_unknown_mode_rejected() {
        let mut params = BTreeMap::new();
        params.insert(
            "zfp_mode".to_string(),
            ciborium::Value::Text("wobble".to_string()),
        );
        let mut desc = float64_desc("none", params);
        desc.compression = "zfp".to_string();
        let err = resolve_compression(
            &desc,
            Dtype::Float64,
            &EncodingType::None,
            &FilterType::None,
        )
        .unwrap_err();
        match err {
            TensogramError::Encoding(msg) => {
                assert!(msg.contains("unknown zfp_mode"), "msg: {msg}")
            }
            other => panic!("expected Encoding error, got: {other:?}"),
        }
    }

    #[cfg(feature = "sz3")]
    #[test]
    fn resolve_compression_sz3_missing_mode_rejected() {
        let mut desc = float64_desc("none", BTreeMap::new());
        desc.compression = "sz3".to_string();
        let err = resolve_compression(
            &desc,
            Dtype::Float64,
            &EncodingType::None,
            &FilterType::None,
        )
        .unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("sz3_error_bound_mode"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[cfg(feature = "sz3")]
    #[test]
    fn resolve_compression_sz3_unknown_mode_rejected() {
        let mut params = BTreeMap::new();
        params.insert(
            "sz3_error_bound_mode".to_string(),
            ciborium::Value::Text("bogus".to_string()),
        );
        params.insert("sz3_error_bound".to_string(), ciborium::Value::Float(1e-3));
        let mut desc = float64_desc("none", params);
        desc.compression = "sz3".to_string();
        let err = resolve_compression(
            &desc,
            Dtype::Float64,
            &EncodingType::None,
            &FilterType::None,
        )
        .unwrap_err();
        match err {
            TensogramError::Encoding(msg) => {
                assert!(msg.contains("unknown sz3_error_bound_mode"), "msg: {msg}")
            }
            other => panic!("expected Encoding error, got: {other:?}"),
        }
    }

    // ── extract_simple_packing_params error paths ────────────────────

    #[test]
    fn extract_simple_packing_params_rejects_nan_reference() {
        let mut params = BTreeMap::new();
        params.insert(
            "sp_reference_value".to_string(),
            ciborium::Value::Float(f64::NAN),
        );
        params.insert(
            "sp_binary_scale_factor".to_string(),
            ciborium::Value::Integer(0i64.into()),
        );
        params.insert(
            "sp_decimal_scale_factor".to_string(),
            ciborium::Value::Integer(0i64.into()),
        );
        params.insert(
            "sp_bits_per_value".to_string(),
            ciborium::Value::Integer(16i64.into()),
        );
        let err = extract_simple_packing_params(&params).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => assert!(msg.contains("finite"), "msg: {msg}"),
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn extract_simple_packing_params_rejects_decimal_scale_out_of_i32() {
        let mut params = BTreeMap::new();
        params.insert(
            "sp_reference_value".to_string(),
            ciborium::Value::Float(0.0),
        );
        params.insert(
            "sp_binary_scale_factor".to_string(),
            ciborium::Value::Integer(0i64.into()),
        );
        params.insert(
            "sp_decimal_scale_factor".to_string(),
            ciborium::Value::Integer((i64::from(i32::MAX) + 1).into()),
        );
        params.insert(
            "sp_bits_per_value".to_string(),
            ciborium::Value::Integer(16i64.into()),
        );
        let err = extract_simple_packing_params(&params).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("sp_decimal_scale_factor"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn extract_simple_packing_params_rejects_binary_scale_out_of_i32() {
        let mut params = BTreeMap::new();
        params.insert(
            "sp_reference_value".to_string(),
            ciborium::Value::Float(0.0),
        );
        params.insert(
            "sp_binary_scale_factor".to_string(),
            ciborium::Value::Integer((i64::from(i32::MAX) + 1).into()),
        );
        params.insert(
            "sp_decimal_scale_factor".to_string(),
            ciborium::Value::Integer(0i64.into()),
        );
        params.insert(
            "sp_bits_per_value".to_string(),
            ciborium::Value::Integer(16i64.into()),
        );
        let err = extract_simple_packing_params(&params).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("sp_binary_scale_factor"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn extract_simple_packing_params_rejects_bits_per_value_out_of_u32() {
        let mut params = BTreeMap::new();
        params.insert(
            "sp_reference_value".to_string(),
            ciborium::Value::Float(0.0),
        );
        params.insert(
            "sp_binary_scale_factor".to_string(),
            ciborium::Value::Integer(0i64.into()),
        );
        params.insert(
            "sp_decimal_scale_factor".to_string(),
            ciborium::Value::Integer(0i64.into()),
        );
        params.insert(
            "sp_bits_per_value".to_string(),
            ciborium::Value::Integer((u64::from(u32::MAX) + 1).into()),
        );
        let err = extract_simple_packing_params(&params).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("sp_bits_per_value"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    // ── resolve_simple_packing_params: auto-compute paths (1217-1267) ──

    #[test]
    fn resolve_simple_packing_params_noop_for_non_simple_packing() {
        let mut desc = float64_desc("none", BTreeMap::new());
        resolve_simple_packing_params(&mut desc, &[0u8; 8]).unwrap();
        // No params added for encoding=none.
        assert!(desc.params.is_empty());
    }

    #[test]
    fn resolve_simple_packing_params_rejects_decimal_scale_out_of_i32() {
        // Only sp_bits_per_value set (no ref/bsf), forcing the
        // auto-compute path; bad decimal scale triggers i32 error.
        let mut params = BTreeMap::new();
        params.insert(
            "sp_bits_per_value".to_string(),
            ciborium::Value::Integer(16i64.into()),
        );
        params.insert(
            "sp_decimal_scale_factor".to_string(),
            ciborium::Value::Integer((i64::from(i32::MAX) + 1).into()),
        );
        let mut desc = float64_desc("simple_packing", params);
        let data: Vec<u8> = (0..4).flat_map(|i| (i as f64).to_le_bytes()).collect();
        let err = resolve_simple_packing_params(&mut desc, &data).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("sp_decimal_scale_factor"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn resolve_simple_packing_params_auto_computes_and_stamps_four_keys() {
        let mut params = BTreeMap::new();
        params.insert(
            "sp_bits_per_value".to_string(),
            ciborium::Value::Integer(16i64.into()),
        );
        let mut desc = float64_desc("simple_packing", params);
        let data: Vec<u8> = (0..8).flat_map(|i| (i as f64).to_le_bytes()).collect();
        resolve_simple_packing_params(&mut desc, &data).unwrap();
        assert!(desc.params.contains_key("sp_reference_value"));
        assert!(desc.params.contains_key("sp_binary_scale_factor"));
        assert!(desc.params.contains_key("sp_decimal_scale_factor"));
        assert!(desc.params.contains_key("sp_bits_per_value"));
    }

    #[test]
    fn resolve_simple_packing_params_explicit_pair_defaults_decimal() {
        // Both ref + bsf present: skip auto-compute, default decimal.
        let mut params = BTreeMap::new();
        params.insert(
            "sp_reference_value".to_string(),
            ciborium::Value::Float(0.0),
        );
        params.insert(
            "sp_binary_scale_factor".to_string(),
            ciborium::Value::Integer(0i64.into()),
        );
        params.insert(
            "sp_bits_per_value".to_string(),
            ciborium::Value::Integer(16i64.into()),
        );
        let mut desc = float64_desc("simple_packing", params);
        resolve_simple_packing_params(&mut desc, &[0u8; 8]).unwrap();
        assert_eq!(
            desc.params.get("sp_decimal_scale_factor"),
            Some(&ciborium::Value::Integer(0i64.into()))
        );
    }

    #[test]
    fn resolve_simple_packing_params_partial_pair_rejected() {
        // Only ref set, bsf missing — must error (provide both or neither).
        let mut params = BTreeMap::new();
        params.insert(
            "sp_reference_value".to_string(),
            ciborium::Value::Float(0.0),
        );
        params.insert(
            "sp_bits_per_value".to_string(),
            ciborium::Value::Integer(16i64.into()),
        );
        let mut desc = float64_desc("simple_packing", params);
        let err = resolve_simple_packing_params(&mut desc, &[0u8; 8]).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("simple_packing"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    // ── bytes_as_f64_vec error path ──────────────────────────────────

    #[test]
    fn bytes_as_f64_vec_rejects_non_multiple_of_8() {
        let err = bytes_as_f64_vec(&[0u8; 7], ByteOrder::Little).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("multiple of 8"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn bytes_as_f64_vec_big_endian_roundtrip() {
        let v = bytes_as_f64_vec(&1.5f64.to_be_bytes(), ByteOrder::Big).unwrap();
        assert_eq!(v, vec![1.5]);
    }

    // ── get_*_param error branches (1311-1313, 1322-1331, 1355-1356) ──

    #[test]
    fn get_f64_param_rejects_wrong_type() {
        let mut params = BTreeMap::new();
        params.insert("tol".to_string(), ciborium::Value::Text("x".to_string()));
        let err = get_f64_param(&params, "tol").unwrap_err();
        match err {
            TensogramError::Metadata(msg) => assert!(msg.contains("expected number"), "msg: {msg}"),
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn get_f64_param_missing_key_rejected() {
        let params = BTreeMap::new();
        let err = get_f64_param(&params, "tol").unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("missing required parameter"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn get_i64_param_rejects_wrong_type() {
        let mut params = BTreeMap::new();
        params.insert("n".to_string(), ciborium::Value::Float(1.5));
        let err = get_i64_param(&params, "n").unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("expected integer"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn get_i64_param_missing_key_rejected() {
        let params = BTreeMap::new();
        let err = get_i64_param(&params, "n").unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("missing required parameter"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn get_i64_param_or_default_rejects_out_of_i64_range() {
        // An integer beyond i64::MAX (representable in CBOR as a large
        // unsigned) must error in the present-Integer branch.
        let mut params = BTreeMap::new();
        params.insert("n".to_string(), ciborium::Value::Integer((u64::MAX).into()));
        let err = get_i64_param_or_default(&params, "n", 0).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("out of i64 range"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn get_i64_param_rejects_out_of_i64_range() {
        let mut params = BTreeMap::new();
        params.insert("n".to_string(), ciborium::Value::Integer((u64::MAX).into()));
        let err = get_i64_param(&params, "n").unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("out of i64 range"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn get_u64_param_rejects_negative() {
        let mut params = BTreeMap::new();
        params.insert("n".to_string(), ciborium::Value::Integer((-1i64).into()));
        let err = get_u64_param(&params, "n").unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("out of u64 range"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn get_u64_param_rejects_wrong_type() {
        let mut params = BTreeMap::new();
        params.insert("n".to_string(), ciborium::Value::Float(1.0));
        let err = get_u64_param(&params, "n").unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("expected integer"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn get_u64_param_missing_key_rejected() {
        let params = BTreeMap::new();
        let err = get_u64_param(&params, "n").unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("missing required parameter"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    // ── validate_szip_block_offsets: empty + range errors (1431-1457) ──

    #[test]
    fn validate_szip_block_offsets_empty_rejected() {
        let mut params = BTreeMap::new();
        params.insert(
            "szip_block_offsets".to_string(),
            ciborium::Value::Array(vec![]),
        );
        let err = validate_szip_block_offsets(&params, 100).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("must not be empty"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn validate_szip_block_offsets_negative_element_rejected() {
        let mut params = BTreeMap::new();
        params.insert(
            "szip_block_offsets".to_string(),
            ciborium::Value::Array(vec![ciborium::Value::Integer((-1i64).into())]),
        );
        let err = validate_szip_block_offsets(&params, 100).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("out of u64 range"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    // ── compose_payload_region: mask composition ─────────────────────

    #[test]
    fn compose_payload_region_empty_masks_is_passthrough() {
        let payload = vec![1u8, 2, 3, 4];
        let (region, meta) = compose_payload_region(
            payload.clone(),
            MaskSet::empty(0),
            &MaskMethod::Roaring,
            &MaskMethod::Roaring,
            &MaskMethod::Roaring,
            128,
        )
        .unwrap();
        assert_eq!(region, payload);
        assert!(meta.is_none());
    }

    #[test]
    fn encode_nan_without_allow_nan_is_hard_error() {
        // A NaN float32 input without allow_nan must be a hard error
        // (covers the substitute-and-mask reject path).
        let desc = make_descriptor(vec![2]);
        let mut data = Vec::new();
        data.extend_from_slice(&f32::NAN.to_le_bytes());
        data.extend_from_slice(&1.0f32.to_le_bytes());
        let options = EncodeOptions {
            hashing: false,
            allow_nan: false,
            allow_inf: false,
            ..Default::default()
        };
        let err = encode(&meta_default(), &[(&desc, data.as_slice())], &options);
        assert!(err.is_err(), "NaN without allow_nan must error");
    }

    #[test]
    fn encode_inf_without_allow_inf_is_hard_error() {
        let desc = make_descriptor(vec![2]);
        let mut data = Vec::new();
        data.extend_from_slice(&f32::INFINITY.to_le_bytes());
        data.extend_from_slice(&1.0f32.to_le_bytes());
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        let err = encode(&meta_default(), &[(&desc, data.as_slice())], &options);
        assert!(err.is_err(), "Inf without allow_inf must error");
    }

    #[test]
    fn encode_nan_with_allow_nan_produces_mask_and_roundtrips() {
        // allow_nan substitutes NaN with 0.0 and records a mask; the
        // composed payload region must round-trip through decode.
        // Use a large array so the mask exceeds the small-mask
        // threshold and the requested method is honoured.
        let desc = make_descriptor(vec![2048]);
        let mut data = Vec::with_capacity(2048 * 4);
        for i in 0..2048u32 {
            if i % 3 == 0 {
                data.extend_from_slice(&f32::NAN.to_le_bytes());
            } else {
                data.extend_from_slice(&(i as f32).to_le_bytes());
            }
        }
        let options = EncodeOptions {
            hashing: false,
            allow_nan: true,
            small_mask_threshold_bytes: 0,
            ..Default::default()
        };
        let msg = encode(&meta_default(), &[(&desc, data.as_slice())], &options).unwrap();
        let (_, objects) = decode(&msg, &DecodeOptions::default()).unwrap();
        assert_eq!(objects.len(), 1);
        let (decoded_desc, _) = &objects[0];
        assert!(
            decoded_desc.masks.is_some(),
            "decoded descriptor should carry a NaN mask"
        );
    }

    fn meta_default() -> GlobalMetadata {
        GlobalMetadata::default()
    }

    // ── encode_one_mask: per-method coverage ─────────────────────────

    #[test]
    fn encode_one_mask_none_method_packs_raw() {
        // A small mask with threshold > size falls back to None.
        let bits = vec![true, false, true, false];
        let (blob, used) = encode_one_mask(&bits, MaskMethod::Roaring, 128).unwrap();
        assert!(matches!(used, MaskMethod::None));
        assert!(!blob.is_empty());
    }

    #[test]
    fn encode_one_mask_rle_method() {
        // Large mask, threshold 0 disables fallback — RLE honoured.
        let bits = vec![true; 2048];
        let (blob, used) = encode_one_mask(&bits, MaskMethod::Rle, 0).unwrap();
        assert!(matches!(used, MaskMethod::Rle));
        assert!(!blob.is_empty());
    }

    #[test]
    fn encode_one_mask_roaring_method() {
        let mut bits = vec![false; 2048];
        bits[5] = true;
        bits[1000] = true;
        let (blob, used) = encode_one_mask(&bits, MaskMethod::Roaring, 0).unwrap();
        assert!(matches!(used, MaskMethod::Roaring));
        assert!(!blob.is_empty());
    }

    #[cfg(feature = "lz4")]
    #[test]
    fn encode_one_mask_lz4_method() {
        let bits = vec![true; 2048];
        let (blob, used) = encode_one_mask(&bits, MaskMethod::Lz4, 0).unwrap();
        assert!(matches!(used, MaskMethod::Lz4));
        assert!(!blob.is_empty());
    }

    #[test]
    fn encode_one_mask_zstd_method() {
        let bits = vec![true; 2048];
        let (blob, used) = encode_one_mask(&bits, MaskMethod::Zstd { level: Some(3) }, 0).unwrap();
        assert!(matches!(used, MaskMethod::Zstd { .. }));
        assert!(!blob.is_empty());
    }

    #[cfg(feature = "blosc2")]
    #[test]
    fn encode_one_mask_blosc2_method() {
        use tensogram_encodings::pipeline::Blosc2Codec;
        let bits = vec![true; 2048];
        let (blob, used) = encode_one_mask(
            &bits,
            MaskMethod::Blosc2 {
                codec: Blosc2Codec::Lz4,
                level: 5,
            },
            0,
        )
        .unwrap();
        assert!(matches!(used, MaskMethod::Blosc2 { .. }));
        assert!(!blob.is_empty());
    }

    // ── mask_params_cbor: all method shapes ──────────────────────────

    #[test]
    fn mask_params_cbor_paramless_methods_empty() {
        for m in [
            MaskMethod::None,
            MaskMethod::Rle,
            MaskMethod::Roaring,
            MaskMethod::Lz4,
        ] {
            assert!(
                mask_params_cbor(&m).is_empty(),
                "method {m:?} must be paramless"
            );
        }
    }

    #[test]
    fn mask_params_cbor_zstd_with_level() {
        let params = mask_params_cbor(&MaskMethod::Zstd { level: Some(7) });
        assert_eq!(
            params.get("level"),
            Some(&ciborium::Value::Integer(7i64.into()))
        );
    }

    #[test]
    fn mask_params_cbor_zstd_without_level_empty() {
        let params = mask_params_cbor(&MaskMethod::Zstd { level: None });
        assert!(params.is_empty());
    }

    #[cfg(feature = "blosc2")]
    #[test]
    fn mask_params_cbor_blosc2_all_codecs() {
        use tensogram_encodings::pipeline::Blosc2Codec;
        let codecs = [
            (Blosc2Codec::Blosclz, "blosclz"),
            (Blosc2Codec::Lz4, "lz4"),
            (Blosc2Codec::Lz4hc, "lz4hc"),
            (Blosc2Codec::Zlib, "zlib"),
            (Blosc2Codec::Zstd, "zstd"),
        ];
        for (codec, name) in codecs {
            let params = mask_params_cbor(&MaskMethod::Blosc2 { codec, level: 4 });
            assert_eq!(
                params.get("codec"),
                Some(&ciborium::Value::Text(name.to_string()))
            );
            assert_eq!(
                params.get("level"),
                Some(&ciborium::Value::Integer(4i64.into()))
            );
        }
    }

    // ── compose_payload_region with explicit non-default methods ─────

    #[test]
    fn compose_payload_region_all_three_masks_with_distinct_methods() {
        // Exercises append_one across nan/pos_inf/neg_inf and records
        // distinct descriptors at increasing offsets.
        let mk = |seed: usize| -> Vec<bool> {
            (0..2048).map(|i| (i + seed).is_multiple_of(7)).collect()
        };
        let masks = MaskSet {
            nan: Some(mk(0)),
            pos_inf: Some(mk(1)),
            neg_inf: Some(mk(2)),
            n_elements: 2048,
        };
        let payload = vec![0xAAu8; 64];
        let (region, meta) = compose_payload_region(
            payload.clone(),
            masks,
            &MaskMethod::Roaring,
            &MaskMethod::Rle,
            &MaskMethod::Zstd { level: Some(1) },
            0,
        )
        .unwrap();
        let meta = meta.expect("masks present");
        assert!(region.len() > payload.len());
        let nan = meta.nan.expect("nan");
        let pos = meta.pos_inf.expect("pos_inf");
        let neg = meta.neg_inf.expect("neg_inf");
        assert_eq!(nan.method, "roaring");
        assert_eq!(pos.method, "rle");
        assert_eq!(neg.method, "zstd");
        // Offsets strictly increase, starting at the payload end.
        assert_eq!(nan.offset, payload.len() as u64);
        assert!(pos.offset > nan.offset);
        assert!(neg.offset > pos.offset);
    }

    // ── validate_object basic error branches (238-267) ───────────────

    #[test]
    fn validate_object_rejects_empty_obj_type() {
        let mut desc = make_descriptor(vec![2]);
        desc.obj_type = String::new();
        let err = validate_object(&desc, 8).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => assert!(msg.contains("obj_type"), "msg: {msg}"),
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn validate_object_rejects_ndim_shape_mismatch() {
        let mut desc = make_descriptor(vec![2, 3]);
        desc.ndim = 3; // shape.len() is 2
        let err = validate_object(&desc, 24).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => assert!(msg.contains("ndim"), "msg: {msg}"),
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn validate_object_rejects_strides_shape_mismatch() {
        let mut desc = make_descriptor(vec![2, 3]);
        desc.strides = vec![1]; // wrong length
        let err = validate_object(&desc, 24).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => assert!(msg.contains("strides.len()"), "msg: {msg}"),
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn validate_object_rejects_data_len_mismatch() {
        // float32 shape [4] => 16 bytes expected; supply 8.
        let desc = make_descriptor(vec![4]);
        let err = validate_object(&desc, 8).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("does not match expected"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    // ── resolve_simple_packing_params: dtype + missing-bits (1153/1166) ──

    #[test]
    fn resolve_simple_packing_params_rejects_non_float64_dtype() {
        let mut params = BTreeMap::new();
        params.insert(
            "sp_bits_per_value".to_string(),
            ciborium::Value::Integer(16i64.into()),
        );
        let mut desc = float64_desc("simple_packing", params);
        desc.dtype = Dtype::Float32;
        let err = resolve_simple_packing_params(&mut desc, &[0u8; 4]).unwrap_err();
        match err {
            TensogramError::Encoding(msg) => {
                assert!(
                    msg.contains("simple_packing only supports float64"),
                    "msg: {msg}"
                )
            }
            other => panic!("expected Encoding error, got: {other:?}"),
        }
    }

    #[test]
    fn resolve_simple_packing_params_rejects_missing_bits_per_value() {
        // simple_packing with no sp_bits_per_value at all must error.
        let desc_params = BTreeMap::new();
        let mut desc = float64_desc("simple_packing", desc_params);
        let err = resolve_simple_packing_params(&mut desc, &[0u8; 8]).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("sp_bits_per_value"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn resolve_simple_packing_params_rejects_non_finite_data() {
        // Auto-compute path with a NaN in the data: compute_params
        // surfaces a PackingError.
        let mut params = BTreeMap::new();
        params.insert(
            "sp_bits_per_value".to_string(),
            ciborium::Value::Integer(16i64.into()),
        );
        let mut desc = float64_desc("simple_packing", params);
        let mut data = Vec::new();
        data.extend_from_slice(&f64::NAN.to_le_bytes());
        data.extend_from_slice(&1.0f64.to_le_bytes());
        let err = resolve_simple_packing_params(&mut desc, &data).unwrap_err();
        assert!(matches!(err, TensogramError::Encoding(_)));
    }

    // ── End-to-end rle / roaring on bitmask dtype (1031-1042) ────────

    fn bitmask_desc(compression: &str, n_bits: u64) -> DataObjectDescriptor {
        DataObjectDescriptor {
            obj_type: "ntensor".to_string(),
            ndim: 1,
            shape: vec![n_bits],
            strides: vec![1],
            dtype: Dtype::Bitmask,
            byte_order: ByteOrder::native(),
            encoding: "none".to_string(),
            filter: "none".to_string(),
            compression: compression.to_string(),
            params: BTreeMap::new(),
            masks: None,
        }
    }

    #[test]
    fn encode_bitmask_rle_round_trips() {
        let desc = bitmask_desc("rle", 64);
        // 64 bits => 8 bytes, all set.
        let data = vec![0xFFu8; 8];
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        let msg = encode(&meta_default(), &[(&desc, data.as_slice())], &options).unwrap();
        let (_, objects) = decode(&msg, &DecodeOptions::default()).unwrap();
        assert_eq!(objects[0].1, data);
    }

    #[test]
    fn encode_bitmask_roaring_round_trips() {
        let desc = bitmask_desc("roaring", 64);
        let mut data = vec![0u8; 8];
        data[0] = 0b1010_1010;
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        let msg = encode(&meta_default(), &[(&desc, data.as_slice())], &options).unwrap();
        let (_, objects) = decode(&msg, &DecodeOptions::default()).unwrap();
        assert_eq!(objects[0].1, data);
    }

    // ── Codec bits_per_sample / typesize combos via end-to-end ───────

    #[cfg(any(feature = "szip", feature = "szip-pure"))]
    #[test]
    fn encode_szip_with_shuffle_filter_round_trips() {
        // Exercises the (None, Shuffle) bits_per_sample = 8 branch (904).
        let mut params = BTreeMap::new();
        params.insert(
            "shuffle_element_size".to_string(),
            ciborium::Value::Integer(4i64.into()),
        );
        params.insert(
            "szip_rsi".to_string(),
            ciborium::Value::Integer(128i64.into()),
        );
        params.insert(
            "szip_block_size".to_string(),
            ciborium::Value::Integer(32i64.into()),
        );
        params.insert(
            "szip_flags".to_string(),
            ciborium::Value::Integer(0i64.into()),
        );
        let desc = DataObjectDescriptor {
            obj_type: "ntensor".to_string(),
            ndim: 1,
            shape: vec![256],
            strides: vec![1],
            dtype: Dtype::Float32,
            byte_order: ByteOrder::native(),
            encoding: "none".to_string(),
            filter: "shuffle".to_string(),
            compression: "szip".to_string(),
            params,
            masks: None,
        };
        let data: Vec<u8> = (0..256u32).flat_map(|i| (i as f32).to_le_bytes()).collect();
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        let msg = encode(&meta_default(), &[(&desc, data.as_slice())], &options).unwrap();
        let (_, objects) = decode(&msg, &DecodeOptions::default()).unwrap();
        assert_eq!(objects[0].1, data);
    }

    #[cfg(feature = "blosc2")]
    #[test]
    fn encode_blosc2_with_shuffle_filter_round_trips() {
        // Exercises the blosc2 (None, Shuffle) typesize = 1 branch (958).
        let mut params = BTreeMap::new();
        params.insert(
            "shuffle_element_size".to_string(),
            ciborium::Value::Integer(4i64.into()),
        );
        params.insert(
            "blosc2_codec".to_string(),
            ciborium::Value::Text("lz4".to_string()),
        );
        let desc = DataObjectDescriptor {
            obj_type: "ntensor".to_string(),
            ndim: 1,
            shape: vec![256],
            strides: vec![1],
            dtype: Dtype::Float32,
            byte_order: ByteOrder::native(),
            encoding: "none".to_string(),
            filter: "shuffle".to_string(),
            compression: "blosc2".to_string(),
            params,
            masks: None,
        };
        let data: Vec<u8> = (0..256u32).flat_map(|i| (i as f32).to_le_bytes()).collect();
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        let msg = encode(&meta_default(), &[(&desc, data.as_slice())], &options).unwrap();
        let (_, objects) = decode(&msg, &DecodeOptions::default()).unwrap();
        assert_eq!(objects[0].1, data);
    }

    // ── resolve_compression: bits_per_sample / typesize match arms ───

    #[cfg(any(feature = "szip", feature = "szip-pure"))]
    #[test]
    fn resolve_compression_szip_none_none_uses_dtype_bit_width() {
        // (EncodingType::None, FilterType::None) bits_per_sample arm (905).
        let mut params = BTreeMap::new();
        params.insert(
            "szip_rsi".to_string(),
            ciborium::Value::Integer(128i64.into()),
        );
        params.insert(
            "szip_block_size".to_string(),
            ciborium::Value::Integer(32i64.into()),
        );
        params.insert(
            "szip_flags".to_string(),
            ciborium::Value::Integer(0i64.into()),
        );
        let mut desc = float64_desc("none", params);
        desc.compression = "szip".to_string();
        let c = resolve_compression(
            &desc,
            Dtype::Float64,
            &EncodingType::None,
            &FilterType::None,
        )
        .unwrap();
        match c {
            CompressionType::Szip {
                bits_per_sample, ..
            } => {
                assert_eq!(bits_per_sample, 64); // float64 = 8 bytes * 8
            }
            other => panic!("expected Szip, got: {other:?}"),
        }
    }

    #[cfg(any(feature = "szip", feature = "szip-pure"))]
    #[test]
    fn resolve_compression_szip_simple_packing_uses_pack_bits() {
        // (EncodingType::SimplePacking, _) bits_per_sample arm (903).
        use tensogram_encodings::simple_packing::SimplePackingParams;
        let mut params = BTreeMap::new();
        params.insert(
            "szip_rsi".to_string(),
            ciborium::Value::Integer(128i64.into()),
        );
        params.insert(
            "szip_block_size".to_string(),
            ciborium::Value::Integer(32i64.into()),
        );
        params.insert(
            "szip_flags".to_string(),
            ciborium::Value::Integer(0i64.into()),
        );
        let mut desc = float64_desc("none", params);
        desc.compression = "szip".to_string();
        let enc = EncodingType::SimplePacking(SimplePackingParams {
            reference_value: 0.0,
            binary_scale_factor: 0,
            decimal_scale_factor: 0,
            bits_per_value: 12,
        });
        let c = resolve_compression(&desc, Dtype::Float64, &enc, &FilterType::None).unwrap();
        match c {
            CompressionType::Szip {
                bits_per_sample, ..
            } => assert_eq!(bits_per_sample, 12),
            other => panic!("expected Szip, got: {other:?}"),
        }
    }

    #[cfg(feature = "blosc2")]
    #[test]
    fn resolve_compression_blosc2_simple_packing_typesize_rounds_up() {
        // (EncodingType::SimplePacking, _) typesize arm (955-956): 12 bits => 2 bytes.
        use tensogram_encodings::simple_packing::SimplePackingParams;
        let mut params = BTreeMap::new();
        params.insert(
            "blosc2_codec".to_string(),
            ciborium::Value::Text("lz4".to_string()),
        );
        let mut desc = float64_desc("none", params);
        desc.compression = "blosc2".to_string();
        let enc = EncodingType::SimplePacking(SimplePackingParams {
            reference_value: 0.0,
            binary_scale_factor: 0,
            decimal_scale_factor: 0,
            bits_per_value: 12,
        });
        let c = resolve_compression(&desc, Dtype::Float64, &enc, &FilterType::None).unwrap();
        match c {
            CompressionType::Blosc2 { typesize, .. } => assert_eq!(typesize, 2),
            other => panic!("expected Blosc2, got: {other:?}"),
        }
    }

    #[cfg(feature = "zfp")]
    #[test]
    fn resolve_compression_zfp_fixed_rate_and_accuracy() {
        // fixed_rate (979) and fixed_accuracy (990-991) arms.
        for (mode, key) in [
            ("fixed_rate", "zfp_rate"),
            ("fixed_accuracy", "zfp_tolerance"),
        ] {
            let mut params = BTreeMap::new();
            params.insert(
                "zfp_mode".to_string(),
                ciborium::Value::Text(mode.to_string()),
            );
            params.insert(key.to_string(), ciborium::Value::Float(8.0));
            let mut desc = float64_desc("none", params);
            desc.compression = "zfp".to_string();
            let c = resolve_compression(
                &desc,
                Dtype::Float64,
                &EncodingType::None,
                &FilterType::None,
            )
            .unwrap();
            assert!(matches!(c, CompressionType::Zfp { .. }), "mode {mode}");
        }
    }

    // ── encode_pre_encoded szip block-offset validation ──────────────

    #[cfg(any(feature = "szip", feature = "szip-pure"))]
    #[test]
    fn encode_pre_encoded_szip_validates_block_offsets() {
        // PreEncoded mode with szip compression + szip_block_offsets
        // exercises the validate_szip_block_offsets call.
        let mut params = BTreeMap::new();
        params.insert(
            "szip_rsi".to_string(),
            ciborium::Value::Integer(128i64.into()),
        );
        params.insert(
            "szip_block_size".to_string(),
            ciborium::Value::Integer(32i64.into()),
        );
        params.insert(
            "szip_flags".to_string(),
            ciborium::Value::Integer(0i64.into()),
        );
        params.insert(
            "szip_block_offsets".to_string(),
            ciborium::Value::Array(vec![ciborium::Value::Integer(0i64.into())]),
        );
        let desc = DataObjectDescriptor {
            obj_type: "ntensor".to_string(),
            ndim: 1,
            shape: vec![4],
            strides: vec![1],
            dtype: Dtype::Float32,
            byte_order: ByteOrder::native(),
            encoding: "none".to_string(),
            filter: "none".to_string(),
            compression: "szip".to_string(),
            params,
            masks: None,
        };
        let data = vec![0u8; 16];
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        // The opaque pre-encoded bytes are passed through; offset 0 is
        // valid against the 16-byte (128-bit) bound.
        let msg =
            encode_pre_encoded(&meta_default(), &[(&desc, data.as_slice())], &options).unwrap();
        assert!(!msg.is_empty());
    }

    #[cfg(any(feature = "szip", feature = "szip-pure"))]
    #[test]
    fn encode_pre_encoded_szip_rejects_offset_beyond_bound() {
        let mut params = BTreeMap::new();
        params.insert(
            "szip_rsi".to_string(),
            ciborium::Value::Integer(128i64.into()),
        );
        params.insert(
            "szip_block_size".to_string(),
            ciborium::Value::Integer(32i64.into()),
        );
        params.insert(
            "szip_flags".to_string(),
            ciborium::Value::Integer(0i64.into()),
        );
        // bit-bound for 16 bytes is 128; an offset of 9999 is out of range.
        params.insert(
            "szip_block_offsets".to_string(),
            ciborium::Value::Array(vec![
                ciborium::Value::Integer(0i64.into()),
                ciborium::Value::Integer(9999i64.into()),
            ]),
        );
        let desc = DataObjectDescriptor {
            obj_type: "ntensor".to_string(),
            ndim: 1,
            shape: vec![4],
            strides: vec![1],
            dtype: Dtype::Float32,
            byte_order: ByteOrder::native(),
            encoding: "none".to_string(),
            filter: "none".to_string(),
            compression: "szip".to_string(),
            params,
            masks: None,
        };
        let data = vec![0u8; 16];
        let options = EncodeOptions {
            hashing: false,
            ..Default::default()
        };
        let err =
            encode_pre_encoded(&meta_default(), &[(&desc, data.as_slice())], &options).unwrap_err();
        assert!(matches!(err, TensogramError::Metadata(_)));
    }
}