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
// (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::error::{Result, TensogramError};
use crate::types::{DataObjectDescriptor, GlobalMetadata, HashFrame, IndexFrame};

/// Key reserved for library-managed metadata (ndim/shape/strides/dtype/provenance).
pub const RESERVED_KEY: &str = "_reserved_";

/// Serialize global metadata to deterministic CBOR bytes (RFC 8949 Section 4.2).
pub fn global_metadata_to_cbor(metadata: &GlobalMetadata) -> Result<Vec<u8>> {
    let mut value: ciborium::Value = ciborium::Value::serialized(metadata)
        .map_err(|e| TensogramError::Metadata(format!("failed to serialize metadata: {e}")))?;
    canonicalize(&mut value)?;
    value_to_bytes(&value)
}

/// Deserialize global metadata from CBOR bytes.
///
/// The CBOR metadata frame is free-form: only `base`, `_reserved_`, and
/// `_extra_` are named sections the library interprets.  Any other
/// top-level **text** key (including a stray legacy `"version"` key
/// emitted by pre-0.17 encoders) is routed into `_extra_` for
/// forward-compatibility.  The wire-format version lives exclusively
/// in the preamble (see [`crate::wire::WIRE_VERSION`]).
///
/// # Strict-input rules
///
/// - **Non-text top-level keys are rejected.**  Canonical CBOR uses
///   text keys for our schema (RFC 8949 §4.2 + `plans/WIRE_FORMAT.md`).
///   A malformed producer emitting integer / bytes / map keys at the
///   top level surfaces as `MetadataError` rather than being silently
///   dropped — silent drop would lose round-trip fidelity without
///   informing the caller.
/// - **Collisions between explicit `_extra_` and free-form top-level
///   keys are rejected.**  Both `{"_extra_": {"version": 1}, "version": 99}`
///   forms convey the same intent ambiguously; the producer must
///   choose one.  Earlier versions silently preferred the explicit
///   `_extra_` entry, which made the surprise discoverable only by
///   reading the source.
pub fn cbor_to_global_metadata(cbor_bytes: &[u8]) -> Result<GlobalMetadata> {
    let value: ciborium::Value = ciborium::from_reader(cbor_bytes)
        .map_err(|e| TensogramError::Metadata(format!("failed to parse CBOR: {e}")))?;

    let map = match value {
        ciborium::Value::Map(m) => m,
        _ => {
            return Err(TensogramError::Metadata(
                "global metadata CBOR is not a map".to_string(),
            ));
        }
    };

    let mut meta = GlobalMetadata::default();
    // Accumulate free-form top-level entries in a separate bucket so
    // the explicit `_extra_` section (processed once below) can be
    // checked for collisions before merge.
    let mut free_form: BTreeMap<String, ciborium::Value> = BTreeMap::new();

    for (k, v) in map {
        let key = match k {
            ciborium::Value::Text(s) => s,
            other => {
                return Err(TensogramError::Metadata(format!(
                    "global metadata CBOR has non-text top-level key {}; \
                     canonical CBOR uses text keys for the tensogram schema \
                     (RFC 8949 §4.2 + WIRE_FORMAT.md). \
                     Re-encode through a canonical CBOR producer.",
                    cbor_kind_label(&other),
                )));
            }
        };

        match key.as_str() {
            "base" => {
                let entries: Vec<BTreeMap<String, ciborium::Value>> =
                    v.deserialized().map_err(|e| {
                        TensogramError::Metadata(format!("failed to deserialize base: {e}"))
                    })?;
                meta.base = entries;
            }
            "_reserved_" => {
                let entries: BTreeMap<String, ciborium::Value> = v.deserialized().map_err(|e| {
                    TensogramError::Metadata(format!("failed to deserialize _reserved_: {e}"))
                })?;
                meta.reserved = entries;
            }
            "_extra_" => {
                let entries: BTreeMap<String, ciborium::Value> = v.deserialized().map_err(|e| {
                    TensogramError::Metadata(format!("failed to deserialize _extra_: {e}"))
                })?;
                meta.extra = entries;
            }
            // Anything else (including a stray legacy `"version"` key)
            // flows into `_extra_` via the free-form bucket.
            _ => {
                free_form.insert(key, v);
            }
        }
    }

    // Strict collision check: a key cannot appear both as a top-level
    // free-form entry AND inside `_extra_`.  Earlier versions silently
    // preferred the explicit entry; the new rule rejects ambiguity.
    for k in free_form.keys() {
        if meta.extra.contains_key(k) {
            return Err(TensogramError::Metadata(format!(
                "ambiguous metadata: key {k:?} appears both at the top \
                 level and inside `_extra_`. Producers must pick one \
                 placement; the wire format does not allow both."
            )));
        }
    }

    // No collisions — promote every free-form key into `_extra_`.
    for (k, v) in free_form {
        meta.extra.insert(k, v);
    }

    Ok(meta)
}

/// Human-readable label for a non-text CBOR top-level key, used in
/// the strict-input error message above.  Trims to a short tag so
/// the error stays readable even when the key is a long byte array.
fn cbor_kind_label(value: &ciborium::Value) -> &'static str {
    use ciborium::Value;
    match value {
        Value::Integer(_) => "(integer key)",
        Value::Bytes(_) => "(byte-string key)",
        Value::Float(_) => "(float key)",
        Value::Bool(_) => "(boolean key)",
        Value::Null => "(null key)",
        Value::Tag(_, _) => "(tagged key)",
        Value::Array(_) => "(array key)",
        Value::Map(_) => "(map key)",
        Value::Text(_) => "(text key)",
        _ => "(unknown CBOR key kind)",
    }
}

/// Human-readable label for a CBOR value's kind, suitable for
/// "expected X, got Y" diagnostics.  Friendlier than the raw
/// `Debug` impl on `ciborium::Value` (which produces verbose
/// `Integer(42)` / `Text("foo")` strings) — this returns short
/// tags like `"integer"`, `"text"`, `"array"`.
///
/// Used by encoder param accessors that reject wrong-type CBOR
/// values: see [`crate::encode::get_i64_param`] and friends.
pub(crate) fn cbor_value_kind(value: &ciborium::Value) -> &'static str {
    use ciborium::Value;
    match value {
        Value::Integer(_) => "integer",
        Value::Bytes(_) => "byte-string",
        Value::Float(_) => "float",
        Value::Bool(_) => "boolean",
        Value::Null => "null",
        Value::Tag(_, _) => "tagged value",
        Value::Array(_) => "array",
        Value::Map(_) => "map",
        Value::Text(_) => "text",
        _ => "unknown CBOR value kind",
    }
}

/// Serialize a data object descriptor to deterministic CBOR bytes.
pub fn object_descriptor_to_cbor(desc: &DataObjectDescriptor) -> Result<Vec<u8>> {
    let mut value: ciborium::Value = ciborium::Value::serialized(desc)
        .map_err(|e| TensogramError::Metadata(format!("failed to serialize descriptor: {e}")))?;
    canonicalize(&mut value)?;
    value_to_bytes(&value)
}

/// Deserialize a data object descriptor from CBOR bytes.
pub fn cbor_to_object_descriptor(cbor_bytes: &[u8]) -> Result<DataObjectDescriptor> {
    let value: ciborium::Value = ciborium::from_reader(cbor_bytes)
        .map_err(|e| TensogramError::Metadata(format!("failed to parse descriptor CBOR: {e}")))?;
    value
        .deserialized()
        .map_err(|e| TensogramError::Metadata(format!("failed to deserialize descriptor: {e}")))
}

/// Serialize an index frame to deterministic CBOR bytes.
///
/// v3 CBOR structure (see `plans/WIRE_FORMAT.md` §6.2):
/// ```cbor
/// { "offsets": [uint, ...], "lengths": [uint, ...] }
/// ```
///
/// Object count is derived from `offsets.len()` — no separate
/// `object_count` key.
pub fn index_to_cbor(index: &IndexFrame) -> Result<Vec<u8>> {
    use ciborium::Value;
    let map = Value::Map(vec![
        (
            Value::Text("offsets".to_string()),
            Value::Array(
                index
                    .offsets
                    .iter()
                    .map(|&o| Value::Integer(o.into()))
                    .collect(),
            ),
        ),
        (
            Value::Text("lengths".to_string()),
            Value::Array(
                index
                    .lengths
                    .iter()
                    .map(|&l| Value::Integer(l.into()))
                    .collect(),
            ),
        ),
    ]);
    let mut sorted = map;
    canonicalize(&mut sorted)?;
    value_to_bytes(&sorted)
}

/// Deserialize an index frame from CBOR bytes.
pub fn cbor_to_index(cbor_bytes: &[u8]) -> Result<IndexFrame> {
    let value: ciborium::Value = ciborium::from_reader(cbor_bytes)
        .map_err(|e| TensogramError::Metadata(format!("failed to parse index CBOR: {e}")))?;

    let map = match &value {
        ciborium::Value::Map(m) => m,
        _ => {
            return Err(TensogramError::Metadata(
                "index CBOR is not a map".to_string(),
            ));
        }
    };

    let mut index = IndexFrame::default();

    for (k, v) in map {
        // Non-text keys in a closed schema (index frame) are
        // strict-input errors — there's no forward-compat slot they
        // could slot into.  Unknown text keys still pass through for
        // forward-compat (a future version may add fields).
        let key = match k {
            ciborium::Value::Text(s) => s,
            other => {
                return Err(TensogramError::Metadata(format!(
                    "index frame CBOR has non-text key {}\
                     the index schema uses text keys only",
                    cbor_kind_label(other),
                )));
            }
        };
        match key.as_str() {
            "offsets" => {
                index.offsets = cbor_to_u64_array(v, "offsets")?;
            }
            "lengths" => {
                index.lengths = cbor_to_u64_array(v, "lengths")?;
            }
            _ => {} // unknown text keys reserved for future versions
        }
    }

    // v3: object count is derived from offsets.len(); cross-check
    // lengths has the same cardinality.
    if index.offsets.len() != index.lengths.len() {
        return Err(TensogramError::Metadata(format!(
            "index offsets.len() ({}) != lengths.len() ({})",
            index.offsets.len(),
            index.lengths.len()
        )));
    }

    Ok(index)
}

/// Serialize a hash frame to deterministic CBOR bytes.
///
/// v3 CBOR structure (see `plans/WIRE_FORMAT.md` §6.3):
/// ```cbor
/// { "algorithm": "xxh3", "hashes": ["hex", ...] }
/// ```
///
/// Object count is derived from `hashes.len()` — no separate
/// `object_count` key.
pub fn hash_frame_to_cbor(hf: &HashFrame) -> Result<Vec<u8>> {
    use ciborium::Value;
    let map = Value::Map(vec![
        (
            Value::Text("algorithm".to_string()),
            Value::Text(hf.algorithm.clone()),
        ),
        (
            Value::Text("hashes".to_string()),
            Value::Array(hf.hashes.iter().map(|h| Value::Text(h.clone())).collect()),
        ),
    ]);
    let mut sorted = map;
    canonicalize(&mut sorted)?;
    value_to_bytes(&sorted)
}

/// Deserialize a hash frame from CBOR bytes.
///
/// v3 only accepts the new schema (`algorithm`, `hashes`).  The old
/// v2 keys (`hash_type`, `object_count`) are silently ignored as
/// unknown — callers that need to detect the legacy form should
/// check for their presence explicitly.
pub fn cbor_to_hash_frame(cbor_bytes: &[u8]) -> Result<HashFrame> {
    let value: ciborium::Value = ciborium::from_reader(cbor_bytes)
        .map_err(|e| TensogramError::Metadata(format!("failed to parse hash CBOR: {e}")))?;

    let map = match &value {
        ciborium::Value::Map(m) => m,
        _ => {
            return Err(TensogramError::Metadata(
                "hash frame CBOR is not a map".to_string(),
            ));
        }
    };

    let mut algorithm = String::new();
    let mut hashes = Vec::new();

    for (k, v) in map {
        // Closed schema: non-text keys are strict-input errors.
        let key = match k {
            ciborium::Value::Text(s) => s,
            other => {
                return Err(TensogramError::Metadata(format!(
                    "hash frame CBOR has non-text key {}\
                     the hash-frame schema uses text keys only",
                    cbor_kind_label(other),
                )));
            }
        };
        match key.as_str() {
            "algorithm" => {
                algorithm = match v {
                    ciborium::Value::Text(s) => s.clone(),
                    _ => {
                        return Err(TensogramError::Metadata(
                            "algorithm must be text".to_string(),
                        ));
                    }
                };
            }
            "hashes" => {
                hashes = match v {
                    ciborium::Value::Array(arr) => arr
                        .iter()
                        .map(|item| match item {
                            ciborium::Value::Text(s) => Ok(s.clone()),
                            _ => Err(TensogramError::Metadata(
                                "hash entry must be text".to_string(),
                            )),
                        })
                        .collect::<Result<Vec<_>>>()?,
                    _ => {
                        return Err(TensogramError::Metadata(
                            "hashes must be an array".to_string(),
                        ));
                    }
                };
            }
            _ => {} // unknown text keys reserved for future versions
        }
    }

    Ok(HashFrame { algorithm, hashes })
}

// ── Common-key extraction ────────────────────────────────────────────────────

/// Extract keys common to ALL base entries.
///
/// Returns `(common_keys, remaining_per_object_entries)` where:
/// - `common_keys`: keys present in ALL entries with identical CBOR values
/// - `remaining`: per-object entries with only the varying keys
///
/// The `_reserved_` key is excluded from common computation (it's library-managed
/// and varies per object due to ndim/shape/strides/dtype).
///
/// Edge cases:
/// - 0 entries: returns (empty, empty vec)
/// - 1 entry: all keys (except `_reserved_`) are common, remaining is empty
///
/// **NaN handling:** CBOR `Float(NaN)` values use IEEE 754 equality
/// (`NaN != NaN`), so a key whose value is NaN in all entries will NOT
/// be classified as common.  This is conservative — no data is lost,
/// the key simply appears per-object rather than in the common set.
pub fn compute_common(
    base: &[BTreeMap<String, ciborium::Value>],
) -> (
    BTreeMap<String, ciborium::Value>,
    Vec<BTreeMap<String, ciborium::Value>>,
) {
    if base.is_empty() {
        return (BTreeMap::new(), Vec::new());
    }

    let first = &base[0];
    let mut common = BTreeMap::new();

    // Candidate keys come from the first entry (minus _reserved_).
    // A key is common only if every other entry has the same key with the same value.
    // Note: uses cbor_values_equal() for NaN-safe float comparison.
    for (key, value) in first {
        if key == RESERVED_KEY {
            continue;
        }
        let is_common = base[1..]
            .iter()
            .all(|entry| entry.get(key).is_some_and(|v| cbor_values_equal(v, value)));
        if is_common {
            common.insert(key.clone(), value.clone());
        }
    }

    // Build per-object remaining entries: everything that isn't common or _reserved_.
    let remaining = base
        .iter()
        .map(|entry| {
            entry
                .iter()
                .filter(|(k, _)| *k != RESERVED_KEY && !common.contains_key(*k))
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect()
        })
        .collect();

    (common, remaining)
}

// ── CBOR helpers ─────────────────────────────────────────────────────────────

/// NaN-safe equality for CBOR values.
///
/// Standard `PartialEq` for `ciborium::Value` derives from `f64::eq`,
/// so `Float(NaN) != Float(NaN)`.  This function compares floats
/// bitwise (via `to_bits`) so NaN values with identical bit patterns
/// are considered equal — matching RFC 8949 deterministic encoding
/// where the canonical NaN bit pattern is fixed.
fn cbor_values_equal(a: &ciborium::Value, b: &ciborium::Value) -> bool {
    use ciborium::Value;
    match (a, b) {
        (Value::Float(fa), Value::Float(fb)) => fa.to_bits() == fb.to_bits(),
        (Value::Array(aa), Value::Array(ab)) => {
            aa.len() == ab.len()
                && aa
                    .iter()
                    .zip(ab.iter())
                    .all(|(x, y)| cbor_values_equal(x, y))
        }
        (Value::Map(ma), Value::Map(mb)) => {
            ma.len() == mb.len()
                && ma.iter().zip(mb.iter()).all(|((ka, va), (kb, vb))| {
                    cbor_values_equal(ka, kb) && cbor_values_equal(va, vb)
                })
        }
        (Value::Tag(ta, va), Value::Tag(tb, vb)) => ta == tb && cbor_values_equal(va, vb),
        // All other variants: delegate to standard PartialEq
        _ => a == b,
    }
}

fn value_to_bytes(value: &ciborium::Value) -> Result<Vec<u8>> {
    let mut buf = Vec::new();
    ciborium::into_writer(value, &mut buf)
        .map_err(|e| TensogramError::Metadata(format!("failed to write CBOR: {e}")))?;
    Ok(buf)
}

fn cbor_to_u64(v: &ciborium::Value, field: &str) -> Result<u64> {
    match v {
        ciborium::Value::Integer(i) => {
            let n: i128 = (*i).into();
            u64::try_from(n).map_err(|_| {
                TensogramError::Metadata(format!("{field} value {n} out of u64 range"))
            })
        }
        _ => Err(TensogramError::Metadata(format!(
            "{field} must be an integer"
        ))),
    }
}

fn cbor_to_u64_array(v: &ciborium::Value, field: &str) -> Result<Vec<u64>> {
    match v {
        ciborium::Value::Array(arr) => arr.iter().map(|item| cbor_to_u64(item, field)).collect(),
        _ => Err(TensogramError::Metadata(format!(
            "{field} must be an array"
        ))),
    }
}

/// Recursively sort all map keys in a ciborium::Value tree for canonical encoding.
/// Keys are sorted by their CBOR-encoded byte representation (lexicographic).
pub(crate) fn canonicalize(value: &mut ciborium::Value) -> Result<()> {
    match value {
        ciborium::Value::Map(entries) => {
            for (k, v) in entries.iter_mut() {
                canonicalize(k)?;
                canonicalize(v)?;
            }
            let mut keyed: Vec<(Vec<u8>, (ciborium::Value, ciborium::Value))> = Vec::new();
            for (k, v) in entries.drain(..) {
                let mut key_bytes = Vec::new();
                ciborium::into_writer(&k, &mut key_bytes).map_err(|e| {
                    TensogramError::Metadata(format!("CBOR key serialisation failed: {e}"))
                })?;
                keyed.push((key_bytes, (k, v)));
            }
            keyed.sort_by(|(a, _), (b, _)| a.cmp(b));
            *entries = keyed.into_iter().map(|(_, kv)| kv).collect();
        }
        ciborium::Value::Array(items) => {
            for item in items.iter_mut() {
                canonicalize(item)?;
            }
        }
        ciborium::Value::Tag(_, inner) => {
            canonicalize(inner)?;
        }
        _ => {}
    }
    Ok(())
}

/// Verify that CBOR bytes are in RFC 8949 §4.2.1 canonical form.
///
/// Checks that all map keys are sorted by their encoded byte representation
/// (length-first, then lexicographic). Returns `Ok(())` if canonical, or an
/// error describing the first violation.
pub fn verify_canonical_cbor(cbor_bytes: &[u8]) -> Result<()> {
    let value: ciborium::Value = ciborium::from_reader(cbor_bytes)
        .map_err(|e| TensogramError::Metadata(format!("failed to parse CBOR: {e}")))?;
    verify_canonical_value(&value)
}

fn verify_canonical_value(value: &ciborium::Value) -> Result<()> {
    match value {
        ciborium::Value::Map(entries) => {
            // Check keys are sorted by encoded byte representation
            let mut prev_key_bytes: Option<Vec<u8>> = None;
            for (k, v) in entries {
                let mut key_bytes = Vec::new();
                ciborium::into_writer(k, &mut key_bytes).map_err(|e| {
                    TensogramError::Metadata(format!("CBOR key serialisation failed: {e}"))
                })?;

                if let Some(ref prev) = prev_key_bytes
                    && key_bytes <= *prev
                {
                    return Err(TensogramError::Metadata(format!(
                        "CBOR map keys not in canonical order: key {:?} should come before {:?}",
                        prev, key_bytes
                    )));
                }
                prev_key_bytes = Some(key_bytes);

                // Recurse into key and value
                verify_canonical_value(k)?;
                verify_canonical_value(v)?;
            }
        }
        ciborium::Value::Array(items) => {
            for item in items {
                verify_canonical_value(item)?;
            }
        }
        ciborium::Value::Tag(_, inner) => {
            verify_canonical_value(inner)?;
        }
        _ => {}
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dtype::Dtype;
    use crate::types::ByteOrder;
    use std::collections::BTreeMap;

    fn make_test_global_metadata() -> GlobalMetadata {
        let mut mars = BTreeMap::new();
        mars.insert("class".to_string(), ciborium::Value::Text("od".to_string()));
        mars.insert("type".to_string(), ciborium::Value::Text("fc".to_string()));

        let mars_value = ciborium::Value::Map(
            mars.into_iter()
                .map(|(k, v)| (ciborium::Value::Text(k), v))
                .collect(),
        );

        let mut base_entry = BTreeMap::new();
        base_entry.insert("mars".to_string(), mars_value);

        GlobalMetadata {
            base: vec![base_entry],
            ..Default::default()
        }
    }

    fn make_test_descriptor() -> DataObjectDescriptor {
        DataObjectDescriptor {
            obj_type: "ntensor".to_string(),
            ndim: 2,
            shape: vec![10, 20],
            strides: vec![20, 1],
            dtype: Dtype::Float32,
            byte_order: ByteOrder::native(),
            encoding: "none".to_string(),
            filter: "none".to_string(),
            compression: "none".to_string(),
            params: BTreeMap::new(),
            masks: None,
        }
    }

    #[test]
    fn test_global_metadata_round_trip() {
        let meta = make_test_global_metadata();
        let bytes = global_metadata_to_cbor(&meta).unwrap();
        let decoded = cbor_to_global_metadata(&bytes).unwrap();
        assert_eq!(decoded.base.len(), 1);
        assert!(decoded.base[0].contains_key("mars"));
    }

    #[test]
    fn test_cbor_has_no_version_key() {
        // The wire-format version is carried in the preamble, NOT in the
        // CBOR metadata frame.  A round-trip through the encoder must
        // never stamp a top-level `"version"` key.
        let meta = make_test_global_metadata();
        let bytes = global_metadata_to_cbor(&meta).unwrap();
        let value: ciborium::Value = ciborium::from_reader(bytes.as_slice()).unwrap();
        let map = match value {
            ciborium::Value::Map(m) => m,
            other => panic!("expected CBOR map, got {other:?}"),
        };
        for (k, _) in &map {
            if let ciborium::Value::Text(key) = k {
                assert_ne!(
                    key, "version",
                    "encoder must not write a top-level `version` key to CBOR"
                );
            }
        }
    }

    #[test]
    fn test_legacy_version_routed_to_extra() {
        // A producer that still emits a stray `version` top-level key
        // (legacy encoders pre-0.17) must decode cleanly under the
        // free-form rule — the key flows into `_extra_` instead of
        // being rejected or silently dropped.
        use ciborium::Value;

        let legacy_map = Value::Map(vec![
            (Value::Text("version".to_string()), Value::Integer(3.into())),
            (
                Value::Text("_extra_".to_string()),
                Value::Map(vec![(
                    Value::Text("note".to_string()),
                    Value::Text("hi".to_string()),
                )]),
            ),
        ]);
        let mut bytes = Vec::new();
        ciborium::into_writer(&legacy_map, &mut bytes).unwrap();

        let decoded = cbor_to_global_metadata(&bytes).unwrap();
        assert!(decoded.base.is_empty());
        assert_eq!(
            decoded.extra.get("version"),
            Some(&Value::Integer(3.into())),
            "legacy `version` key must land in `_extra_`"
        );
        assert_eq!(
            decoded.extra.get("note"),
            Some(&Value::Text("hi".to_string())),
            "explicit `_extra_` entries must still be preserved"
        );
    }

    #[test]
    fn test_free_form_top_level_keys_routed_to_extra() {
        // Arbitrary top-level keys the caller puts in the CBOR (e.g.
        // `"product"`, `"foo"`) must also flow into `_extra_` on
        // decode.  This is the free-form invariant.
        use ciborium::Value;

        let free_form = Value::Map(vec![
            (
                Value::Text("foo".to_string()),
                Value::Text("bar".to_string()),
            ),
            (
                Value::Text("product".to_string()),
                Value::Text("efi".to_string()),
            ),
        ]);
        let mut bytes = Vec::new();
        ciborium::into_writer(&free_form, &mut bytes).unwrap();

        let decoded = cbor_to_global_metadata(&bytes).unwrap();
        assert_eq!(
            decoded.extra.get("foo"),
            Some(&Value::Text("bar".to_string()))
        );
        assert_eq!(
            decoded.extra.get("product"),
            Some(&Value::Text("efi".to_string()))
        );
    }

    #[test]
    fn test_global_metadata_rejects_collision_between_extra_and_top_level() {
        // Strict-input contract: a key cannot appear both in the
        // explicit `_extra_` section AND as a free-form top-level
        // key.  Earlier versions silently preferred the explicit
        // entry; the new rule rejects the ambiguity so the producer
        // is forced to pick one placement.
        use ciborium::Value;

        let colliding = Value::Map(vec![
            (
                Value::Text("_extra_".to_string()),
                Value::Map(vec![(
                    Value::Text("version".to_string()),
                    Value::Integer(1.into()),
                )]),
            ),
            (
                Value::Text("version".to_string()),
                Value::Integer(99.into()),
            ),
        ]);
        let mut bytes = Vec::new();
        ciborium::into_writer(&colliding, &mut bytes).unwrap();

        let err = cbor_to_global_metadata(&bytes).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("ambiguous metadata"), "msg: {msg}");
                assert!(msg.contains("version"), "msg: {msg}");
                assert!(msg.contains("`_extra_`"), "msg: {msg}");
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn test_global_metadata_rejects_non_text_top_level_key() {
        // Strict-input contract: a non-text key at the top level is
        // rejected, not silently dropped.  Canonical CBOR uses text
        // keys for our schema; an integer key here likely indicates
        // a malformed producer.
        use ciborium::Value;

        let bad = Value::Map(vec![(
            Value::Integer(42i64.into()),
            Value::Text("oops".to_string()),
        )]);
        let mut bytes = Vec::new();
        ciborium::into_writer(&bad, &mut bytes).unwrap();

        let err = cbor_to_global_metadata(&bytes).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("non-text top-level key"), "msg: {msg}");
                assert!(msg.contains("integer"), "msg: {msg}");
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn test_index_frame_rejects_non_text_key() {
        use ciborium::Value;
        let bad = Value::Map(vec![(
            Value::Integer(7i64.into()),
            Value::Array(vec![Value::Integer(0u64.into())]),
        )]);
        let mut bytes = Vec::new();
        ciborium::into_writer(&bad, &mut bytes).unwrap();

        let err = cbor_to_index(&bytes).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("non-text key"), "msg: {msg}");
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn test_hash_frame_rejects_non_text_key() {
        use ciborium::Value;
        let bad = Value::Map(vec![(
            Value::Bytes(vec![1, 2, 3]),
            Value::Text("xxh3".to_string()),
        )]);
        let mut bytes = Vec::new();
        ciborium::into_writer(&bad, &mut bytes).unwrap();

        let err = cbor_to_hash_frame(&bytes).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("non-text key"), "msg: {msg}");
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn test_global_metadata_deterministic() {
        let meta = make_test_global_metadata();
        let b1 = global_metadata_to_cbor(&meta).unwrap();
        let b2 = global_metadata_to_cbor(&meta).unwrap();
        assert_eq!(b1, b2);
    }

    #[test]
    fn test_descriptor_round_trip() {
        let desc = make_test_descriptor();
        let bytes = object_descriptor_to_cbor(&desc).unwrap();
        let decoded = cbor_to_object_descriptor(&bytes).unwrap();
        assert_eq!(decoded.obj_type, "ntensor");
        assert_eq!(decoded.shape, vec![10, 20]);
        assert_eq!(decoded.dtype, Dtype::Float32);
        assert_eq!(decoded.encoding, "none");
    }

    #[test]
    fn test_index_round_trip() {
        let index = IndexFrame {
            offsets: vec![100, 500, 1200],
            lengths: vec![400, 700, 300],
        };
        let bytes = index_to_cbor(&index).unwrap();
        let decoded = cbor_to_index(&bytes).unwrap();
        assert_eq!(decoded.offsets.len(), 3);
        assert_eq!(decoded.offsets, vec![100, 500, 1200]);
        assert_eq!(decoded.lengths, vec![400, 700, 300]);
    }

    #[test]
    fn test_hash_frame_round_trip() {
        let hf = HashFrame {
            algorithm: "xxh3".to_string(),
            hashes: vec![
                "abcdef0123456789".to_string(),
                "1234567890abcdef".to_string(),
            ],
        };
        let bytes = hash_frame_to_cbor(&hf).unwrap();
        let decoded = cbor_to_hash_frame(&bytes).unwrap();
        assert_eq!(decoded.hashes.len(), 2);
        assert_eq!(decoded.algorithm, "xxh3");
        assert_eq!(decoded.hashes, hf.hashes);
    }

    #[test]
    fn test_empty_global_metadata() {
        let meta = GlobalMetadata::default();
        let bytes = global_metadata_to_cbor(&meta).unwrap();
        let decoded = cbor_to_global_metadata(&bytes).unwrap();
        assert!(decoded.base.is_empty());
        assert!(decoded.extra.is_empty());
    }

    // ── Phase 7: Canonical CBOR verification tests ───────────────────

    #[test]
    fn test_global_metadata_cbor_is_canonical() {
        let meta = make_test_global_metadata();
        let bytes = global_metadata_to_cbor(&meta).unwrap();
        verify_canonical_cbor(&bytes).unwrap();
    }

    #[test]
    fn test_descriptor_cbor_is_canonical() {
        let desc = make_test_descriptor();
        let bytes = object_descriptor_to_cbor(&desc).unwrap();
        verify_canonical_cbor(&bytes).unwrap();
    }

    #[test]
    fn test_index_cbor_is_canonical() {
        let index = IndexFrame {
            offsets: vec![100, 500, 1200],
            lengths: vec![400, 700, 300],
        };
        let bytes = index_to_cbor(&index).unwrap();
        verify_canonical_cbor(&bytes).unwrap();
    }

    #[test]
    fn test_hash_frame_cbor_is_canonical() {
        let hf = HashFrame {
            algorithm: "xxh3".to_string(),
            hashes: vec!["abc".to_string(), "def".to_string()],
        };
        let bytes = hash_frame_to_cbor(&hf).unwrap();
        verify_canonical_cbor(&bytes).unwrap();
    }

    #[test]
    fn test_verify_rejects_non_canonical() {
        // Build a map with keys intentionally out of order (longer key first)
        use ciborium::Value;
        let non_canonical = Value::Map(vec![
            (
                Value::Text("zzz_long_key".to_string()),
                Value::Integer(1.into()),
            ),
            (Value::Text("a".to_string()), Value::Integer(2.into())),
        ]);
        let mut buf = Vec::new();
        ciborium::into_writer(&non_canonical, &mut buf).unwrap();

        let result = verify_canonical_cbor(&buf);
        assert!(result.is_err(), "non-canonical CBOR should be rejected");
    }

    #[test]
    fn test_canonicalize_sorts_nested_maps() {
        use ciborium::Value;
        // Create a map with nested maps, keys out of order
        let mut value = Value::Map(vec![
            (
                Value::Text("z".to_string()),
                Value::Map(vec![
                    (Value::Text("b".to_string()), Value::Integer(2.into())),
                    (Value::Text("a".to_string()), Value::Integer(1.into())),
                ]),
            ),
            (Value::Text("a".to_string()), Value::Integer(0.into())),
        ]);

        canonicalize(&mut value).unwrap();

        // Serialize and verify canonical
        let mut bytes = Vec::new();
        ciborium::into_writer(&value, &mut bytes).unwrap();
        verify_canonical_cbor(&bytes).unwrap();
    }

    #[test]
    fn test_encoding_determinism_across_key_insertion_orders() {
        // Insert keys in two different orders, verify same CBOR output
        let mut base1 = BTreeMap::new();
        base1.insert("zebra".to_string(), ciborium::Value::Integer(1.into()));
        base1.insert("apple".to_string(), ciborium::Value::Integer(2.into()));
        let meta1 = GlobalMetadata {
            base: vec![base1],
            ..Default::default()
        };

        let mut base2 = BTreeMap::new();
        base2.insert("apple".to_string(), ciborium::Value::Integer(2.into()));
        base2.insert("zebra".to_string(), ciborium::Value::Integer(1.into()));
        let meta2 = GlobalMetadata {
            base: vec![base2],
            ..Default::default()
        };

        let bytes1 = global_metadata_to_cbor(&meta1).unwrap();
        let bytes2 = global_metadata_to_cbor(&meta2).unwrap();
        assert_eq!(
            bytes1, bytes2,
            "CBOR output must be independent of insertion order"
        );
    }

    // ── compute_common tests ─────────────────────────────────────────

    #[test]
    fn test_compute_common_empty() {
        let (common, remaining) = compute_common(&[]);
        assert!(common.is_empty());
        assert!(remaining.is_empty());
    }

    #[test]
    fn test_compute_common_single_entry() {
        let mut entry = BTreeMap::new();
        entry.insert("class".to_string(), ciborium::Value::Text("od".to_string()));
        entry.insert("_reserved_".to_string(), ciborium::Value::Integer(1.into()));

        let (common, remaining) = compute_common(&[entry]);
        assert_eq!(common.len(), 1); // only "class", _reserved_ excluded
        assert!(common.contains_key("class"));
        assert!(!common.contains_key("_reserved_"));
        assert_eq!(remaining.len(), 1);
        assert!(remaining[0].is_empty());
    }

    #[test]
    fn test_compute_common_all_identical() {
        let mut e1 = BTreeMap::new();
        e1.insert("class".to_string(), ciborium::Value::Text("od".to_string()));
        e1.insert(
            "date".to_string(),
            ciborium::Value::Text("20260401".to_string()),
        );
        let e2 = e1.clone();

        let (common, remaining) = compute_common(&[e1, e2]);
        assert_eq!(common.len(), 2);
        assert!(remaining[0].is_empty());
        assert!(remaining[1].is_empty());
    }

    #[test]
    fn test_compute_common_one_varying() {
        let mut e1 = BTreeMap::new();
        e1.insert("class".to_string(), ciborium::Value::Text("od".to_string()));
        e1.insert("param".to_string(), ciborium::Value::Text("2t".to_string()));

        let mut e2 = BTreeMap::new();
        e2.insert("class".to_string(), ciborium::Value::Text("od".to_string()));
        e2.insert(
            "param".to_string(),
            ciborium::Value::Text("msl".to_string()),
        );

        let (common, remaining) = compute_common(&[e1, e2]);
        assert_eq!(common.len(), 1); // only "class"
        assert!(common.contains_key("class"));
        assert_eq!(remaining[0].len(), 1); // "param"
        assert_eq!(remaining[1].len(), 1); // "param"
    }

    #[test]
    fn test_compute_common_reserved_excluded() {
        let mut e1 = BTreeMap::new();
        e1.insert("class".to_string(), ciborium::Value::Text("od".to_string()));
        e1.insert("_reserved_".to_string(), ciborium::Value::Map(vec![]));
        let mut e2 = BTreeMap::new();
        e2.insert("class".to_string(), ciborium::Value::Text("od".to_string()));
        e2.insert("_reserved_".to_string(), ciborium::Value::Map(vec![]));

        let (common, remaining) = compute_common(&[e1, e2]);
        assert!(common.contains_key("class"));
        assert!(!common.contains_key("_reserved_"));
        // _reserved_ excluded from remaining too
        assert!(remaining[0].is_empty());
        assert!(remaining[1].is_empty());
    }

    #[test]
    fn test_compute_common_key_missing_in_some_entries() {
        // Key present in first entry but absent in second => not common
        let mut e1 = BTreeMap::new();
        e1.insert("class".to_string(), ciborium::Value::Text("od".to_string()));
        e1.insert(
            "extra".to_string(),
            ciborium::Value::Text("only_here".to_string()),
        );

        let mut e2 = BTreeMap::new();
        e2.insert("class".to_string(), ciborium::Value::Text("od".to_string()));

        let (common, remaining) = compute_common(&[e1, e2]);
        assert_eq!(common.len(), 1);
        assert!(common.contains_key("class"));
        assert_eq!(remaining[0].len(), 1); // "extra" is per-object for e1
        assert!(remaining[1].is_empty()); // e2 has nothing left
    }

    #[test]
    fn test_compute_common_three_entries() {
        let mut e1 = BTreeMap::new();
        e1.insert("class".to_string(), ciborium::Value::Text("od".to_string()));
        e1.insert("step".to_string(), ciborium::Value::Integer(0.into()));

        let mut e2 = BTreeMap::new();
        e2.insert("class".to_string(), ciborium::Value::Text("od".to_string()));
        e2.insert("step".to_string(), ciborium::Value::Integer(6.into()));

        let mut e3 = BTreeMap::new();
        e3.insert("class".to_string(), ciborium::Value::Text("od".to_string()));
        e3.insert("step".to_string(), ciborium::Value::Integer(12.into()));

        let (common, remaining) = compute_common(&[e1, e2, e3]);
        assert_eq!(common.len(), 1); // "class"
        assert!(common.contains_key("class"));
        // Each remaining has "step"
        assert_eq!(remaining[0].len(), 1);
        assert_eq!(remaining[1].len(), 1);
        assert_eq!(remaining[2].len(), 1);
    }

    #[test]
    fn test_compute_common_nan_values_treated_as_equal() {
        // NaN values with identical bit patterns should be treated as common
        let mut e1 = BTreeMap::new();
        e1.insert("class".to_string(), ciborium::Value::Text("od".to_string()));
        e1.insert("fill".to_string(), ciborium::Value::Float(f64::NAN));

        let mut e2 = BTreeMap::new();
        e2.insert("class".to_string(), ciborium::Value::Text("od".to_string()));
        e2.insert("fill".to_string(), ciborium::Value::Float(f64::NAN));

        let (common, remaining) = compute_common(&[e1, e2]);
        // Both "class" and "fill" should be common (NaN-safe comparison)
        assert_eq!(common.len(), 2);
        assert!(common.contains_key("class"));
        assert!(common.contains_key("fill"));
        assert!(remaining[0].is_empty());
        assert!(remaining[1].is_empty());
    }

    #[test]
    fn test_compute_common_nested_maps_with_nan() {
        // Nested CBOR maps containing NaN should still compare correctly
        let make_entry = || {
            let nested = ciborium::Value::Map(vec![(
                ciborium::Value::Text("fill_value".to_string()),
                ciborium::Value::Float(f64::NAN),
            )]);
            let mut e = BTreeMap::new();
            e.insert("params".to_string(), nested);
            e
        };

        let (common, remaining) = compute_common(&[make_entry(), make_entry()]);
        assert_eq!(common.len(), 1);
        assert!(common.contains_key("params"));
        assert!(remaining[0].is_empty());
        assert!(remaining[1].is_empty());
    }

    #[test]
    fn test_cbor_values_equal_basic() {
        use super::cbor_values_equal;

        // NaN == NaN (bitwise)
        assert!(cbor_values_equal(
            &ciborium::Value::Float(f64::NAN),
            &ciborium::Value::Float(f64::NAN)
        ));

        // Normal floats
        assert!(cbor_values_equal(
            &ciborium::Value::Float(1.5),
            &ciborium::Value::Float(1.5)
        ));
        assert!(!cbor_values_equal(
            &ciborium::Value::Float(1.5),
            &ciborium::Value::Float(2.5)
        ));

        // Mixed types
        assert!(!cbor_values_equal(
            &ciborium::Value::Float(1.0),
            &ciborium::Value::Integer(1.into())
        ));

        // Text
        assert!(cbor_values_equal(
            &ciborium::Value::Text("a".to_string()),
            &ciborium::Value::Text("a".to_string())
        ));
    }

    // ── Edge case: compute_common with different key sets ────────────────

    #[test]
    fn test_compute_common_different_key_sets() {
        // Entry 0 has "a", "b"; entry 1 has "b", "c".
        // Only "b" can be common if values match.
        let mut e1 = BTreeMap::new();
        e1.insert("a".to_string(), ciborium::Value::Integer(1.into()));
        e1.insert("b".to_string(), ciborium::Value::Text("shared".to_string()));

        let mut e2 = BTreeMap::new();
        e2.insert("b".to_string(), ciborium::Value::Text("shared".to_string()));
        e2.insert("c".to_string(), ciborium::Value::Integer(3.into()));

        let (common, remaining) = compute_common(&[e1, e2]);
        assert_eq!(common.len(), 1);
        assert!(common.contains_key("b"));
        // Note: "c" is NOT considered as a common candidate because
        // compute_common only examines keys from the first entry.
        // "a" is in remaining[0], "c" is in remaining[1].
        assert_eq!(remaining[0].len(), 1); // "a"
        assert!(remaining[0].contains_key("a"));
        assert_eq!(remaining[1].len(), 1); // "c"
        assert!(remaining[1].contains_key("c"));
    }

    #[test]
    fn test_compute_common_key_in_later_entry_only() {
        // Key "z" present in entry 1 only, not in entry 0 — never a common candidate.
        let mut e1 = BTreeMap::new();
        e1.insert("a".to_string(), ciborium::Value::Integer(1.into()));

        let mut e2 = BTreeMap::new();
        e2.insert("a".to_string(), ciborium::Value::Integer(1.into()));
        e2.insert("z".to_string(), ciborium::Value::Integer(99.into()));

        let (common, remaining) = compute_common(&[e1, e2]);
        assert_eq!(common.len(), 1);
        assert!(common.contains_key("a"));
        // "z" only in entry 1's remaining
        assert!(remaining[0].is_empty());
        assert_eq!(remaining[1].len(), 1);
        assert!(remaining[1].contains_key("z"));
    }

    // ── cbor_values_equal edge cases ────────────────────────────────────

    #[test]
    fn test_cbor_values_equal_booleans() {
        use super::cbor_values_equal;
        assert!(cbor_values_equal(
            &ciborium::Value::Bool(true),
            &ciborium::Value::Bool(true)
        ));
        assert!(!cbor_values_equal(
            &ciborium::Value::Bool(true),
            &ciborium::Value::Bool(false)
        ));
    }

    #[test]
    fn test_cbor_values_equal_bytes() {
        use super::cbor_values_equal;
        assert!(cbor_values_equal(
            &ciborium::Value::Bytes(vec![1, 2, 3]),
            &ciborium::Value::Bytes(vec![1, 2, 3])
        ));
        assert!(!cbor_values_equal(
            &ciborium::Value::Bytes(vec![1, 2, 3]),
            &ciborium::Value::Bytes(vec![1, 2, 4])
        ));
    }

    #[test]
    fn test_cbor_values_equal_arrays_different_lengths() {
        use super::cbor_values_equal;
        let a = ciborium::Value::Array(vec![ciborium::Value::Integer(1.into())]);
        let b = ciborium::Value::Array(vec![
            ciborium::Value::Integer(1.into()),
            ciborium::Value::Integer(2.into()),
        ]);
        assert!(!cbor_values_equal(&a, &b));
    }

    #[test]
    fn test_cbor_values_equal_nested_arrays_with_nan() {
        use super::cbor_values_equal;
        let a = ciborium::Value::Array(vec![
            ciborium::Value::Float(f64::NAN),
            ciborium::Value::Integer(1.into()),
        ]);
        let b = ciborium::Value::Array(vec![
            ciborium::Value::Float(f64::NAN),
            ciborium::Value::Integer(1.into()),
        ]);
        assert!(cbor_values_equal(&a, &b));
    }

    #[test]
    fn test_cbor_values_equal_maps_different_lengths() {
        use super::cbor_values_equal;
        let a = ciborium::Value::Map(vec![(
            ciborium::Value::Text("a".to_string()),
            ciborium::Value::Integer(1.into()),
        )]);
        let b = ciborium::Value::Map(vec![
            (
                ciborium::Value::Text("a".to_string()),
                ciborium::Value::Integer(1.into()),
            ),
            (
                ciborium::Value::Text("b".to_string()),
                ciborium::Value::Integer(2.into()),
            ),
        ]);
        assert!(!cbor_values_equal(&a, &b));
    }

    #[test]
    fn test_cbor_values_equal_tags() {
        use super::cbor_values_equal;
        let a = ciborium::Value::Tag(1, Box::new(ciborium::Value::Integer(42.into())));
        let b = ciborium::Value::Tag(1, Box::new(ciborium::Value::Integer(42.into())));
        assert!(cbor_values_equal(&a, &b));

        let c = ciborium::Value::Tag(2, Box::new(ciborium::Value::Integer(42.into())));
        assert!(!cbor_values_equal(&a, &c));

        let d = ciborium::Value::Tag(1, Box::new(ciborium::Value::Integer(99.into())));
        assert!(!cbor_values_equal(&a, &d));
    }

    #[test]
    fn test_cbor_values_equal_null() {
        use super::cbor_values_equal;
        assert!(cbor_values_equal(
            &ciborium::Value::Null,
            &ciborium::Value::Null
        ));
        assert!(!cbor_values_equal(
            &ciborium::Value::Null,
            &ciborium::Value::Bool(false)
        ));
    }

    #[test]
    fn test_cbor_values_equal_tags_with_nan_inside() {
        use super::cbor_values_equal;
        let a = ciborium::Value::Tag(1, Box::new(ciborium::Value::Float(f64::NAN)));
        let b = ciborium::Value::Tag(1, Box::new(ciborium::Value::Float(f64::NAN)));
        assert!(cbor_values_equal(&a, &b));
    }

    // ── Mutation-testing gap-fillers ────────────────────────────────────

    #[test]
    fn test_cbor_values_equal_map_same_keys_different_values() {
        // Kills: replace && with || in cbor_values_equal (line 464).
        // With ||, matching keys alone would make the whole pair "equal"
        // even when values differ.
        use super::cbor_values_equal;
        let a = ciborium::Value::Map(vec![(
            ciborium::Value::Text("k".to_string()),
            ciborium::Value::Integer(1.into()),
        )]);
        let b = ciborium::Value::Map(vec![(
            ciborium::Value::Text("k".to_string()),
            ciborium::Value::Integer(2.into()),
        )]);
        assert!(
            !cbor_values_equal(&a, &b),
            "maps with same keys but different values must not be equal"
        );
    }

    #[test]
    fn test_cbor_values_equal_map_different_keys_same_values() {
        // Also kills && → || : matching values alone would make the pair
        // "equal" even when keys differ.
        use super::cbor_values_equal;
        let a = ciborium::Value::Map(vec![(
            ciborium::Value::Text("x".to_string()),
            ciborium::Value::Integer(1.into()),
        )]);
        let b = ciborium::Value::Map(vec![(
            ciborium::Value::Text("y".to_string()),
            ciborium::Value::Integer(1.into()),
        )]);
        assert!(
            !cbor_values_equal(&a, &b),
            "maps with different keys but same values must not be equal"
        );
    }

    #[test]
    fn test_canonicalize_recurses_into_tagged_values() {
        // Kills: delete match arm Tag in canonicalize (line 528).
        // A tagged value wrapping a map with unsorted keys must still
        // be canonicalized.
        use ciborium::Value;
        let mut tagged = Value::Tag(
            1,
            Box::new(Value::Map(vec![
                (Value::Text("z".to_string()), Value::Integer(2.into())),
                (Value::Text("a".to_string()), Value::Integer(1.into())),
            ])),
        );
        canonicalize(&mut tagged).unwrap();

        // After canonicalization, the inner map keys must be sorted.
        let mut bytes = Vec::new();
        ciborium::into_writer(&tagged, &mut bytes).unwrap();
        // Extract the inner map and verify key order.
        match tagged {
            Value::Tag(_, inner) => match *inner {
                Value::Map(entries) => {
                    let keys: Vec<_> = entries
                        .iter()
                        .map(|(k, _)| match k {
                            Value::Text(s) => s.as_str(),
                            _ => panic!("expected text key"),
                        })
                        .collect();
                    assert_eq!(keys, vec!["a", "z"], "tagged map keys must be sorted");
                }
                _ => panic!("expected map inside tag"),
            },
            _ => panic!("expected tag"),
        }
    }

    #[test]
    fn test_verify_canonical_recurses_into_arrays() {
        // Kills: delete match arm Array in verify_canonical_value (line 573).
        // An array containing a non-canonical map must be detected.
        use ciborium::Value;
        let non_canonical_in_array = Value::Array(vec![Value::Map(vec![
            (Value::Text("z".to_string()), Value::Integer(2.into())),
            (Value::Text("a".to_string()), Value::Integer(1.into())),
        ])]);
        let mut bytes = Vec::new();
        ciborium::into_writer(&non_canonical_in_array, &mut bytes).unwrap();
        assert!(
            verify_canonical_cbor(&bytes).is_err(),
            "non-canonical map inside array must be detected"
        );
    }

    #[test]
    fn test_verify_canonical_recurses_into_tags() {
        // Kills: delete match arm Tag in verify_canonical_value (line 578).
        // A tagged value wrapping a non-canonical map must be detected.
        use ciborium::Value;
        let non_canonical_in_tag = Value::Tag(
            1,
            Box::new(Value::Map(vec![
                (Value::Text("z".to_string()), Value::Integer(2.into())),
                (Value::Text("a".to_string()), Value::Integer(1.into())),
            ])),
        );
        let mut bytes = Vec::new();
        ciborium::into_writer(&non_canonical_in_tag, &mut bytes).unwrap();
        assert!(
            verify_canonical_cbor(&bytes).is_err(),
            "non-canonical map inside tag must be detected"
        );
    }

    #[test]
    fn test_compute_common_cbor_maps_with_different_key_order() {
        // CBOR Maps with same content but different key ordering should be
        // considered equal because cbor_values_equal compares element-by-element
        // after canonicalization by BTreeMap (CBOR maps are compared positionally).
        // But here we use ciborium::Value::Map which preserves insertion order.
        // Two maps with same keys/values in different order: NOT equal by the
        // current positional comparison (this is correct — CBOR canonical encoding
        // ensures all maps are sorted, so different-order maps from a canonical
        // encoder can't happen).
        let map1 = ciborium::Value::Map(vec![
            (
                ciborium::Value::Text("a".to_string()),
                ciborium::Value::Integer(1.into()),
            ),
            (
                ciborium::Value::Text("b".to_string()),
                ciborium::Value::Integer(2.into()),
            ),
        ]);
        let map2 = ciborium::Value::Map(vec![
            (
                ciborium::Value::Text("b".to_string()),
                ciborium::Value::Integer(2.into()),
            ),
            (
                ciborium::Value::Text("a".to_string()),
                ciborium::Value::Integer(1.into()),
            ),
        ]);
        // With the current implementation, positional comparison means different
        // key orders are NOT equal.
        let mut e1 = BTreeMap::new();
        e1.insert("data".to_string(), map1);
        let mut e2 = BTreeMap::new();
        e2.insert("data".to_string(), map2);

        let (common, remaining) = compute_common(&[e1, e2]);
        // "data" will NOT be common because the maps differ positionally.
        // This is the expected behavior: canonical encoding ensures maps are
        // always in sorted order, so this scenario only arises with
        // non-canonical input.
        assert!(common.is_empty());
        assert_eq!(remaining[0].len(), 1);
        assert_eq!(remaining[1].len(), 1);
    }

    // ── cbor_to_global_metadata error paths ──────────────────────────

    fn to_cbor(value: &ciborium::Value) -> Vec<u8> {
        let mut bytes = Vec::new();
        ciborium::into_writer(value, &mut bytes).unwrap();
        bytes
    }

    #[test]
    fn cbor_to_global_metadata_rejects_non_map_top_level() {
        // A bare array (not a map) at the top level must error.
        let bytes = to_cbor(&ciborium::Value::Array(vec![ciborium::Value::Integer(
            1.into(),
        )]));
        let err = cbor_to_global_metadata(&bytes).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => assert!(msg.contains("not a map"), "msg: {msg}"),
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn cbor_to_global_metadata_rejects_invalid_cbor() {
        // Truncated / garbage bytes surface as a parse error.
        let err = cbor_to_global_metadata(&[0xff, 0xff, 0xff]).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => assert!(msg.contains("failed to parse"), "msg: {msg}"),
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn cbor_to_global_metadata_rejects_base_wrong_shape() {
        // `base` must deserialize to a Vec<Map>; supplying an integer
        // triggers the deserialize-error branch.
        use ciborium::Value;
        let bytes = to_cbor(&Value::Map(vec![(
            Value::Text("base".to_string()),
            Value::Integer(42.into()),
        )]));
        let err = cbor_to_global_metadata(&bytes).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("deserialize base"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn cbor_to_global_metadata_rejects_reserved_wrong_shape() {
        use ciborium::Value;
        let bytes = to_cbor(&Value::Map(vec![(
            Value::Text("_reserved_".to_string()),
            Value::Integer(42.into()),
        )]));
        let err = cbor_to_global_metadata(&bytes).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("deserialize _reserved_"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn cbor_to_global_metadata_rejects_extra_wrong_shape() {
        use ciborium::Value;
        let bytes = to_cbor(&Value::Map(vec![(
            Value::Text("_extra_".to_string()),
            Value::Integer(42.into()),
        )]));
        let err = cbor_to_global_metadata(&bytes).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("deserialize _extra_"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    // ── cbor_kind_label covers every non-text variant (138-145) ──────

    #[test]
    fn cbor_to_global_metadata_non_text_key_labels() {
        use ciborium::Value;
        // Each non-text top-level key produces a distinctive label in
        // the error message — exercises the cbor_kind_label arms.
        let cases: Vec<(Value, &str)> = vec![
            (Value::Float(1.0), "float"),
            (Value::Bool(true), "boolean"),
            (Value::Null, "null"),
            (Value::Tag(1, Box::new(Value::Integer(0.into()))), "tagged"),
            (Value::Array(vec![]), "array"),
            (Value::Bytes(vec![1]), "byte-string"),
        ];
        for (key, needle) in cases {
            let bytes = to_cbor(&Value::Map(vec![(key, Value::Integer(0.into()))]));
            let err = cbor_to_global_metadata(&bytes).unwrap_err();
            match err {
                TensogramError::Metadata(msg) => {
                    assert!(msg.contains(needle), "expected {needle:?} in: {msg}")
                }
                other => panic!("expected Metadata error, got: {other:?}"),
            }
        }
    }

    // ── cbor_value_kind covers every variant (157-169) ───────────────

    #[test]
    fn cbor_value_kind_labels_all_variants() {
        use ciborium::Value;
        assert_eq!(cbor_value_kind(&Value::Integer(0.into())), "integer");
        assert_eq!(cbor_value_kind(&Value::Bytes(vec![])), "byte-string");
        assert_eq!(cbor_value_kind(&Value::Float(0.0)), "float");
        assert_eq!(cbor_value_kind(&Value::Bool(false)), "boolean");
        assert_eq!(cbor_value_kind(&Value::Null), "null");
        assert_eq!(
            cbor_value_kind(&Value::Tag(1, Box::new(Value::Null))),
            "tagged value"
        );
        assert_eq!(cbor_value_kind(&Value::Array(vec![])), "array");
        assert_eq!(cbor_value_kind(&Value::Map(vec![])), "map");
        assert_eq!(cbor_value_kind(&Value::Text(String::new())), "text");
    }

    // ── cbor_to_index error paths (236-238, 273-277, 266) ────────────

    #[test]
    fn cbor_to_index_rejects_non_map() {
        let bytes = to_cbor(&ciborium::Value::Integer(7.into()));
        let err = cbor_to_index(&bytes).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => assert!(msg.contains("not a map"), "msg: {msg}"),
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn cbor_to_index_rejects_length_mismatch() {
        use ciborium::Value;
        let bytes = to_cbor(&Value::Map(vec![
            (
                Value::Text("offsets".to_string()),
                Value::Array(vec![Value::Integer(0.into()), Value::Integer(10.into())]),
            ),
            (
                Value::Text("lengths".to_string()),
                Value::Array(vec![Value::Integer(10.into())]),
            ),
        ]));
        let err = cbor_to_index(&bytes).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("offsets.len()"), "msg: {msg}");
                assert!(msg.contains("lengths.len()"), "msg: {msg}");
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn cbor_to_index_ignores_unknown_text_key() {
        // Forward-compat: an unknown text key is ignored, not rejected.
        use ciborium::Value;
        let bytes = to_cbor(&Value::Map(vec![
            (
                Value::Text("offsets".to_string()),
                Value::Array(vec![Value::Integer(0.into())]),
            ),
            (
                Value::Text("lengths".to_string()),
                Value::Array(vec![Value::Integer(5.into())]),
            ),
            (
                Value::Text("future_field".to_string()),
                Value::Integer(99.into()),
            ),
        ]));
        let index = cbor_to_index(&bytes).unwrap();
        assert_eq!(index.offsets, vec![0]);
        assert_eq!(index.lengths, vec![5]);
    }

    // ── cbor_to_hash_frame error paths (322-372) ─────────────────────

    #[test]
    fn cbor_to_hash_frame_rejects_non_map() {
        let bytes = to_cbor(&ciborium::Value::Integer(7.into()));
        let err = cbor_to_hash_frame(&bytes).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => assert!(msg.contains("not a map"), "msg: {msg}"),
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn cbor_to_hash_frame_rejects_non_text_algorithm() {
        use ciborium::Value;
        let bytes = to_cbor(&Value::Map(vec![(
            Value::Text("algorithm".to_string()),
            Value::Integer(1.into()),
        )]));
        let err = cbor_to_hash_frame(&bytes).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("algorithm must be text"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn cbor_to_hash_frame_rejects_non_array_hashes() {
        use ciborium::Value;
        let bytes = to_cbor(&Value::Map(vec![(
            Value::Text("hashes".to_string()),
            Value::Integer(1.into()),
        )]));
        let err = cbor_to_hash_frame(&bytes).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("hashes must be an array"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn cbor_to_hash_frame_rejects_non_text_hash_entry() {
        use ciborium::Value;
        let bytes = to_cbor(&Value::Map(vec![(
            Value::Text("hashes".to_string()),
            Value::Array(vec![Value::Integer(1.into())]),
        )]));
        let err = cbor_to_hash_frame(&bytes).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("hash entry must be text"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn cbor_to_hash_frame_ignores_unknown_text_key() {
        use ciborium::Value;
        let bytes = to_cbor(&Value::Map(vec![
            (
                Value::Text("algorithm".to_string()),
                Value::Text("xxh3".to_string()),
            ),
            (
                Value::Text("hashes".to_string()),
                Value::Array(vec![Value::Text("ab".to_string())]),
            ),
            // Legacy v2 keys ignored as unknown.
            (
                Value::Text("object_count".to_string()),
                Value::Integer(1.into()),
            ),
        ]));
        let hf = cbor_to_hash_frame(&bytes).unwrap();
        assert_eq!(hf.algorithm, "xxh3");
        assert_eq!(hf.hashes, vec!["ab".to_string()]);
    }

    // ── cbor_to_u64 / cbor_to_u64_array error paths (485-499) ────────

    #[test]
    fn cbor_to_index_rejects_negative_offset() {
        use ciborium::Value;
        let bytes = to_cbor(&Value::Map(vec![
            (
                Value::Text("offsets".to_string()),
                Value::Array(vec![Value::Integer((-1i64).into())]),
            ),
            (
                Value::Text("lengths".to_string()),
                Value::Array(vec![Value::Integer(5.into())]),
            ),
        ]));
        let err = cbor_to_index(&bytes).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 cbor_to_index_rejects_non_integer_offset() {
        use ciborium::Value;
        let bytes = to_cbor(&Value::Map(vec![(
            Value::Text("offsets".to_string()),
            Value::Array(vec![Value::Text("nope".to_string())]),
        )]));
        let err = cbor_to_index(&bytes).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("must be an integer"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    #[test]
    fn cbor_to_index_rejects_offsets_not_array() {
        use ciborium::Value;
        let bytes = to_cbor(&Value::Map(vec![(
            Value::Text("offsets".to_string()),
            Value::Integer(5.into()),
        )]));
        let err = cbor_to_index(&bytes).unwrap_err();
        match err {
            TensogramError::Metadata(msg) => {
                assert!(msg.contains("must be an array"), "msg: {msg}")
            }
            other => panic!("expected Metadata error, got: {other:?}"),
        }
    }

    // ── Round-trip edge cases: empty + large structures ──────────────

    #[test]
    fn index_round_trip_empty() {
        let index = IndexFrame {
            offsets: vec![],
            lengths: vec![],
        };
        let bytes = index_to_cbor(&index).unwrap();
        let decoded = cbor_to_index(&bytes).unwrap();
        assert!(decoded.offsets.is_empty());
        assert!(decoded.lengths.is_empty());
    }

    #[test]
    fn hash_frame_round_trip_empty() {
        let hf = HashFrame {
            algorithm: "xxh3".to_string(),
            hashes: vec![],
        };
        let bytes = hash_frame_to_cbor(&hf).unwrap();
        let decoded = cbor_to_hash_frame(&bytes).unwrap();
        assert_eq!(decoded.algorithm, "xxh3");
        assert!(decoded.hashes.is_empty());
    }

    #[test]
    fn index_round_trip_large() {
        let n = 10_000u64;
        let index = IndexFrame {
            offsets: (0..n).map(|i| i * 16).collect(),
            lengths: (0..n).map(|_| 16).collect(),
        };
        let bytes = index_to_cbor(&index).unwrap();
        verify_canonical_cbor(&bytes).unwrap();
        let decoded = cbor_to_index(&bytes).unwrap();
        assert_eq!(decoded.offsets.len(), n as usize);
        assert_eq!(decoded.lengths.len(), n as usize);
        assert_eq!(decoded.offsets, index.offsets);
    }
}