stuffr_core/fidelity.rs
1use std::fmt;
2
3use crate::format::FormatId;
4
5/// Which rung of the adaptive stream ladder a read landed on.
6#[derive(Clone, Copy, PartialEq, Eq, Debug)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize))]
8#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
9pub enum Rung {
10 /// Input was seekable. Authoritative index, full metadata.
11 Exact,
12 /// Not seekable, parsed forward. Real data, approximate metadata.
13 ForwardOnly,
14 /// Spooled to memory/temp then read exactly. Costs disk, not accuracy.
15 Spilled,
16 /// Best-effort salvage. Partial results by construction.
17 Degraded,
18}
19
20impl Rung {
21 /// Whether the read used the format's authoritative structures.
22 ///
23 /// Note `Spilled` is authoritative: spilling trades disk for accuracy, and
24 /// treating it as lossy would make `--strict-fidelity` reject exact reads.
25 pub fn is_authoritative(&self) -> bool {
26 matches!(self, Rung::Exact | Rung::Spilled)
27 }
28
29 /// Ordering by *quality loss*, worst = highest. Used by `merge`.
30 fn severity(&self) -> u8 {
31 match self {
32 Rung::Exact => 0,
33 Rung::Spilled => 1,
34 Rung::ForwardOnly => 2,
35 Rung::Degraded => 3,
36 }
37 }
38}
39
40impl fmt::Display for Rung {
41 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42 let s = match self {
43 Rung::Exact => "exact",
44 Rung::ForwardOnly => "forward-only",
45 Rung::Spilled => "spilled",
46 Rung::Degraded => "degraded",
47 };
48 f.write_str(s)
49 }
50}
51
52/// Which metadata fields are **missing**. `true` means absent, not present.
53#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
54#[cfg_attr(feature = "serde", derive(serde::Serialize))]
55pub struct MetaFields {
56 pub mtime: bool,
57 pub mode: bool,
58 pub uid_gid: bool,
59 pub comment: bool,
60 pub extra: bool,
61 pub crc: bool,
62}
63
64impl MetaFields {
65 pub fn missing(&self) -> Vec<&'static str> {
66 let mut v = Vec::new();
67 if self.mtime {
68 v.push("mtime")
69 }
70 if self.mode {
71 v.push("mode")
72 }
73 if self.uid_gid {
74 v.push("uid_gid")
75 }
76 if self.comment {
77 v.push("comment")
78 }
79 if self.extra {
80 v.push("extra")
81 }
82 if self.crc {
83 v.push("crc")
84 }
85 v
86 }
87}
88
89/// One specific, structured thing that was lost or approximated.
90#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
91#[cfg_attr(feature = "serde", derive(serde::Serialize))]
92#[cfg_attr(feature = "serde", serde(tag = "kind", rename_all = "kebab-case"))]
93#[non_exhaustive]
94pub enum Fidelity {
95 #[error(
96 "`{format}` central/trailing index was never read; entry metadata came from inline headers"
97 )]
98 TrailingIndexUnread { format: FormatId },
99
100 #[error("size of entry `{entry}` was only known after its data (data descriptor)")]
101 SizeFromDataDescriptor { entry: String },
102
103 #[error("total entry count is unknown without the trailing index")]
104 EntryCountUnknown,
105
106 /// The archive's own index declares more records than the reader was able
107 /// to enumerate, so entries exist in the file that no caller can reach.
108 ///
109 /// Distinct from [`Self::EntryCountUnknown`], which is the forward reader
110 /// admitting it never saw a count at all. Here the count WAS read, from
111 /// the format's authoritative structure, and it disagrees with what came
112 /// back — the strongest evidence available that a read is incomplete, and
113 /// the one a seekable `Rung::Exact` read would otherwise have no way to
114 /// express. Without it a partial enumeration is indistinguishable from a
115 /// complete one, which is the failure this variant exists to prevent:
116 /// listing six of eight records and calling it exact fidelity.
117 ///
118 /// Raised, not recovered. Reaching the shadowed records would mean
119 /// re-parsing the index by hand; naming the shortfall is what the caller
120 /// needs in order to know not to trust the result, and
121 /// `--strict-fidelity` turns it into exit 4.
122 ///
123 /// `reason` is an owned `String` for the same reason
124 /// [`Self::EntrySkipped`]'s is: the cause is specific to the container
125 /// and the reader, and a shortfall that cannot say WHY is one the user
126 /// cannot act on.
127 #[error(
128 "`{format}` index declares {declared} entries but only {enumerated} are \
129 reachable: {reason}"
130 )]
131 EntryCountMismatch {
132 format: FormatId,
133 /// What the archive's own index says it holds.
134 declared: u64,
135 /// What the reader was actually able to enumerate.
136 enumerated: u64,
137 /// Why the two differ, in terms the caller can act on.
138 reason: String,
139 },
140
141 #[error("entry `{entry}` is missing metadata: {}", fields.missing().join(", "))]
142 MetadataIncomplete { entry: String, fields: MetaFields },
143
144 #[error("decoded a solid block, wasting {wasted_bytes} bytes, to reach the requested entry")]
145 SolidBlockFullyDecoded { wasted_bytes: u64 },
146
147 #[error("skipped encrypted entry `{entry}`")]
148 EncryptedEntrySkipped { entry: String },
149
150 /// An entry this build cannot materialise, named along with why.
151 ///
152 /// Distinct from [`Self::MetadataIncomplete`], which is about an entry
153 /// that WAS written and lost some of its metadata: here the entry itself
154 /// is absent from the result. Extraction raises it for a device node,
155 /// fifo, socket or hardlink — [`crate::EntryKind::Other`], the honest
156 /// answer a container gives for an entry shape `EntryKind` has no variant
157 /// for yet. Writing one out as a regular file carrying its "contents"
158 /// would be a silent lie about what the archive held. The write side
159 /// raises it too, for something met on disk that no container here can
160 /// store — a socket, an undecodable name, a directory being packed into
161 /// `ar`.
162 ///
163 /// `reason` is an owned `String` rather than a `&'static str` because the
164 /// write side's reasons carry runtime detail — the failing errno, the
165 /// container's own name, the undecodable bytes — and a reason that cannot
166 /// name the particular thing that went wrong is a reason the user cannot
167 /// act on.
168 #[error("skipped entry `{entry}`: {reason}")]
169 EntrySkipped { entry: String, reason: String },
170
171 /// A file that changed length between the moment its size was recorded
172 /// and the moment its bytes were read, stored at the length its header
173 /// already declares.
174 ///
175 /// Distinct from [`Self::EntrySkipped`]: the entry IS in the archive, and
176 /// the archive is structurally valid. What was lost is the tail of a file
177 /// that grew, or the tail of a file that shrank — replaced by zeros,
178 /// because the entry header was written before the payload was read and a
179 /// container cannot un-write it. Refusing instead would throw away the
180 /// whole archive over one file that a live system happened to touch,
181 /// which is what `pack ~ -o backup.tar` over a running home directory does
182 /// routinely; GNU tar prints `file changed as we read it` and continues,
183 /// and this is the same bargain, with the loss named rather than printed
184 /// and forgotten.
185 ///
186 /// `--strict-fidelity` still refuses on it, which is the half of the
187 /// bargain that keeps it honest.
188 #[error(
189 "entry `{entry}` changed size while it was being read: its header declares \
190 {declared} bytes, {fixup}"
191 )]
192 EntrySizeChanged {
193 entry: String,
194 /// The length written into the entry header, from the walk's `stat`.
195 declared: u64,
196 /// What the file actually supplied and what was done about it.
197 ///
198 /// Prose rather than a second `u64` because the two directions know
199 /// different things: a file that shrank supplies an exact count, while
200 /// a file that grew is only known to have had *more* — measuring how
201 /// much more would mean reading a tail that is deliberately not being
202 /// stored. A field that could name the figure in one case and not the
203 /// other would have to lie in one of them.
204 fixup: String,
205 },
206
207 #[error("stream truncated at offset {at}")]
208 TruncatedStream { at: u64 },
209}
210
211/// What a read cost in fidelity. Returned alongside data, never logged and
212/// discarded — the caller must be able to discover what was approximated.
213#[derive(Clone, PartialEq, Eq, Debug)]
214#[cfg_attr(feature = "serde", derive(serde::Serialize))]
215pub struct FidelityReport {
216 pub rung: Rung,
217 pub warnings: Vec<Fidelity>,
218}
219
220impl FidelityReport {
221 pub fn exact() -> Self {
222 Self::new(Rung::Exact)
223 }
224
225 pub fn new(rung: Rung) -> Self {
226 Self {
227 rung,
228 warnings: Vec::new(),
229 }
230 }
231
232 pub fn warn(&mut self, w: Fidelity) {
233 self.warnings.push(w);
234 }
235
236 /// Whether anything was approximated. **This is the `--strict-fidelity`
237 /// gate** (exit code 4).
238 ///
239 /// Gating on warnings rather than on the rung is deliberate: a tar read
240 /// from a pipe lands on `ForwardOnly`, but tar has no trailing index, so
241 /// nothing was lost. Failing it would hand a script an error it cannot act
242 /// on. The rung stays diagnostic — reported by `stuffr info`.
243 pub fn has_warnings(&self) -> bool {
244 !self.warnings.is_empty()
245 }
246
247 /// True only if the rung was authoritative *and* nothing was approximated.
248 ///
249 /// Deliberately **not** the `--strict-fidelity` gate — see
250 /// [`Self::has_warnings`]. This is the stronger "the format's own index was
251 /// read and nothing was lost" claim, useful for archival verification.
252 pub fn is_lossless(&self) -> bool {
253 self.rung.is_authoritative() && self.warnings.is_empty()
254 }
255
256 /// Fold another report in: worst rung wins, warnings are unioned.
257 ///
258 /// For combining reports from independently-resolved layers — e.g. a
259 /// codec's own report merged with the inner container's, once a chain has
260 /// more than one — rather than for a single container's own findings,
261 /// which it now records by calling [`Self::warn`] directly on the report
262 /// it inherited from the ladder (see [`crate::ladder::seed_report`]). A
263 /// warning already present is not repeated, so folding the same loss in
264 /// from two sources still tells the caller about it once.
265 pub fn merge(&mut self, other: &FidelityReport) {
266 if other.rung.severity() > self.rung.severity() {
267 self.rung = other.rung;
268 }
269 for w in &other.warnings {
270 if !self.warnings.contains(w) {
271 self.warnings.push(w.clone());
272 }
273 }
274 }
275}
276
277impl Default for FidelityReport {
278 fn default() -> Self {
279 Self::exact()
280 }
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286 use crate::format::FormatId;
287
288 #[test]
289 fn spilled_is_authoritative_even_though_it_is_a_lower_rung() {
290 // Spilling costs disk, not accuracy. Treating it as lossy would make
291 // `--strict-fidelity` reject perfectly exact reads.
292 assert!(Rung::Exact.is_authoritative());
293 assert!(Rung::Spilled.is_authoritative());
294 assert!(!Rung::ForwardOnly.is_authoritative());
295 assert!(!Rung::Degraded.is_authoritative());
296 }
297
298 #[test]
299 fn exact_report_is_lossless() {
300 let r = FidelityReport::exact();
301 assert_eq!(r.rung, Rung::Exact);
302 assert!(r.is_lossless());
303 assert!(r.warnings.is_empty());
304 }
305
306 #[test]
307 fn a_warning_makes_an_otherwise_exact_report_lossy() {
308 let mut r = FidelityReport::exact();
309 r.warn(Fidelity::EntryCountUnknown);
310 assert!(!r.is_lossless());
311 assert_eq!(r.warnings.len(), 1);
312 }
313
314 #[test]
315 fn forward_only_is_lossy_even_with_no_warnings() {
316 assert!(!FidelityReport::new(Rung::ForwardOnly).is_lossless());
317 }
318
319 #[test]
320 fn merge_keeps_the_worst_rung_and_concatenates_warnings() {
321 let mut a = FidelityReport::exact();
322 a.warn(Fidelity::EntryCountUnknown);
323
324 let mut b = FidelityReport::new(Rung::Degraded);
325 b.warn(Fidelity::TruncatedStream { at: 99 });
326
327 a.merge(&b);
328 assert_eq!(a.rung, Rung::Degraded);
329 assert_eq!(a.warnings.len(), 2);
330 }
331
332 #[test]
333 fn merge_does_not_upgrade_a_worse_rung() {
334 let mut a = FidelityReport::new(Rung::Degraded);
335 a.merge(&FidelityReport::exact());
336 assert_eq!(a.rung, Rung::Degraded);
337 }
338
339 #[test]
340 fn merge_does_not_repeat_a_warning_already_present() {
341 // The ladder and the container can each independently observe the same
342 // loss; the caller should be told once.
343 let mut a = FidelityReport::exact();
344 a.warn(Fidelity::EntryCountUnknown);
345
346 let mut b = FidelityReport::new(Rung::ForwardOnly);
347 b.warn(Fidelity::EntryCountUnknown);
348
349 a.merge(&b);
350 assert_eq!(a.warnings.len(), 1);
351 assert_eq!(a.rung, Rung::ForwardOnly);
352 }
353
354 #[test]
355 fn warnings_carry_actionable_detail_not_just_a_kind() {
356 // The whole premise is that the caller can find out WHAT was lost.
357 let f = Fidelity::SizeFromDataDescriptor {
358 entry: "logs/a.txt".into(),
359 };
360 assert!(format!("{f}").contains("logs/a.txt"));
361
362 let f = Fidelity::TrailingIndexUnread {
363 format: FormatId::new("zip"),
364 };
365 assert!(format!("{f}").contains("zip"));
366
367 let f = Fidelity::SolidBlockFullyDecoded {
368 wasted_bytes: 41_943_040,
369 };
370 assert!(format!("{f}").contains("41943040"));
371
372 let f = Fidelity::EntrySkipped {
373 entry: "dev/null".into(),
374 reason: "device nodes, fifos and hardlinks are not created".into(),
375 };
376 let s = format!("{f}");
377 assert!(
378 s.contains("dev/null") && s.contains("hardlinks"),
379 "a skip must say both which entry and why: {s}"
380 );
381
382 let f = Fidelity::EntryCountMismatch {
383 format: FormatId::new("zip"),
384 declared: 8,
385 enumerated: 6,
386 reason: "records sharing a name collapse into one".into(),
387 };
388 let s = format!("{f}");
389 assert!(
390 s.contains('8') && s.contains('6') && s.contains("sharing a name"),
391 "a shortfall must name BOTH counts and the cause, or the caller \
392 cannot tell how much is missing or why: {s}"
393 );
394
395 let f = Fidelity::MetadataIncomplete {
396 entry: "b.bin".into(),
397 fields: MetaFields {
398 mode: true,
399 ..Default::default()
400 },
401 };
402 let s = format!("{f}");
403 assert!(s.contains("b.bin") && s.contains("mode"));
404 }
405
406 #[test]
407 fn meta_fields_lists_only_the_missing_ones() {
408 let m = MetaFields {
409 mtime: true,
410 crc: true,
411 ..Default::default()
412 };
413 assert_eq!(m.missing(), vec!["mtime", "crc"]);
414 assert!(MetaFields::default().missing().is_empty());
415 }
416
417 #[test]
418 fn a_forward_only_read_that_lost_nothing_passes_strict_mode() {
419 // tar on a pipe: rung is ForwardOnly, but tar has no trailing index, so
420 // nothing was approximated. Strict mode must not fail this.
421 let r = FidelityReport::new(Rung::ForwardOnly);
422 assert!(!r.has_warnings(), "nothing was approximated");
423 assert!(!r.is_lossless(), "but the rung was not authoritative");
424 }
425
426 #[test]
427 fn strict_mode_fires_on_any_warning_regardless_of_rung() {
428 let mut r = FidelityReport::exact();
429 r.warn(Fidelity::EntryCountUnknown);
430 assert!(r.has_warnings());
431 }
432
433 #[test]
434 fn a_clean_exact_read_passes_both_predicates() {
435 let r = FidelityReport::exact();
436 assert!(!r.has_warnings());
437 assert!(r.is_lossless());
438 }
439}