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
//! Mock formats for testing the ladder and governor without any real codec.
//!
//! Enabled by `cfg(test)` in this crate and by the `testing` feature for
//! downstream crates.

use std::io::{Read, Write};

use crate::archive::{
    ArchiveRead, ArchiveWrite, Codec, Container, CreateOpts, DecodeOpts, EncodeOpts, Entry,
    EntryMeta, OpenOpts, Sink,
};
use crate::error::{Error, Result};
use crate::fidelity::{Fidelity, FidelityReport, Rung};
use crate::format::{CodecCaps, ContainerCaps, FormatId, FormatMeta, MagicRule};
use crate::ladder::Resolved;
use crate::source::Source;

pub use crate::conformance::{
    assert_codec_conforms, assert_codec_conforms_with, compressible, incompressible,
};
pub use crate::container_conformance::{
    ContainerFixture, ExpectedEntry, assert_container_conforms, assert_container_conforms_skipping,
    assert_container_conforms_with, assert_container_conforms_with_skipping, open_forward_only,
};
pub use crate::honesty::{
    Attestation, check_display_has_no_raw_controls, check_entries_carried, check_entry_count,
    check_entry_size, check_error_is_classified, check_extraction_contained, check_fidelity_claim,
    check_salvage_claim,
};

/// The fuzzer's codec selector table: byte `n % CODEC_SLOTS.len()` names a
/// format, so this ordering is the wire format of every GENERATED corpus seed.
///
/// **Append only. NEVER reorder, never remove — retire a slot by leaving it in
/// place.** Reordering silently changes what every generated seed means: a
/// seed written for `bzip2` would start feeding `brotli` instead, and nothing
/// would fail to tell you.
///
/// **What append-only protects is narrower than "every input on disk".** The
/// generator writes each seed's canonical index, below `len`, which no append
/// moves. An input the FUZZER accumulated carries whatever byte mutation left,
/// and appending changes `len` and with it `n % len`: measured at Salvage
/// Stage 3 Task 2's append to [`SALVAGE_SLOTS`], 4,491 of 12,013 accumulated
/// `salvage` inputs (37%) now route to a different slot. That is harmless —
/// `fuzz/corpus` is regenerated and gitignored — but it is not protected.
///
/// This lives in `stuffr-core` rather than in the fuzz targets because a later
/// task's corpus generator runs inside this crate and must write the *same*
/// selector byte the targets decode. `stuffr-core` cannot depend on `fuzz/`,
/// which is excluded from the workspace, so a copy in each would be free to
/// drift — precisely the failure the append-only rule exists to prevent.
pub const CODEC_SLOTS: &[&str] = &[
    "gzip", "zlib", "deflate", "bzip2", "brotli", "lz4", "snappy", "zstd", "xz", "lzma", "lzip",
    // Phase 3b. APPENDED, never inserted: the index of each name is the
    // selector byte of every generated corpus seed. `compress` is
    // read-only, so its corpus seed comes from a committed fixture rather
    // than from encoding through this build's own code — see
    // `crates/stuffr/tests/fuzz_corpus.rs`.
    "compress",
];

/// The fuzzer's container selector table. Same append-only rule as
/// [`CODEC_SLOTS`], for the same reason.
pub const CONTAINER_SLOTS: &[&str] = &[
    "tar", "ar", "cpio", "zip",
    // Phase 3b. APPENDED, never inserted, same reason as `compress` above.
    // Their corpus seeds are fixture-sourced rather than written by this
    // build — which was because neither could write when the slots landed,
    // and is now a deliberate choice: `lha` gained an encoder in Phase 3c
    // Task 6 and `arj` in Task 7, and both seeds still come from
    // `fixtures/legacy/` so the fuzzer explores outward from bytes this
    // project's own encoders did not produce. See `fuzz_corpus.rs`'s
    // `legacy_container_fixture`.
    "lha", "arj",
    // Phase 3c. APPENDED, never inserted. Read-only too, and the two slots
    // whose framing and decoders are this project's own from-scratch code
    // rather than a wrapped crate — which is precisely the kind the
    // `container` target exists to hammer. `zoo` adds a shape no other slot
    // has: a directory chain of attacker-controlled absolute file offsets,
    // where a mutated link is a walk that must still terminate.
    "arc", "zoo",
];

/// The `salvage` fuzz target's own selector table: its leading byte, `n %
/// SALVAGE_SLOTS.len()`, names the format `stuffr::entries::SalvageOpts::format`
/// is forced to — the same leading-selector-byte shape [`CONTAINER_SLOTS`]
/// already uses, rather than a second one invented for this target.
///
/// Lists only formats `stuffr::entries::salvage_scanner` actually dispatches
/// to a real scanner: `zip` (Salvage Stage 1), `arc` (Stage 2 Task 3), `zoo`
/// (Stage 2 Task 4), `lha` (Stage 2 Task 5), `arj` (Stage 2 Task 6), `tar`
/// (Stage 3 Task 2), `cpio` (Stage 3 Task 3) and `ar` (Stage 3 Task 4) —
/// every registered container, as of that task. A format with no scanner
/// answers `Error::Unsupported` from that dispatch (a claim about this BUILD,
/// not the archive; see `salvage_scan`'s own doc), so listing one here
/// before its own scanner lands would spend a share of every fuzzing run
/// proving nothing but that already-known refusal. Append a name in the same
/// commit that wires its scanner into `salvage_scanner`, never before.
///
/// **This is the fuzz target's wire format, not the answer to "which formats
/// can be salvaged"** — that is [`crate::ContainerCaps::salvage`], which
/// `stuffr::entries`' `salvage_caps_tests` pins to the dispatch for every
/// registered container (Salvage Stage 3 Task 5 deleted the older test that
/// pinned this list to the dispatch instead). A slot naming a format with no
/// scanner still fails loudly: the fuzz target's `attestation` and the corpus
/// generator's `top_tier` both read `stuffr::entries::salvage_attestation`,
/// and panic on `None`.
///
/// **Append-only, the identical rule [`CODEC_SLOTS`] and [`CONTAINER_SLOTS`]
/// carry, for the identical reason: the index is the wire format of every
/// generated corpus seed** — and, as [`CODEC_SLOTS`] says, of nothing the
/// fuzzer accumulated, whose `n % len` an append does move. Never reorder,
/// never remove — retire a slot by leaving it in place.
pub const SALVAGE_SLOTS: &[&str] = &["zip", "arc", "zoo", "lha", "arj", "tar", "cpio", "ar"];

/// The per-entry ceiling the `salvage` fuzz target runs under, in place of
/// [`crate::salvage::SalvagePolicy`]'s own 4 GiB default.
///
/// It lives here rather than in `fuzz/fuzz_targets/salvage.rs` for the same
/// reason [`SALVAGE_SLOTS`] does: `fuzz/` is excluded from the workspace, so
/// nothing the gate runs can see a constant declared there — and a ceiling
/// only the fuzz target knows is a ceiling no test can check a seed against.
/// Stage 2 Task 8 shipped it as a target-local constant and the review found
/// the consequence immediately: a future seed carrying an entry over it would
/// be silently `Unverified(OverEntryCeiling)` inside every run, contributing
/// nothing, with the whole suite green.
/// `crates/stuffr/tests/fuzz_corpus.rs`'s
/// `every_salvage_seed_is_scanned_the_way_the_fuzz_target_scans_it` now
/// asserts against this figure directly.
///
/// **256 KiB, and the number is a DISK bound, not only an allocation one**,
/// because that target writes what it recovers into a real destination
/// (Ruling S-O). It sits more than an order of magnitude above the largest
/// entry any seed carries, so nothing the corpus starts from is refused for
/// its size; an entry a mutation inflated past it is reported
/// `Unverified(OverEntryCeiling)` — a per-entry STATUS, never an error, so it
/// cannot end a run or take the entries around it with it.
pub const SALVAGE_FUZZ_MAX_ENTRY: u64 = 256 * 1024;

pub const MOCK_CODEC: FormatId = FormatId::new("mock-codec");
pub const MOCK_CONTAINER: FormatId = FormatId::new("mock-container");

/// A symmetric XOR-0xFF "codec". Trivially verifiable, and symmetric so a
/// round-trip bug cannot hide behind a matching pair of mistakes.
pub struct MockCodec;

struct XorReader(Box<dyn Read + Send>);

impl Read for XorReader {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let n = self.0.read(buf)?;
        for b in &mut buf[..n] {
            *b ^= 0xFF;
        }
        Ok(n)
    }
}

struct XorSink(Box<dyn Write + Send>);

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

    fn flush(&mut self) -> std::io::Result<()> {
        self.0.flush()
    }
}

impl Sink for XorSink {
    fn finish(mut self: Box<Self>) -> Result<()> {
        self.0.flush()?;
        Ok(())
    }
}

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

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

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

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

impl MockCodec {
    /// Stands in for what a real MT codec does: ask the governor for workers,
    /// use them, release. The mock immediately releases; a real codec would
    /// hold the set for the duration of the work.
    pub fn workers_for_opts(&self, o: &DecodeOpts) -> usize {
        match (&o.governor, o.threads) {
            (Some(g), want) => g.acquire_many(want.unwrap_or(1), 0).workers(),
            (None, _) => 1,
        }
    }
}

/// A deliberately ZIP-shaped mock container.
///
/// ```text
/// repeat: "ME" | name_len u16le | name | data_len u64le | data
/// footer: "MI" | count u32le | count * (offset u64le) | "MEND"
/// ```
///
/// `forward_parse` walks the `ME` records; `trailing_index` marks the `MI`
/// footer as authoritative. That combination is what exercises the same ladder
/// branches a real zip does.
pub struct MockContainer;

/// Builds a valid mock archive in memory. Used by tests across the crate.
pub fn mock_archive_bytes(entries: &[(&str, &[u8])]) -> Vec<u8> {
    let mut out = Vec::new();
    let mut offsets = Vec::new();
    for (name, data) in entries {
        offsets.push(out.len() as u64);
        out.extend_from_slice(b"ME");
        out.extend_from_slice(&(name.len() as u16).to_le_bytes());
        out.extend_from_slice(name.as_bytes());
        out.extend_from_slice(&(data.len() as u64).to_le_bytes());
        out.extend_from_slice(data);
    }
    out.extend_from_slice(b"MI");
    out.extend_from_slice(&(entries.len() as u32).to_le_bytes());
    for o in &offsets {
        out.extend_from_slice(&o.to_le_bytes());
    }
    out.extend_from_slice(b"MEND");
    out
}

pub struct MockArchiveRead {
    buf: Vec<u8>,
    pos: usize,
    report: FidelityReport,
    index: Option<Vec<u64>>,
}

impl MockContainer {
    fn parse_index(buf: &[u8]) -> Option<Vec<u64>> {
        if !buf.ends_with(b"MEND") {
            return None;
        }
        // Walk back: MEND(4) + offsets(8*count) + count(4) + "MI"(2)
        let end = buf.len() - 4;
        // Find "MI" by trying each plausible count.
        for count in 0..=((end.saturating_sub(6)) / 8) {
            let start = end.checked_sub(8 * count + 4 + 2)?;
            if &buf[start..start + 2] == b"MI" {
                let declared =
                    u32::from_le_bytes(buf[start + 2..start + 6].try_into().ok()?) as usize;
                if declared != count {
                    continue;
                }
                let mut offsets = Vec::with_capacity(count);
                for i in 0..count {
                    let o = start + 6 + i * 8;
                    offsets.push(u64::from_le_bytes(buf[o..o + 8].try_into().ok()?));
                }
                return Some(offsets);
            }
        }
        None
    }

    /// First offset at which a record marker appears. Used only by the
    /// Degraded rung, where the leading bytes cannot be trusted.
    fn find_first_record(buf: &[u8]) -> Option<usize> {
        buf.windows(2).position(|w| w == b"ME")
    }
}

impl Container for MockContainer {
    fn id(&self) -> FormatId {
        MOCK_CONTAINER
    }

    fn caps(&self) -> ContainerCaps {
        ContainerCaps {
            read: true,
            write: true,
            forward_parse: true,
            trailing_index: true,
            ..Default::default()
        }
    }

    fn open(&self, resolved: Resolved, _o: &OpenOpts) -> Result<Box<dyn ArchiveRead>> {
        let Resolved {
            mut source,
            rung,
            report,
            ..
        } = resolved;
        let seekable = source.caps().seekable;
        let mut buf = Vec::new();
        source.read_to_end(&mut buf)?;

        // Degraded means "salvage what you can": do not trust the stream to
        // begin at a record boundary, scan for one. Reachable because the
        // ladder only ever selects Degraded for a NON-seekable source — if it
        // were seekable, rung 1 would have returned Exact long before.
        let pos = if rung == Rung::Degraded {
            Self::find_first_record(&buf).unwrap_or(buf.len())
        } else {
            0
        };

        let index = if seekable {
            Self::parse_index(&buf)
        } else {
            None
        };

        // Start from the ladder's report rather than re-deriving it, then add
        // only what parsing itself discovered.
        let mut report = report;
        if seekable && index.is_none() {
            report.warn(Fidelity::TruncatedStream {
                at: buf.len() as u64,
            });
        }

        Ok(Box::new(MockArchiveRead {
            buf,
            pos,
            report,
            index,
        }))
    }

    fn create(&self, dst: Box<dyn Sink>, _o: &CreateOpts) -> Result<Box<dyn ArchiveWrite>> {
        Ok(Box::new(MockArchiveWrite {
            dst,
            offsets: Vec::new(),
            written: 0,
        }))
    }
}

impl MockArchiveRead {
    fn read_record_at(&self, at: usize) -> Result<Option<(EntryMeta, usize, usize)>> {
        let b = &self.buf;
        if at + 2 > b.len() || &b[at..at + 2] != b"ME" {
            return Ok(None);
        }
        let name_len = u16::from_le_bytes(
            b[at + 2..at + 4]
                .try_into()
                .map_err(|_| Error::Corrupt("short name_len".into()))?,
        ) as usize;
        let name_at = at + 4;
        let size_at = name_at + name_len;
        if size_at + 8 > b.len() {
            return Err(Error::Corrupt("truncated entry header".into()));
        }
        let name = String::from_utf8_lossy(&b[name_at..size_at]).into_owned();
        let data_len = u64::from_le_bytes(
            b[size_at..size_at + 8]
                .try_into()
                .map_err(|_| Error::Corrupt("short len".into()))?,
        ) as usize;
        let data_at = size_at + 8;
        if data_at + data_len > b.len() {
            return Err(Error::Corrupt("truncated entry data".into()));
        }
        let mut meta = EntryMeta::file(name);
        meta.size = Some(data_len as u64);
        Ok(Some((meta, data_at, data_len)))
    }
}

impl ArchiveRead for MockArchiveRead {
    fn next_entry(&mut self) -> Result<Option<Entry<'_>>> {
        let Some((meta, data_at, data_len)) = self.read_record_at(self.pos)? else {
            return Ok(None);
        };
        self.pos = data_at + data_len;
        let slice = &self.buf[data_at..data_at + data_len];
        Ok(Some(Entry::new(
            meta,
            Box::new(std::io::Cursor::new(slice)),
        )))
    }

    fn by_index(&mut self, index: usize) -> Result<Entry<'_>> {
        let offsets = self
            .index
            .as_ref()
            .ok_or(Error::NotSeekable {
                format: MOCK_CONTAINER,
            })?
            .clone();
        let at = *offsets
            .get(index)
            .ok_or_else(|| Error::EntryNotFound(index.to_string()))?;
        let (meta, data_at, data_len) = self
            .read_record_at(at as usize)?
            .ok_or_else(|| Error::Corrupt("index points at a non-record".into()))?;
        let slice = &self.buf[data_at..data_at + data_len];
        Ok(Entry::new(meta, Box::new(std::io::Cursor::new(slice))))
    }

    fn fidelity(&self) -> &FidelityReport {
        &self.report
    }
}

pub struct MockArchiveWrite {
    dst: Box<dyn Sink>,
    offsets: Vec<u64>,
    written: u64,
}

impl ArchiveWrite for MockArchiveWrite {
    fn add(&mut self, meta: &EntryMeta, data: &mut dyn Read) -> Result<()> {
        let mut payload = Vec::new();
        data.read_to_end(&mut payload)?;

        self.offsets.push(self.written);
        let name = meta.name.as_bytes();
        self.dst.write_all(b"ME")?;
        self.dst.write_all(&(name.len() as u16).to_le_bytes())?;
        self.dst.write_all(name)?;
        self.dst.write_all(&(payload.len() as u64).to_le_bytes())?;
        self.dst.write_all(&payload)?;
        self.written += 2 + 2 + name.len() as u64 + 8 + payload.len() as u64;
        Ok(())
    }

    fn finish(mut self: Box<Self>) -> Result<Box<dyn Sink>> {
        self.dst.write_all(b"MI")?;
        self.dst
            .write_all(&(self.offsets.len() as u32).to_le_bytes())?;
        for o in &self.offsets {
            self.dst.write_all(&o.to_le_bytes())?;
        }
        self.dst.write_all(b"MEND")?;
        // Returned, not finished: completion belongs to the caller, once, at
        // the outermost layer.
        Ok(self.dst)
    }
}

/// A well-behaved FRAMED double for the container conformance harness,
/// analogous to `conformance::framed_mock::FramedMock` on the codec side.
///
/// `MockContainer` above stays exactly as it is — governor, ladder and probe
/// tests rely on its shape — but it reads its whole source to end before
/// returning even the first entry, which is fine for those tests and would
/// fail the harness's incrementality property outright (Task 2). This double
/// streams instead: [`ArchiveRead::next_entry`] parses one length-prefixed
/// record at a time and only ever buffers a single entry's payload, never the
/// whole archive.
///
/// Wire format:
/// ```text
/// repeat: "FE" | name_len u32le | name | data_len u64le | data
/// trailer: "FZ"
/// ```
pub struct FramedMockContainer;

pub const FRAMED_CONTAINER: FormatId = FormatId::new("framed-mock-container");

const FRAMED_MAGICS: &[MagicRule] = &[MagicRule {
    offset: 0,
    bytes: b"FE",
    format: FRAMED_CONTAINER,
}];

/// Registration metadata for [`FramedMockContainer`], for
/// `assert_container_conforms(&FramedMockContainer, &framed_container_meta())`.
pub fn framed_container_meta() -> FormatMeta {
    FormatMeta::container(FRAMED_CONTAINER, &["fmc"], FRAMED_MAGICS)
}

impl Container for FramedMockContainer {
    fn id(&self) -> FormatId {
        FRAMED_CONTAINER
    }

    fn caps(&self) -> ContainerCaps {
        ContainerCaps {
            read: true,
            write: true,
            forward_parse: true,
            ..Default::default()
        }
    }

    fn open(&self, resolved: Resolved, _o: &OpenOpts) -> Result<Box<dyn ArchiveRead>> {
        let Resolved { source, report, .. } = resolved;
        Ok(Box::new(FramedArchiveRead {
            source,
            pending: 0,
            report,
        }))
    }

    fn create(&self, dst: Box<dyn Sink>, _o: &CreateOpts) -> Result<Box<dyn ArchiveWrite>> {
        Ok(Box::new(FramedArchiveWrite { dst }))
    }
}

struct FramedArchiveWrite {
    dst: Box<dyn Sink>,
}

impl ArchiveWrite for FramedArchiveWrite {
    fn add(&mut self, meta: &EntryMeta, data: &mut dyn Read) -> Result<()> {
        let mut payload = Vec::new();
        data.read_to_end(&mut payload)?;
        let name = meta.name.as_bytes();
        self.dst.write_all(b"FE")?;
        self.dst.write_all(&(name.len() as u32).to_le_bytes())?;
        self.dst.write_all(name)?;
        self.dst.write_all(&(payload.len() as u64).to_le_bytes())?;
        self.dst.write_all(&payload)?;
        Ok(())
    }

    fn finish(mut self: Box<Self>) -> Result<Box<dyn Sink>> {
        self.dst.write_all(b"FZ")?;
        Ok(self.dst)
    }
}

/// Bounds reads to `*remaining` bytes of `*source`, decrementing it as bytes
/// are actually delivered. Lets [`FramedArchiveRead::next_entry`] tell how
/// many bytes of a partially-read entry still need to be skipped before the
/// next record can be parsed.
struct BoundedReader<'a> {
    source: &'a mut Box<dyn Source>,
    remaining: &'a mut u64,
}

impl Read for BoundedReader<'_> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if *self.remaining == 0 {
            return Ok(0);
        }
        let cap = (buf.len() as u64).min(*self.remaining) as usize;
        let n = self.source.read(&mut buf[..cap])?;
        *self.remaining -= n as u64;
        Ok(n)
    }
}

/// Streams one length-prefixed record at a time — see the struct's own doc
/// comment on why `MockArchiveRead`'s whole-source read cannot stand in once
/// the incrementality property (Task 2) exists.
struct FramedArchiveRead {
    source: Box<dyn Source>,
    /// Bytes of the current entry's payload not yet delivered to the caller.
    pending: u64,
    report: FidelityReport,
}

impl FramedArchiveRead {
    /// Discards whatever is left of the entry the caller did not fully read,
    /// so the next call starts exactly at the next record's tag.
    fn skip_pending(&mut self) -> Result<()> {
        if self.pending > 0 {
            let mut reader = BoundedReader {
                source: &mut self.source,
                remaining: &mut self.pending,
            };
            std::io::copy(&mut reader, &mut std::io::sink())?;
        }
        Ok(())
    }
}

/// Reads exactly `buf.len()` bytes, reclassifying a bare `UnexpectedEof` —
/// the shape every truncated stream produces once it runs out of bytes
/// mid-record — onto [`Error::Corrupt`], so a cut archive surfaces as
/// `io::ErrorKind::InvalidData` (conformance property 9) rather than a
/// generic `Error::Io`. Any other kind, notably a genuine source failure such
/// as `PermissionDenied`, passes through unchanged as `Error::Io` so it is
/// never mistaken for corruption (property 10).
fn read_exact_or_corrupt(source: &mut Box<dyn Source>, buf: &mut [u8]) -> Result<()> {
    source.read_exact(buf).map_err(|e| {
        if e.kind() == std::io::ErrorKind::UnexpectedEof {
            Error::Corrupt("framed mock container: truncated stream".into())
        } else {
            Error::Io(e)
        }
    })
}

impl ArchiveRead for FramedArchiveRead {
    fn next_entry(&mut self) -> Result<Option<Entry<'_>>> {
        self.skip_pending()?;

        let mut tag = [0u8; 2];
        read_exact_or_corrupt(&mut self.source, &mut tag)?;
        match &tag {
            b"FZ" => Ok(None),
            b"FE" => {
                let mut len_buf = [0u8; 4];
                read_exact_or_corrupt(&mut self.source, &mut len_buf)?;
                let name_len = u32::from_le_bytes(len_buf) as usize;
                let mut name_buf = vec![0u8; name_len];
                read_exact_or_corrupt(&mut self.source, &mut name_buf)?;
                let name = String::from_utf8_lossy(&name_buf).into_owned();

                let mut dlen_buf = [0u8; 8];
                read_exact_or_corrupt(&mut self.source, &mut dlen_buf)?;
                let data_len = u64::from_le_bytes(dlen_buf);
                self.pending = data_len;

                let mut meta = EntryMeta::file(name);
                meta.size = Some(data_len);

                let reader = BoundedReader {
                    source: &mut self.source,
                    remaining: &mut self.pending,
                };
                Ok(Some(Entry::new(meta, Box::new(reader))))
            }
            _ => Err(Error::Corrupt(
                "framed mock container: unrecognised record tag".into(),
            )),
        }
    }

    fn by_index(&mut self, _index: usize) -> Result<Entry<'_>> {
        // No index is implemented by this double — every consumer of it so
        // far only needs forward iteration.
        Err(Error::NotSeekable {
            format: FRAMED_CONTAINER,
        })
    }

    fn fidelity(&self) -> &FidelityReport {
        &self.report
    }
}

/// A `'static`, cloneable in-memory sink.
///
/// `Codec::encoder` takes `Box<dyn Write + Send>` and `Container::create` a
/// `Box<dyn Sink>` (a `SharedBuf` reaches that through [`crate::PlainSink`]),
/// both implicitly `+ 'static`, so a test cannot hand them `&mut local_vec`.
/// Cloning a `SharedBuf` gives the test a handle on whatever the writer wrote.
#[derive(Clone, Default)]
pub struct SharedBuf(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);

impl SharedBuf {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn contents(&self) -> Vec<u8> {
        self.0.lock().expect("SharedBuf mutex poisoned").clone()
    }
}

impl Write for SharedBuf {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.0
            .lock()
            .expect("SharedBuf mutex poisoned")
            .extend_from_slice(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

/// A [`Source`] that delivers `prefix` and then fails with `kind` forever.
///
/// The shape every "where does this error land, and how is it classified?"
/// test needs: the prefix is what lets a container get far enough to reach the
/// read that matters, and the failure is what that read then meets.
///
/// Pair it with [`decode_side_failing_source`] and [`raw_failing_source`],
/// which are the same bytes with and without
/// [`crate::source::mark_decode_side`] applied. Those two are the only
/// difference the classification turns on, so a test that runs both proves the
/// marking is what decided — not the error's kind, and not the call site.
pub struct FailsAfterPrefix {
    prefix: Vec<u8>,
    pos: usize,
    kind: std::io::ErrorKind,
    message: &'static str,
}

impl Read for FailsAfterPrefix {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if self.pos < self.prefix.len() {
            let n = (self.prefix.len() - self.pos).min(buf.len());
            buf[..n].copy_from_slice(&self.prefix[self.pos..self.pos + n]);
            self.pos += n;
            return Ok(n);
        }
        Err(std::io::Error::new(self.kind, self.message))
    }
}

impl Source for FailsAfterPrefix {
    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
    }
}

/// The message [`decode_side_failing_source`] and [`raw_failing_source`] raise,
/// so a test can assert the decoder's own wording survived classification.
pub const FAILING_SOURCE_MESSAGE: &str = "the stream is malformed from here on";

/// `prefix` bytes, then a failure of `kind`, **marked as decode-side**.
///
/// Models a codec decoder that produced good bytes and then met malformed
/// input — the exact shape a 21-byte zstd frame whose decoded bytes open with
/// ARJ's `60 EA` magic presents to everything above it.
pub fn decode_side_failing_source(prefix: &[u8], kind: std::io::ErrorKind) -> Box<dyn Source> {
    crate::source::DecodeSideSource::wrap(raw_failing_source(prefix, kind))
}

/// `prefix` bytes, then a failure of `kind`, **unmarked**.
///
/// Models the raw source failing — a disk error, a pipe that broke — which
/// must stay [`crate::Error::Io`] however the failing read is spelled.
pub fn raw_failing_source(prefix: &[u8], kind: std::io::ErrorKind) -> Box<dyn Source> {
    Box::new(FailsAfterPrefix {
        prefix: prefix.to_vec(),
        pos: 0,
        kind,
        message: FAILING_SOURCE_MESSAGE,
    })
}

/// A reader that returns at most `chunk` bytes per `read` call, so tests can
/// exercise paths that only appear across several short reads. A `Cursor` hands
/// over everything at once and hides them.
pub struct ChunkedReader {
    data: Vec<u8>,
    pos: usize,
    chunk: usize,
}

impl ChunkedReader {
    pub fn new(data: Vec<u8>, chunk: usize) -> Self {
        assert!(chunk > 0, "chunk must be non-zero");
        Self {
            data,
            pos: 0,
            chunk,
        }
    }
}

impl Read for ChunkedReader {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let n = self.chunk.min(buf.len()).min(self.data.len() - self.pos);
        buf[..n].copy_from_slice(&self.data[self.pos..self.pos + n]);
        self.pos += n;
        Ok(n)
    }
}

/// A source that counts the bytes it DELIVERS — every byte a scanner asked
/// for and got, re-reads included. Wrapped around the source handed to a
/// `salvage_*` entry point, it measures the scan's work in the unit
/// [`check_scan_is_linear`] bounds.
#[derive(Debug)]
pub struct CountingSource<R> {
    inner: R,
    read: u64,
}

impl<R> CountingSource<R> {
    pub fn new(inner: R) -> Self {
        Self { inner, read: 0 }
    }
    pub fn bytes_read(&self) -> u64 {
        self.read
    }
    pub fn into_inner(self) -> R {
        self.inner
    }
}

impl<R: std::io::Read> std::io::Read for CountingSource<R> {
    fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
        let n = self.inner.read(out)?;
        self.read += n as u64;
        Ok(n)
    }
}

impl<R: std::io::Seek> std::io::Seek for CountingSource<R> {
    fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result<u64> {
        self.inner.seek(to)
    }
}

/// The bound every salvage scan is held to: bytes delivered to the scanner
/// at most `SCAN_READ_FACTOR × file_len + SCAN_READ_SLACK`. The `salvage`
/// fuzz target applies it to every input's independent second scan, and
/// each scanner's own tests apply it to its hostile shapes at 256 KiB-1 MiB.
///
/// **Measured, 0.10.3 Task 4 (2026-10-09)**, over the local `salvage`
/// corpus — 12,907 inputs, 12,723 reaching a scanner, 0 to 11,529 bytes
/// (13.4 MiB in all) — with `STUFFR_FUZZ_SCAN_TRACE`. Largest ratio of bytes
/// read to input length, per slot, after that task's scanner fixes (before
/// them in brackets):
///
/// | slot | inputs | max ratio | before |
/// |---|---|---|---|
/// | `zip`  | 5,557 | 3.40 | 218.1 |
/// | `zoo`  | 2,075 | 5.72 | 131.9 |
/// | `lha`  |   606 | 3.24 | 106.2 |
/// | `arc`  |   269 | 1.83 |  93.3 |
/// | `arj`  |   202 | 1.09 |  15.0 |
/// | `cpio` |   100 | 2.65 |   3.1 |
/// | `tar`  | 2,792 | 1.60 |   2.2 |
/// | `ar`   | 1,122 | 2.00 |   2.0 |
///
/// No input read past `8 × len`; the largest single scan read 65,499 bytes
/// (`zoo`, an 11,454-byte input), so the tightest input sits 2.4x under
/// this bound. The figures are kept at the plan's ceiling rather than
/// lowered to the corpus: fuzz-scale inputs (≤ 11.5 KiB) sit almost wholly
/// inside the slack, and the scanners' own MiB-scale hostile fixtures
/// still reach 6-8x once fixed (`tar_salvage.rs`'s converging and
/// mixed-chain shapes), which a tighter factor would fail. Re-measure with the
/// `STUFFR_FUZZ_SCAN_TRACE` recipe in `CONTRIBUTING.md` before changing
/// either figure, and never raise one to fit a scanner.
pub const SCAN_READ_FACTOR: u64 = 8;
/// See [`SCAN_READ_FACTOR`].
pub const SCAN_READ_SLACK: u64 = 64 * 1024;

/// `Err` naming both figures when a scan read more than
/// [`SCAN_READ_FACTOR`] × `file_len` + [`SCAN_READ_SLACK`] bytes — work
/// that grows faster than its input, the class 0.10.3 closed in cpio
/// (zero-run rescans) and tar (converging extension chains).
pub fn check_scan_is_linear(bytes_read: u64, file_len: u64) -> std::result::Result<(), String> {
    let bound = SCAN_READ_FACTOR
        .saturating_mul(file_len)
        .saturating_add(SCAN_READ_SLACK);
    if bytes_read > bound {
        return Err(format!(
            "salvage scan read {bytes_read} bytes of a {file_len}-byte input, past the \
             {SCAN_READ_FACTOR}x + {SCAN_READ_SLACK} bound: its work grows faster than its input"
        ));
    }
    Ok(())
}

/// `Err` unless `sightings` came out of a [`crate::salvage::SightingLog`]
/// with its default cap and stand for exactly `total` sightings (0.10.4):
/// at most [`crate::salvage::SightingLog::DEFAULT_CAP`] stored per (format,
/// shape, kind), each group's stored offsets strictly ascending — the
/// smallest, so the offsets a caller lists are the ones an uncapped list
/// would show — and the stored count plus every [`Sighting::more`] equal to
/// `total`.
///
/// [`Sighting::more`]: crate::salvage::Sighting::more
pub fn check_sightings_bounded(
    sightings: &[crate::salvage::Sighting],
    total: u64,
) -> std::result::Result<(), String> {
    use crate::salvage::{SightingKind, SightingLog};
    let mut groups: Vec<((FormatId, &'static str, SightingKind), usize, u64)> = Vec::new();
    for s in sightings {
        let key = (s.format, s.shape, s.kind);
        match groups.iter_mut().find(|(k, _, _)| *k == key) {
            Some((_, stored, last)) => {
                if s.offset <= *last {
                    return Err(format!(
                        "{} {:?} stored offset {} after {last}: not ascending",
                        s.format, s.shape, s.offset
                    ));
                }
                *stored += 1;
                *last = s.offset;
            }
            None => groups.push((key, 1, s.offset)),
        }
    }
    if let Some(((format, shape, _), stored, _)) = groups
        .iter()
        .find(|(_, stored, _)| *stored > SightingLog::DEFAULT_CAP)
    {
        return Err(format!(
            "{stored} {format} {shape:?} sightings stored, past the cap of {}",
            SightingLog::DEFAULT_CAP
        ));
    }
    let counted: u64 = sightings.iter().map(|s| 1 + s.more).sum();
    if counted != total {
        return Err(format!("the sightings stand for {counted}, not {total}"));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::source::ReaderSource;
    use std::io::Read;

    /// Runs `src` through the ladder with `MockContainer`'s own capabilities
    /// and the default policy, producing the `Resolved` that `open` now
    /// requires. Most tests here care about `open`'s behaviour, not the
    /// ladder's, so this keeps that plumbing out of their way.
    fn resolve_default(src: Box<dyn Source>) -> Resolved {
        crate::resolve(
            src,
            MOCK_CONTAINER,
            MockContainer.caps(),
            &Default::default(),
        )
        .unwrap()
    }

    #[test]
    fn a_decoder_returns_a_source_so_capabilities_survive_the_layer() {
        // The point of the Source return type: a decoded stream can report what
        // it supports. The ordinary codec reports no seek; a codec with a frame
        // index would report otherwise, and the ladder could then run between
        // codec and container.
        let encoded: Vec<u8> = b"the quick brown fox".iter().map(|b| b ^ 0xFF).collect();
        let src: Box<dyn Source> = Box::new(ReaderSource::new(std::io::Cursor::new(encoded)));
        let dec = MockCodec.decoder(src, &DecodeOpts::default()).unwrap();
        assert!(!dec.caps().seekable);
    }

    #[test]
    fn mock_codec_round_trips() {
        let plain = b"the quick brown fox".to_vec();
        let codec = MockCodec;

        let sink = SharedBuf::new();
        {
            let mut s = codec
                .encoder(Box::new(sink.clone()), &EncodeOpts::default())
                .unwrap();
            std::io::Write::write_all(&mut s, &plain).unwrap();
            s.finish().unwrap();
        }
        let encoded = sink.contents();
        assert_ne!(encoded, plain, "the mock must actually transform the bytes");

        let src: Box<dyn Source> = Box::new(ReaderSource::new(std::io::Cursor::new(encoded)));
        let mut dec = codec.decoder(src, &DecodeOpts::default()).unwrap();
        let mut out = Vec::new();
        dec.read_to_end(&mut out).unwrap();
        assert_eq!(out, plain);
    }

    #[test]
    fn mock_codec_declares_both_directions() {
        let c = MockCodec.caps();
        assert!(c.encode && c.decode);
    }

    #[test]
    fn mock_archive_reads_back_every_entry_in_order() {
        let bytes = mock_archive_bytes(&[("a.txt", b"alpha"), ("b.bin", b"bravo!!")]);
        let src: Box<dyn Source> = Box::new(ReaderSource::new(std::io::Cursor::new(bytes)));
        let mut ar = MockContainer
            .open(resolve_default(src), &OpenOpts::default())
            .unwrap();

        let mut seen = Vec::new();
        while let Some(mut e) = ar.next_entry().unwrap() {
            let name = e.meta().name.clone();
            let mut data = Vec::new();
            e.reader().read_to_end(&mut data).unwrap();
            seen.push((name, data));
        }

        assert_eq!(seen.len(), 2);
        assert_eq!(seen[0], ("a.txt".to_string(), b"alpha".to_vec()));
        assert_eq!(seen[1], ("b.bin".to_string(), b"bravo!!".to_vec()));
    }

    #[test]
    fn mock_container_declares_zip_shaped_capabilities() {
        let c = MockContainer.caps();
        assert!(c.read && c.write);
        assert!(c.forward_parse, "must exercise the ForwardOnly rung");
        assert!(c.trailing_index, "must exercise the index-loss warning");
        assert!(!c.needs_seek);
    }

    #[test]
    fn mock_archive_writer_output_is_readable_by_the_reader() {
        let sink = SharedBuf::new();
        {
            let mut w = MockContainer
                .create(
                    crate::archive::PlainSink::new(Box::new(sink.clone())),
                    &CreateOpts::default(),
                )
                .unwrap();
            w.add(&EntryMeta::file("only.txt"), &mut &b"hello"[..])
                .unwrap();
            w.finish().unwrap().finish().unwrap();
        }
        let buf = sink.contents();
        let src: Box<dyn Source> = Box::new(ReaderSource::new(std::io::Cursor::new(buf)));
        let mut ar = MockContainer
            .open(resolve_default(src), &OpenOpts::default())
            .unwrap();
        let mut e = ar.next_entry().unwrap().expect("one entry");
        assert_eq!(e.meta().name, "only.txt");
        let mut data = Vec::new();
        e.reader().read_to_end(&mut data).unwrap();
        assert_eq!(data, b"hello");
    }

    #[test]
    fn traits_are_object_safe() {
        // Regression guard: a `&self`-less or generic method would break every
        // registry lookup, and the failure would surface far from the cause.
        let _c: &dyn Codec = &MockCodec;
        let _k: &dyn Container = &MockContainer;
    }

    #[test]
    fn by_index_reaches_entries_out_of_order_and_agrees_with_sequential_reads() {
        // by_index trusts offsets recorded by the writer. Reading out of order
        // is what distinguishes real random access from an accidental
        // sequential walk, and cross-checking against next_entry proves the
        // two paths agree rather than merely that each returns something.
        let bytes =
            mock_archive_bytes(&[("a.txt", b"alpha"), ("b.bin", b"bravo!!"), ("c.log", b"")]);

        let seekable = || -> Box<dyn Source> {
            let mut f = tempfile::NamedTempFile::new().unwrap();
            std::io::Write::write_all(&mut f, &bytes).unwrap();
            let (_, path) = f.keep().unwrap();
            Box::new(crate::source::FileSource::open(&path).unwrap())
        };

        // Sequential pass, for cross-checking.
        let mut ar = MockContainer
            .open(resolve_default(seekable()), &OpenOpts::default())
            .unwrap();
        let mut sequential = Vec::new();
        while let Some(mut e) = ar.next_entry().unwrap() {
            let name = e.meta().name.clone();
            let mut data = Vec::new();
            e.reader().read_to_end(&mut data).unwrap();
            sequential.push((name, data));
        }

        // Random access, deliberately out of order.
        let mut ar = MockContainer
            .open(resolve_default(seekable()), &OpenOpts::default())
            .unwrap();
        for i in [2usize, 0, 1] {
            let mut e = ar.by_index(i).unwrap();
            let name = e.meta().name.clone();
            let mut data = Vec::new();
            e.reader().read_to_end(&mut data).unwrap();
            assert_eq!(
                (name, data),
                sequential[i].clone(),
                "by_index({i}) disagreed with the sequential read"
            );
        }

        // Past the end is a miss, not a panic or a wrong entry.
        let mut ar = MockContainer
            .open(resolve_default(seekable()), &OpenOpts::default())
            .unwrap();
        assert!(matches!(
            ar.by_index(99),
            Err(crate::Error::EntryNotFound(_))
        ));
    }

    #[test]
    fn open_reports_lossless_fidelity_on_a_seekable_source() {
        let bytes = mock_archive_bytes(&[("a.txt", b"alpha")]);
        let mut f = tempfile::NamedTempFile::new().unwrap();
        std::io::Write::write_all(&mut f, &bytes).unwrap();
        let src: Box<dyn Source> = Box::new(crate::source::FileSource::open(f.path()).unwrap());

        let ar = MockContainer
            .open(resolve_default(src), &OpenOpts::default())
            .unwrap();
        let report = ar.fidelity();
        assert_eq!(report.rung, crate::Rung::Exact);
        assert!(
            report.is_lossless(),
            "a seekable source must yield an authoritative, warning-free report"
        );
    }

    #[test]
    fn open_reports_index_and_count_loss_on_a_non_seekable_source() {
        let bytes = mock_archive_bytes(&[("a.txt", b"alpha")]);
        let src: Box<dyn Source> = Box::new(ReaderSource::new(std::io::Cursor::new(bytes)));

        let ar = MockContainer
            .open(resolve_default(src), &OpenOpts::default())
            .unwrap();
        let report = ar.fidelity();
        assert_eq!(report.rung, crate::Rung::ForwardOnly);
        assert!(
            report
                .warnings
                .contains(&crate::Fidelity::TrailingIndexUnread {
                    format: MOCK_CONTAINER
                })
        );
        assert!(
            report
                .warnings
                .contains(&crate::Fidelity::EntryCountUnknown)
        );
    }

    #[test]
    fn a_container_can_see_the_rung_it_was_opened_at() {
        // Before this change the ladder could select Degraded but no container
        // could learn it had been asked for a salvage scan.
        let bytes = mock_archive_bytes(&[("a.txt", b"alpha")]);
        let caps = ContainerCaps {
            degraded_parse: true,
            ..MockContainer.caps()
        };
        let policy = crate::StreamPolicy::Adaptive {
            allow_forward_only: false,
            spill: crate::SpillPolicy::Off,
            allow_degraded: true,
        };
        let src: Box<dyn Source> = Box::new(ReaderSource::new(std::io::Cursor::new(bytes)));
        let resolved = crate::resolve(src, MOCK_CONTAINER, caps, &policy).unwrap();
        assert_eq!(resolved.rung, crate::Rung::Degraded);

        let ar = MockContainer.open(resolved, &OpenOpts::default()).unwrap();
        assert_eq!(
            ar.fidelity().rung,
            crate::Rung::Degraded,
            "the rung must reach the container"
        );
    }

    #[test]
    fn a_spilled_read_reports_spilled_without_a_manual_merge() {
        // The ladder spills, so the container sees a SEEKABLE source. Before
        // this change it therefore reported Exact, and the spill was invisible
        // to anyone reading fidelity() alone.
        let bytes = mock_archive_bytes(&[("a.txt", b"alpha")]);
        let policy = crate::StreamPolicy::Adaptive {
            allow_forward_only: false,
            spill: crate::SpillPolicy::default(),
            allow_degraded: true,
        };
        let src: Box<dyn Source> = Box::new(ReaderSource::new(std::io::Cursor::new(bytes)));
        let resolved = crate::resolve(src, MOCK_CONTAINER, MockContainer.caps(), &policy).unwrap();
        assert_eq!(resolved.rung, crate::Rung::Spilled);

        let ar = MockContainer.open(resolved, &OpenOpts::default()).unwrap();
        assert_eq!(ar.fidelity().rung, crate::Rung::Spilled);
        assert!(
            ar.fidelity().is_lossless(),
            "spilling costs disk, not accuracy"
        );
    }

    #[test]
    fn the_container_inherits_the_ladders_seed_rather_than_rederiving_it() {
        // The ladder seeds TrailingIndexUnread + EntryCountUnknown from caps.
        // The container must not independently derive the same two — inheriting
        // them is what removes the duplication merge() had to paper over.
        let bytes = mock_archive_bytes(&[("a.txt", b"alpha")]);
        let src: Box<dyn Source> = Box::new(ReaderSource::new(std::io::Cursor::new(bytes)));
        let resolved = crate::resolve(
            src,
            MOCK_CONTAINER,
            MockContainer.caps(),
            &Default::default(),
        )
        .unwrap();
        let ar = MockContainer.open(resolved, &OpenOpts::default()).unwrap();

        let n = ar
            .fidelity()
            .warnings
            .iter()
            .filter(|w| matches!(w, crate::Fidelity::EntryCountUnknown))
            .count();
        assert_eq!(n, 1, "EntryCountUnknown must appear exactly once");
    }

    #[test]
    fn degraded_salvages_a_stream_that_forward_only_cannot_parse() {
        // Eight bytes of junk before the first record. A forward parse trusts
        // offset 0 and finds nothing; a salvage scan finds the record. Both
        // sources are non-seekable, so this is the difference the Degraded rung
        // actually buys — and it is reachable, unlike a difference gated on
        // seekability, which the ladder never pairs with Degraded.
        let mut bytes = b"JUNKJUNK".to_vec();
        bytes.extend_from_slice(&mock_archive_bytes(&[("a.txt", b"alpha")]));

        let forward = crate::resolve(
            Box::new(ReaderSource::new(std::io::Cursor::new(bytes.clone()))),
            MOCK_CONTAINER,
            MockContainer.caps(),
            &crate::StreamPolicy::default(),
        )
        .unwrap();
        assert_eq!(forward.rung, crate::Rung::ForwardOnly);
        let mut ar = MockContainer.open(forward, &OpenOpts::default()).unwrap();
        assert!(
            ar.next_entry().unwrap().is_none(),
            "a forward parse cannot start mid-junk"
        );

        let caps = ContainerCaps {
            degraded_parse: true,
            ..MockContainer.caps()
        };
        let policy = crate::StreamPolicy::Adaptive {
            allow_forward_only: false,
            spill: crate::SpillPolicy::Off,
            allow_degraded: true,
        };
        let salvage = crate::resolve(
            Box::new(ReaderSource::new(std::io::Cursor::new(bytes))),
            MOCK_CONTAINER,
            caps,
            &policy,
        )
        .unwrap();
        assert_eq!(salvage.rung, crate::Rung::Degraded);
        let mut ar = MockContainer.open(salvage, &OpenOpts::default()).unwrap();
        let mut e = ar
            .next_entry()
            .unwrap()
            .expect("salvage must recover the record");
        assert_eq!(e.meta().name, "a.txt");
        let mut data = Vec::new();
        e.reader().read_to_end(&mut data).unwrap();
        assert_eq!(data, b"alpha");
    }

    #[test]
    fn a_codec_parallelises_only_when_handed_a_governor() {
        // The seam: no ambient global. Without a governor the codec must not
        // claim workers; with one it draws from the shared budget.
        let plain = b"the quick brown fox".to_vec();

        let solo = DecodeOpts::default();
        assert!(solo.governor.is_none());
        assert_eq!(MockCodec.workers_for_opts(&solo), 1);

        let gov = crate::Governor::new(4, 1024 * 1024 * 1024);
        let opts = DecodeOpts {
            threads: Some(4),
            governor: Some(std::sync::Arc::clone(&gov)),
            ..Default::default()
        };
        assert_eq!(MockCodec.workers_for_opts(&opts), 4);
        assert_eq!(gov.outstanding(), 0, "the lease must be released again");

        // Decoding still works either way.
        let encoded: Vec<u8> = plain.iter().map(|b| b ^ 0xFF).collect();
        let src: Box<dyn Source> = Box::new(ReaderSource::new(std::io::Cursor::new(encoded)));
        let mut dec = MockCodec.decoder(src, &opts).unwrap();
        let mut out = Vec::new();
        dec.read_to_end(&mut out).unwrap();
        assert_eq!(out, plain);
    }

    #[test]
    fn opts_debug_does_not_require_a_debug_bound_on_governor() {
        let gov = crate::Governor::new(2, 1024);
        let o = DecodeOpts {
            threads: None,
            governor: Some(gov),
            ..Default::default()
        };
        assert!(format!("{o:?}").contains("governor"));
    }

    #[test]
    fn counting_source_counts_delivered_bytes() {
        use std::io::{Cursor, Seek, SeekFrom};
        let mut src = CountingSource::new(Cursor::new(vec![1u8; 100]));
        let mut buf = [0u8; 30];
        src.read_exact(&mut buf).unwrap();
        src.seek(SeekFrom::Start(0)).unwrap();
        src.read_exact(&mut buf).unwrap();
        assert_eq!(src.bytes_read(), 60);
    }

    #[test]
    fn the_linear_bound_is_factor_times_length_plus_slack() {
        let len = 1_000_000;
        assert!(check_scan_is_linear(SCAN_READ_FACTOR * len + SCAN_READ_SLACK, len).is_ok());
        let err =
            check_scan_is_linear(SCAN_READ_FACTOR * len + SCAN_READ_SLACK + 1, len).unwrap_err();
        assert!(err.contains("read"), "{err}");
    }
}