stuffr-core 0.25.2

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
use std::fmt;

use crate::display::fmt_name;
use crate::format::FormatId;

/// Which rung of the adaptive stream ladder a read landed on.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum Rung {
    /// Input was seekable. Authoritative index, full metadata.
    Exact,
    /// Not seekable, parsed forward. Real data, approximate metadata.
    ForwardOnly,
    /// Spooled to memory/temp then read exactly. Costs disk, not accuracy.
    Spilled,
    /// Best-effort salvage. Partial results by construction.
    Degraded,
}

impl Rung {
    /// Whether the read used the format's authoritative structures.
    ///
    /// Note `Spilled` is authoritative: spilling trades disk for accuracy, and
    /// treating it as lossy would make `--strict-fidelity` reject exact reads.
    pub fn is_authoritative(&self) -> bool {
        matches!(self, Rung::Exact | Rung::Spilled)
    }

    /// Ordering by *quality loss*, worst = highest. Used by `merge`.
    fn severity(&self) -> u8 {
        match self {
            Rung::Exact => 0,
            Rung::Spilled => 1,
            Rung::ForwardOnly => 2,
            Rung::Degraded => 3,
        }
    }
}

impl fmt::Display for Rung {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Rung::Exact => "exact",
            Rung::ForwardOnly => "forward-only",
            Rung::Spilled => "spilled",
            Rung::Degraded => "degraded",
        };
        f.write_str(s)
    }
}

/// Which metadata fields are **missing**. `true` means absent, not present.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct MetaFields {
    pub mtime: bool,
    pub mode: bool,
    pub uid_gid: bool,
    pub comment: bool,
    pub extra: bool,
    pub crc: bool,
}

impl MetaFields {
    pub fn missing(&self) -> Vec<&'static str> {
        let mut v = Vec::new();
        if self.mtime {
            v.push("mtime")
        }
        if self.mode {
            v.push("mode")
        }
        if self.uid_gid {
            v.push("uid_gid")
        }
        if self.comment {
            v.push("comment")
        }
        if self.extra {
            v.push("extra")
        }
        if self.crc {
            v.push("crc")
        }
        v
    }
}

/// One specific, structured thing that was lost or approximated.
#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(tag = "kind", rename_all = "kebab-case"))]
#[non_exhaustive]
pub enum Fidelity {
    #[error(
        "`{format}` central/trailing index was never read; entry metadata came from inline headers"
    )]
    TrailingIndexUnread { format: FormatId },

    #[error("size of entry `{}` was only known after its data (data descriptor)", fmt_name(.entry))]
    SizeFromDataDescriptor { entry: String },

    #[error("total entry count is unknown without the trailing index")]
    EntryCountUnknown,

    /// The archive's own index declares a different number of records than
    /// the reader enumerated. Usually FEWER were enumerated, so entries exist
    /// in the file that no caller can reach; zip can also enumerate MORE, when
    /// its end-of-central-directory record's two counts contradict each other
    /// (the v0.7.0 deep-fuzz finding), so the message names both figures
    /// without saying which way round they are.
    ///
    /// Distinct from [`Self::EntryCountUnknown`], which is the forward reader
    /// admitting it never saw a count at all. Here the count WAS read, from
    /// the format's authoritative structure, and it disagrees with what came
    /// back — the strongest evidence available that a read is incomplete, and
    /// the one a seekable `Rung::Exact` read would otherwise have no way to
    /// express. Without it a partial enumeration is indistinguishable from a
    /// complete one, which is the failure this variant exists to prevent:
    /// listing six of eight records and calling it exact fidelity.
    ///
    /// Raised, not recovered. Reaching the shadowed records would mean
    /// re-parsing the index by hand; naming the shortfall is what the caller
    /// needs in order to know not to trust the result, and
    /// `--strict-fidelity` turns it into exit 4.
    ///
    /// `reason` is an owned `String` for the same reason
    /// [`Self::EntrySkipped`]'s is: the cause is specific to the container
    /// and the reader, and a shortfall that cannot say WHY is one the user
    /// cannot act on.
    #[error(
        "`{format}` index declares {declared} entries but {enumerated} were \
         enumerated: {}",
        fmt_name(.reason)
    )]
    EntryCountMismatch {
        format: FormatId,
        /// What the archive's own index says it holds.
        declared: u64,
        /// What the reader was actually able to enumerate.
        enumerated: u64,
        /// Why the two differ, in terms the caller can act on.
        reason: String,
    },

    #[error("entry `{}` is missing metadata: {}", fmt_name(.entry), fields.missing().join(", "))]
    MetadataIncomplete { entry: String, fields: MetaFields },

    #[error("decoded a solid block, wasting {wasted_bytes} bytes, to reach the requested entry")]
    SolidBlockFullyDecoded { wasted_bytes: u64 },

    #[error("skipped encrypted entry `{}`", fmt_name(.entry))]
    EncryptedEntrySkipped { entry: String },

    /// An entry this build cannot materialise, named along with why.
    ///
    /// Distinct from [`Self::MetadataIncomplete`], which is about an entry
    /// that WAS written and lost some of its metadata: here the entry itself
    /// is absent from the result. Extraction raises it for a device node,
    /// fifo or socket — [`crate::EntryKind::Other`], the honest answer a
    /// container gives for an entry shape `EntryKind` has no variant for yet
    /// — and for a [`crate::EntryKind::Hardlink`] whose target it did not
    /// write, or whose target is a directory. Writing one out as a regular
    /// file carrying its "contents" would be a silent lie about what the
    /// archive held. The write side
    /// raises it too, for something met on disk that no container here can
    /// store — a socket, an undecodable name, a directory being packed into
    /// `ar`.
    ///
    /// `reason` is an owned `String` rather than a `&'static str` because the
    /// write side's reasons carry runtime detail — the failing errno, the
    /// container's own name, the undecodable bytes — and a reason that cannot
    /// name the particular thing that went wrong is a reason the user cannot
    /// act on.
    #[error("skipped entry `{}`: {}", fmt_name(.entry), fmt_name(.reason))]
    EntrySkipped { entry: String, reason: String },

    /// A file that changed length between the moment its size was recorded
    /// and the moment its bytes were read, stored at the length its header
    /// already declares.
    ///
    /// Distinct from [`Self::EntrySkipped`]: the entry IS in the archive, and
    /// the archive is structurally valid. What was lost is the tail of a file
    /// that grew, or the tail of a file that shrank — replaced by zeros,
    /// because the entry header was written before the payload was read and a
    /// container cannot un-write it. Refusing instead would throw away the
    /// whole archive over one file that a live system happened to touch,
    /// which is what `pack ~ -o backup.tar` over a running home directory does
    /// routinely; GNU tar prints `file changed as we read it` and continues,
    /// and this is the same bargain, with the loss named rather than printed
    /// and forgotten.
    ///
    /// `--strict-fidelity` still refuses on it, which is the half of the
    /// bargain that keeps it honest.
    #[error(
        "entry `{}` changed size while it was being read: its header declares \
         {declared} bytes, {}",
        fmt_name(.entry),
        fmt_name(.fixup)
    )]
    EntrySizeChanged {
        entry: String,
        /// The length written into the entry header, from the walk's `stat`.
        declared: u64,
        /// What the file actually supplied and what was done about it.
        ///
        /// Prose rather than a second `u64` because the two directions know
        /// different things: a file that shrank supplies an exact count, while
        /// a file that grew is only known to have had *more* — measuring how
        /// much more would mean reading a tail that is deliberately not being
        /// stored. A field that could name the figure in one case and not the
        /// other would have to lie in one of them.
        fixup: String,
    },

    #[error("stream truncated at offset {at}")]
    TruncatedStream { at: u64 },

    /// A directory record carries a checksum over ITSELF, and it does not
    /// match the bytes the record is made of.
    ///
    /// Distinct from every other integrity signal in this enum: those are
    /// about an entry's CONTENT, and a content checksum that fails is
    /// [`crate::Error::Corrupt`], not a warning, because there is nothing
    /// honest to hand back. This is about the METADATA record, and the
    /// verdict is deliberately softer for one measured reason — the format
    /// that carries such a field may itself treat it as advisory. ZOO is the
    /// first: `zoo` 2.10's own lister prints a `*` beside an entry whose
    /// `dir_crc` fails and carries on listing it, so refusing would be
    /// stricter than the reference implementation, which is how a guard comes
    /// to fire on input a real tool accepts.
    ///
    /// What it must NOT do is stay silent. A record whose own checksum fails
    /// has been altered since it was written, and every field a caller is
    /// about to trust — the entry's name, size, offset, and the link to the
    /// next record — comes out of it. `--strict-fidelity` turns this into
    /// exit 4, which is the whole point: a verb that says "exact fidelity"
    /// over an altered record is making a claim the archive itself disputes.
    ///
    /// `offset` is the record's own position in the file, because a record
    /// that fails its checksum may have no usable name to identify it by —
    /// the reproducer that motivated this variant is a record whose name
    /// field is intact and whose link field is not.
    #[error(
        "`{format}` directory record at offset {offset} fails its own checksum \
         ({computed:#06x} computed against {recorded:#06x} recorded); the record has been \
         altered since it was written"
    )]
    DirectoryRecordChecksum {
        format: FormatId,
        offset: u64,
        computed: u16,
        recorded: u16,
    },

    /// A zip entry's local file header and its central-directory record
    /// disagree on a field both carry — the "cloaking" shape (GHSA-m665-v7pm-
    /// 7grj), where one archive shows different names or contents depending
    /// on which of its two descriptions a reader trusts.
    ///
    /// A warning, not [`crate::Error::Corrupt`]: the bytes handed back are
    /// still a coherent reading (the central directory's on a seekable
    /// source, the local headers' on a pipe), and the archive is not
    /// self-contradictory within either description. What cannot be claimed
    /// is that the reading is the only one, so `--strict-fidelity` turns this
    /// into exit 4.
    ///
    /// `fields` lists, in a fixed order and never empty, every field the
    /// two records disagree on for this one entry — one warning per entry,
    /// not per field (it was per field up to 0.22.0, as `field`). Each is
    /// one of `"order"`, `"name"`, `"compression method"`, `"CRC-32"`,
    /// `"compressed size"`, `"uncompressed size"`, `"encryption flag"`,
    /// `"data-descriptor flag"`, `"UTF-8 flag"` or `"entry count"`. `entry`
    /// is the name as the authoritative description (the central directory,
    /// when it was read) spells it, decoded as the reader decodes names.
    ///
    /// An archive lists at most 64 entries this way; the rest are counted
    /// in one [`Fidelity::HeadersDisagreeUnlisted`].
    #[error(
        "`{format}` local header and central directory disagree on {} for entry `{}`",
        .fields.join(", "),
        fmt_name(.entry)
    )]
    HeadersDisagree {
        format: FormatId,
        entry: String,
        fields: Vec<&'static str>,
    },

    /// More entries whose local header and central record disagree, past
    /// the 64 an archive lists as [`Fidelity::HeadersDisagree`]: `entries`
    /// counts them. Each listed warning copies its entry's name, so an
    /// archive of a hundred thousand cloaked records would otherwise make a
    /// report as large as its index; the count keeps the verdict
    /// (`--strict-fidelity` exits 4 on either) without the copies.
    #[error(
        "`{format}` local header and central directory disagree for {entries} more \
         entr(y/ies), not listed"
    )]
    HeadersDisagreeUnlisted { format: FormatId, entries: u64 },

    /// A codec stream whose last complete, verified member (or stream) is
    /// followed by bytes that are neither another member nor padding, and
    /// were ignored.
    ///
    /// gzip and bzip2 files are legitimately concatenations, and the tools
    /// that write them sometimes pad the end with NUL or `'X'` bytes, which
    /// stay silent. Anything else after a verified member is ambiguous: it
    /// may be harmless junk, or it may be the next member with its first
    /// magic byte flipped — one byte that drops every later member while the
    /// members before it still verify. The data handed back is the members
    /// that did verify, so this is a warning rather than
    /// [`crate::Error::Corrupt`] (the reference tools likewise say "trailing
    /// garbage ignored" and recover the data), and `--strict-fidelity` turns
    /// it into exit 4. A tail that starts like a damaged member header — the
    /// magic intact and a field behind it impossible — is `Corrupt` instead,
    /// and never reaches this variant.
    ///
    /// `bytes` is how many bytes were ignored, counted while the tail was
    /// read through (never buffered).
    #[error(
        "`{format}` stream is followed by {bytes} byte(s) that are neither another member \
         nor padding; they were ignored"
    )]
    TrailingDataIgnored { format: FormatId, bytes: u64 },

    /// The local headers of `entries` entries were not compared with their
    /// central-directory records ([`Fidelity::HeadersDisagree`] could not be
    /// ruled out for them), because the comparison ran out of its work
    /// budget.
    ///
    /// Each comparison reads a local header — up to 128 KiB of name and extra
    /// field — and an index whose records keep pointing at the same few fat
    /// headers (or at headers overlapping one another) makes every record pay
    /// that again. The reads are bounded by a budget proportional to the
    /// archive's own length, generous enough that a well-formed archive,
    /// which reads each local header once, never reaches it. Past it, the
    /// remaining entries are delivered as the central directory describes
    /// them, unchecked, and this says so; `--strict-fidelity` turns it into
    /// exit 4.
    #[error(
        "`{format}` local headers of {entries} entr(y/ies) were not compared with the central \
         directory: the archive's records point at the same header bytes again and again, \
         and the comparison's work budget ran out"
    )]
    LocalHeadersUnchecked { format: FormatId, entries: u64 },
}

/// Where a codec's decoder records what it approximated.
///
/// A codec layer hands back only a byte stream, and what it notices — trailing
/// data after its last member, so far — is noticed at the END of that stream,
/// long after [`crate::Codec::decoder`] returned. So the driver hands the
/// decoder this shared, cloneable list through [`crate::DecodeOpts::fidelity`]
/// and folds it into its own [`FidelityReport`] once the stream has been read
/// ([`Self::drain_into`]). Cloning shares the list: every layer of a chain
/// built from one `DecodeOpts` records into the same one.
///
/// A driver that never drains it loses the warnings, the same as a caller
/// that never looks at a report; every driver that reports fidelity drains it.
#[derive(Clone, Default)]
pub struct FidelitySink(std::sync::Arc<std::sync::Mutex<Vec<Fidelity>>>);

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

    /// Records one warning.
    pub fn warn(&self, w: Fidelity) {
        self.lock().push(w);
    }

    /// Moves every recorded warning into `report` (de-duplicated as
    /// [`FidelityReport::merge`] does), leaving the sink empty.
    pub fn drain_into(&self, report: &mut FidelityReport) {
        for w in std::mem::take(&mut *self.lock()) {
            if !report.warnings.contains(&w) {
                report.warn(w);
            }
        }
    }

    /// A copy of what has been recorded so far.
    pub fn warnings(&self) -> Vec<Fidelity> {
        self.lock().clone()
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<Fidelity>> {
        // A panic while holding this lock leaves a Vec that is still whole;
        // the warnings in it are as true as before.
        self.0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }
}

impl fmt::Debug for FidelitySink {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("FidelitySink").field(&*self.lock()).finish()
    }
}

/// What a read cost in fidelity. Returned alongside data, never logged and
/// discarded — the caller must be able to discover what was approximated.
#[derive(Clone, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct FidelityReport {
    pub rung: Rung,
    pub warnings: Vec<Fidelity>,
}

impl FidelityReport {
    pub fn exact() -> Self {
        Self::new(Rung::Exact)
    }

    pub fn new(rung: Rung) -> Self {
        Self {
            rung,
            warnings: Vec::new(),
        }
    }

    pub fn warn(&mut self, w: Fidelity) {
        self.warnings.push(w);
    }

    /// Whether anything was approximated. **This is the `--strict-fidelity`
    /// gate** (exit code 4).
    ///
    /// Gating on warnings rather than on the rung is deliberate: a tar read
    /// from a pipe lands on `ForwardOnly`, but tar has no trailing index, so
    /// nothing was lost. Failing it would hand a script an error it cannot act
    /// on. The rung stays diagnostic — reported by `stuffr info`.
    pub fn has_warnings(&self) -> bool {
        !self.warnings.is_empty()
    }

    /// True only if the rung was authoritative *and* nothing was approximated.
    ///
    /// Deliberately **not** the `--strict-fidelity` gate — see
    /// [`Self::has_warnings`]. This is the stronger "the format's own index was
    /// read and nothing was lost" claim, useful for archival verification.
    pub fn is_lossless(&self) -> bool {
        self.rung.is_authoritative() && self.warnings.is_empty()
    }

    /// Fold another report in: worst rung wins, warnings are unioned.
    ///
    /// For combining reports from independently-resolved layers — e.g. a
    /// codec's own report merged with the inner container's, once a chain has
    /// more than one — rather than for a single container's own findings,
    /// which it now records by calling [`Self::warn`] directly on the report
    /// it inherited from the ladder (see `crate::ladder::seed_report`). A
    /// warning already present is not repeated, so folding the same loss in
    /// from two sources still tells the caller about it once.
    pub fn merge(&mut self, other: &FidelityReport) {
        if other.rung.severity() > self.rung.severity() {
            self.rung = other.rung;
        }
        for w in &other.warnings {
            if !self.warnings.contains(w) {
                self.warnings.push(w.clone());
            }
        }
    }
}

impl Default for FidelityReport {
    fn default() -> Self {
        Self::exact()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::format::FormatId;

    #[test]
    fn free_text_in_fidelity_messages_is_escaped() {
        let r = || String::from("a\x1bb");
        let all = [
            Fidelity::EntrySkipped {
                entry: "e".into(),
                reason: r(),
            },
            Fidelity::EntryCountMismatch {
                format: FormatId::new("tar"),
                declared: 1,
                enumerated: 0,
                reason: r(),
            },
            Fidelity::EntrySizeChanged {
                entry: "e".into(),
                declared: 1,
                fixup: r(),
            },
        ];
        for f in all {
            let m = f.to_string();
            assert!(!m.contains('\x1b'), "raw ESC in {m:?}");
            assert!(m.contains("a\\x1bb"), "{m:?}");
        }
        let plain = "a `b` \"c\" naïve 日本";
        let m = Fidelity::EntrySkipped {
            entry: "e".into(),
            reason: plain.into(),
        }
        .to_string();
        assert_eq!(m, format!("skipped entry `e`: {plain}"));
    }

    #[test]
    fn entry_names_in_fidelity_messages_are_escaped() {
        let n = || String::from("a\x1bb");
        let all = [
            Fidelity::SizeFromDataDescriptor { entry: n() },
            Fidelity::MetadataIncomplete {
                entry: n(),
                fields: MetaFields::default(),
            },
            Fidelity::EncryptedEntrySkipped { entry: n() },
            Fidelity::EntrySkipped {
                entry: n(),
                reason: "r".into(),
            },
            Fidelity::EntrySizeChanged {
                entry: n(),
                declared: 1,
                fixup: "f".into(),
            },
            Fidelity::HeadersDisagree {
                format: FormatId::new("zip"),
                entry: n(),
                fields: vec!["name", "CRC-32"],
            },
        ];
        for f in all {
            let m = f.to_string();
            assert!(m.contains("a\\x1bb"), "{m}");
            assert!(!m.contains('\x1b'), "{m:?}");
        }
    }

    #[test]
    fn headers_disagree_names_every_field_on_one_line() {
        let w = Fidelity::HeadersDisagree {
            format: FormatId::new("zip"),
            entry: "a.txt".into(),
            fields: vec!["name", "CRC-32"],
        };
        assert_eq!(
            w.to_string(),
            "`zip` local header and central directory disagree on name, CRC-32 for entry `a.txt`"
        );
        let more = Fidelity::HeadersDisagreeUnlisted {
            format: FormatId::new("zip"),
            entries: 3,
        };
        assert_eq!(
            more.to_string(),
            "`zip` local header and central directory disagree for 3 more entr(y/ies), not listed"
        );
    }

    #[test]
    fn spilled_is_authoritative_even_though_it_is_a_lower_rung() {
        // Spilling costs disk, not accuracy. Treating it as lossy would make
        // `--strict-fidelity` reject perfectly exact reads.
        assert!(Rung::Exact.is_authoritative());
        assert!(Rung::Spilled.is_authoritative());
        assert!(!Rung::ForwardOnly.is_authoritative());
        assert!(!Rung::Degraded.is_authoritative());
    }

    #[test]
    fn exact_report_is_lossless() {
        let r = FidelityReport::exact();
        assert_eq!(r.rung, Rung::Exact);
        assert!(r.is_lossless());
        assert!(r.warnings.is_empty());
    }

    #[test]
    fn a_warning_makes_an_otherwise_exact_report_lossy() {
        let mut r = FidelityReport::exact();
        r.warn(Fidelity::EntryCountUnknown);
        assert!(!r.is_lossless());
        assert_eq!(r.warnings.len(), 1);
    }

    #[test]
    fn forward_only_is_lossy_even_with_no_warnings() {
        assert!(!FidelityReport::new(Rung::ForwardOnly).is_lossless());
    }

    #[test]
    fn merge_keeps_the_worst_rung_and_concatenates_warnings() {
        let mut a = FidelityReport::exact();
        a.warn(Fidelity::EntryCountUnknown);

        let mut b = FidelityReport::new(Rung::Degraded);
        b.warn(Fidelity::TruncatedStream { at: 99 });

        a.merge(&b);
        assert_eq!(a.rung, Rung::Degraded);
        assert_eq!(a.warnings.len(), 2);
    }

    #[test]
    fn merge_does_not_upgrade_a_worse_rung() {
        let mut a = FidelityReport::new(Rung::Degraded);
        a.merge(&FidelityReport::exact());
        assert_eq!(a.rung, Rung::Degraded);
    }

    #[test]
    fn merge_does_not_repeat_a_warning_already_present() {
        // The ladder and the container can each independently observe the same
        // loss; the caller should be told once.
        let mut a = FidelityReport::exact();
        a.warn(Fidelity::EntryCountUnknown);

        let mut b = FidelityReport::new(Rung::ForwardOnly);
        b.warn(Fidelity::EntryCountUnknown);

        a.merge(&b);
        assert_eq!(a.warnings.len(), 1);
        assert_eq!(a.rung, Rung::ForwardOnly);
    }

    #[test]
    fn warnings_carry_actionable_detail_not_just_a_kind() {
        // The whole premise is that the caller can find out WHAT was lost.
        let f = Fidelity::SizeFromDataDescriptor {
            entry: "logs/a.txt".into(),
        };
        assert!(format!("{f}").contains("logs/a.txt"));

        let f = Fidelity::TrailingIndexUnread {
            format: FormatId::new("zip"),
        };
        assert!(format!("{f}").contains("zip"));

        let f = Fidelity::SolidBlockFullyDecoded {
            wasted_bytes: 41_943_040,
        };
        assert!(format!("{f}").contains("41943040"));

        let f = Fidelity::EntrySkipped {
            entry: "dev/null".into(),
            reason: "device nodes, fifos and sockets are not created".into(),
        };
        let s = format!("{f}");
        assert!(
            s.contains("dev/null") && s.contains("sockets"),
            "a skip must say both which entry and why: {s}"
        );

        let f = Fidelity::EntryCountMismatch {
            format: FormatId::new("zip"),
            declared: 8,
            enumerated: 6,
            reason: "records sharing a name collapse into one".into(),
        };
        let s = format!("{f}");
        assert!(
            s.contains('8') && s.contains('6') && s.contains("sharing a name"),
            "a shortfall must name BOTH counts and the cause, or the caller \
             cannot tell how much is missing or why: {s}"
        );

        let f = Fidelity::MetadataIncomplete {
            entry: "b.bin".into(),
            fields: MetaFields {
                mode: true,
                ..Default::default()
            },
        };
        let s = format!("{f}");
        assert!(s.contains("b.bin") && s.contains("mode"));
    }

    #[test]
    fn meta_fields_lists_only_the_missing_ones() {
        let m = MetaFields {
            mtime: true,
            crc: true,
            ..Default::default()
        };
        assert_eq!(m.missing(), vec!["mtime", "crc"]);
        assert!(MetaFields::default().missing().is_empty());
    }

    #[test]
    fn a_forward_only_read_that_lost_nothing_passes_strict_mode() {
        // tar on a pipe: rung is ForwardOnly, but tar has no trailing index, so
        // nothing was approximated. Strict mode must not fail this.
        let r = FidelityReport::new(Rung::ForwardOnly);
        assert!(!r.has_warnings(), "nothing was approximated");
        assert!(!r.is_lossless(), "but the rung was not authoritative");
    }

    #[test]
    fn strict_mode_fires_on_any_warning_regardless_of_rung() {
        let mut r = FidelityReport::exact();
        r.warn(Fidelity::EntryCountUnknown);
        assert!(r.has_warnings());
    }

    #[test]
    fn a_clean_exact_read_passes_both_predicates() {
        let r = FidelityReport::exact();
        assert!(!r.has_warnings());
        assert!(r.is_lossless());
    }

    #[test]
    fn trailing_data_names_the_format_and_the_byte_count() {
        let s = Fidelity::TrailingDataIgnored {
            format: FormatId::new("gzip"),
            bytes: 1_401_287,
        }
        .to_string();
        assert!(s.contains("gzip") && s.contains("1401287"), "{s}");
    }

    #[test]
    fn a_sink_shared_by_clones_drains_once_into_the_report() {
        let sink = FidelitySink::new();
        let layer = sink.clone();
        let w = Fidelity::TrailingDataIgnored {
            format: FormatId::new("bzip2"),
            bytes: 3,
        };
        layer.warn(w.clone());
        layer.warn(w.clone());
        assert_eq!(
            sink.warnings().len(),
            2,
            "a clone records into the same list"
        );

        let mut report = FidelityReport::exact();
        sink.drain_into(&mut report);
        assert_eq!(report.warnings, vec![w], "de-duplicated as merge does");
        assert!(sink.warnings().is_empty(), "drained");
        sink.drain_into(&mut report);
        assert_eq!(report.warnings.len(), 1);
    }
}