stuffr-core 0.10.4

Core traits, stream ladder and resource governor for the stuffr toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
//! A conformance harness every codec adopts in one line.
//!
//! Phase 1b proved a property about gzip using a test double that lived in
//! gzip's own private test module. That does not survive contact with nine
//! codecs: the double gets copy-pasted, or quietly skipped for exactly the
//! codec where the property is hardest to satisfy. Here, adopting the whole
//! set costs one line and skipping a property is impossible without editing
//! shared code a reviewer reads.
//!
//! Properties that do not apply to a given codec are skipped on evidence
//! rather than on trust: magic from the registered rules, trailer presence by
//! measurement, corruption detection from a declared capability.
//!
//! A codec that cannot encode its own test input — the pure-Rust decode-only
//! fallbacks `Registry::require_decoder` is written for — cannot exercise
//! properties 7 through 10 by itself. [`assert_codec_conforms_with`] accepts a
//! `fixture`: a known-good encoded stream, supplied by the caller, that stands
//! in for the codec's own encode step. A decode-capable codec given neither an
//! `encode` capability nor a fixture skips those properties with a message
//! naming what is missing, rather than silently passing having exercised
//! nothing.
//!
//! Every codec is also checked for identity: `FormatMeta::id` must agree with
//! `Codec::id`, or a mismatched registration is silent. That check is not part
//! of the numbered list below — it is a registration sanity check, not a
//! property of encode/decode behavior — but its panic still says "property 1"
//! for the same reason every other panic is numbered: so a failure names
//! exactly which property broke.
//!
//! The behavioral properties, numbered to match each assertion's panic
//! message:
//!
//! 2. Round trip: encode then decode returns the original bytes, checked
//!    empty, one byte, and with a large incompressible payload.
//! 3. Magic agreement: encoded output matches AT LEAST ONE magic rule the
//!    format registers, so a file this build wrote is a file it can identify.
//!    A format with alternative signatures (lz4's frame and legacy-frame
//!    magics, zstd's legacy magic) registers more than one rule and only one
//!    need match.
//! 4. `finish()` flushes the underlying writer, since `Codec::encoder` takes
//!    the destination by value and leaves the caller no handle to do it.
//! 5. `finish()` surfaces a write error that `Drop` would otherwise swallow.
//!    The failure threshold is measured per codec by counting bytes written
//!    by a real encode, not assumed — a wrong threshold tests `Write` instead
//!    of `finish`, or never fails at all.
//! 6. An out-of-range level — probed at both ends, `i32::MIN` and `i32::MAX`,
//!    not just the upper bound — is either accepted or a `Usage` error, never
//!    a panic or another error variant, and `encoder()` agrees with
//!    `check_encode_opts()` on the same options.
//! 7. The decoder claims random access only if the format declares a frame
//!    index, or a container above it would seek and read the wrong bytes.
//! 8. Decoding is incremental, not read-to-end: output must begin long before
//!    the input is exhausted. The threshold is relative to the stream's own
//!    length, not an absolute figure tuned to one codec's window.
//! 9. Corrupted input is reported as `InvalidData`, run for every declared
//!    `detects_corruption` state except [`CorruptionDetection::Never`] — a
//!    format with no integrity check genuinely cannot detect corruption, and
//!    demanding it would force a fake. Swept over BOTH an incompressible and
//!    a compressible payload: an incompressible-only fixture left this
//!    property blind to two codecs whose corrupted-decode failure path is
//!    only reached through a compressible stream's match/back-reference
//!    structure — see [`compressible`]'s doc.
//! 10. Truncated input is rejected — or, for a codec declaring
//!     `CodecCaps::truncation_undetectable`, decodes to a genuine PREFIX of
//!     the untruncated output that never shrinks as truncation eases
//!     (monotonicity across the swept cuts) and is never trivially empty
//!     once the untruncated decode is not. Unlike property 9, nothing
//!     switches this off to a bare skip: every framed format detects
//!     premature EOF regardless of checksum, so a codec failing the strict
//!     form should either detect truncation or be reconsidered. This is not
//!     the same guarantee as property 9's: even a raw, unframed stream can
//!     often still catch truncation structurally — raw deflate has no
//!     checksum (so corruption decodes to silently wrong bytes, property 9's
//!     exact gap) but its `BFINAL` bit means a stream cut short before the
//!     final block surfaces as `UnexpectedEof` anyway. That split —
//!     truncation catchable without any checksum, corruption not — is
//!     exactly why the two properties are gated differently.
//!     `CodecCaps::truncation_undetectable` is the one declaration that
//!     changes this property's SHAPE rather than skipping it — see that
//!     field's own doc for the one codec (Unix compress, `legacy::
//!     compress_z`) that sets it, backed by a bit-level measurement and two
//!     independent reference tools agreeing that truncation there always
//!     yields a strict prefix, never garbage. It is not a loophole:
//!     `testing::MockCodec`, the harness's own bare unframed double,
//!     deliberately does NOT set it and is proven, in this module's own
//!     tests, to still fail the strict form; `a_decoder_that_returns_a_non_
//!     prefix_on_truncation_is_caught` proves the weaker form still catches
//!     wrong trailing bytes, and `a_decoder_that_always_answers_empty_on_
//!     truncation_is_caught` proves it also catches the residual gap a bare
//!     prefix check alone leaves — the empty string is a prefix of
//!     everything, so a decoder that always answers empty on truncated
//!     input would otherwise pass outright. The field changes what is
//!     demanded, never removes the demand. Cuts at
//!     several lengths, not only the midpoint — including one byte short of
//!     the full length and a small prefix — because a cut exactly at a
//!     format's own internal framing boundary (lz4's 64 KiB block boundary,
//!     say) is a different code path than a cut through the middle of a
//!     block's payload, and only sweeping the midpoint can miss it entirely
//!     (see Phase 1d's final fix wave, item 1 and item 2: this property used
//!     to cut only at `len/2`, and lz4's own truncated-frame data loss lived
//!     entirely at block boundaries the midpoint alone never reached). Each
//!     cut's error is also run through `Error::from_decode_io` and required
//!     to classify as `Error::Corrupt` (exit 5), not merely checked for
//!     `is_err()` — the entire purpose of each codec's `NormalizeDecodeErrors`
//!     is that truncation lands on exit 5 rather than exit 1, and a property
//!     that only checked `is_err()` could not have caught a codec whose
//!     adapter classified truncation as some other error entirely.
//! 11. A genuine I/O failure reading the SOURCE — not malformed content the
//!     codec itself rejects — surfaces from the codec's decoder still
//!     classified as `Error::Io` (exit 1), never `Error::Corrupt` (exit 5).
//!     Unconditional on `caps.decode` alone, like property 10: no declared
//!     capability describes a codec's error-passthrough behavior, so none
//!     can gate this. Promoted from a hand-copied test that used to live,
//!     verbatim, in five separate codec modules (gzip, bzip2, brotli, lz4,
//!     snappy) and was silently absent from two more (zlib, deflate) — see
//!     Phase 1d's final fix wave, item 3.
//! 12. Parallel encode: run only for `caps.parallel_encode`, like properties
//!     3, 5 and 9's capability-gated skips. Asserts the governor lease was
//!     actually TAKEN — observed while the sink is alive, since it is
//!     released on `finish`/`Drop` — not merely that the encoded bytes round
//!     trip. A parallel test that only checks round-tripping passes whether
//!     or not parallelism engaged: a codec that ignores the governor entirely
//!     satisfies it perfectly. That shape — a test that cannot fail — has
//!     been found ten times across four phases, most recently in Phase 1e's
//!     backend-selection test, which was green while a `c-backed` binary
//!     silently selected the pure backends.

use std::io::{Read, Write};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use crate::archive::{Codec, DecodeOpts, EncodeOpts};
use crate::format::{CodecCaps, CorruptionDetection, FormatMeta};
use crate::source::{ReaderSource, Source};
use crate::testing::SharedBuf;

/// A pseudo-random, incompressible payload.
///
/// Deliberately NOT a repeating pattern. Phase 1b's incrementality test used
/// `i % 251`, which gzip took from 16 MiB down to 65 KB — small enough that a
/// read-to-end decoder passed the test anyway. Incompressibility is what makes
/// the input large after encoding, and that is what the property depends on.
pub fn incompressible(len: usize) -> Vec<u8> {
    let mut s: u32 = 1;
    (0..len)
        .map(|_| {
            s = s.wrapping_mul(1103515245).wrapping_add(12345);
            (s >> 16) as u8
        })
        .collect()
}

/// A pseudo-random, HIGHLY compressible payload: repetitive prose, not
/// random bytes.
///
/// Property 9 corrupts the ENCODED stream and expects `InvalidData`. An
/// incompressible plaintext encodes to a stream that is almost entirely
/// literal bytes copied through with little to no back-reference or
/// match-length machinery exercised — real data is not shaped like that, and
/// two codecs (lz4, xz-pure) were measured raising `io::ErrorKind::Other`
/// instead of `InvalidData` for a corrupted byte that lands inside the
/// decode path only a compressible stream's matches/literals structure
/// reaches. `incompressible`'s own fixture never turned this up because it
/// never produces that structure. See `normalize.rs`'s
/// `XZ_PURE_MALFORMED_AS_INVALID_DATA_INPUT_EOF` and lz4.rs's fold constant
/// for the codecs this was measured against directly.
pub fn compressible(len: usize) -> Vec<u8> {
    const PHRASE: &[u8] =
        b"the quick brown fox jumps over the lazy dog, again and again and again. ";
    PHRASE.iter().copied().cycle().take(len).collect()
}

/// The plaintext size property 8 encodes when the codec can encode its own
/// input.
///
/// 4 MiB, with the relative `/4` threshold (see property 8) giving a 1 MiB
/// discrimination margin — the same absolute figure Phase 1b used, now
/// derived from a stream instead of hardcoded, so it moves if the stream
/// does. A codec whose block or window is larger than this payload can never
/// pass property 8 by construction, no matter how genuinely incremental its
/// decoder is: the whole stream fits in under one block, so nothing can
/// arrive before the last byte does. If Phase 1d adds a codec configured
/// with a block that large (lz4 supports up to 4 MiB, though its own default
/// is 64 KiB), the payload here is the knob to turn, not the property — see
/// the threshold-too-small guard below, which says so at the point it would
/// otherwise look like a codec defect.
///
/// Shrunk once already from Phase 1b's 8 MiB. That earlier attempt paired an
/// 8 MiB payload with a `/4` divisor for a 2 MiB threshold — WIDER than
/// today's 1 MiB, not narrower, so it was never actually a regression against
/// bzip2's 900 KiB default block; the second cut, straight to 2 MiB (a 512
/// KiB threshold), was: half of the 1 MiB absolute figure it replaced, with
/// no margin left for exactly the case A3 was written to accommodate. 4 MiB
/// restores the original margin — bzip2's 900 KiB block at level 9 needs the
/// `/4` threshold to sit at 1 MiB, and a smaller payload fails a correct
/// codec at that level.
///
/// Do not shrink this to make the suite faster: that job now belongs to
/// `fastest_accepted_level`, which encodes this property's payload at the
/// codec's fastest accepted level (bzip2's own default is 6, brotli's is 11
/// — the slowest setting brotli has) rather than at
/// `EncodeOpts::default()`. This constant stays sized for the worst case at
/// ANY level, including the default, since a fixture supplied by a
/// decode-only codec still runs through this same threshold unmodified.
const PROPERTY_8_PLAIN_LEN: usize = 4 * 1024 * 1024;

fn encode(codec: &dyn Codec, plain: &[u8]) -> Vec<u8> {
    encode_with(codec, plain, &EncodeOpts::default())
}

fn encode_with(codec: &dyn Codec, plain: &[u8], opts: &EncodeOpts) -> Vec<u8> {
    let id = codec.id();
    let buf = SharedBuf::new();
    let mut sink = codec
        .encoder(Box::new(buf.clone()), opts)
        .unwrap_or_else(|e| panic!("conformance[{id}] encoder: {e}"));
    sink.write_all(plain)
        .unwrap_or_else(|e| panic!("conformance[{id}] write: {e}"));
    sink.finish()
        .unwrap_or_else(|e| panic!("conformance[{id}] finish: {e}"));
    buf.contents()
}

/// Finds the fastest level the codec's own `check_encode_opts` accepts, for
/// property 8's large timing-sensitive payload.
///
/// Property 8 encodes 4 MiB and property 9's siblings (bzip2 at its default
/// level 6, brotli at its default quality 11 — the slowest setting brotli
/// has) made that payload prohibitively slow in a debug build. Probing `0`
/// then `1` and falling back to the codec's default if both are rejected
/// costs nothing new: no API addition, no capability field, just the
/// pre-flight check every codec already implements.
///
/// This does NOT weaken property 8. The property exists to catch a
/// read-to-end decoder — one that consumes the entire input before producing
/// any output — and such an implementation behaves identically at every
/// level, because the bug is in how much of the STREAM it reads, not how the
/// stream was produced. Level only changes how much a legitimately
/// block-buffering codec buffers before it can emit anything; encoding at a
/// lower level can only make a correct codec's first output arrive EARLIER,
/// which moves it further inside the incrementality threshold rather than
/// closer to it. Lowering the level is the safe direction for this property,
/// never the direction that could hide a real defect.
fn fastest_accepted_level(codec: &dyn Codec) -> Option<i32> {
    [0, 1].into_iter().find(|&level| {
        codec
            .check_encode_opts(&EncodeOpts {
                level: Some(level),
                ..Default::default()
            })
            .is_ok()
    })
}

fn decode(codec: &dyn Codec, packed: Vec<u8>) -> Vec<u8> {
    let id = codec.id();
    let src: Box<dyn Source> = Box::new(ReaderSource::new(std::io::Cursor::new(packed)));
    let mut dec = codec
        .decoder(src, &DecodeOpts::default())
        .unwrap_or_else(|e| panic!("conformance[{id}] decoder: {e}"));
    let mut out = Vec::new();
    dec.read_to_end(&mut out)
        .unwrap_or_else(|e| panic!("conformance[{id}] read_to_end: {e}"));
    out
}

/// Supplies the encoded stream properties 7-10 need: the codec's own encode
/// when it can, otherwise the caller-supplied fixture.
///
/// `None` means neither is available — a decode-only codec was handed no
/// fixture — and the caller must skip with a message naming what to pass.
fn test_input(
    caps: CodecCaps,
    fixture: Option<&[u8]>,
    make: impl FnOnce() -> Vec<u8>,
) -> Option<Vec<u8>> {
    if caps.encode {
        Some(make())
    } else {
        fixture.map(<[u8]>::to_vec)
    }
}

/// Reports a skipped property visibly rather than silently doing nothing —
/// every skip in this harness goes through here, whatever the reason, so a
/// Phase 1d author sees *why* a property did not run instead of a quiet pass.
fn skip(id: crate::format::FormatId, property: u32, reason: &str) {
    eprintln!("conformance[{id}] property {property}: skipped — {reason}");
}

const NO_FIXTURE: &str = "this codec cannot encode its own test input and no fixture was \
                           supplied; pass one via assert_codec_conforms_with";

/// Property 10: truncated input is rejected — or, for a codec declaring
/// `CodecCaps::truncation_undetectable`, decodes to a genuine,
/// monotonically-growing, non-trivial prefix of the untruncated output.
/// Gated on caps.decode alone, not on detects_corruption: no declaration can
/// switch this off to a bare skip. The incentive on a red property 9 at
/// 11pm is to flip detects_corruption to Never, and the only consequence
/// used to be that property 9 disappeared. Even a codec with no checksum at
/// all often still catches this structurally — see the module doc's note on
/// raw deflate's BFINAL bit — so a codec failing the strict form should
/// detect truncation or be reconsidered, not assumed exempt because it is
/// also exempt from property 9. `truncation_undetectable` narrows what is
/// demanded; it never removes the demand — see that field's own doc.
///
/// Cuts at several lengths — see the module doc's note on this property for
/// why the midpoint alone is not enough — and, for the strict form,
/// requires the classified error, not merely that one occurred: see the
/// module doc's note on `Error::from_decode_io`.
///
/// A free function, not inlined into [`assert_codec_conforms_impl`], so it
/// can be exercised directly in a test — bypassing properties 1-9, in
/// particular property 8's incrementality check, which a double whose
/// OUTPUT depends on the TOTAL length of its input (such as the one
/// `a_decoder_that_always_answers_empty_on_truncation_is_caught` uses)
/// cannot pass by construction: it must see the whole input before it can
/// answer anything, which is itself the read-to-end shape property 8
/// exists to catch. Testing property 10 in isolation is the only way to
/// prove that SPECIFIC double is caught by property 10 rather than merely
/// by property 8 firing first for an unrelated reason.
fn check_property_10(
    codec: &dyn Codec,
    id: crate::format::FormatId,
    caps: CodecCaps,
    corruption_input: &Option<Vec<u8>>,
) {
    match corruption_input {
        Some(base) if base.is_empty() => {
            skip(
                id,
                10,
                "the encoded stream/fixture is empty; nothing to truncate",
            );
        }
        Some(base) => {
            let len = base.len();
            let mut cuts: Vec<usize> = vec![1, len / 2, len.saturating_sub(1)];
            cuts.retain(|&c| c < len);
            cuts.sort_unstable();
            cuts.dedup();

            // The weaker form's reference point: what THIS codec decodes
            // the FULL, untruncated input to. Every truncated decode that
            // does not error must be a prefix of this. Computed once, up
            // front, only when the weaker form is in play — the strict
            // form never needs it.
            let full_reference = if caps.truncation_undetectable {
                let src: Box<dyn Source> =
                    Box::new(ReaderSource::new(std::io::Cursor::new(base.clone())));
                let mut dec = codec
                    .decoder(src, &DecodeOpts::default())
                    .unwrap_or_else(|e| {
                        panic!(
                            "conformance[{id}] property 10 (truncation_undetectable): \
                             opening the FULL, untruncated input failed: {e}"
                        )
                    });
                let mut out = Vec::new();
                dec.read_to_end(&mut out).unwrap_or_else(|e| {
                    panic!(
                        "conformance[{id}] property 10 (truncation_undetectable): decoding \
                         the FULL, untruncated fixture must succeed — it is the reference \
                         every truncated decode is checked against: {e}"
                    )
                });
                Some(out)
            } else {
                None
            };

            // Monotonicity across this same sweep, for the weaker form
            // only: cuts are visited ascending, so `last_ok_len` holds
            // whichever of them decoded successfully most recently. A
            // bare prefix check alone leaves a residual gap — the empty
            // string is a prefix of every string — so a decoder that
            // always answers empty on truncated input would pass it
            // outright. Two things close that gap: (a) output length
            // must never SHRINK as a less-severe (larger) truncation is
            // tried, checked pairwise below; (b) checked once after the
            // loop, the LARGEST cut tried — one byte short of the whole
            // stream, in the `len - 1` case — must decode to SOME output
            // whenever the untruncated reference is non-empty. An
            // always-empty decoder satisfies (a) trivially (0 never
            // shrinks) but fails (b): see
            // `a_decoder_that_always_answers_empty_on_truncation_is_caught`.
            //
            // (b) needs its own variable, and the reason is a defect this
            // guard shipped with: keyed off `last_ok_len` it asked about
            // the last cut that SUCCEEDED, not the largest cut tried. A
            // codec answering `Ok(empty)` at cut 1 (a partial header —
            // nothing to emit yet, nothing wrong yet) and ERRORING at
            // every larger cut therefore failed, with a message stating
            // the opposite of what happened — punished for being
            // stricter than the property requires. `.Z` dodged it by
            // accident alone: `parse_header` errors on a 1-byte input, so
            // it never produces that `Ok(empty)`.
            let mut last_ok_len: Option<usize> = None;
            // `Some(n)`: the largest cut in this sweep decoded without
            // error, to `n` bytes. `None`: it errored — which is the
            // strict form, stricter than this property demands, and
            // nothing to check.
            let mut largest_cut_ok_len: Option<usize> = None;
            let largest_cut = cuts.last().copied();

            for cut in cuts {
                let truncated = base[..cut].to_vec();
                let src: Box<dyn Source> =
                    Box::new(ReaderSource::new(std::io::Cursor::new(truncated)));
                let mut dec = codec
                    .decoder(src, &DecodeOpts::default())
                    .unwrap_or_else(|e| {
                        panic!("conformance[{id}] property 10 decoder (cut {cut}/{len}): {e}")
                    });
                let mut out = Vec::new();
                match dec.read_to_end(&mut out) {
                    Ok(_) => match &full_reference {
                        Some(full) => {
                            assert!(
                                out.len() <= full.len() && full[..out.len()] == out[..],
                                "conformance[{id}] property 10 (truncation_undetectable): \
                                 truncated input (cut to {cut} of {len} bytes) decoded to \
                                 {} bytes that are NOT a prefix of the {}-byte reference \
                                 decode of the full input — a codec declaring \
                                 truncation_undetectable must still decode truncated input \
                                 to a genuine prefix, never fabricated, reordered or padded \
                                 bytes",
                                out.len(),
                                full.len()
                            );
                            if let Some(prev_len) = last_ok_len {
                                assert!(
                                    out.len() >= prev_len,
                                    "conformance[{id}] property 10 (truncation_undetectable): \
                                     monotonicity violated — cut {cut} of {len} bytes (a \
                                     LESS severe truncation than an earlier, smaller cut \
                                     already tried in this same sweep) decoded to {} bytes, \
                                     FEWER than that earlier cut's {prev_len} bytes; an \
                                     honest prefix-producing decoder's output never shrinks \
                                     as less of the stream is missing",
                                    out.len()
                                );
                            }
                            last_ok_len = Some(out.len());
                            if Some(cut) == largest_cut {
                                largest_cut_ok_len = Some(out.len());
                            }
                        }
                        None => panic!(
                            "conformance[{id}] property 10: truncated input (cut to {cut} \
                             of {len} bytes) decoded without error; a codec failing this \
                             should either detect truncation or be reconsidered"
                        ),
                    },
                    Err(e) => {
                        let classified = crate::Error::from_decode_io(e);
                        assert!(
                            matches!(classified, crate::Error::Corrupt(_)),
                            "conformance[{id}] property 10: truncated input (cut to {cut} \
                             of {len} bytes) raised {classified:?}, expected \
                             Error::Corrupt (exit 5) — NormalizeDecodeErrors should \
                             classify truncation as InvalidData"
                        );
                        assert_eq!(
                            classified.exit_code(),
                            5,
                            "conformance[{id}] property 10: Error::Corrupt must be exit \
                             code 5"
                        );
                    }
                }
            }

            if let Some(full) = &full_reference
                && let Some(largest_ok_len) = largest_cut_ok_len
            {
                assert!(
                    largest_ok_len > 0 || full.is_empty(),
                    "conformance[{id}] property 10 (truncation_undetectable): the largest \
                     cut in this sweep ({} of {len} bytes) decoded without error to EMPTY \
                     output, but the untruncated input decodes to {} bytes — a decoder \
                     that always answers empty on truncation would otherwise pass the \
                     bare prefix check (the empty string is a prefix of everything); this \
                     closes that gap",
                    largest_cut.unwrap_or(0),
                    full.len()
                );
            }
        }
        None => skip(id, 10, NO_FIXTURE),
    }
}

/// Asserts every conformance property that applies to `codec`, using `fixture`
/// as the encoded test input for a codec that cannot encode its own — see the
/// module docs.
fn assert_codec_conforms_impl(codec: &dyn Codec, meta: &FormatMeta, fixture: Option<&[u8]>) {
    let id = codec.id();
    let caps = codec.caps();

    // 1. Identity: a mismatched registration is otherwise silent.
    assert_eq!(
        meta.id, id,
        "conformance[{id}] property 1: FormatMeta::id ({}) disagrees with Codec::id ({id})",
        meta.id
    );

    if caps.encode && caps.decode {
        // 2. Round trip. Empty first: it is where codecs most often break,
        //    because a zero-length body still needs a header and trailer.
        // 256 KiB, not 1 MiB: this property proves round-trip fidelity, which
        // does not need a megabyte, and its level is deliberately left at
        // EncodeOpts::default() — unlike property 8 below — because the
        // default is what users actually get and fidelity must hold there.
        for (label, plain) in [
            ("empty", Vec::new()),
            ("one byte", vec![0x42]),
            ("256 KiB incompressible", incompressible(256 * 1024)),
        ] {
            let packed = encode(codec, &plain);
            let back = decode(codec, packed);
            assert_eq!(
                back, plain,
                "conformance[{id}] property 2: {label} did not round-trip"
            );
        }
    }

    if caps.encode && !meta.magics.is_empty() {
        // 3. Magic agreement: AT LEAST ONE registered rule must match, not
        //    every one. A format with alternative signatures — lz4 registers
        //    a frame magic and a legacy-frame magic, zstd has a legacy magic
        //    — would otherwise fail outright on its second or third rule.
        let packed = encode(codec, b"conformance");
        let matched = meta.magics.iter().any(|rule| {
            let start = rule.offset;
            let end = start + rule.bytes.len();
            packed.len() >= end && &packed[start..end] == rule.bytes
        });
        if !matched {
            let tried: Vec<String> = meta
                .magics
                .iter()
                .map(|r| format!("offset {} expects {:02x?}", r.offset, r.bytes))
                .collect();
            let seen = &packed[..packed.len().min(16)];
            panic!(
                "conformance[{id}] property 3: encoded output matched none of its registered \
                 magic rules (tried: {}); output began with {seen:02x?}",
                tried.join(", ")
            );
        }
    }

    if caps.encode {
        // 6. An absurd level — probed at both ends, since a codec validating
        //    only `n > max` while indexing an array by `level` panics on a
        //    negative one just as readily — is either accepted (the codec has
        //    no levels) or a Usage error. Never a panic, never another
        //    variant: a level is a user-supplied number and it must not be
        //    able to produce a misleading error class. `encoder()` must agree
        //    with `check_encode_opts()` on the very same options in both
        //    directions: a codec whose `encoder()` does not re-validate would
        //    otherwise pass this property while still mishandling an absurd
        //    level on the real encode path, and `check_encode_opts` is a
        //    pre-flight call a codec could easily forget to also apply where
        //    it matters.
        for level in [i32::MIN, -1, i32::MAX] {
            let opts = EncodeOpts {
                level: Some(level),
                ..Default::default()
            };
            match codec.check_encode_opts(&opts) {
                Ok(()) => {
                    let encoder_result = codec.encoder(Box::new(SharedBuf::new()), &opts);
                    assert!(
                        !matches!(encoder_result, Err(crate::Error::Usage(_))),
                        "conformance[{id}] property 6: level {level} passed check_encode_opts \
                         but encoder() rejected it as Error::Usage — the two must agree"
                    );
                }
                Err(crate::Error::Usage(_)) => {
                    let encoder_result = codec.encoder(Box::new(SharedBuf::new()), &opts);
                    assert!(
                        matches!(encoder_result, Err(crate::Error::Usage(_))),
                        "conformance[{id}] property 6: level {level} was rejected by \
                         check_encode_opts as Error::Usage, but encoder() did not also reject \
                         it as Error::Usage — encoder() must re-validate, not rely on a \
                         pre-flight caller checked separately"
                    );
                }
                Err(other) => panic!(
                    "conformance[{id}] property 6: level {level} produced {other:?} from \
                     check_encode_opts, expected Ok or Error::Usage"
                ),
            }
        }
    }

    if caps.encode {
        // 4. finish() flushes the underlying writer.
        //
        // `Codec::encoder` takes the destination by value, so after handing it
        // over the caller holds no handle to flush. Forgetting is silent on an
        // unbuffered File and loses the tail on a buffered destination —
        // stdout's LineWriter auto-flushes only on '\n', which a run of binary
        // output may not contain.
        #[derive(Clone)]
        struct FlushSpy(Arc<std::sync::atomic::AtomicBool>);
        impl Write for FlushSpy {
            fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
                Ok(b.len())
            }
            fn flush(&mut self) -> std::io::Result<()> {
                self.0.store(true, Ordering::Relaxed);
                Ok(())
            }
        }
        let flushed = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let mut sink = codec
            .encoder(
                Box::new(FlushSpy(Arc::clone(&flushed))),
                &EncodeOpts::default(),
            )
            .unwrap_or_else(|e| panic!("conformance[{id}] property 4 encoder: {e}"));
        sink.write_all(b"conformance")
            .unwrap_or_else(|e| panic!("conformance[{id}] property 4 write: {e}"));
        sink.finish()
            .unwrap_or_else(|e| panic!("conformance[{id}] property 4 finish: {e}"));
        assert!(
            flushed.load(Ordering::Relaxed),
            "conformance[{id}] property 4: finish() did not flush the underlying writer"
        );

        // 5. finish() surfaces a write error that Drop would swallow.
        //
        // The threshold is MEASURED, not assumed: encode through a counter and
        // see how many bytes land before finish. A writer that fails earlier
        // would fail inside write_all, testing Write rather than finish; one
        // that fails later never fails at all. gzip's figure is its 10-byte
        // header; every codec's differs, which is why this is computed.
        struct Counting(Arc<AtomicU64>);
        impl Write for Counting {
            fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
                self.0.fetch_add(b.len() as u64, Ordering::Relaxed);
                Ok(b.len())
            }
            fn flush(&mut self) -> std::io::Result<()> {
                Ok(())
            }
        }
        let count = Arc::new(AtomicU64::new(0));
        let mut sink = codec
            .encoder(
                Box::new(Counting(Arc::clone(&count))),
                &EncodeOpts::default(),
            )
            .unwrap_or_else(|e| panic!("conformance[{id}] property 5 encoder: {e}"));
        sink.write_all(b"conformance")
            .unwrap_or_else(|e| panic!("conformance[{id}] property 5 write: {e}"));
        let before_finish = count.load(Ordering::Relaxed);
        sink.finish()
            .unwrap_or_else(|e| panic!("conformance[{id}] property 5 finish: {e}"));
        let after_finish = count.load(Ordering::Relaxed);

        if after_finish > before_finish {
            // finish emits bytes, so there is something for a failing writer to
            // reject. A codec whose finish emits nothing (a raw stream with no
            // trailer) is skipped: the property is vacuous, not violated.
            struct FailAfter {
                budget: u64,
                written: u64,
            }
            impl Write for FailAfter {
                fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
                    if self.written >= self.budget {
                        return Err(std::io::Error::other("conformance: writer failed"));
                    }
                    let n = std::cmp::min(b.len() as u64, self.budget - self.written);
                    self.written += n;
                    Ok(n as usize)
                }
                fn flush(&mut self) -> std::io::Result<()> {
                    Ok(())
                }
            }
            let mut sink = codec
                .encoder(
                    Box::new(FailAfter {
                        budget: before_finish,
                        written: 0,
                    }),
                    &EncodeOpts::default(),
                )
                .unwrap_or_else(|e| panic!("conformance[{id}] property 5 encoder: {e}"));
            sink.write_all(b"conformance").unwrap_or_else(|e| {
                panic!("conformance[{id}] property 5: pre-finish writes must succeed: {e}")
            });
            assert!(
                sink.finish().is_err(),
                "conformance[{id}] property 5: finish() swallowed a write error \
                 that Drop would also have swallowed"
            );
        }
    }

    if caps.decode {
        // 7. The decoder claims random access only if the format has an index.
        //    A container above would otherwise seek and read wrong bytes.
        match test_input(caps, fixture, || encode(codec, b"conformance")) {
            Some(packed) => {
                let src: Box<dyn Source> =
                    Box::new(ReaderSource::new(std::io::Cursor::new(packed)));
                let dec = codec
                    .decoder(src, &DecodeOpts::default())
                    .unwrap_or_else(|e| panic!("conformance[{id}] property 7 decoder: {e}"));
                assert!(
                    !dec.caps().seekable || caps.frame_index,
                    "conformance[{id}] property 7: decoder claims seekable without frame_index"
                );
            }
            None => skip(id, 7, NO_FIXTURE),
        }

        // 8. Decoding is incremental, not read-to-end. Peak heap is not
        //    observable from a test without a custom allocator, so the
        //    measurable property is that output begins long before the input
        //    is exhausted. The threshold is relative to the stream's own
        //    length — `consumed < len / 4` — rather than an absolute figure:
        //    an absolute 1 MiB threshold is tuned to gzip's 32 KiB window and
        //    wrongly fails a codec whose block or window is merely a few
        //    hundred KiB to a few MiB (bzip2's 900 KiB block, brotli's and
        //    lz4's multi-MiB window/block options), while a relative
        //    threshold still discriminates decisively against a read-to-end
        //    implementation, which always consumes the input exactly.
        // Encoded at the codec's own fastest accepted level, not
        // EncodeOpts::default() — see fastest_accepted_level's doc comment
        // for why this does not weaken what the property proves.
        let property_8_opts = EncodeOpts {
            level: fastest_accepted_level(codec),
            ..Default::default()
        };
        match test_input(caps, fixture, || {
            encode_with(
                codec,
                &incompressible(PROPERTY_8_PLAIN_LEN),
                &property_8_opts,
            )
        }) {
            Some(big) => {
                if caps.encode {
                    assert!(
                        big.len() > PROPERTY_8_PLAIN_LEN / 2,
                        "conformance[{id}] property 8: incompressible input did not stay large \
                         once encoded, so this property cannot discriminate"
                    );
                }
                let big_len = big.len() as u64;
                let threshold = big_len / 4;
                if threshold == 0 {
                    // Not a codec defect: the stream itself is too small for
                    // ANY threshold to be satisfiable — `consumed` can never
                    // be negative, so `consumed < 0` would reject every
                    // decoder, incremental or not. This is a sizing problem
                    // with the payload (or, for a decode-only codec, the
                    // fixture passed to assert_codec_conforms_with) — raise
                    // PROPERTY_8_PLAIN_LEN or pass a bigger fixture.
                    panic!(
                        "conformance[{id}] property 8: the encoded stream is only {big_len} \
                         bytes long, so big_len/4 rounds down to 0 and no decoder could ever \
                         satisfy this threshold — this names a sizing problem with the \
                         payload/fixture, not the codec"
                    );
                }

                struct Metered {
                    inner: std::io::Cursor<Vec<u8>>,
                    served: Arc<AtomicU64>,
                }
                impl Read for Metered {
                    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
                        let n = self.inner.read(buf)?;
                        self.served.fetch_add(n as u64, Ordering::Relaxed);
                        Ok(n)
                    }
                }
                impl Source for Metered {
                    fn caps(&self) -> crate::source::SourceCaps {
                        crate::source::SourceCaps {
                            seekable: false,
                            len: None,
                        }
                    }
                    fn as_seek(&mut self) -> Option<&mut dyn crate::source::SeekRead> {
                        None
                    }
                }

                let served = Arc::new(AtomicU64::new(0));
                let src: Box<dyn Source> = Box::new(Metered {
                    inner: std::io::Cursor::new(big),
                    served: Arc::clone(&served),
                });
                let mut dec = codec
                    .decoder(src, &DecodeOpts::default())
                    .unwrap_or_else(|e| panic!("conformance[{id}] property 8 decoder: {e}"));
                let mut first = [0u8; 1024];
                let n = dec
                    .read(&mut first)
                    .unwrap_or_else(|e| panic!("conformance[{id}] property 8 first read: {e}"));
                assert!(
                    n > 0,
                    "conformance[{id}] property 8: decoder produced no output"
                );
                let consumed = served.load(Ordering::Relaxed);
                assert!(
                    consumed < threshold,
                    "conformance[{id}] property 8: first output arrived only after reading \
                     {consumed} of {big_len} bytes (threshold {threshold}); a read-to-end \
                     implementation looks exactly like this"
                );
            }
            None => skip(id, 8, NO_FIXTURE),
        }

        // Shared base for property 10: a modest incompressible payload,
        // encoded (or drawn from the ordinary round-trip `fixture` above)
        // once. Property 9 below draws its own, separate compressible base
        // the same way, rather than reusing this one — see its own comment
        // for why both shapes matter.
        let corruption_input =
            test_input(caps, fixture, || encode(codec, &incompressible(64 * 1024)));

        // 9. Corrupted input is reported as InvalidData — run for every
        //    declared state except Never, because a format with no integrity
        //    check genuinely cannot detect it and a harness that demanded it
        //    would force a fake.
        //
        //    Swept over BOTH an incompressible and a compressible payload,
        //    not just the incompressible one property 10 reuses: a whole-
        //    branch review measured this property passing for lz4 and
        //    xz-pure ONLY because an incompressible fixture never reaches
        //    the decode path (matches/back-references) where those two
        //    codecs' backends raise `io::ErrorKind::Other` instead of
        //    `InvalidData` on corruption — the same trap that already hid a
        //    truncation defect in lzma_pure's own tests once. Real data is
        //    compressible; that is the shape a fixture must cover, in
        //    addition to (not instead of) the incompressible one, so this
        //    does not just trade one blind spot for another.
        if caps.detects_corruption == CorruptionDetection::Never {
            skip(
                id,
                9,
                "this codec declares CorruptionDetection::Never — no check exists to prove",
            );
        } else {
            let compressible_input =
                test_input(caps, fixture, || encode(codec, &compressible(64 * 1024)));
            for (shape, base) in [
                ("incompressible", &corruption_input),
                ("compressible", &compressible_input),
            ] {
                match base {
                    Some(base) => {
                        let mut bytes = base.clone();
                        let mid = bytes.len() / 2;
                        bytes[mid] ^= 0xFF;
                        let src: Box<dyn Source> =
                            Box::new(ReaderSource::new(std::io::Cursor::new(bytes)));
                        let mut dec =
                            codec
                                .decoder(src, &DecodeOpts::default())
                                .unwrap_or_else(|e| {
                                    panic!("conformance[{id}] property 9 ({shape}) decoder: {e}")
                                });
                        let mut out = Vec::new();
                        match dec.read_to_end(&mut out) {
                            Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {}
                            Err(e) => panic!(
                                "conformance[{id}] property 9 ({shape}): corrupted input gave \
                                 {:?}, expected InvalidData — Error::from_decode_io keys exit 5 \
                                 off that kind",
                                e.kind()
                            ),
                            Ok(_) => panic!(
                                "conformance[{id}] property 9 ({shape}): corrupted input decoded \
                                 without error, but this codec declares detects_corruption = \
                                 {:?}",
                                caps.detects_corruption
                            ),
                        }
                    }
                    None => skip(id, 9, NO_FIXTURE),
                }
            }
        }

        // 10. See [`check_property_10`] — broken out into its own function
        //     so it can be exercised directly, bypassing properties 1-9.
        check_property_10(codec, id, caps, &corruption_input);

        // 11. A genuine I/O failure reading the SOURCE — not malformed
        //     content the codec itself rejects — must surface unchanged as
        //     Error::Io (exit 1), never reclassified as Error::Corrupt (exit
        //     5). See the module doc's note on this property for why it
        //     replaces five hand-copied codec tests and fills a gap in two
        //     more.
        struct AlwaysPermissionDenied;
        impl Read for AlwaysPermissionDenied {
            fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
                Err(std::io::Error::new(
                    std::io::ErrorKind::PermissionDenied,
                    "conformance: simulated disk error",
                ))
            }
        }
        impl Source for AlwaysPermissionDenied {
            fn caps(&self) -> crate::source::SourceCaps {
                crate::source::SourceCaps {
                    seekable: false,
                    len: None,
                }
            }
            fn as_seek(&mut self) -> Option<&mut dyn crate::source::SeekRead> {
                None
            }
        }

        let src: Box<dyn Source> = Box::new(AlwaysPermissionDenied);
        let mut dec = codec
            .decoder(src, &DecodeOpts::default())
            .unwrap_or_else(|e| panic!("conformance[{id}] property 11 decoder: {e}"));
        let mut out = Vec::new();
        match dec.read_to_end(&mut out) {
            Ok(_) => panic!(
                "conformance[{id}] property 11: decoding from an always-failing source \
                 succeeded"
            ),
            Err(io_err) => {
                assert_eq!(
                    io_err.kind(),
                    std::io::ErrorKind::PermissionDenied,
                    "conformance[{id}] property 11: the decoder must not fold a genuine disk \
                     error onto InvalidData — got {:?}",
                    io_err.kind()
                );
                let classified = crate::Error::from_decode_io(io_err);
                assert!(
                    matches!(classified, crate::Error::Io(_)),
                    "conformance[{id}] property 11: a genuine disk error must classify as \
                     Error::Io, not Error::Corrupt — got {classified:?}"
                );
                assert_eq!(
                    classified.exit_code(),
                    1,
                    "conformance[{id}] property 11: Error::Io must be exit code 1"
                );
            }
        }

        // 12. Parallel encode. Skipped on the declared capability, like
        //     properties 3, 5 and 9 — a codec whose backend has no
        //     multi-threaded encoder cannot demonstrate one, and demanding it
        //     would force a fake.
        if !caps.parallel_encode {
            skip(id, 12, "declares parallel_encode: false");
        } else {
            let plain = incompressible(PROPERTY_8_PLAIN_LEN);
            let per_worker = caps.memory_per_worker.unwrap_or(0);
            // Four workers and room for all of them: this property is about
            // whether the codec USES a grant, not about clamping. The refusal
            // path (a grant of one) is each codec's own test — see the plan.
            let gov = crate::Governor::new(4, per_worker.saturating_mul(4).max(1));

            let buf = SharedBuf::new();
            let mut sink = codec
                .encoder(
                    Box::new(buf.clone()),
                    &EncodeOpts {
                        governor: Some(Arc::clone(&gov)),
                        ..EncodeOpts::default()
                    },
                )
                .unwrap_or_else(|e| panic!("conformance[{id}] property 12: encoder: {e}"));
            sink.write_all(&plain)
                .unwrap_or_else(|e| panic!("conformance[{id}] property 12: write: {e}"));

            // THE ANTI-FAKE CHECK, and the reason this property is worth
            // having. A codec that ignores the governor still round-trips
            // perfectly, so bytes alone prove nothing. Observed while the
            // sink is ALIVE, because the lease is released on finish/drop.
            //
            // `> 1`, not `> 0`: a lone worker is not parallelism, and `> 0`
            // alone cannot tell a codec that genuinely spread the work across
            // four workers from one that grabbed a single-worker lease and
            // then encoded on that thread anyway. It also silently stops
            // discriminating the moment `memory_per_worker` regresses to an
            // under-declared figure — this governor's budget is exactly
            // `per_worker * 4`, so a HONEST figure leaves room for all four
            // workers the real `encoder()` call asks for (which uses its own,
            // separately measured, level-aware per-worker figure — see each
            // codec's `per_worker_bytes`), while a figure too small to cover
            // what `encoder()` actually needs narrows the real grant to one
            // worker via the governor's progress-guarantee floor, without
            // erroring anywhere else in the suite. Whole-branch review LOW-3
            // (2026-09-02): setting all four codecs' `memory_per_worker` to
            // `Some(1)` left the entire suite green under the old `> 0` form.
            assert!(
                gov.outstanding() > 1,
                "conformance[{id}] property 12: declares parallel_encode and a \
                 memory_per_worker that should leave room for {} of the governor's 4 \
                 workers, but only {} were held while encoding — either it is not using \
                 the governor at all, or memory_per_worker is declared too small for what \
                 encoder() actually asks per worker. Round-tripping does not demonstrate \
                 parallelism.",
                gov.workers_for(per_worker),
                gov.outstanding()
            );

            sink.finish()
                .unwrap_or_else(|e| panic!("conformance[{id}] property 12: finish: {e}"));

            assert_eq!(
                gov.outstanding(),
                0,
                "conformance[{id}] property 12: lease not released after finish — the \
                 Sink must own the LeaseSet so the budget frees when the encode ends"
            );

            let packed = buf.contents();
            let src: Box<dyn Source> = Box::new(ReaderSource::new(std::io::Cursor::new(packed)));
            let mut dec = codec
                .decoder(src, &DecodeOpts::default())
                .unwrap_or_else(|e| panic!("conformance[{id}] property 12: decoder: {e}"));
            let mut out = Vec::new();
            dec.read_to_end(&mut out)
                .unwrap_or_else(|e| panic!("conformance[{id}] property 12: read: {e}"));
            assert_eq!(
                out, plain,
                "conformance[{id}] property 12: parallel-encoded stream did not round \
                 trip. Bytes may differ from single-threaded output; DATA may not."
            );
        }
    }
}

/// Asserts every conformance property that applies to `codec`.
///
/// Equivalent to `assert_codec_conforms_with(codec, meta, None)` — for a codec
/// that can encode its own test input. See [`assert_codec_conforms_with`] for
/// a codec that cannot.
pub fn assert_codec_conforms(codec: &dyn Codec, meta: &FormatMeta) {
    assert_codec_conforms_impl(codec, meta, None)
}

/// Asserts every conformance property that applies to `codec`, using `fixture`
/// as the encoded test input for a codec that cannot encode its own — see the
/// module docs.
pub fn assert_codec_conforms_with(codec: &dyn Codec, meta: &FormatMeta, fixture: Option<&[u8]>) {
    assert_codec_conforms_impl(codec, meta, fixture)
}

/// Runs `assert_codec_conforms` and asserts it panics with a message
/// containing `expected` — not merely that it panics at all.
///
/// `catch_unwind` alone proves nothing about *which* property fired: every
/// codec here shares one property (10, truncation, unconditional on
/// `caps.decode`) that a bare, unframed double cannot satisfy, so a test that
/// only checked `result.is_err()` would pass even when the property it names
/// was never actually exercised — mutating it away left the suite green.
/// Checking the panic's own message is what ties each test back to the one
/// property it claims to cover.
#[cfg(test)]
fn assert_panics_naming(codec: &dyn Codec, meta: &FormatMeta, expected: &str) {
    let id = codec.id();
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        assert_codec_conforms(codec, meta);
    }));
    match result {
        Ok(()) => panic!(
            "conformance[{id}]: expected assert_codec_conforms to panic naming {expected:?}, \
             but it passed"
        ),
        Err(payload) => {
            let message = payload
                .downcast_ref::<String>()
                .map(String::as_str)
                .or_else(|| payload.downcast_ref::<&str>().copied())
                .unwrap_or("<non-string panic payload>");
            assert!(
                message.contains(expected),
                "conformance[{id}]: panicked, but the message did not mention {expected:?}: \
                 {message}"
            );
        }
    }
}

/// [`assert_panics_naming`]'s sibling for a decode-only double that needs a
/// fixture (`assert_codec_conforms_with`) to exercise properties 7-10 at
/// all — see that function's own doc for why the panic message, not merely
/// `is_err()`, is what is checked.
#[cfg(test)]
fn assert_panics_naming_with_fixture(
    codec: &dyn Codec,
    meta: &FormatMeta,
    fixture: &[u8],
    expected: &str,
) {
    let id = codec.id();
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        assert_codec_conforms_with(codec, meta, Some(fixture));
    }));
    match result {
        Ok(()) => panic!(
            "conformance[{id}]: expected assert_codec_conforms_with to panic naming \
             {expected:?}, but it passed"
        ),
        Err(payload) => {
            let message = payload
                .downcast_ref::<String>()
                .map(String::as_str)
                .or_else(|| payload.downcast_ref::<&str>().copied())
                .unwrap_or("<non-string panic payload>");
            assert!(
                message.contains(expected),
                "conformance[{id}]: panicked, but the message did not mention {expected:?}: \
                 {message}"
            );
        }
    }
}

/// A minimally FRAMED double, built only to prove the harness's full property
/// set — including 9 and 10, which need an actual integrity check — can be
/// satisfied by a well-behaved codec.
///
/// `testing::MockCodec` stays a bare XOR pass-through: dozens of unrelated
/// tests (governor, ladder, container) rely on it being exactly that, with no
/// framing to get in the way. Property 10 is unconditional on any
/// decode-capable codec (see its module docs), and a bare XOR stream has no
/// way to notice its input was cut short, so `MockCodec` itself can no longer
/// be the "conforms to everything" fixture once property 10 exists.
/// `FramedMock` is that fixture instead, kept local to this test module so
/// the change carries no weight anywhere else. `MockCodec` remains useful as
/// the harness's second shape — see `mock_codec_clears_every_property_up_to_
/// truncation` below — one that is well-behaved everywhere EXCEPT the one
/// property framing actually buys.
///
/// Wire format: XOR(payload) followed by a 4-byte big-endian checksum of the
/// XORed bytes — the same shape a real codec's CRC trailer takes, just with a
/// byte-sum instead of a CRC32. That single trailer is what lets one double
/// stand in for both properties: missing or short means truncated (10),
/// present but wrong means corrupted (9).
#[cfg(test)]
mod framed_mock {
    use super::*;
    use crate::archive::Sink;

    const TRAILER_LEN: usize = 4;

    fn fold(sum: u32, byte: u8) -> u32 {
        sum.wrapping_mul(31).wrapping_add(byte as u32)
    }

    pub struct FramedMock;

    impl Codec for FramedMock {
        fn id(&self) -> crate::format::FormatId {
            crate::testing::MOCK_CODEC
        }

        fn caps(&self) -> CodecCaps {
            CodecCaps {
                encode: true,
                decode: true,
                detects_corruption: CorruptionDetection::Always,
                ..Default::default()
            }
        }

        fn decoder(&self, src: Box<dyn Source>, _o: &DecodeOpts) -> crate::Result<Box<dyn Source>> {
            Ok(Box::new(crate::source::StreamOnly::new(FramedReader {
                inner: src,
                pending: std::collections::VecDeque::new(),
                sum: 0,
                inner_eof: false,
                trailer_ok: None,
            })))
        }

        fn encoder(
            &self,
            dst: Box<dyn Write + Send>,
            _o: &EncodeOpts,
        ) -> crate::Result<Box<dyn Sink>> {
            Ok(Box::new(FramedSink { dst, sum: 0 }))
        }
    }

    struct FramedSink {
        dst: Box<dyn Write + Send>,
        sum: u32,
    }

    impl Write for FramedSink {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            let flipped: Vec<u8> = buf.iter().map(|b| b ^ 0xFF).collect();
            self.dst.write_all(&flipped)?;
            self.sum = flipped.iter().fold(self.sum, |acc, &b| fold(acc, b));
            Ok(buf.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            self.dst.flush()
        }
    }

    impl Sink for FramedSink {
        fn finish(mut self: Box<Self>) -> crate::Result<()> {
            self.dst.write_all(&self.sum.to_be_bytes())?;
            self.dst.flush()?;
            Ok(())
        }
    }

    /// Un-XORs the wire bytes it is handed, holding back the last
    /// `TRAILER_LEN` bytes at all times (they might still turn out to be the
    /// trailer, not payload) until the inner reader reports EOF, at which
    /// point the held-back bytes must equal the checksum of everything
    /// emitted plus everything still queued — computed as a read-only preview
    /// so the real running `sum` is only ever advanced by bytes actually
    /// handed to the caller, exactly once each.
    struct FramedReader<R> {
        inner: R,
        pending: std::collections::VecDeque<u8>,
        sum: u32,
        inner_eof: bool,
        trailer_ok: Option<bool>,
    }

    impl<R: Read> Read for FramedReader<R> {
        fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
            if self.trailer_ok == Some(false) {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "framed mock: truncated or corrupted stream",
                ));
            }
            if self.trailer_ok == Some(true) && self.pending.is_empty() {
                return Ok(0);
            }

            while !self.inner_eof && self.pending.len() <= TRAILER_LEN {
                let mut chunk = [0u8; 4096];
                let n = self.inner.read(&mut chunk)?;
                if n == 0 {
                    self.inner_eof = true;
                } else {
                    self.pending.extend(chunk[..n].iter().copied());
                }
            }

            if self.inner_eof && self.trailer_ok.is_none() {
                if self.pending.len() >= TRAILER_LEN {
                    let split_at = self.pending.len() - TRAILER_LEN;
                    let projected = self
                        .pending
                        .iter()
                        .take(split_at)
                        .fold(self.sum, |acc, &b| fold(acc, b));
                    let trailer_bytes: Vec<u8> =
                        self.pending.iter().skip(split_at).copied().collect();
                    let got = u32::from_be_bytes(trailer_bytes.try_into().unwrap());
                    self.trailer_ok = Some(got == projected);
                    if self.trailer_ok == Some(true) {
                        self.pending.truncate(split_at);
                    }
                } else {
                    self.trailer_ok = Some(false);
                }
                if self.trailer_ok == Some(false) {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "framed mock: truncated or corrupted stream",
                    ));
                }
            }

            let safe = if self.trailer_ok == Some(true) {
                self.pending.len()
            } else {
                self.pending.len().saturating_sub(TRAILER_LEN)
            };
            let n = safe.min(out.len());
            for slot in out.iter_mut().take(n) {
                let b = self.pending.pop_front().expect("counted as safe above");
                self.sum = fold(self.sum, b);
                *slot = b ^ 0xFF;
            }
            Ok(n)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::format::{FormatId, FormatMeta, MagicRule};
    use crate::testing::{MOCK_CODEC, MockCodec};
    use framed_mock::FramedMock;

    #[test]
    fn framed_mock_conforms_to_every_property() {
        // FramedMock is the fully-conforming shape: a real trailer gives it
        // both an integrity check (property 9) and truncation detection
        // (property 10), so assert_codec_conforms should raise nothing at
        // all. MockCodec — the harness's OTHER reference shape, honestly
        // missing that framing — is exercised separately below, in
        // mock_codec_clears_every_property_up_to_truncation.
        assert_codec_conforms(&FramedMock, &FormatMeta::codec(MOCK_CODEC, &["mock"], &[]));
    }

    #[test]
    fn mock_codec_clears_every_property_up_to_truncation() {
        // MockCodec is a bare XOR pass-through: no magic (property 3 skips on
        // evidence), no trailer (property 5's skip-on-measurement branch —
        // finish() emits nothing extra, so the branch never fires), and
        // detects_corruption: CorruptionDetection::Never (property 9's skip-on-declaration
        // branch). Asserting it panics naming property 10 SPECIFICALLY — not
        // any earlier property — is what proves it clears 1 through 9
        // cleanly, including both skip branches: a wrongly-firing property 5
        // or 9 would name itself in the message instead of 10.
        //
        // This is the harness's second reference shape, restored: a codec
        // that is well-behaved everywhere except where framing genuinely
        // matters, same as raw deflate would be.
        assert_panics_naming(
            &MockCodec,
            &FormatMeta::codec(MOCK_CODEC, &["mock"], &[]),
            "property 10",
        );
    }

    /// A `Read` adapter that forwards bytes from `inner` unchanged, then
    /// appends exactly one fixed sentinel byte once `inner` reports EOF —
    /// whether that EOF is genuine (the full input) or a truncated prefix.
    /// Decoding a truncated prefix therefore disagrees with the reference
    /// decode of the full input at the position right after the cut (a real
    /// source byte there, in the full decode; the sentinel, in the
    /// truncated one) — a non-prefix result, never a mere shortfall.
    struct AppendSentinelReader<R> {
        inner: R,
        appended: bool,
    }

    impl<R: Read> Read for AppendSentinelReader<R> {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            if buf.is_empty() {
                return Ok(0);
            }
            let n = self.inner.read(buf)?;
            if n > 0 {
                return Ok(n);
            }
            if !self.appended {
                self.appended = true;
                buf[0] = 0xAA;
                return Ok(1);
            }
            Ok(0)
        }
    }

    /// Declares `truncation_undetectable: true` — so property 10 no longer
    /// demands an outright error — but its decoder ([`AppendSentinelReader`])
    /// is deliberately broken: on truncated input it still decodes WITHOUT
    /// error, to bytes that are NOT a prefix of the full decode. This is the
    /// falsification `CodecCaps::truncation_undetectable`'s own doc promises:
    /// proof that the weaker property still catches a real defect (wrong
    /// trailing bytes), the same way `mock_codec_clears_every_property_up_
    /// to_truncation` above proves the strict property fires at all.
    #[derive(Debug)]
    struct NonPrefixOnTruncation;

    impl Codec for NonPrefixOnTruncation {
        fn id(&self) -> FormatId {
            MOCK_CODEC
        }

        fn caps(&self) -> CodecCaps {
            CodecCaps {
                decode: true,
                truncation_undetectable: true,
                ..Default::default()
            }
        }

        fn decoder(&self, src: Box<dyn Source>, _o: &DecodeOpts) -> crate::Result<Box<dyn Source>> {
            Ok(Box::new(crate::source::StreamOnly::new(
                AppendSentinelReader {
                    inner: src,
                    appended: false,
                },
            )))
        }

        fn encoder(
            &self,
            _dst: Box<dyn Write + Send>,
            _o: &EncodeOpts,
        ) -> crate::Result<Box<dyn crate::archive::Sink>> {
            panic!("NonPrefixOnTruncation cannot encode — the harness must never call this")
        }
    }

    #[test]
    fn a_decoder_that_returns_a_non_prefix_on_truncation_is_caught() {
        // Large enough that property 8's incremental threshold holds
        // comfortably, and every byte non-zero so the sentinel (0xAA) never
        // coincides with real fixture content by construction.
        let fixture: Vec<u8> = (0u32..8192).map(|i| (i % 251) as u8 + 1).collect();
        assert_panics_naming_with_fixture(
            &NonPrefixOnTruncation,
            &FormatMeta::codec(MOCK_CODEC, &["mock"], &[]),
            &fixture,
            "property 10",
        );
    }

    /// Declares `truncation_undetectable: true` and decodes the FULL input
    /// correctly (identity), but answers EMPTY for any shorter (truncated)
    /// one. This passes the bare prefix check trivially — the empty string
    /// is a prefix of everything — which is exactly the residual gap
    /// `check_property_10`'s closing checks (monotonicity, then
    /// non-triviality of the largest cut) exist to catch.
    ///
    /// Its `decoder` reads the WHOLE input eagerly to compare `buf.len()`
    /// against the length it was told is "full" — its output is a function
    /// of the TOTAL length of its input, so it cannot be incremental BY
    /// CONSTRUCTION (it must see everything before it can answer anything).
    /// That is exactly the read-to-end shape conformance property 8 exists
    /// to catch, so this double is tested directly against
    /// [`check_property_10`] below, not through
    /// `assert_codec_conforms`/`_with`'s full pipeline — see that function's
    /// own doc for why going through the full pipeline would name property 8
    /// instead of property 10, proving nothing about the property this
    /// double exists to exercise.
    #[derive(Debug)]
    struct AlwaysEmptyOnTruncation {
        full_len: usize,
    }

    impl Codec for AlwaysEmptyOnTruncation {
        fn id(&self) -> FormatId {
            MOCK_CODEC
        }

        fn caps(&self) -> CodecCaps {
            CodecCaps {
                decode: true,
                truncation_undetectable: true,
                ..Default::default()
            }
        }

        fn decoder(
            &self,
            mut src: Box<dyn Source>,
            _o: &DecodeOpts,
        ) -> crate::Result<Box<dyn Source>> {
            let mut buf = Vec::new();
            src.read_to_end(&mut buf)?;
            let out = if buf.len() == self.full_len {
                buf
            } else {
                Vec::new()
            };
            Ok(Box::new(crate::source::StreamOnly::new(
                std::io::Cursor::new(out),
            )))
        }

        fn encoder(
            &self,
            _dst: Box<dyn Write + Send>,
            _o: &EncodeOpts,
        ) -> crate::Result<Box<dyn crate::archive::Sink>> {
            panic!("AlwaysEmptyOnTruncation cannot encode — the harness must never call this")
        }
    }

    #[test]
    fn a_decoder_that_always_answers_empty_on_truncation_is_caught() {
        let fixture: Vec<u8> = (0u32..8192).map(|i| (i % 251) as u8 + 1).collect();
        let codec = AlwaysEmptyOnTruncation {
            full_len: fixture.len(),
        };
        let id = codec.id();
        let caps = codec.caps();
        let corruption_input = Some(fixture);

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            check_property_10(&codec, id, caps, &corruption_input);
        }));
        match result {
            Ok(()) => {
                panic!("expected check_property_10 to panic naming \"property 10\", but it passed")
            }
            Err(payload) => {
                let message = payload
                    .downcast_ref::<String>()
                    .map(String::as_str)
                    .or_else(|| payload.downcast_ref::<&str>().copied())
                    .unwrap_or("<non-string panic payload>");
                assert!(
                    message.contains("property 10"),
                    "panicked, but the message did not mention \"property 10\": {message}"
                );
            }
        }
    }

    /// The over-strictness guard for `check_property_10`'s closing check,
    /// and the shape that used to FAIL it: `Ok(empty)` at the smallest cut,
    /// a classified error at every larger one.
    ///
    /// That is a legitimate — indeed stricter than required — decoder. Cut 1
    /// is a partial header: nothing to emit yet, and nothing detectably
    /// wrong yet, so answering empty is honest. At `len / 2` and `len - 1`
    /// enough structure is present to see the stream is cut short, so it
    /// errors, which is the STRICT form of property 10 the weaker
    /// `truncation_undetectable` form does not even ask for.
    ///
    /// Keyed off the last cut that SUCCEEDED, the closing check read that as
    /// "every truncated cut that decoded produced empty output" and failed
    /// the codec, with a message stating the opposite of what happened. It
    /// now keys off the LARGEST cut tried, as its own comment always said it
    /// did, so this passes. `.Z` never met the defect because `parse_header`
    /// errors on a 1-byte input — accident, not design, and Phase 3c's
    /// formats have no reason to share the accident.
    ///
    /// Tested directly against [`check_property_10`] for the same reason
    /// `AlwaysEmptyOnTruncation` is: its output depends on the TOTAL length
    /// of its input, so it cannot pass property 8's incrementality check by
    /// construction.
    #[derive(Debug)]
    struct StricterThanRequiredOnTruncation {
        full_len: usize,
    }

    impl Codec for StricterThanRequiredOnTruncation {
        fn id(&self) -> FormatId {
            MOCK_CODEC
        }

        fn caps(&self) -> CodecCaps {
            CodecCaps {
                decode: true,
                truncation_undetectable: true,
                ..Default::default()
            }
        }

        fn decoder(
            &self,
            mut src: Box<dyn Source>,
            _o: &DecodeOpts,
        ) -> crate::Result<Box<dyn Source>> {
            let mut buf = Vec::new();
            src.read_to_end(&mut buf)?;
            let n = buf.len();
            let out: Box<dyn std::io::Read + Send> = if n == self.full_len {
                Box::new(std::io::Cursor::new(buf))
            } else if n <= 1 {
                // A partial header: nothing decodable yet, nothing wrong yet.
                Box::new(std::io::Cursor::new(Vec::new()))
            } else {
                // Enough structure to see the stream is cut short. The kind
                // matters: property 10's strict arm requires the error to
                // classify as `Error::Corrupt` (exit 5).
                Box::new(FailingReader)
            };
            Ok(Box::new(crate::source::StreamOnly::new(out)))
        }

        fn encoder(
            &self,
            _dst: Box<dyn Write + Send>,
            _o: &EncodeOpts,
        ) -> crate::Result<Box<dyn crate::archive::Sink>> {
            panic!(
                "StricterThanRequiredOnTruncation cannot encode — the harness must never call \
                 this"
            )
        }
    }

    /// Raises `InvalidData` on every read — what a decoder that has detected
    /// a truncated stream reports, and what `Error::from_decode_io` folds
    /// onto `Error::Corrupt`.
    struct FailingReader;

    impl std::io::Read for FailingReader {
        fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
            Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "truncated stream",
            ))
        }
    }

    #[test]
    fn a_codec_stricter_than_truncation_undetectable_requires_is_not_punished() {
        let fixture: Vec<u8> = (0u32..8192).map(|i| (i % 251) as u8 + 1).collect();
        let codec = StricterThanRequiredOnTruncation {
            full_len: fixture.len(),
        };
        let id = codec.id();
        let caps = codec.caps();
        let corruption_input = Some(fixture);

        // No panic: the largest cut ERRORED, which is stricter than this
        // property demands, so the non-triviality check has nothing to say.
        check_property_10(&codec, id, caps, &corruption_input);
    }

    #[test]
    fn framed_mock_conforms_when_only_one_of_several_registered_magics_matches() {
        // The direct regression test for A1: lz4 registers a frame magic AND
        // a legacy-frame magic; zstd has a legacy magic. Property 3 must
        // accept a codec whose output matches at least one registered rule,
        // not demand every one. FramedMock XORs "conformance" with 0xFF, so
        // its output begins with 0x63^0xFF, 0x6F^0xFF = 0x9C, 0x90.
        const MAGICS: &[MagicRule] = &[
            MagicRule {
                offset: 0,
                bytes: &[0x9C, 0x90],
                format: MOCK_CODEC,
            },
            MagicRule {
                offset: 0,
                bytes: &[0x00, 0x00],
                format: MOCK_CODEC,
            },
        ];
        assert_codec_conforms(
            &FramedMock,
            &FormatMeta::codec(MOCK_CODEC, &["mock"], MAGICS),
        );
    }

    #[test]
    fn a_decode_only_codec_wrapping_framed_mock_is_tested_from_a_fixture() {
        // The motivating shape: the pure-Rust zstd/xz fallbacks from spec
        // §1.3, which can decode but not encode. Build a fixture the normal
        // way (through the real encoder), then hand the harness only the
        // decode half plus that fixture — properties 7-10 must still run.
        struct DecodeOnlyMock;
        impl Codec for DecodeOnlyMock {
            fn id(&self) -> FormatId {
                MOCK_CODEC
            }
            fn caps(&self) -> CodecCaps {
                CodecCaps {
                    decode: true,
                    detects_corruption: CorruptionDetection::Always,
                    ..Default::default()
                }
            }
            fn decoder(
                &self,
                src: Box<dyn Source>,
                o: &DecodeOpts,
            ) -> crate::Result<Box<dyn Source>> {
                FramedMock.decoder(src, o)
            }
            fn encoder(
                &self,
                _dst: Box<dyn Write + Send>,
                _o: &EncodeOpts,
            ) -> crate::Result<Box<dyn crate::archive::Sink>> {
                panic!("DecodeOnlyMock cannot encode — the harness must never call this")
            }
        }

        let fixture = encode(&FramedMock, &incompressible(256 * 1024));
        assert_codec_conforms_with(
            &DecodeOnlyMock,
            &FormatMeta::codec(MOCK_CODEC, &["mock"], &[]),
            Some(&fixture),
        );
    }

    #[test]
    fn a_decode_only_codec_with_no_fixture_skips_rather_than_panics() {
        // No fixture, no encode capability: properties 7-10 have nothing to
        // run against. The harness must skip visibly, not silently pass by
        // doing nothing, and it must not panic for lack of a fixture either.
        struct DecodeOnlyNoFixture;
        impl Codec for DecodeOnlyNoFixture {
            fn id(&self) -> FormatId {
                MOCK_CODEC
            }
            fn caps(&self) -> CodecCaps {
                CodecCaps {
                    decode: true,
                    ..Default::default()
                }
            }
            fn decoder(
                &self,
                src: Box<dyn Source>,
                o: &DecodeOpts,
            ) -> crate::Result<Box<dyn Source>> {
                MockCodec.decoder(src, o)
            }
            fn encoder(
                &self,
                _dst: Box<dyn Write + Send>,
                _o: &EncodeOpts,
            ) -> crate::Result<Box<dyn crate::archive::Sink>> {
                panic!("DecodeOnlyNoFixture cannot encode — the harness must never call this")
            }
        }

        assert_codec_conforms(
            &DecodeOnlyNoFixture,
            &FormatMeta::codec(MOCK_CODEC, &["mock"], &[]),
        );
    }
}

/// Proof that the harness can actually fail.
///
/// A conformance suite nobody has watched fail is exactly the defect class
/// this project has spent two phases hunting — A1 (property 3's ANY-vs-EVERY
/// bug) shipped because nothing exercised property 3's loop semantics. Each
/// test here builds a codec that breaks exactly one property and asserts,
/// via [`assert_panics_naming`], that `assert_codec_conforms` panics
/// specifically naming that property — not merely that it panics at all.
/// That distinction matters here more than almost anywhere else: every
/// broken codec below shares `MockCodec`'s bare, unframed wire format, which
/// means every one of them ALSO fails property 10 (truncation, unconditional
/// — see the module docs). A bare `result.is_err()` check cannot tell "failed
/// for the property this test names" from "failed for property 10 because
/// the property this test names was silently never reached" — which is
/// exactly how a deleted property 2 or 9 check went unnoticed here before.
///
/// Every broken codec delegates to `MockCodec` for everything except the one
/// thing it deliberately gets wrong; two of them (properties 4 and 5) must
/// delegate the ENCODE path through `MockCodec.encoder` specifically, or the
/// missing XOR breaks round-trip as a side effect and property 2 fires first
/// instead of the property each test actually names.
#[cfg(test)]
mod broken_codecs {
    use super::*;
    use crate::archive::Sink;
    use crate::format::{FormatId, MagicRule};
    use crate::testing::{MOCK_CODEC, MockCodec};

    fn mock_meta(magics: &'static [MagicRule]) -> FormatMeta {
        FormatMeta::codec(MOCK_CODEC, &["mock"], magics)
    }

    /// Breaks property 2: encodes as a pass-through (no XOR) but decodes with
    /// the real un-XOR, so encode/decode no longer invert each other.
    struct BrokenRoundTrip;

    struct PassthroughSink(Box<dyn Write + Send>);
    impl Write for PassthroughSink {
        fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
            self.0.write(b)
        }
        fn flush(&mut self) -> std::io::Result<()> {
            self.0.flush()
        }
    }
    impl Sink for PassthroughSink {
        fn finish(mut self: Box<Self>) -> crate::Result<()> {
            self.0.flush()?;
            Ok(())
        }
    }

    impl Codec for BrokenRoundTrip {
        fn id(&self) -> FormatId {
            MOCK_CODEC
        }
        fn caps(&self) -> CodecCaps {
            MockCodec.caps()
        }
        fn decoder(&self, src: Box<dyn Source>, o: &DecodeOpts) -> crate::Result<Box<dyn Source>> {
            MockCodec.decoder(src, o)
        }
        fn encoder(
            &self,
            dst: Box<dyn Write + Send>,
            _o: &EncodeOpts,
        ) -> crate::Result<Box<dyn Sink>> {
            Ok(Box::new(PassthroughSink(dst)))
        }
    }

    #[test]
    fn broken_round_trip_is_caught() {
        assert_panics_naming(&BrokenRoundTrip, &mock_meta(&[]), "property 2");
    }

    #[test]
    fn broken_magic_with_no_match_is_caught() {
        // Two candidate rules, neither matching MockCodec's actual output —
        // the multi-magic case A1 introduced ANY-semantics for. The loop
        // must still correctly detect that NEITHER matched, with more than
        // one candidate to check.
        const MAGICS: &[MagicRule] = &[
            MagicRule {
                offset: 0,
                bytes: &[0x00, 0x00],
                format: MOCK_CODEC,
            },
            MagicRule {
                offset: 0,
                bytes: &[0x11, 0x11],
                format: MOCK_CODEC,
            },
        ];
        assert_panics_naming(&MockCodec, &mock_meta(MAGICS), "property 3");
    }

    /// Breaks property 4: finish() never flushes the underlying writer. Wraps
    /// `MockCodec`'s own `Sink` (not `dst` directly) so writes are still
    /// correctly XORed — only the finish/flush step is broken, not
    /// round-trip.
    struct BrokenFlush;

    struct NoFlushSink(Box<dyn Sink>);
    impl Write for NoFlushSink {
        fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
            self.0.write(b)
        }
        fn flush(&mut self) -> std::io::Result<()> {
            self.0.flush()
        }
    }
    impl Sink for NoFlushSink {
        fn finish(self: Box<Self>) -> crate::Result<()> {
            // BUG: never calls self.0.finish(), so the underlying writer's
            // flush() (which MockCodec's own finish() performs) never runs.
            Ok(())
        }
    }

    impl Codec for BrokenFlush {
        fn id(&self) -> FormatId {
            MOCK_CODEC
        }
        fn caps(&self) -> CodecCaps {
            MockCodec.caps()
        }
        fn decoder(&self, src: Box<dyn Source>, o: &DecodeOpts) -> crate::Result<Box<dyn Source>> {
            MockCodec.decoder(src, o)
        }
        fn encoder(
            &self,
            dst: Box<dyn Write + Send>,
            o: &EncodeOpts,
        ) -> crate::Result<Box<dyn Sink>> {
            Ok(Box::new(NoFlushSink(MockCodec.encoder(dst, o)?)))
        }
    }

    #[test]
    fn broken_flush_is_caught() {
        assert_panics_naming(&BrokenFlush, &mock_meta(&[]), "property 4");
    }

    /// Breaks property 5: finish() writes a trailer but swallows the error if
    /// writing it fails, exactly what `Drop` would also have swallowed. Wraps
    /// `MockCodec`'s own `Sink` so the payload is still correctly XORed; the
    /// extra trailer bytes this adds have no framing for a plain
    /// `MockCodec`-style decoder to strip back out again, so this codec
    /// declares `decode: false` — its whole point is property 5, which never
    /// touches decode, and a `false` here is honest rather than papering over
    /// a round trip this shape cannot actually offer.
    struct BrokenFinishSwallowsError;

    struct SwallowingSink(Box<dyn Sink>);
    impl Write for SwallowingSink {
        fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
            self.0.write(b)
        }
        fn flush(&mut self) -> std::io::Result<()> {
            self.0.flush()
        }
    }
    impl Sink for SwallowingSink {
        fn finish(mut self: Box<Self>) -> crate::Result<()> {
            // BUG: a real trailer write whose error is ignored.
            let _ = self.0.write_all(b"TRAILER!");
            let _ = self.0.finish();
            Ok(())
        }
    }

    impl Codec for BrokenFinishSwallowsError {
        fn id(&self) -> FormatId {
            MOCK_CODEC
        }
        fn caps(&self) -> CodecCaps {
            CodecCaps {
                decode: false,
                ..MockCodec.caps()
            }
        }
        fn decoder(&self, src: Box<dyn Source>, o: &DecodeOpts) -> crate::Result<Box<dyn Source>> {
            MockCodec.decoder(src, o)
        }
        fn encoder(
            &self,
            dst: Box<dyn Write + Send>,
            o: &EncodeOpts,
        ) -> crate::Result<Box<dyn Sink>> {
            Ok(Box::new(SwallowingSink(MockCodec.encoder(dst, o)?)))
        }
    }

    #[test]
    fn broken_finish_swallowing_a_write_error_is_caught() {
        assert_panics_naming(&BrokenFinishSwallowsError, &mock_meta(&[]), "property 5");
    }

    /// Breaks property 6: `check_encode_opts` accepts every level (the
    /// default impl), but `encoder()` indexes an array by the raw level —
    /// the classic lower-bound panic a validator that only checks `n > max`
    /// leaves open. This one panics with Rust's own "index out of bounds"
    /// message rather than one of this harness's "property 6: ..." messages
    /// — which IS the correct signal here: property 6's entire mandate is
    /// "never a panic", so any panic raised from inside its own
    /// `codec.encoder()` call is a genuine property-6 failure, textually
    /// labeled by Rust rather than by us.
    struct BrokenLevelPanics;

    impl Codec for BrokenLevelPanics {
        fn id(&self) -> FormatId {
            MOCK_CODEC
        }
        fn caps(&self) -> CodecCaps {
            MockCodec.caps()
        }
        fn decoder(&self, src: Box<dyn Source>, o: &DecodeOpts) -> crate::Result<Box<dyn Source>> {
            MockCodec.decoder(src, o)
        }
        fn encoder(
            &self,
            dst: Box<dyn Write + Send>,
            o: &EncodeOpts,
        ) -> crate::Result<Box<dyn Sink>> {
            let level = o.level.unwrap_or(0);
            if level > 22 {
                return Err(crate::Error::Usage("level too high".into()));
            }
            let table = [1u8, 2, 3];
            let _ = table[level as usize]; // BUG: panics for level < 0 or level > 2.
            MockCodec.encoder(dst, o)
        }
    }

    #[test]
    fn broken_level_validation_is_caught() {
        assert_panics_naming(&BrokenLevelPanics, &mock_meta(&[]), "index out of bounds");
    }

    /// Breaks property 8: decodes by reading the whole input up front, then
    /// serving it from a buffer — indistinguishable from read-to-end.
    struct BrokenIncremental;

    impl Codec for BrokenIncremental {
        fn id(&self) -> FormatId {
            MOCK_CODEC
        }
        fn caps(&self) -> CodecCaps {
            MockCodec.caps()
        }
        fn decoder(
            &self,
            mut src: Box<dyn Source>,
            _o: &DecodeOpts,
        ) -> crate::Result<Box<dyn Source>> {
            let mut all = Vec::new();
            src.read_to_end(&mut all)?; // BUG: eager, whole-stream read.
            for b in &mut all {
                *b ^= 0xFF;
            }
            Ok(Box::new(crate::source::StreamOnly::new(
                std::io::Cursor::new(all),
            )))
        }
        fn encoder(
            &self,
            dst: Box<dyn Write + Send>,
            o: &EncodeOpts,
        ) -> crate::Result<Box<dyn Sink>> {
            MockCodec.encoder(dst, o)
        }
    }

    #[test]
    fn broken_incremental_decode_is_caught() {
        assert_panics_naming(&BrokenIncremental, &mock_meta(&[]), "property 8");
    }

    /// Breaks property 9: declares `detects_corruption: CorruptionDetection::Always` but the
    /// decoder cannot actually fail on corrupted input (XOR never errors).
    struct LyingAboutCorruption;

    impl Codec for LyingAboutCorruption {
        fn id(&self) -> FormatId {
            MOCK_CODEC
        }
        fn caps(&self) -> CodecCaps {
            CodecCaps {
                detects_corruption: CorruptionDetection::Always, // BUG: nothing backs this claim.
                ..MockCodec.caps()
            }
        }
        fn decoder(&self, src: Box<dyn Source>, o: &DecodeOpts) -> crate::Result<Box<dyn Source>> {
            MockCodec.decoder(src, o)
        }
        fn encoder(
            &self,
            dst: Box<dyn Write + Send>,
            o: &EncodeOpts,
        ) -> crate::Result<Box<dyn Sink>> {
            MockCodec.encoder(dst, o)
        }
    }

    #[test]
    fn lying_about_corruption_detection_is_caught() {
        assert_panics_naming(&LyingAboutCorruption, &mock_meta(&[]), "property 9");
    }

    #[test]
    fn broken_truncation_is_caught() {
        // MockCodec's bare XOR stream has no framing at all, so it is — by
        // construction, not a further bug added here — the ready-made broken
        // codec for property 10: exactly what a raw, checksum-less stream
        // WITHOUT even deflate's BFINAL-style structure looks like.
        assert_panics_naming(&MockCodec, &mock_meta(&[]), "property 10");
    }

    /// Breaks property 11: the decoder wraps its source in an adapter that
    /// reclassifies EVERY error — including a genuine disk failure — onto
    /// `InvalidData`, the exact over-normalisation this file's module doc
    /// warns a codec's own adapter must not do. A real `PermissionDenied`
    /// from the source would be reported as `Error::Corrupt` (exit 5)
    /// instead of `Error::Io` (exit 1).
    ///
    /// Delegates to [`super::framed_mock::FramedMock`], not `MockCodec`:
    /// `MockCodec`'s bare, unframed stream fails property 10 unconditionally
    /// (see `broken_truncation_is_caught` above), which would fire first and
    /// mask the property this test exists to name. `FramedMock` has real
    /// framing and clears properties 1 through 10 on its own, so this is the
    /// only property it can fail.
    struct OverNormalizingDecoder;

    struct FoldsEveryErrorToInvalidData(Box<dyn Source>);
    impl Read for FoldsEveryErrorToInvalidData {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            self.0
                .read(buf)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))
        }
    }
    impl Source for FoldsEveryErrorToInvalidData {
        fn caps(&self) -> crate::source::SourceCaps {
            self.0.caps()
        }
        fn as_seek(&mut self) -> Option<&mut dyn crate::source::SeekRead> {
            None
        }
    }

    impl Codec for OverNormalizingDecoder {
        fn id(&self) -> FormatId {
            MOCK_CODEC
        }
        fn caps(&self) -> CodecCaps {
            super::framed_mock::FramedMock.caps()
        }
        fn decoder(&self, src: Box<dyn Source>, o: &DecodeOpts) -> crate::Result<Box<dyn Source>> {
            // BUG: every error from the source, including a real disk
            // failure, is reclassified as InvalidData before FramedMock's
            // own decoder ever sees it.
            super::framed_mock::FramedMock.decoder(Box::new(FoldsEveryErrorToInvalidData(src)), o)
        }
        fn encoder(
            &self,
            dst: Box<dyn Write + Send>,
            o: &EncodeOpts,
        ) -> crate::Result<Box<dyn Sink>> {
            super::framed_mock::FramedMock.encoder(dst, o)
        }
    }

    #[test]
    fn over_normalizing_decoder_is_caught() {
        assert_panics_naming(&OverNormalizingDecoder, &mock_meta(&[]), "property 11");
    }

    /// Breaks property 12: declares `parallel_encode` but never acquires a
    /// lease, so nothing it does is actually parallel. This is the failure
    /// mode a round-trip-only test cannot see.
    ///
    /// Delegates to [`super::framed_mock::FramedMock`], not `MockCodec`, for
    /// the same reason `OverNormalizingDecoder` does above: `MockCodec`'s
    /// bare, unframed stream fails property 10 unconditionally, which fires
    /// first and masks the property this test exists to name. `FramedMock`
    /// clears properties 1 through 11 on its own (real framing, and
    /// `detects_corruption: Always`), so this is the only property it can
    /// fail.
    #[derive(Debug)]
    struct LiesAboutParallel;

    impl Codec for LiesAboutParallel {
        fn id(&self) -> FormatId {
            FormatId::new("lies-about-parallel")
        }
        fn caps(&self) -> CodecCaps {
            CodecCaps {
                parallel_encode: true,
                memory_per_worker: Some(1024),
                ..super::framed_mock::FramedMock.caps()
            }
        }
        fn decoder(&self, src: Box<dyn Source>, o: &DecodeOpts) -> crate::Result<Box<dyn Source>> {
            super::framed_mock::FramedMock.decoder(src, o)
        }
        fn encoder(
            &self,
            dst: Box<dyn Write + Send>,
            o: &EncodeOpts,
        ) -> crate::Result<Box<dyn Sink>> {
            // The bug: ignores `o.governor` entirely.
            super::framed_mock::FramedMock.encoder(dst, o)
        }
    }

    #[test]
    fn property_12_catches_a_codec_that_declares_parallel_and_ignores_the_governor() {
        assert_panics_naming(
            &LiesAboutParallel,
            &FormatMeta::codec(FormatId::new("lies-about-parallel"), &["lap"], &[]),
            "property 12",
        );
    }
}