asupersync 0.3.1

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! RaptorQ decode proof artifact for explainable failures.
//!
//! This module provides a compact, deterministic artifact that explains
//! how a decode operation proceeded and why it succeeded or failed.
//!
//! # Design Goals
//!
//! 1. **Deterministic**: Same inputs produce identical artifacts
//! 2. **Bounded size**: Explicit caps on unbounded collections
//! 3. **Explainable**: Human-readable failure reasons
//! 4. **Replayable**: Sufficient info to reproduce decoder state transitions

use crate::raptorq::decoder::{DecodeError, InactivationDecoder, ReceivedSymbol};
use crate::types::ObjectId;
use crate::util::DetHasher;
use std::collections::BinaryHeap;
use std::fmt;

/// Maximum number of pivot events to record before truncation.
pub const MAX_PIVOT_EVENTS: usize = 256;

/// Maximum number of received symbol IDs to record.
pub const MAX_RECEIVED_SYMBOLS: usize = 1024;

/// Version of the proof artifact schema.
pub const PROOF_SCHEMA_VERSION: u8 = 2;

// ============================================================================
// Proof artifact types
// ============================================================================

/// A proof-carrying decode artifact that explains the decode process.
///
/// This artifact is produced during decoding and captures:
/// - Configuration and inputs
/// - Key decision points (pivots, inactivation)
/// - Final outcome with explanation
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecodeProof {
    /// Schema version for forward compatibility.
    pub version: u8,
    /// Configuration used for decoding.
    pub config: DecodeConfig,
    /// Summary of received symbols.
    pub received: ReceivedSummary,
    /// Phase 1: Peeling events.
    pub peeling: PeelingTrace,
    /// Phase 2: Inactivation and elimination events.
    pub elimination: EliminationTrace,
    /// Final outcome.
    pub outcome: ProofOutcome,
}

impl DecodeProof {
    /// Create a new proof builder.
    #[must_use]
    #[inline]
    pub fn builder(config: DecodeConfig) -> DecodeProofBuilder {
        DecodeProofBuilder::new(config)
    }

    /// Compute a deterministic hash of the proof for deduplication/verification.
    #[must_use]
    pub fn content_hash(&self) -> u64 {
        use std::hash::{Hash, Hasher};
        let mut hasher = DetHasher::default();
        self.version.hash(&mut hasher);
        self.config.hash(&mut hasher);
        self.received.hash(&mut hasher);
        self.peeling.hash(&mut hasher);
        self.elimination.hash(&mut hasher);
        self.outcome.hash(&mut hasher);
        hasher.finish()
    }

    /// Replay the decode with the provided symbols and verify the proof trace matches.
    ///
    /// Returns a detailed [`ReplayError`] if any divergence is detected.
    pub fn replay_and_verify(&self, symbols: &[ReceivedSymbol]) -> Result<(), ReplayError> {
        let decoder =
            InactivationDecoder::new(self.config.k, self.config.symbol_size, self.config.seed);
        let actual =
            match decoder.decode_with_proof(symbols, self.config.object_id, self.config.sbn) {
                Ok(result) => result.proof,
                Err((_err, proof)) => proof,
            };
        compare_proofs(self, &actual)
    }
}

#[inline]
fn recovered_source_hash(source: &[Vec<u8>]) -> u64 {
    use std::hash::Hasher;

    let mut hasher = DetHasher::default();
    hasher.write_u64(0x5251_5052_4f4f_4653);
    hasher.write_usize(source.len());
    for row in source {
        hasher.write_usize(row.len());
        hasher.write(row);
    }
    hasher.finish()
}

#[derive(Default)]
struct ReceivedEsiMultisetHashState {
    count: u64,
    sum: u64,
    sum_products: u64,
    mix: u64,
}

impl ReceivedEsiMultisetHashState {
    #[inline]
    fn observe(&mut self, esi: u32, is_source: bool) {
        use std::hash::{Hash, Hasher};

        let mut hasher = DetHasher::default();
        (esi, is_source).hash(&mut hasher);
        let digest = hasher.finish();

        self.count = self.count.wrapping_add(1);
        self.sum = self.sum.wrapping_add(digest);
        self.sum_products = self
            .sum_products
            .wrapping_add(digest.wrapping_mul(digest | 1));
        self.mix = self
            .mix
            .wrapping_add(digest.rotate_left(17) ^ digest.wrapping_mul(0x9E37_79B9_7F4A_7C15));
    }

    #[inline]
    fn finish(self) -> u64 {
        use std::hash::{Hash, Hasher};

        let mut hasher = DetHasher::default();
        self.count.hash(&mut hasher);
        self.sum.hash(&mut hasher);
        self.sum_products.hash(&mut hasher);
        self.mix.hash(&mut hasher);
        hasher.finish()
    }
}

// ============================================================================
// Replay verification
// ============================================================================

/// Detailed error for proof replay verification.
#[derive(Debug)]
pub enum ReplayError {
    /// Generic mismatch for scalar fields.
    Mismatch {
        /// Name of the mismatched field.
        field: &'static str,
        /// Expected value (formatted).
        expected: String,
        /// Actual value (formatted).
        actual: String,
    },
    /// Sequence mismatch at a specific index.
    SequenceMismatch {
        /// Name of the sequence being compared.
        label: &'static str,
        /// Index of the first mismatch.
        index: usize,
        /// Expected value at the mismatch (formatted).
        expected: String,
        /// Actual value at the mismatch (formatted).
        actual: String,
    },
}

impl fmt::Display for ReplayError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Mismatch {
                field,
                expected,
                actual,
            } => write!(f, "mismatch for {field}: expected {expected}, got {actual}"),
            Self::SequenceMismatch {
                label,
                index,
                expected,
                actual,
            } => write!(
                f,
                "sequence mismatch for {label} at index {index}: expected {expected}, got {actual}"
            ),
        }
    }
}

impl std::error::Error for ReplayError {}

#[inline]
fn mismatch<T: fmt::Debug>(field: &'static str, expected: T, actual: T) -> ReplayError {
    ReplayError::Mismatch {
        field,
        expected: format!("{expected:?}"),
        actual: format!("{actual:?}"),
    }
}

#[inline]
fn sequence_mismatch(
    label: &'static str,
    index: usize,
    expected: String,
    actual: String,
) -> ReplayError {
    ReplayError::SequenceMismatch {
        label,
        index,
        expected,
        actual,
    }
}

fn compare_prefix<T: PartialEq + fmt::Debug>(
    label: &'static str,
    expected: &[T],
    actual: &[T],
    truncated: bool,
) -> Result<(), ReplayError> {
    if actual.len() != expected.len() {
        let idx = expected.len().min(actual.len());
        let (expected_item, actual_item) = if actual.len() < expected.len() {
            (
                format!("{:?}", expected.get(actual.len())),
                "missing".to_string(),
            )
        } else if truncated {
            (
                format!("len {}", expected.len()),
                format!("len {}", actual.len()),
            )
        } else {
            (
                "missing".to_string(),
                format!("{:?}", actual.get(expected.len())),
            )
        };
        return Err(sequence_mismatch(label, idx, expected_item, actual_item));
    }
    for (idx, (exp, act)) in expected.iter().zip(actual.iter()).enumerate() {
        if exp != act {
            return Err(sequence_mismatch(
                label,
                idx,
                format!("{exp:?}"),
                format!("{act:?}"),
            ));
        }
    }
    Ok(())
}

#[allow(clippy::too_many_lines)]
fn compare_proofs(expected: &DecodeProof, actual: &DecodeProof) -> Result<(), ReplayError> {
    if expected.version != actual.version {
        return Err(mismatch("version", expected.version, actual.version));
    }
    if expected.config != actual.config {
        return Err(mismatch("config", &expected.config, &actual.config));
    }

    let exp_recv = &expected.received;
    let act_recv = &actual.received;
    if exp_recv.total != act_recv.total {
        return Err(mismatch("received.total", exp_recv.total, act_recv.total));
    }
    if exp_recv.source_count != act_recv.source_count {
        return Err(mismatch(
            "received.source_count",
            exp_recv.source_count,
            act_recv.source_count,
        ));
    }
    if exp_recv.repair_count != act_recv.repair_count {
        return Err(mismatch(
            "received.repair_count",
            exp_recv.repair_count,
            act_recv.repair_count,
        ));
    }
    if exp_recv.esi_multiset_hash != act_recv.esi_multiset_hash {
        return Err(mismatch(
            "received.esi_multiset_hash",
            exp_recv.esi_multiset_hash,
            act_recv.esi_multiset_hash,
        ));
    }
    if exp_recv.truncated != act_recv.truncated {
        return Err(mismatch(
            "received.truncated",
            exp_recv.truncated,
            act_recv.truncated,
        ));
    }
    compare_prefix(
        "received.esis",
        &exp_recv.esis,
        &act_recv.esis,
        exp_recv.truncated,
    )?;

    let exp_peel = &expected.peeling;
    let act_peel = &actual.peeling;
    if exp_peel.solved != act_peel.solved {
        return Err(mismatch("peeling.solved", exp_peel.solved, act_peel.solved));
    }
    if exp_peel.truncated != act_peel.truncated {
        return Err(mismatch(
            "peeling.truncated",
            exp_peel.truncated,
            act_peel.truncated,
        ));
    }
    compare_prefix(
        "peeling.solved_indices",
        &exp_peel.solved_indices,
        &act_peel.solved_indices,
        exp_peel.truncated,
    )?;

    let exp_elim = &expected.elimination;
    let act_elim = &actual.elimination;
    if exp_elim.inactivated != act_elim.inactivated {
        return Err(mismatch(
            "elimination.inactivated",
            exp_elim.inactivated,
            act_elim.inactivated,
        ));
    }
    if exp_elim.pivots != act_elim.pivots {
        return Err(mismatch(
            "elimination.pivots",
            exp_elim.pivots,
            act_elim.pivots,
        ));
    }
    if exp_elim.row_ops != act_elim.row_ops {
        return Err(mismatch(
            "elimination.row_ops",
            exp_elim.row_ops,
            act_elim.row_ops,
        ));
    }
    if exp_elim.inactive_cols_truncated != act_elim.inactive_cols_truncated {
        return Err(mismatch(
            "elimination.inactive_cols_truncated",
            exp_elim.inactive_cols_truncated,
            act_elim.inactive_cols_truncated,
        ));
    }
    if exp_elim.pivot_events_truncated != act_elim.pivot_events_truncated {
        return Err(mismatch(
            "elimination.pivot_events_truncated",
            exp_elim.pivot_events_truncated,
            act_elim.pivot_events_truncated,
        ));
    }
    if exp_elim.strategy_transitions_truncated != act_elim.strategy_transitions_truncated {
        return Err(mismatch(
            "elimination.strategy_transitions_truncated",
            exp_elim.strategy_transitions_truncated,
            act_elim.strategy_transitions_truncated,
        ));
    }
    if exp_elim.strategy != act_elim.strategy {
        return Err(mismatch(
            "elimination.strategy",
            exp_elim.strategy,
            act_elim.strategy,
        ));
    }
    compare_prefix(
        "elimination.inactive_cols",
        &exp_elim.inactive_cols,
        &act_elim.inactive_cols,
        exp_elim.inactive_cols_truncated,
    )?;
    compare_prefix(
        "elimination.pivot_events",
        &exp_elim.pivot_events,
        &act_elim.pivot_events,
        exp_elim.pivot_events_truncated,
    )?;
    compare_prefix(
        "elimination.strategy_transitions",
        &exp_elim.strategy_transitions,
        &act_elim.strategy_transitions,
        exp_elim.strategy_transitions_truncated,
    )?;

    if expected.outcome != actual.outcome {
        return Err(mismatch("outcome", &expected.outcome, &actual.outcome));
    }

    Ok(())
}

/// Decode configuration captured in the proof.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct DecodeConfig {
    /// Object ID being decoded.
    pub object_id: ObjectId,
    /// Source block number.
    pub sbn: u8,
    /// Number of source symbols (K).
    pub k: usize,
    /// Number of LDPC symbols (S).
    pub s: usize,
    /// Number of HDPC symbols (H).
    pub h: usize,
    /// Total intermediate symbols (L = K + S + H).
    pub l: usize,
    /// Symbol size in bytes.
    pub symbol_size: usize,
    /// Seed used for encoding.
    pub seed: u64,
}

/// Summary of received symbols.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct ReceivedSummary {
    /// Total symbols received.
    pub total: usize,
    /// Number of source symbols received.
    pub source_count: usize,
    /// Number of repair symbols received.
    pub repair_count: usize,
    /// Deterministic hash of the full received ESI/source multiset.
    ///
    /// This binds replay verification to entries that fall outside the bounded
    /// preview list once `esis` is truncated.
    pub esi_multiset_hash: u64,
    /// ESIs of received symbols (sorted, truncated to MAX_RECEIVED_SYMBOLS).
    pub esis: Vec<u32>,
    /// True if ESI list was truncated.
    pub truncated: bool,
}

impl ReceivedSummary {
    /// Create from a list of (ESI, is_source) pairs.
    ///
    /// ESIs are recorded in deterministic ascending order and truncated
    /// to the smallest MAX_RECEIVED_SYMBOLS entries.
    #[must_use]
    pub fn from_received(symbols: impl Iterator<Item = (u32, bool)>) -> Self {
        let mut source_count = 0;
        let mut repair_count = 0;
        let mut total = 0usize;
        let mut esis_heap: BinaryHeap<u32> = BinaryHeap::new();
        let mut hash_state = ReceivedEsiMultisetHashState::default();

        for (esi, is_source) in symbols {
            total += 1;
            if is_source {
                source_count += 1;
            } else {
                repair_count += 1;
            }
            hash_state.observe(esi, is_source);
            if esis_heap.len() < MAX_RECEIVED_SYMBOLS {
                esis_heap.push(esi);
                continue;
            }
            if let Some(&max) = esis_heap.peek() {
                if esi < max {
                    esis_heap.pop();
                    esis_heap.push(esi);
                }
            }
        }

        let truncated = total > MAX_RECEIVED_SYMBOLS;
        let esi_multiset_hash = hash_state.finish();
        let mut esis = esis_heap.into_vec();
        esis.sort_unstable();
        Self {
            total,
            source_count,
            repair_count,
            esi_multiset_hash,
            esis,
            truncated,
        }
    }
}

/// Trace of peeling (belief propagation) phase.
#[derive(Debug, Clone, Default, Hash, PartialEq, Eq)]
pub struct PeelingTrace {
    /// Number of symbols solved via peeling.
    pub solved: usize,
    /// Intermediate symbol indices solved during peeling.
    pub solved_indices: Vec<usize>,
    /// True if solved_indices was truncated.
    pub truncated: bool,
}

impl PeelingTrace {
    /// Record a solved symbol index.
    pub fn record_solved(&mut self, col: usize) {
        self.solved += 1;
        if self.solved_indices.len() < MAX_PIVOT_EVENTS {
            self.solved_indices.push(col);
        } else {
            self.truncated = true;
        }
    }
}

/// Trace of inactivation and Gaussian elimination phase.
#[derive(Debug, Clone, Default, Hash, PartialEq, Eq)]
pub struct EliminationTrace {
    /// Inactivation strategy selected for this decode.
    pub strategy: InactivationStrategy,
    /// Number of columns marked as inactive.
    pub inactivated: usize,
    /// Column indices that were inactivated.
    pub inactive_cols: Vec<usize>,
    /// Number of pivot selections.
    pub pivots: usize,
    /// Pivot events: (column, pivot_row) pairs.
    pub pivot_events: Vec<PivotEvent>,
    /// True if inactive_cols was truncated.
    pub inactive_cols_truncated: bool,
    /// True if pivot_events was truncated.
    pub pivot_events_truncated: bool,
    /// Number of row operations performed.
    pub row_ops: usize,
    /// Strategy transitions recorded during decode.
    pub strategy_transitions: Vec<StrategyTransition>,
    /// True if strategy_transitions was truncated.
    pub strategy_transitions_truncated: bool,
}

impl EliminationTrace {
    /// Set the strategy used by the decoder.
    pub fn set_strategy(&mut self, strategy: InactivationStrategy) {
        self.strategy = strategy;
    }

    /// Record a strategy transition.
    pub fn record_strategy_transition(
        &mut self,
        from: InactivationStrategy,
        to: InactivationStrategy,
        reason: &'static str,
    ) {
        if from == to {
            self.strategy = to;
            return;
        }
        if self.strategy_transitions.len() < MAX_PIVOT_EVENTS {
            self.strategy_transitions
                .push(StrategyTransition { from, to, reason });
        } else {
            self.strategy_transitions_truncated = true;
        }
        self.strategy = to;
    }

    /// Record an inactivated column.
    pub fn record_inactivation(&mut self, col: usize) {
        self.inactivated += 1;
        if self.inactive_cols.len() < MAX_PIVOT_EVENTS {
            self.inactive_cols.push(col);
        } else {
            self.inactive_cols_truncated = true;
        }
    }

    /// Record a pivot selection.
    pub fn record_pivot(&mut self, col: usize, row: usize) {
        self.pivots += 1;
        if self.pivot_events.len() < MAX_PIVOT_EVENTS {
            self.pivot_events.push(PivotEvent { col, row });
        } else {
            self.pivot_events_truncated = true;
        }
    }

    /// Record a row operation.
    pub fn record_row_op(&mut self) {
        self.row_ops += 1;
    }
}

/// Inactivation strategy used by the decoder.
#[derive(Debug, Clone, Copy, Default, Hash, PartialEq, Eq)]
pub enum InactivationStrategy {
    /// Legacy behavior: inactivate all remaining unsolved columns in their natural order.
    #[default]
    AllAtOnce,
    /// Hard-regime behavior: inactivate columns ordered by descending equation support.
    HighSupportFirst,
    /// Accelerated hard-regime behavior: deterministic block-Schur partitioning with
    /// conservative fallback to high-support ordering when assumptions break.
    BlockSchurLowRank,
}

/// A single strategy transition event.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct StrategyTransition {
    /// Previous strategy.
    pub from: InactivationStrategy,
    /// New strategy.
    pub to: InactivationStrategy,
    /// Deterministic reason for the transition.
    pub reason: &'static str,
}

/// A single pivot selection event.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct PivotEvent {
    /// Column being eliminated.
    pub col: usize,
    /// Row selected as pivot.
    pub row: usize,
}

/// Final decode outcome.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum ProofOutcome {
    /// Decode succeeded.
    Success {
        /// Total source symbols recovered.
        symbols_recovered: usize,
        /// Deterministic hash of the recovered source payload.
        source_payload_hash: u64,
    },
    /// Decode failed with a specific reason.
    Failure {
        /// The error that occurred.
        reason: FailureReason,
    },
}

/// Detailed failure reason for proof artifact.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum FailureReason {
    /// Not enough symbols received.
    InsufficientSymbols {
        /// Symbols received.
        received: usize,
        /// Symbols required.
        required: usize,
    },
    /// Matrix became singular during elimination.
    SingularMatrix {
        /// Row that couldn't find a pivot.
        row: usize,
        /// Columns that were attempted.
        attempted_cols: Vec<usize>,
    },
    /// Symbol size mismatch.
    SymbolSizeMismatch {
        /// Expected size.
        expected: usize,
        /// Actual size.
        actual: usize,
    },
    /// Received symbol has mismatched equation vectors.
    SymbolEquationArityMismatch {
        /// ESI of malformed symbol.
        esi: u32,
        /// Number of column indices.
        columns: usize,
        /// Number of coefficients.
        coefficients: usize,
    },
    /// Received symbol references an invalid column outside [0, L).
    ColumnIndexOutOfRange {
        /// ESI of malformed symbol.
        esi: u32,
        /// Offending column index.
        column: usize,
        /// Exclusive upper bound for valid columns.
        max_valid: usize,
    },
    /// A source symbol used an ESI outside the systematic source domain [0, K).
    SourceEsiOutOfRange {
        /// ESI of malformed source symbol.
        esi: u32,
        /// Exclusive upper bound for valid source ESIs.
        max_valid: usize,
    },
    /// A source symbol did not use the required identity equation `C[esi] = data`.
    InvalidSourceSymbolEquation {
        /// ESI of malformed source symbol.
        esi: u32,
        /// Required intermediate column for that source symbol.
        expected_column: usize,
    },
    /// Decoder produced output that failed equation verification.
    CorruptDecodedOutput {
        /// ESI of mismatched equation row.
        esi: u32,
        /// First mismatching byte index.
        byte_index: usize,
        /// Reconstructed byte from decoded intermediate symbols.
        expected: u8,
        /// Received RHS byte from input symbol.
        actual: u8,
    },
}

impl From<&DecodeError> for FailureReason {
    fn from(err: &DecodeError) -> Self {
        match err {
            DecodeError::InsufficientSymbols { received, required } => Self::InsufficientSymbols {
                received: *received,
                required: *required,
            },
            DecodeError::SingularMatrix { row } => Self::SingularMatrix {
                row: *row,
                attempted_cols: Vec::new(), // Filled in by caller if available
            },
            DecodeError::SymbolSizeMismatch { expected, actual } => Self::SymbolSizeMismatch {
                expected: *expected,
                actual: *actual,
            },
            DecodeError::SymbolEquationArityMismatch {
                esi,
                columns,
                coefficients,
            } => Self::SymbolEquationArityMismatch {
                esi: *esi,
                columns: *columns,
                coefficients: *coefficients,
            },
            DecodeError::ColumnIndexOutOfRange {
                esi,
                column,
                max_valid,
            } => Self::ColumnIndexOutOfRange {
                esi: *esi,
                column: *column,
                max_valid: *max_valid,
            },
            DecodeError::SourceEsiOutOfRange { esi, max_valid } => Self::SourceEsiOutOfRange {
                esi: *esi,
                max_valid: *max_valid,
            },
            DecodeError::InvalidSourceSymbolEquation {
                esi,
                expected_column,
            } => Self::InvalidSourceSymbolEquation {
                esi: *esi,
                expected_column: *expected_column,
            },
            DecodeError::CorruptDecodedOutput {
                esi,
                byte_index,
                expected,
                actual,
            } => Self::CorruptDecodedOutput {
                esi: *esi,
                byte_index: *byte_index,
                expected: *expected,
                actual: *actual,
            },
        }
    }
}

// ============================================================================
// Builder for incremental construction
// ============================================================================

/// Builder for constructing a decode proof incrementally.
#[derive(Debug)]
pub struct DecodeProofBuilder {
    config: DecodeConfig,
    received: Option<ReceivedSummary>,
    peeling: PeelingTrace,
    elimination: EliminationTrace,
    outcome: Option<ProofOutcome>,
}

impl DecodeProofBuilder {
    /// Create a new builder with the given configuration.
    #[must_use]
    pub fn new(config: DecodeConfig) -> Self {
        Self {
            config,
            received: None,
            peeling: PeelingTrace::default(),
            elimination: EliminationTrace::default(),
            outcome: None,
        }
    }

    /// Set the received symbols summary.
    pub fn set_received(&mut self, received: ReceivedSummary) {
        self.received = Some(received);
    }

    /// Get mutable access to the peeling trace.
    pub fn peeling_mut(&mut self) -> &mut PeelingTrace {
        &mut self.peeling
    }

    /// Get mutable access to the elimination trace.
    pub fn elimination_mut(&mut self) -> &mut EliminationTrace {
        &mut self.elimination
    }

    /// Mark decode as successful.
    pub fn set_success(&mut self, recovered_source: &[Vec<u8>]) {
        self.outcome = Some(ProofOutcome::Success {
            symbols_recovered: recovered_source.len(),
            source_payload_hash: recovered_source_hash(recovered_source),
        });
    }

    /// Mark decode as failed.
    pub fn set_failure(&mut self, reason: FailureReason) {
        self.outcome = Some(ProofOutcome::Failure { reason });
    }

    /// Build the final proof artifact.
    ///
    /// # Panics
    ///
    /// Panics if received or outcome hasn't been set.
    #[must_use]
    pub fn build(self) -> DecodeProof {
        DecodeProof {
            version: PROOF_SCHEMA_VERSION,
            config: self.config,
            received: self.received.expect("received must be set before build"),
            peeling: self.peeling,
            elimination: self.elimination,
            outcome: self.outcome.expect("outcome must be set before build"),
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::raptorq::decoder::{InactivationDecoder, ReceivedSymbol};
    use crate::raptorq::systematic::SystematicEncoder;
    use serde_json::json;

    fn make_test_config() -> DecodeConfig {
        DecodeConfig {
            object_id: ObjectId::new(0, 1),
            sbn: 0,
            k: 10,
            s: 3,
            h: 2,
            l: 15,
            symbol_size: 64,
            seed: 42,
        }
    }

    fn make_test_recovered(config: &DecodeConfig) -> Vec<Vec<u8>> {
        vec![vec![0u8; config.symbol_size]; config.k]
    }

    fn scrub_failure_reason_for_snapshot_test(reason: &FailureReason) -> serde_json::Value {
        match reason {
            FailureReason::InsufficientSymbols { received, required } => json!({
                "kind": "InsufficientSymbols",
                "received": received,
                "required": required,
            }),
            FailureReason::SingularMatrix {
                row,
                attempted_cols,
            } => json!({
                "kind": "SingularMatrix",
                "row": row,
                "attempted_cols": attempted_cols,
            }),
            FailureReason::SymbolSizeMismatch { expected, actual } => json!({
                "kind": "SymbolSizeMismatch",
                "expected": expected,
                "actual": actual,
            }),
            FailureReason::SymbolEquationArityMismatch {
                esi,
                columns,
                coefficients,
            } => json!({
                "kind": "SymbolEquationArityMismatch",
                "esi": esi,
                "columns": columns,
                "coefficients": coefficients,
            }),
            FailureReason::ColumnIndexOutOfRange {
                esi,
                column,
                max_valid,
            } => json!({
                "kind": "ColumnIndexOutOfRange",
                "esi": esi,
                "column": column,
                "max_valid": max_valid,
            }),
            FailureReason::SourceEsiOutOfRange { esi, max_valid } => json!({
                "kind": "SourceEsiOutOfRange",
                "esi": esi,
                "max_valid": max_valid,
            }),
            FailureReason::InvalidSourceSymbolEquation {
                esi,
                expected_column,
            } => json!({
                "kind": "InvalidSourceSymbolEquation",
                "esi": esi,
                "expected_column": expected_column,
            }),
            FailureReason::CorruptDecodedOutput {
                esi,
                byte_index,
                expected,
                actual,
            } => json!({
                "kind": "CorruptDecodedOutput",
                "esi": esi,
                "byte_index": byte_index,
                "expected": expected,
                "actual": actual,
            }),
        }
    }

    fn scrub_decode_proof_for_snapshot_test(proof: &DecodeProof) -> serde_json::Value {
        json!({
            "version": proof.version,
            "content_hash": proof.content_hash(),
            "config": {
                "object_id": "[object_id]",
                "sbn": proof.config.sbn,
                "k": proof.config.k,
                "s": proof.config.s,
                "h": proof.config.h,
                "l": proof.config.l,
                "symbol_size": proof.config.symbol_size,
                "seed": "[seed]",
            },
            "received": {
                "total": proof.received.total,
                "source_count": proof.received.source_count,
                "repair_count": proof.received.repair_count,
                "esi_multiset_hash": proof.received.esi_multiset_hash,
                "esis": proof.received.esis,
                "truncated": proof.received.truncated,
            },
            "peeling": {
                "solved": proof.peeling.solved,
                "solved_indices": proof.peeling.solved_indices,
                "truncated": proof.peeling.truncated,
            },
            "elimination": {
                "strategy": format!("{:?}", proof.elimination.strategy),
                "inactivated": proof.elimination.inactivated,
                "inactive_cols": proof.elimination.inactive_cols,
                "inactive_cols_truncated": proof.elimination.inactive_cols_truncated,
                "pivots": proof.elimination.pivots,
                "pivot_events": proof
                    .elimination
                    .pivot_events
                    .iter()
                    .map(|event| json!({"col": event.col, "row": event.row}))
                    .collect::<Vec<_>>(),
                "pivot_events_truncated": proof.elimination.pivot_events_truncated,
                "row_ops": proof.elimination.row_ops,
                "strategy_transitions": proof
                    .elimination
                    .strategy_transitions
                    .iter()
                    .map(|transition| {
                        json!({
                            "from": format!("{:?}", transition.from),
                            "to": format!("{:?}", transition.to),
                            "reason": transition.reason,
                        })
                    })
                    .collect::<Vec<_>>(),
                "strategy_transitions_truncated": proof.elimination.strategy_transitions_truncated,
            },
            "outcome": match &proof.outcome {
                ProofOutcome::Success {
                    symbols_recovered,
                    source_payload_hash,
                } => json!({
                    "kind": "Success",
                    "symbols_recovered": symbols_recovered,
                    "source_payload_hash": source_payload_hash,
                }),
                ProofOutcome::Failure { reason } => json!({
                    "kind": "Failure",
                    "reason": scrub_failure_reason_for_snapshot_test(reason),
                }),
            },
        })
    }

    fn make_success_proof_for_snapshot_test() -> DecodeProof {
        let config = make_test_config();
        let recovered = make_test_recovered(&config);
        let mut builder = DecodeProof::builder(config);

        builder.set_received(ReceivedSummary::from_received(
            (0..15).map(|esi| (esi, esi < 10)),
        ));
        builder.peeling_mut().record_solved(0);
        builder.peeling_mut().record_solved(4);
        builder.peeling_mut().record_solved(7);

        let elimination = builder.elimination_mut();
        elimination.set_strategy(InactivationStrategy::AllAtOnce);
        elimination.record_strategy_transition(
            InactivationStrategy::AllAtOnce,
            InactivationStrategy::HighSupportFirst,
            "dense_repair_mix",
        );
        elimination.record_inactivation(11);
        elimination.record_pivot(11, 2);
        elimination.record_row_op();
        elimination.record_pivot(13, 5);
        elimination.record_row_op();

        builder.set_success(&recovered);
        builder.build()
    }

    fn make_degraded_singular_proof_for_snapshot_test() -> DecodeProof {
        let mut config = make_test_config();
        config.seed = 1337;
        let mut builder = DecodeProof::builder(config);

        builder.set_received(ReceivedSummary::from_received(
            [(0, true), (1, true), (3, true), (10, false), (11, false)].into_iter(),
        ));
        builder.peeling_mut().record_solved(0);

        let elimination = builder.elimination_mut();
        elimination.set_strategy(InactivationStrategy::HighSupportFirst);
        elimination.record_inactivation(8);
        elimination.record_inactivation(9);
        elimination.record_pivot(8, 1);
        elimination.record_row_op();
        elimination.record_strategy_transition(
            InactivationStrategy::HighSupportFirst,
            InactivationStrategy::BlockSchurLowRank,
            "rank_drop_detected",
        );

        builder.set_failure(FailureReason::SingularMatrix {
            row: 6,
            attempted_cols: vec![8, 9, 12],
        });
        builder.build()
    }

    fn make_degraded_insufficient_proof_for_snapshot_test() -> DecodeProof {
        let mut config = make_test_config();
        config.seed = 7;
        let required = config.l;
        let mut builder = DecodeProof::builder(config);

        builder.set_received(ReceivedSummary::from_received(
            (0..6).map(|esi| (esi, true)),
        ));
        builder.peeling_mut().record_solved(1);
        builder.peeling_mut().record_solved(2);
        builder
            .elimination_mut()
            .set_strategy(InactivationStrategy::AllAtOnce);

        builder.set_failure(FailureReason::InsufficientSymbols {
            received: 6,
            required,
        });
        builder.build()
    }

    fn make_source_block_payload_for_snapshot_test(
        k: usize,
        symbol_size: usize,
        salt: u8,
    ) -> Vec<Vec<u8>> {
        (0..k)
            .map(|i| {
                (0..symbol_size)
                    .map(|j| ((i * 37 + j * 19 + usize::from(salt)) % 256) as u8)
                    .collect()
            })
            .collect()
    }

    fn make_known_good_source_block_proof_for_snapshot_test() -> DecodeProof {
        let k = 8;
        let symbol_size = 32;
        let seed = 2026;
        let source = make_source_block_payload_for_snapshot_test(k, symbol_size, 0x21);
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let mut received = decoder.constraint_symbols();

        for (esi, data) in source.iter().enumerate() {
            received.push(ReceivedSymbol::source(esi as u32, data.clone()));
        }

        let proof = decoder
            .decode_with_proof(&received, ObjectId::new_for_test(2026), 0)
            .expect("known-good source block should decode")
            .proof;
        assert!(
            matches!(proof.outcome, ProofOutcome::Success { .. }),
            "known-good snapshot scenario must produce a success certificate"
        );
        proof
    }

    fn make_known_bad_source_block_proof_for_snapshot_test() -> DecodeProof {
        let k = 8;
        let symbol_size = 32;
        let seed = 2026;
        let source = make_source_block_payload_for_snapshot_test(k, symbol_size, 0x4D);
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let mut received = decoder.constraint_symbols();

        for (esi, data) in source.iter().enumerate().take(4) {
            received.push(ReceivedSymbol::source(esi as u32, data.clone()));
        }

        let (_err, proof) = decoder
            .decode_with_proof(&received, ObjectId::new_for_test(3030), 0)
            .expect_err("known-bad source block should fail decode");
        assert!(
            matches!(proof.outcome, ProofOutcome::Failure { .. }),
            "known-bad snapshot scenario must produce a failure certificate"
        );
        proof
    }

    #[test]
    fn proof_builder_success() {
        let config = make_test_config();
        let recovered = make_test_recovered(&config);
        let mut builder = DecodeProof::builder(config);

        builder.set_received(ReceivedSummary {
            total: 15,
            source_count: 10,
            repair_count: 5,
            esi_multiset_hash: 123,
            esis: (0..15).collect(),
            truncated: false,
        });

        builder.peeling_mut().record_solved(0);
        builder.peeling_mut().record_solved(1);

        builder.elimination_mut().record_inactivation(2);
        builder.elimination_mut().record_pivot(2, 0);
        builder.elimination_mut().record_row_op();

        builder.set_success(&recovered);

        let proof = builder.build();

        assert_eq!(proof.version, PROOF_SCHEMA_VERSION);
        assert_eq!(proof.peeling.solved, 2);
        assert_eq!(proof.elimination.pivots, 1);
        assert!(matches!(proof.outcome, ProofOutcome::Success { .. }));
    }

    #[test]
    fn proof_builder_failure() {
        let config = make_test_config();
        let mut builder = DecodeProof::builder(config);

        builder.set_received(ReceivedSummary {
            total: 5,
            source_count: 5,
            repair_count: 0,
            esi_multiset_hash: 456,
            esis: (0..5).collect(),
            truncated: false,
        });

        builder.set_failure(FailureReason::InsufficientSymbols {
            received: 5,
            required: 15,
        });

        let proof = builder.build();

        assert!(matches!(
            proof.outcome,
            ProofOutcome::Failure {
                reason: FailureReason::InsufficientSymbols { .. }
            }
        ));
    }

    #[test]
    fn decode_proof_certificate_scrubbed() {
        let success = make_success_proof_for_snapshot_test();
        let degraded_singular = make_degraded_singular_proof_for_snapshot_test();
        let degraded_insufficient = make_degraded_insufficient_proof_for_snapshot_test();
        let source_block_success = make_known_good_source_block_proof_for_snapshot_test();
        let source_block_failure = make_known_bad_source_block_proof_for_snapshot_test();

        insta::assert_json_snapshot!(
            "decode_proof_certificate_scrubbed",
            json!({
                "success": scrub_decode_proof_for_snapshot_test(&success),
                "degraded_singular": scrub_decode_proof_for_snapshot_test(&degraded_singular),
                "degraded_insufficient": scrub_decode_proof_for_snapshot_test(&degraded_insufficient),
                "source_block_success": scrub_decode_proof_for_snapshot_test(&source_block_success),
                "source_block_failure": scrub_decode_proof_for_snapshot_test(&source_block_failure),
            })
        );
    }

    #[test]
    fn source_block_decode_proof_hashes_are_stable() {
        let success1 = make_known_good_source_block_proof_for_snapshot_test();
        let success2 = make_known_good_source_block_proof_for_snapshot_test();
        let failure1 = make_known_bad_source_block_proof_for_snapshot_test();
        let failure2 = make_known_bad_source_block_proof_for_snapshot_test();

        assert_eq!(success1.content_hash(), success2.content_hash());
        assert_eq!(failure1.content_hash(), failure2.content_hash());
    }

    #[test]
    fn received_summary_truncation() {
        let symbols = (0..2000).map(|i| (i, i < 1000));
        let summary = ReceivedSummary::from_received(symbols);

        assert_eq!(summary.total, 2000);
        assert_eq!(summary.source_count, 1000);
        assert_eq!(summary.repair_count, 1000);
        assert_eq!(summary.esis.len(), MAX_RECEIVED_SYMBOLS);
        assert!(summary.truncated);
    }

    #[test]
    fn received_summary_hash_changes_when_high_esis_change_beyond_preview() {
        let total = MAX_RECEIVED_SYMBOLS as u32 + 8;
        let original = ReceivedSummary::from_received((0..total).map(|esi| (esi, esi < 8)));
        let mutated = ReceivedSummary::from_received(
            (0..(total - 1))
                .map(|esi| (esi, esi < 8))
                .chain(std::iter::once((u32::MAX - 7, false))),
        );

        assert_eq!(original.total, mutated.total);
        assert_eq!(original.source_count, mutated.source_count);
        assert_eq!(original.repair_count, mutated.repair_count);
        assert_eq!(
            original.esis, mutated.esis,
            "preview ESIs should stay identical when only higher truncated ESIs differ"
        );
        assert!(original.truncated);
        assert!(mutated.truncated);
        assert_ne!(
            original.esi_multiset_hash, mutated.esi_multiset_hash,
            "full multiset hash must distinguish divergence beyond the preview window"
        );
    }

    #[test]
    fn received_summary_hash_is_order_independent_for_same_multiset() {
        let ordered = [
            (9, false),
            (1, true),
            (7, false),
            (1, true),
            (4, false),
            (2, true),
        ];
        let permuted = [
            (2, true),
            (4, false),
            (1, true),
            (9, false),
            (1, true),
            (7, false),
        ];

        let ordered_summary = ReceivedSummary::from_received(ordered.into_iter());
        let permuted_summary = ReceivedSummary::from_received(permuted.into_iter());

        assert_eq!(ordered_summary.total, permuted_summary.total);
        assert_eq!(ordered_summary.source_count, permuted_summary.source_count);
        assert_eq!(ordered_summary.repair_count, permuted_summary.repair_count);
        assert_eq!(ordered_summary.esis, permuted_summary.esis);
        assert_eq!(
            ordered_summary.esi_multiset_hash, permuted_summary.esi_multiset_hash,
            "multiset hash must remain stable across input orderings"
        );
    }

    #[test]
    fn content_hash_deterministic() {
        let config = make_test_config();
        let recovered = make_test_recovered(&config);
        let mut builder1 = DecodeProof::builder(config.clone());
        let mut builder2 = DecodeProof::builder(config);

        for builder in [&mut builder1, &mut builder2] {
            builder.set_received(ReceivedSummary {
                total: 15,
                source_count: 10,
                repair_count: 5,
                esi_multiset_hash: 999,
                esis: (0..15).collect(),
                truncated: false,
            });
            builder.set_success(&recovered);
        }

        let proof1 = builder1.build();
        let proof2 = builder2.build();

        assert_eq!(proof1.content_hash(), proof2.content_hash());
    }

    #[test]
    fn recovered_source_hash_binds_symbol_boundaries() {
        let split_symbols = vec![vec![0x10, 0x20], vec![0x30, 0x40]];
        let merged_suffix = vec![vec![0x10], vec![0x20, 0x30, 0x40]];

        assert_eq!(
            split_symbols.concat(),
            merged_suffix.concat(),
            "test setup should keep the flattened payload identical"
        );
        assert_ne!(
            recovered_source_hash(&split_symbols),
            recovered_source_hash(&merged_suffix),
            "proof success hash must bind per-symbol boundaries, not just flattened bytes"
        );
    }

    #[test]
    fn recovered_source_hash_binds_symbol_order() {
        let ordered = vec![vec![0xAA, 0x01], vec![0xBB, 0x02], vec![0xCC, 0x03]];
        let reordered = vec![vec![0xCC, 0x03], vec![0xBB, 0x02], vec![0xAA, 0x01]];

        assert_ne!(
            recovered_source_hash(&ordered),
            recovered_source_hash(&reordered),
            "proof success hash must distinguish reordered recovered source symbols"
        );
    }

    #[test]
    fn replay_verification_roundtrip() {
        let k = 8;
        let symbol_size = 32;
        let seed = 99u64;

        let source: Vec<Vec<u8>> = (0..k)
            .map(|i| {
                (0..symbol_size)
                    .map(|j| ((i * 53 + j * 19 + 3) % 256) as u8)
                    .collect()
            })
            .collect();

        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        // Start with constraint symbols (LDPC + HDPC with zero data)
        let mut received = decoder.constraint_symbols();

        // Add source symbols
        for (i, data) in source.iter().enumerate() {
            received.push(ReceivedSymbol::source(i as u32, data.clone()));
        }

        // Add repair symbols
        for esi in (k as u32)..(l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let object_id = ObjectId::new_for_test(777);
        let proof = decoder
            .decode_with_proof(&received, object_id, 0)
            .expect("decode should succeed")
            .proof;

        proof
            .replay_and_verify(&received)
            .expect("replay verification should succeed");
    }

    // Pure data-type tests (wave 18 – CyanBarn)

    #[test]
    fn decode_config_debug_clone_hash_eq() {
        let cfg = make_test_config();
        let cfg2 = cfg.clone();
        assert_eq!(cfg, cfg2);
        assert!(format!("{cfg:?}").contains("DecodeConfig"));
    }

    #[test]
    fn received_summary_debug_clone_hash_eq() {
        let summary = ReceivedSummary {
            total: 10,
            source_count: 7,
            repair_count: 3,
            esi_multiset_hash: 789,
            esis: vec![0, 1, 2],
            truncated: false,
        };
        let summary2 = summary.clone();
        assert_eq!(summary, summary2);
        assert!(format!("{summary:?}").contains("ReceivedSummary"));
    }

    #[test]
    fn received_summary_from_received_empty() {
        let summary = ReceivedSummary::from_received(std::iter::empty());
        assert_eq!(summary.total, 0);
        assert_eq!(summary.source_count, 0);
        assert_eq!(summary.repair_count, 0);
        assert!(summary.esis.is_empty());
        assert!(!summary.truncated);
    }

    #[test]
    fn peeling_trace_debug_clone_default_hash_eq() {
        let trace = PeelingTrace::default();
        let trace2 = trace.clone();
        assert_eq!(trace, trace2);
        assert_eq!(trace.solved, 0);
        assert!(format!("{trace:?}").contains("PeelingTrace"));
    }

    #[test]
    fn peeling_trace_record_solved() {
        let mut trace = PeelingTrace::default();
        trace.record_solved(5);
        trace.record_solved(10);
        assert_eq!(trace.solved, 2);
        assert_eq!(trace.solved_indices, vec![5, 10]);
    }

    #[test]
    fn elimination_trace_debug_clone_default_hash_eq() {
        let trace = EliminationTrace::default();
        let trace2 = trace.clone();
        assert_eq!(trace, trace2);
        assert!(format!("{trace:?}").contains("EliminationTrace"));
    }

    #[test]
    fn elimination_trace_record_operations() {
        let mut trace = EliminationTrace::default();
        trace.record_inactivation(3);
        trace.record_pivot(3, 0);
        trace.record_row_op();
        assert_eq!(trace.inactivated, 1);
        assert_eq!(trace.pivots, 1);
        assert_eq!(trace.row_ops, 1);
        assert_eq!(trace.pivot_events.len(), 1);
        assert!(!trace.inactive_cols_truncated);
        assert!(!trace.pivot_events_truncated);
        assert!(!trace.strategy_transitions_truncated);
    }

    #[test]
    fn replay_verification_keeps_non_truncated_elimination_subtraces_strict() {
        let config = make_test_config();
        let recovered = make_test_recovered(&config);
        let mut expected_builder = DecodeProof::builder(config);
        expected_builder.set_received(ReceivedSummary {
            total: 10,
            source_count: 10,
            repair_count: 0,
            esi_multiset_hash: 321,
            esis: (0..10).collect(),
            truncated: false,
        });
        expected_builder.set_success(&recovered);

        let elimination = expected_builder.elimination_mut();
        for col in 0..=MAX_PIVOT_EVENTS {
            elimination.record_inactivation(col);
        }
        elimination.record_pivot(3, 0);
        elimination.record_strategy_transition(
            InactivationStrategy::AllAtOnce,
            InactivationStrategy::HighSupportFirst,
            "dense_or_near_square",
        );

        let expected = expected_builder.build();
        assert!(expected.elimination.inactive_cols_truncated);
        assert!(!expected.elimination.pivot_events_truncated);
        assert!(!expected.elimination.strategy_transitions_truncated);

        let mut actual = expected.clone();
        actual
            .elimination
            .pivot_events
            .push(PivotEvent { col: 9, row: 1 });

        let err = compare_proofs(&expected, &actual)
            .expect_err("extra non-truncated pivot events must fail replay verification");
        assert!(
            err.to_string().contains("elimination.pivot_events"),
            "mismatch should point directly at the non-truncated elimination sub-trace"
        );
    }

    #[test]
    fn replay_verification_rejects_extra_entries_in_truncated_subtraces() {
        let config = make_test_config();
        let recovered = make_test_recovered(&config);
        let mut expected_builder = DecodeProof::builder(config);
        expected_builder.set_received(ReceivedSummary {
            total: 10,
            source_count: 10,
            repair_count: 0,
            esi_multiset_hash: 321,
            esis: (0..10).collect(),
            truncated: false,
        });
        expected_builder.set_success(&recovered);

        let elimination = expected_builder.elimination_mut();
        for col in 0..=MAX_PIVOT_EVENTS {
            elimination.record_inactivation(col);
        }

        let expected = expected_builder.build();
        assert!(expected.elimination.inactive_cols_truncated);

        let mut actual = expected.clone();
        actual.elimination.inactive_cols.push(MAX_PIVOT_EVENTS + 99);

        let err = compare_proofs(&expected, &actual)
            .expect_err("truncated previews must still reject extra recorded entries");
        assert!(
            err.to_string().contains("elimination.inactive_cols"),
            "mismatch should point directly at the truncated elimination preview"
        );
    }

    #[test]
    fn inactivation_strategy_debug_clone_copy_default_hash_eq() {
        let s = InactivationStrategy::default();
        assert_eq!(s, InactivationStrategy::AllAtOnce);
        let s2 = s;
        assert_eq!(s, s2);
        assert!(format!("{s:?}").contains("AllAtOnce"));
    }

    #[test]
    fn inactivation_strategy_all_variants() {
        let variants = [
            InactivationStrategy::AllAtOnce,
            InactivationStrategy::HighSupportFirst,
            InactivationStrategy::BlockSchurLowRank,
        ];
        for (i, v) in variants.iter().enumerate() {
            for (j, v2) in variants.iter().enumerate() {
                if i == j {
                    assert_eq!(v, v2);
                } else {
                    assert_ne!(v, v2);
                }
            }
        }
    }

    #[test]
    fn strategy_transition_debug_clone_hash_eq() {
        let t = StrategyTransition {
            from: InactivationStrategy::AllAtOnce,
            to: InactivationStrategy::HighSupportFirst,
            reason: "escalation",
        };
        let t2 = t.clone();
        assert_eq!(t, t2);
        assert!(format!("{t:?}").contains("StrategyTransition"));
    }

    #[test]
    fn pivot_event_debug_clone_hash_eq() {
        let p = PivotEvent { col: 3, row: 7 };
        let p2 = p.clone();
        assert_eq!(p, p2);
        assert!(format!("{p:?}").contains("PivotEvent"));
    }

    #[test]
    fn proof_outcome_debug_clone_hash_eq() {
        let success = ProofOutcome::Success {
            symbols_recovered: 10,
            source_payload_hash: 123,
        };
        let success2 = success.clone();
        assert_eq!(success, success2);
        assert!(format!("{success:?}").contains("Success"));

        let fail = ProofOutcome::Failure {
            reason: FailureReason::InsufficientSymbols {
                received: 5,
                required: 10,
            },
        };
        assert_ne!(success, fail);
    }

    #[test]
    fn failure_reason_all_variants() {
        let variants: Vec<FailureReason> = vec![
            FailureReason::InsufficientSymbols {
                received: 1,
                required: 2,
            },
            FailureReason::SingularMatrix {
                row: 0,
                attempted_cols: vec![1, 2],
            },
            FailureReason::SymbolSizeMismatch {
                expected: 64,
                actual: 32,
            },
            FailureReason::SymbolEquationArityMismatch {
                esi: 5,
                columns: 3,
                coefficients: 4,
            },
            FailureReason::ColumnIndexOutOfRange {
                esi: 1,
                column: 99,
                max_valid: 15,
            },
            FailureReason::CorruptDecodedOutput {
                esi: 0,
                byte_index: 7,
                expected: 0xAA,
                actual: 0xBB,
            },
        ];
        for v in &variants {
            assert!(!format!("{v:?}").is_empty());
        }
    }

    #[test]
    fn replay_error_display_mismatch() {
        let err = ReplayError::Mismatch {
            field: "version",
            expected: "1".into(),
            actual: "2".into(),
        };
        let s = err.to_string();
        assert!(s.contains("version"));
        assert!(s.contains("expected"));
        assert!(format!("{err:?}").contains("Mismatch"));
    }

    #[test]
    fn replay_error_display_sequence() {
        let err = ReplayError::SequenceMismatch {
            label: "esis",
            index: 5,
            expected: "10".into(),
            actual: "20".into(),
        };
        let s = err.to_string();
        assert!(s.contains("esis"));
        assert!(s.contains("index 5"));
    }

    #[test]
    fn replay_error_trait() {
        let err: Box<dyn std::error::Error> = Box::new(ReplayError::Mismatch {
            field: "test",
            expected: "a".into(),
            actual: "b".into(),
        });
        assert!(!err.to_string().is_empty());
    }

    #[test]
    fn decode_proof_debug_clone_eq() {
        let config = make_test_config();
        let recovered = make_test_recovered(&config);
        let mut builder = DecodeProof::builder(config);
        builder.set_received(ReceivedSummary {
            total: 10,
            source_count: 10,
            repair_count: 0,
            esi_multiset_hash: 321,
            esis: (0..10).collect(),
            truncated: false,
        });
        builder.set_success(&recovered);
        let proof = builder.build();
        let proof2 = proof.clone();
        assert_eq!(proof, proof2);
        assert!(format!("{proof:?}").contains("DecodeProof"));
    }

    #[test]
    fn decode_proof_builder_debug() {
        let builder = DecodeProof::builder(make_test_config());
        assert!(format!("{builder:?}").contains("DecodeProofBuilder"));
    }

    #[test]
    fn elimination_trace_strategy_transition_same_is_noop() {
        let mut trace = EliminationTrace::default();
        trace.record_strategy_transition(
            InactivationStrategy::AllAtOnce,
            InactivationStrategy::AllAtOnce,
            "noop",
        );
        assert!(trace.strategy_transitions.is_empty());
        assert_eq!(trace.strategy, InactivationStrategy::AllAtOnce);
    }

    #[test]
    fn elimination_trace_strategy_transition_records() {
        let mut trace = EliminationTrace::default();
        trace.record_strategy_transition(
            InactivationStrategy::AllAtOnce,
            InactivationStrategy::HighSupportFirst,
            "escalation",
        );
        assert_eq!(trace.strategy_transitions.len(), 1);
        assert_eq!(trace.strategy, InactivationStrategy::HighSupportFirst);
    }

    #[test]
    fn replay_verification_detects_mismatch() {
        let k = 6;
        let symbol_size = 24;
        let seed = 17u64;

        let source: Vec<Vec<u8>> = (0..k)
            .map(|i| {
                (0..symbol_size)
                    .map(|j| ((i * 41 + j * 11 + 5) % 256) as u8)
                    .collect()
            })
            .collect();

        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let l = decoder.params().l;

        // Start with constraint symbols (LDPC + HDPC with zero data)
        let mut received = decoder.constraint_symbols();

        // Add source symbols
        for (i, data) in source.iter().enumerate() {
            received.push(ReceivedSymbol::source(i as u32, data.clone()));
        }

        // Add repair symbols
        for esi in (k as u32)..(l as u32) {
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let object_id = ObjectId::new_for_test(42);
        let mut proof = decoder
            .decode_with_proof(&received, object_id, 0)
            .expect("decode should succeed")
            .proof;

        proof.elimination.row_ops = proof.elimination.row_ops.saturating_add(1);

        let err = proof
            .replay_and_verify(&received)
            .expect_err("replay should detect mismatch");
        assert!(err.to_string().contains("row_ops"));
    }

    #[test]
    fn replay_verification_rejects_payload_divergent_success() {
        let k = 8;
        let symbol_size = 32;
        let seed = 123u64;

        let make_source = |salt: u8| -> Vec<Vec<u8>> {
            (0..k)
                .map(|i| {
                    (0..symbol_size)
                        .map(|j| ((i * 53 + j * 19 + usize::from(salt)) % 256) as u8)
                        .collect()
                })
                .collect()
        };
        let make_received =
            |decoder: &InactivationDecoder, source: &[Vec<u8>]| -> Vec<ReceivedSymbol> {
                let encoder = SystematicEncoder::new(source, symbol_size, seed).unwrap();
                let l = decoder.params().l;
                let mut received = decoder.constraint_symbols();
                for (i, data) in source.iter().enumerate() {
                    received.push(ReceivedSymbol::source(i as u32, data.clone()));
                }
                for esi in (k as u32)..(l as u32) {
                    let (cols, coefs) = decoder.repair_equation(esi);
                    let repair_data = encoder.repair_symbol(esi);
                    received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
                }
                received
            };

        let source = make_source(3);
        let mutated_source = make_source(11);
        let decoder = InactivationDecoder::new(k, symbol_size, seed);
        let original_received = make_received(&decoder, &source);
        let mutated_received = make_received(&decoder, &mutated_source);
        let object_id = ObjectId::new_for_test(8080);

        let proof = decoder
            .decode_with_proof(&original_received, object_id, 0)
            .expect("original decode should succeed")
            .proof;
        let mutated_result = decoder
            .decode_with_proof(&mutated_received, object_id, 0)
            .expect("mutated decode should still succeed");
        assert_eq!(mutated_result.result.source, mutated_source);
        assert_ne!(mutated_result.result.source, source);

        let err = proof
            .replay_and_verify(&mutated_received)
            .expect_err("payload-divergent replay must fail verification");
        assert!(err.to_string().contains("source_payload_hash"));
    }

    #[test]
    fn replay_verification_rejects_high_esi_divergence_when_received_preview_truncates() {
        let k = 8;
        let symbol_size = 32;
        let seed = 321u64;
        let repair_count = MAX_RECEIVED_SYMBOLS as u32 + 32;

        let source: Vec<Vec<u8>> = (0..k)
            .map(|i| {
                (0..symbol_size)
                    .map(|j| ((i * 37 + j * 17 + 9) % 256) as u8)
                    .collect()
            })
            .collect();
        let encoder = SystematicEncoder::new(&source, symbol_size, seed).unwrap();
        let decoder = InactivationDecoder::new(k, symbol_size, seed);

        let mut original_received = decoder.constraint_symbols();
        for (i, data) in source.iter().enumerate() {
            original_received.push(ReceivedSymbol::source(i as u32, data.clone()));
        }
        for offset in 0..repair_count {
            let esi = k as u32 + offset;
            let (cols, coefs) = decoder.repair_equation(esi);
            let repair_data = encoder.repair_symbol(esi);
            original_received.push(ReceivedSymbol::repair(esi, cols, coefs, repair_data));
        }

        let mut mutated_received = original_received.clone();
        let replaced_esi = k as u32 + repair_count - 1;
        let replacement_esi = replaced_esi + 10_000;
        let (replacement_cols, replacement_coefs) = decoder.repair_equation(replacement_esi);
        let replacement_data = encoder.repair_symbol(replacement_esi);
        let replacement = ReceivedSymbol::repair(
            replacement_esi,
            replacement_cols,
            replacement_coefs,
            replacement_data,
        );
        let replaced_symbol = mutated_received
            .last_mut()
            .expect("repair-heavy test input must contain a trailing repair symbol");
        assert_eq!(replaced_symbol.esi, replaced_esi);
        *replaced_symbol = replacement;

        let object_id = ObjectId::new_for_test(9090);
        let proof = decoder
            .decode_with_proof(&original_received, object_id, 0)
            .expect("original decode should succeed")
            .proof;
        let mutated_result = decoder
            .decode_with_proof(&mutated_received, object_id, 0)
            .expect("mutated decode should still succeed with enough symbols");
        assert_eq!(mutated_result.result.source, source);

        let original_summary =
            ReceivedSummary::from_received(original_received.iter().map(|s| (s.esi, s.is_source)));
        let mutated_summary =
            ReceivedSummary::from_received(mutated_received.iter().map(|s| (s.esi, s.is_source)));
        assert_eq!(
            original_summary.esis, mutated_summary.esis,
            "preview ESIs should not expose the high-ESI divergence"
        );
        assert_ne!(
            original_summary.esi_multiset_hash, mutated_summary.esi_multiset_hash,
            "full multiset binding must distinguish the mutated higher ESI"
        );

        let err = proof
            .replay_and_verify(&mutated_received)
            .expect_err("truncated received-summary replay must reject higher-ESI divergence");
        assert!(err.to_string().contains("received.esi_multiset_hash"));
    }
}