Skip to main content

rivet/pipeline/
validate_manifest.rs

1//! **Layer: Observability**
2//!
3//! Manifest-aware verification for `--validate` (ADR-0012 §M5 / §M6,
4//! constrained by the ADR-0013 trust-flag contract that says: no new flags;
5//! manifest-aware checks live under the existing `--validate`).
6//!
7//! Although this module reads from a `Destination` (technically L2 surface),
8//! it makes **no execution decisions**: it does not write data, advance
9//! cursors, mutate state, or change the pipeline path.  Its only output is
10//! a structured `ManifestVerification` verdict the run report renders.
11//! Per ADR-0003, that places it firmly in L4 Observability — the
12//! destination read surface is just the carrier.
13//!
14//! Inputs (read-only):
15//! - the destination's `manifest.json` body
16//! - the destination's `_SUCCESS` body, if present
17//! - the listing of every object under the destination prefix
18//!
19//! Outputs:
20//! - [`ManifestVerification`] — a structured verdict the run report renders
21//!   into the operator-facing "Verdicts" section.
22//!
23//! Out of scope here:
24//! - per-file row-count check (that runs *during* the export, against the
25//!   local temp file before upload — see `pipeline::validate::validate_output`).
26//! - source-side reconciliation (lives in [`pipeline::reconcile_cmd`] and
27//!   is what `--reconcile` adds on top of this).
28//! - re-fingerprinting parts (`--validate --deep`, future).
29//!
30//! Failure modes are explicit: each check produces a `Failure` enum variant
31//! that is rendered verbatim in `summary.json` so an Airflow / CI consumer
32//! can branch on the kind, not parse strings.
33
34use serde::{Deserialize, Serialize};
35
36use crate::destination::Destination;
37use crate::error::Result;
38use crate::manifest::{
39    MANIFEST_FILENAME, RunManifest, SUCCESS_FILENAME, join_key, parse_success_marker,
40    success_marker_body,
41};
42use crate::pipeline::manifest_reconcile::{PartPresence, reconcile_manifest_against_listing};
43
44/// Upper bound on a destination control artifact (`manifest.json`) the read
45/// path will materialise into memory.  A `manifest.json` is metadata — a few
46/// KB to low single-digit MB even for very large datasets — so 64 MiB is far
47/// above any legitimate body while still bounding the blast radius.
48///
49/// Security (V21, CWE-400): the manifest readers `head()` an object then read
50/// its full body into a `Vec<u8>`.  An attacker who can write the destination
51/// prefix (a shared bucket prefix, a world-writable export dir) can plant a
52/// multi-GB `manifest.json`; an unbounded read would OOM the next `--resume`,
53/// `--validate`, or `rivet repair`.  [`read_capped`] consults the size the
54/// `head()` already reports and bails before the read when it exceeds this cap.
55pub(crate) const MANIFEST_MAX_BYTES: u64 = 64 * 1024 * 1024;
56
57/// Same V21/CWE-400 defense for the sibling control artifact `_SUCCESS`, read by
58/// the SAME `verify_at_destination` under the SAME destination-writable threat
59/// model but previously UNCAPPED. A legitimate marker is ~22 bytes
60/// (`xxh3:<16-hex>\n`); a body past this small cap is corrupt or planted, so it
61/// is treated as malformed WITHOUT materialising it into memory. 4 KiB is orders
62/// of magnitude above any real marker yet trivially bounded.
63pub(crate) const SUCCESS_MARKER_MAX_BYTES: u64 = 4096;
64
65/// How deep a `rivet validate` pass goes — a graded verify layer over the
66/// same checks, letting an operator trade thoroughness for latency / cost.
67///
68/// The variants are a strict superset chain: `Light ⊂ Sample ⊂ Full`.  Each
69/// level runs every check the level below it does, plus more.  Defined here
70/// (the pipeline layer) and re-exported for the CLI grammar so the **same**
71/// enum gates the checks in [`verify_at_destination`] and parses on the
72/// `--depth` flag — no CLI→pipeline back-dependency.
73///
74/// - **Light**: manifest read + self-consistency + `_SUCCESS` only.  Skips the
75///   `list_prefix` reconcile (no per-part presence/size/checksum) and the
76///   untracked-surplus scan, leaving `parts_verified = 0`.  One `head` + one
77///   `read` of `manifest.json` and `_SUCCESS` — a fast "is this prefix a
78///   complete, marked run?" poll with no prefix listing.
79/// - **Sample**: everything Light does **plus** the part reconcile and
80///   untracked surplus (one `list_prefix`).  This is the pre-graded behaviour
81///   minus the Form B value re-read — full structural verification with no
82///   part downloads.
83/// - **Full** (default): everything Sample does **plus** the Form B value-
84///   checksum re-read (re-reads parts, re-derives per-column checksums).  The
85///   most thorough and the only level that downloads part bodies.  Equivalent
86///   to the pre-graded behaviour, so existing callers are unchanged.
87#[derive(clap::ValueEnum, Debug, Clone, Copy, PartialEq, Eq, Default)]
88pub enum ValidateDepth {
89    /// Manifest read + self-consistency + `_SUCCESS` only (no prefix listing).
90    Light,
91    /// Light + part reconcile + untracked surplus (one `list_prefix`).
92    Sample,
93    /// Sample + the Form B value-checksum re-read (downloads parts).
94    #[default]
95    Full,
96}
97
98impl ValidateDepth {
99    /// True iff this level runs the `list_prefix` reconcile (part presence,
100    /// size, checksum) and the untracked-surplus scan — i.e. anything above
101    /// `Light`.  The single predicate the section-3/5 depth gating keys off.
102    fn runs_part_reconcile(self) -> bool {
103        !matches!(self, ValidateDepth::Light)
104    }
105
106    /// True iff this level downloads part *bodies* — the CDC `__pos` continuity
107    /// check and the Form-B value-checksum re-read, both `Full`-only (the
108    /// `part_reconcile` level above only reads listing metadata). The single
109    /// predicate the section-3/5 part-download gating keys off, parallel to
110    /// [`Self::runs_part_reconcile`] — so adding a depth level edits the enum,
111    /// not the call sites in `validate_cmd`.
112    pub(crate) fn runs_part_download(self) -> bool {
113        matches!(self, ValidateDepth::Full)
114    }
115
116    /// Stable operator-/wire-facing label for the depth a verdict was produced
117    /// at, surfaced in `summary.json` (`depth_level`) and `rivet validate`
118    /// output.
119    pub fn label(self) -> &'static str {
120        match self {
121            ValidateDepth::Light => "light",
122            ValidateDepth::Sample => "sample",
123            ValidateDepth::Full => "full",
124        }
125    }
126}
127
128/// Read `key` into memory only if its `head()`-reported size is within
129/// `max_bytes`; otherwise bail without reading a single byte.
130///
131/// The single enforcement point for the V21 (CWE-400) manifest-read cap shared
132/// by the three control-artifact readers (`--resume` M8 preamble, `--validate`,
133/// `rivet repair`).  Each previously did `head()` then an uncapped `read()`,
134/// discarding the size `head()` already returned; routing through here closes
135/// that gap in one place.
136///
137/// Behaviour:
138/// - object absent (`head` → `None`): `Err` — callers invoke this only after
139///   establishing the object exists, so an absent object here is a hard error,
140///   not the benign "no manifest / legacy prefix" case (which the callers
141///   detect with their own `head()` first).
142/// - oversized (`size_bytes > max_bytes`): `Err` naming the cap, **before** any
143///   body is materialised.
144/// - otherwise: the full body via [`Destination::read`].
145pub(crate) fn read_capped(dest: &dyn Destination, key: &str, max_bytes: u64) -> Result<Vec<u8>> {
146    match dest.head(key)? {
147        None => anyhow::bail!("'{key}' not found at the destination"),
148        Some(meta) => {
149            if meta.size_bytes > max_bytes {
150                anyhow::bail!(
151                    "'{key}' is {} bytes, exceeding the {max_bytes}-byte control-artifact \
152                     read cap — refusing to load it into memory (possible tampering)",
153                    meta.size_bytes
154                );
155            }
156            dest.read(key)
157        }
158    }
159}
160
161/// Outcome of a single `--validate` pass over a destination prefix.
162///
163/// Stable enough to be embedded in `summary.json` directly (see
164/// `pipeline::report::ValidationOutcome`).  Forward-compat: consumers MUST
165/// ignore unknown fields (no `deny_unknown_fields`).
166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
167pub struct ManifestVerification {
168    /// True iff a `manifest.json` was found at the destination and parsed.
169    /// `false` triggers ADR-0012 M6 fallback (legacy run); higher-level
170    /// check results below are then "skipped" rather than "passed".
171    pub manifest_found: bool,
172    /// Mirrors ADR-0012 M6's required `legacy_run` operator-facing label.
173    pub legacy_run: bool,
174    /// Manifest parts whose presence and recorded `size_bytes` were
175    /// confirmed at the destination.  0 when no manifest was found.
176    pub parts_verified: usize,
177    /// Subset of `parts_verified` whose **content** was confirmed via an MD5
178    /// the store surfaced in its listing (no download) — the rest are size-only.
179    /// Lets `passed: true` say how much of the dataset was content-checked
180    /// rather than implying all of it was.  `#[serde(default)]` for back-compat.
181    #[serde(default)]
182    pub parts_md5_verified: usize,
183    /// Manifest parts that were declared `committed` but not actually
184    /// present, present at a different size, or otherwise mismatched.
185    pub parts_failed: usize,
186    /// True iff `_SUCCESS` exists at the destination AND its body matches
187    /// the fingerprint of the bytes we read for `manifest.json`.  An
188    /// existing `_SUCCESS` whose body diverges from the manifest is itself
189    /// an integrity failure — surfaced via `failures`.
190    pub success_marker_consistent: bool,
191    /// Self-consistency of the manifest (`row_count`, `part_count`,
192    /// duplicate `part_id`s).  Skipped when `manifest_found = false`.
193    pub manifest_self_consistent: bool,
194    /// Final verdict, **derived** (not hand-maintained) — `manifest_found` and
195    /// no *fatal* failure ([`Failure::is_fatal`]).  Stored so it stays in the
196    /// `summary.json` contract, but computed in one place
197    /// ([`ManifestVerification::recompute_passed`]) so a new failure variant is
198    /// fatal by default rather than relying on every site to flip a bool.
199    pub passed: bool,
200    /// Per-failure detail.  May be non-empty with `passed = true` for advisory
201    /// (non-fatal) failures like [`Failure::UntrackedObject`].  Stable variant
202    /// set; new variants land under a new manifest version per ADR-0012.
203    pub failures: Vec<Failure>,
204    /// The graded depth this verdict was produced at: `"light"`, `"sample"`,
205    /// or `"full"` (see [`ValidateDepth`]).  Lets a consumer of `summary.json`
206    /// tell **how much** was actually checked — a `passed: true` at `"light"`
207    /// asserts far less than at `"full"` (no part presence was verified).
208    /// `#[serde(default)]` (→ `"full"`) for back-compat: pre-graded verdicts
209    /// always ran the full pass.
210    #[serde(default = "default_depth_level")]
211    pub depth_level: String,
212}
213
214/// `serde(default)` for [`ManifestVerification::depth_level`]: a verdict that
215/// predates the graded layer always ran the full pass, so an absent field
216/// deserializes to `"full"`.
217fn default_depth_level() -> String {
218    ValidateDepth::Full.label().to_string()
219}
220
221#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
222#[serde(tag = "kind", rename_all = "snake_case")]
223pub enum Failure {
224    /// Manifest declared a part that does not exist at the destination.
225    PartMissing { part_id: u32, path: String },
226    /// Manifest declared a part whose actual size differs from `size_bytes`.
227    PartSizeMismatch {
228        part_id: u32,
229        path: String,
230        expected: u64,
231        actual: u64,
232    },
233    /// Part present at the recorded size but its content MD5 (from the store's
234    /// listing metadata) differs from the manifest's — transit / at-rest
235    /// corruption, caught with no download.
236    PartChecksumMismatch {
237        part_id: u32,
238        path: String,
239        expected: String,
240        actual: String,
241    },
242    /// `_SUCCESS` exists but its body is malformed (not `xxh3:<16-hex>` after
243    /// trim).  ADR-0012 M2 — orchestrators rely on this format being strict.
244    SuccessMarkerMalformed { body_preview: String },
245    /// `_SUCCESS` body parsed but does not match `xxh3(manifest.json bytes)`.
246    /// Two legitimate sources: (a) someone overwrote `_SUCCESS` after the
247    /// manifest was rewritten — orchestrator bug; (b) the manifest was
248    /// edited in place after the run — operator bug.  Either way the
249    /// manifest is no longer trustworthy.
250    SuccessMarkerStale {
251        marker_fingerprint: String,
252        manifest_fingerprint: String,
253    },
254    /// `RunManifest::validate_self_consistency` rejected the manifest.
255    /// Usually a writer bug (declared row_count != sum of committed parts'
256    /// rows); blocks the rest of the verification because the manifest
257    /// itself is unreliable.
258    ManifestSelfInconsistent { detail: String },
259    /// Reading `manifest.json` returned an I/O error other than "absent".
260    ManifestReadError { detail: String },
261    /// Reading `_SUCCESS` returned an I/O error other than "absent".
262    SuccessMarkerReadError { detail: String },
263    /// Listing the destination prefix returned an I/O error.  Reduces the
264    /// untracked-parts check (M5 surplus) to a no-op for this run.
265    ListPrefixError { detail: String },
266    /// A file is present at the destination prefix but no manifest entry
267    /// references it.  M9-adjacent: `--validate` only flags it; quarantine
268    /// belongs to `--resume`.
269    UntrackedObject { key: String, size_bytes: u64 },
270    /// The export declared `verify: content` but some parts could only be
271    /// size-verified (no comparable content checksum from the store) — the
272    /// declared integrity contract was not met.
273    ContentVerificationUnmet { size_only: usize, total: usize },
274    /// A manifest was *required* at this prefix (the operator pinned a literal
275    /// `--prefix`, asserting a real dataset lives here) but none was found.
276    /// Without this, an absent manifest at an operator-pinned prefix maps to
277    /// the M6 legacy-run label and exits 0 — indistinguishable from a verified
278    /// run, so a CI gate `rivet validate && deploy` sails past a destination
279    /// that was never written.  Fatal: a required-but-missing manifest is a
280    /// refusal reason, not a "cannot certify" advisory.
281    ManifestRequiredButAbsent { prefix: String },
282}
283
284impl Failure {
285    /// Whether this failure invalidates the dataset (flips `passed` to false).
286    ///
287    /// Every variant is fatal **except** [`Failure::UntrackedObject`]: surplus
288    /// objects are an audit signal whose cleanup is `--resume`'s job (ADR-0012
289    /// M9), not a corruption of the manifest-listed parts.  New variants are
290    /// fatal by default — opt out here explicitly, so a forgotten case fails
291    /// closed (safe) rather than silently passing.
292    pub fn is_fatal(&self) -> bool {
293        !matches!(self, Failure::UntrackedObject { .. })
294    }
295
296    /// Stable `RIVET_VERIFY_*` error code for this failure variant.
297    ///
298    /// One code per variant, intended for orchestrators / CI to branch on
299    /// without parsing the human `Display` string or the per-variant JSON
300    /// fields.  The code is part of the wire contract: it is emitted next to
301    /// `kind` in the JSON report and prefixed in brackets on each pretty line.
302    /// Codes are append-only — never renamed once shipped (a renamed code is a
303    /// silent break for any consumer keying off it).
304    pub fn error_code(&self) -> &'static str {
305        match self {
306            Failure::PartMissing { .. } => "RIVET_VERIFY_PART_MISSING",
307            Failure::PartSizeMismatch { .. } => "RIVET_VERIFY_PART_SIZE_MISMATCH",
308            Failure::PartChecksumMismatch { .. } => "RIVET_VERIFY_PART_CHECKSUM_MISMATCH",
309            Failure::SuccessMarkerMalformed { .. } => "RIVET_VERIFY_SUCCESS_MALFORMED",
310            Failure::SuccessMarkerStale { .. } => "RIVET_VERIFY_SUCCESS_STALE",
311            Failure::ManifestSelfInconsistent { .. } => "RIVET_VERIFY_MANIFEST_INCONSISTENT",
312            Failure::ManifestReadError { .. } => "RIVET_VERIFY_MANIFEST_READ_ERROR",
313            Failure::SuccessMarkerReadError { .. } => "RIVET_VERIFY_SUCCESS_READ_ERROR",
314            Failure::ListPrefixError { .. } => "RIVET_VERIFY_LIST_ERROR",
315            Failure::UntrackedObject { .. } => "RIVET_VERIFY_UNTRACKED_OBJECT",
316            Failure::ContentVerificationUnmet { .. } => "RIVET_VERIFY_CONTENT_UNMET",
317            Failure::ManifestRequiredButAbsent { .. } => "RIVET_VERIFY_MANIFEST_REQUIRED",
318        }
319    }
320}
321
322impl std::fmt::Display for Failure {
323    /// One operator-facing line per failure variant.  Used by:
324    /// - `pipeline::report::render_markdown` (summary.md "failure:" lines)
325    /// - `pipeline::validate_cmd::render_pretty` (`rivet validate` stdout)
326    /// - any future consumer that wants a human-readable failure label
327    ///
328    /// The wire format (`failures[].kind` + per-variant fields) lives in
329    /// the `Serialize` derive above and is the contract Airflow / CI
330    /// consumers branch on.  This `Display` impl is for humans only.
331    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
332        match self {
333            Failure::PartMissing { part_id, path } => {
334                write!(f, "part {} missing at {}", part_id, path)
335            }
336            Failure::PartSizeMismatch {
337                part_id,
338                path,
339                expected,
340                actual,
341            } => write!(
342                f,
343                "part {} size mismatch at {}: manifest {}, dest {}",
344                part_id, path, expected, actual
345            ),
346            Failure::PartChecksumMismatch {
347                part_id,
348                path,
349                expected,
350                actual,
351            } => write!(
352                f,
353                "part {} content mismatch at {}: manifest md5 {}, dest {}",
354                part_id, path, expected, actual
355            ),
356            Failure::SuccessMarkerMalformed { body_preview } => {
357                write!(f, "_SUCCESS body malformed: {body_preview:?}")
358            }
359            Failure::SuccessMarkerStale {
360                marker_fingerprint,
361                manifest_fingerprint,
362            } => write!(
363                f,
364                "_SUCCESS body {} != manifest fingerprint {} (stale marker)",
365                marker_fingerprint, manifest_fingerprint
366            ),
367            Failure::ManifestSelfInconsistent { detail } => {
368                write!(f, "manifest self-consistency: {detail}")
369            }
370            Failure::ManifestReadError { detail } => {
371                write!(f, "manifest read error: {detail}")
372            }
373            Failure::SuccessMarkerReadError { detail } => {
374                write!(f, "_SUCCESS read error: {detail}")
375            }
376            Failure::ListPrefixError { detail } => {
377                write!(f, "destination listing error: {detail}")
378            }
379            Failure::UntrackedObject { key, size_bytes } => {
380                write!(f, "untracked object: {} ({} bytes)", key, size_bytes)
381            }
382            Failure::ContentVerificationUnmet { size_only, total } => write!(
383                f,
384                "verify: content not met — {size_only} of {total} part(s) only \
385                 size-verified (no store checksum); lower max_file_size so parts \
386                 upload as a single PUT, or the backend exposes no checksum"
387            ),
388            Failure::ManifestRequiredButAbsent { prefix } => write!(
389                f,
390                "no manifest at {prefix}: a manifest was required here (operator \
391                 pinned --prefix) but none was found — this prefix was never \
392                 written, or the data was relocated. Run the export first, or \
393                 drop --prefix to validate the config-resolved destination."
394            ),
395        }
396    }
397}
398
399impl ManifestVerification {
400    /// Base verdict: nothing checked yet (no manifest, all counts zero, all
401    /// sub-checks false, `passed = false`).  Every constructor builds on this
402    /// and overrides only what differs, so a new field lands in **one** place
403    /// rather than several near-identical literals.
404    fn empty() -> Self {
405        Self {
406            manifest_found: false,
407            legacy_run: false,
408            parts_verified: 0,
409            parts_md5_verified: 0,
410            parts_failed: 0,
411            success_marker_consistent: false,
412            manifest_self_consistent: false,
413            passed: false,
414            failures: Vec::new(),
415            // Base level; `verify_at_destination` overwrites this with the
416            // depth it was actually called at before returning any verdict.
417            depth_level: default_depth_level(),
418        }
419    }
420
421    /// Recompute `passed` from the verdict's facts: a manifest was found and no
422    /// **fatal** failure was recorded (advisory failures like `UntrackedObject`
423    /// don't count).  The single source of truth — callers set failures and
424    /// call this once, rather than flipping `passed` by hand at every site.
425    fn recompute_passed(&mut self) {
426        self.passed = self.manifest_found && !self.failures.iter().any(Failure::is_fatal);
427    }
428
429    /// Apply the export's `verify` policy (ADR-0013 / review D).  When content
430    /// verification is required but some parts were only size-verified, record
431    /// a fatal [`Failure::ContentVerificationUnmet`] and re-derive `passed`.
432    /// Policy lives here (one place); the composers — run finalize and the
433    /// `rivet validate` command — just call it with their export's intent.
434    pub fn enforce_content_policy(&mut self, require_content: bool) {
435        if require_content && self.manifest_found {
436            let size_only = self.parts_verified.saturating_sub(self.parts_md5_verified);
437            if size_only > 0 {
438                self.failures.push(Failure::ContentVerificationUnmet {
439                    size_only,
440                    total: self.parts_verified,
441                });
442                self.recompute_passed();
443            }
444        }
445    }
446
447    /// Apply the "a manifest must exist here" policy (finding #20).  When the
448    /// operator pinned a literal `--prefix`, an absent manifest is no longer the
449    /// benign M6 legacy-run case — it almost always means the prefix was never
450    /// written (a misconfigured CI gate). Convert that exact verdict — no
451    /// manifest, no other failure (i.e. the [`ManifestVerification::legacy`]
452    /// shape) — into a fatal [`Failure::ManifestRequiredButAbsent`] so the exit
453    /// gate refuses it loudly instead of silently passing.
454    ///
455    /// Deliberately a no-op for every other shape: a real manifest (passed or
456    /// failed), or an absent manifest that already carries a `ManifestReadError`
457    /// / head failure, is left untouched — those are already classified.  Only
458    /// the "legacy / cannot certify" case is escalated, and only when required.
459    pub fn require_manifest_present(&mut self, prefix: &str) {
460        if !self.manifest_found && !self.has_failures() {
461            self.legacy_run = false;
462            self.failures.push(Failure::ManifestRequiredButAbsent {
463                prefix: prefix.to_string(),
464            });
465            self.recompute_passed();
466        }
467    }
468
469    /// Construct the M6 (legacy run) verdict for a destination that has no
470    /// manifest at all.  Caller composes this with the existing per-file
471    /// row-count check; together they form the legacy `--validate` result.
472    pub fn legacy() -> Self {
473        // `passed = false` is intentional — not "validation failed" but "this
474        // verifier cannot certify"; the caller layers per-file row counts on
475        // top and composes the final verdict.
476        Self {
477            legacy_run: true,
478            ..Self::empty()
479        }
480    }
481
482    /// True iff this verification surfaced any explicit failure (i.e. a
483    /// reason an orchestrator should refuse the run).  Distinct from
484    /// `!passed`, which can also mean "legacy / not applicable".
485    pub fn has_failures(&self) -> bool {
486        !self.failures.is_empty()
487    }
488}
489
490/// Run the manifest-aware verification at `manifest_dir` (the destination-
491/// relative directory containing `manifest.json` and `_SUCCESS`).
492///
493/// `manifest_dir` is the same key shape `Destination::write` was called with
494/// for the manifest itself — typically empty (`""`) for prefix-rooted runs,
495/// or the per-export sub-directory.  Trailing `/` is optional.
496///
497/// This function does not panic on any expected I/O outcome — every read
498/// failure becomes a `Failure::*ReadError` so the caller can render a
499/// useful message instead of bailing.
500///
501/// `depth` selects the graded verify layer (see [`ValidateDepth`]):
502/// - [`ValidateDepth::Light`] skips section 3 (the `list_prefix` part
503///   reconcile) and section 5 (untracked surplus), leaving `parts_verified`
504///   at 0 — a fast manifest + `_SUCCESS` poll with no prefix listing.
505/// - [`ValidateDepth::Sample`] and [`ValidateDepth::Full`] run all five
506///   sections here.  The Form B value re-read is **not** in this function;
507///   it is the caller's concern (`run_validate_command`), gated on `Full`.
508///
509/// Regardless of depth, `depth_level` on the returned verdict records the
510/// level this pass ran at.
511pub fn verify_at_destination(
512    dest: &dyn Destination,
513    manifest_dir: &str,
514    depth: ValidateDepth,
515) -> Result<ManifestVerification> {
516    let manifest_key = join_key(manifest_dir, MANIFEST_FILENAME);
517    let success_key = join_key(manifest_dir, SUCCESS_FILENAME);
518
519    // Stamp the depth this pass ran at onto every verdict before it leaves the
520    // function — including the early-return error/legacy shapes — so a consumer
521    // always sees *how much* was checked.  Each `return Ok(v)` below routes
522    // through `with_depth` (or sets `out.depth_level` for the main path).
523    let with_depth = |mut v: ManifestVerification| -> ManifestVerification {
524        v.depth_level = depth.label().to_string();
525        v
526    };
527
528    // ── 1. Manifest read ───────────────────────────────────────────────
529    //
530    // Error-consistency contract: every I/O outcome here surfaces as a
531    // structured `Failure` variant rather than as `Err`.  An operator gets
532    // one verdict shape regardless of whether the destination is missing,
533    // permission-denied, or temporarily unreachable.  The bubbled `Err`
534    // path is reserved for *programmer* errors (caller passes a malformed
535    // `manifest_dir`, a future destination breaks an internal invariant).
536    let manifest_bytes = match dest.head(&manifest_key) {
537        Ok(None) => return Ok(with_depth(ManifestVerification::legacy())),
538        Ok(Some(_)) => match read_capped(dest, &manifest_key, MANIFEST_MAX_BYTES) {
539            Ok(b) => b,
540            Err(e) => {
541                let mut v = ManifestVerification::legacy();
542                v.legacy_run = false;
543                v.failures.push(Failure::ManifestReadError {
544                    detail: format!("{e:#}"),
545                });
546                v.passed = false;
547                return Ok(with_depth(v));
548            }
549        },
550        Err(e) => {
551            // `head` failure is symmetric to a `read` failure — same kind
552            // (`ManifestReadError`) so consumers don't have to branch on
553            // which method tripped.  Distinct from "manifest absent"
554            // (Ok(None) above) which legitimately means "legacy prefix".
555            let mut v = ManifestVerification::legacy();
556            v.legacy_run = false;
557            v.failures.push(Failure::ManifestReadError {
558                detail: format!("manifest head failed: {e:#}"),
559            });
560            v.passed = false;
561            return Ok(with_depth(v));
562        }
563    };
564
565    let manifest: RunManifest = match serde_json::from_slice(&manifest_bytes) {
566        Ok(m) => m,
567        Err(e) => {
568            // A malformed manifest is treated as a self-inconsistency —
569            // semantically equivalent for the operator (the manifest can't
570            // be trusted) but kept distinct in `failures` so the kind is
571            // explicit on the wire.
572            return Ok(with_depth(ManifestVerification {
573                manifest_found: true,
574                failures: vec![Failure::ManifestSelfInconsistent {
575                    detail: format!("manifest.json parse failed: {e}"),
576                }],
577                ..ManifestVerification::empty()
578            }));
579        }
580    };
581
582    // Optimistic base: a found, self-consistent manifest that passes until a
583    // check below flips it.  Overrides only what differs from `empty()`.
584    // Stamp the depth here so the two early `return Ok(out)` paths in section
585    // 4 (success-marker head error, non-utf8 body) carry the right level too.
586    let mut out = ManifestVerification {
587        manifest_found: true,
588        manifest_self_consistent: true,
589        passed: true,
590        depth_level: depth.label().to_string(),
591        ..ManifestVerification::empty()
592    };
593
594    // ── 2. Self-consistency ─────────────────────────────────────────────
595    if let Err(e) = manifest.validate_self_consistency() {
596        out.manifest_self_consistent = false;
597        out.failures.push(Failure::ManifestSelfInconsistent {
598            detail: format!("{e}"),
599        });
600        // Don't short-circuit — we still want to surface part-presence
601        // failures because the operator may want to know both classes at
602        // once rather than fix-then-rerun.
603    }
604
605    // ── 3. Reconcile parts + surplus against ONE prefix listing ────────
606    //
607    // Presence and untracked-surplus both fall out of a single
608    // `reconcile_manifest_against_listing` over one `list_prefix` — the same
609    // pure walk chunked resume uses (`build_resume_plan`).  This replaces the
610    // old per-part `HEAD` loop (N round-trips) and its separate untracked
611    // listing.  Per-part failures are emitted here (step 3); untracked is
612    // emitted at step 5 so the failure ordering an operator reads is stable.
613    //
614    // Trade-off: presence now rides the listing, not per-part `HEAD`.  If the
615    // listing cannot be read, an audit cannot certify the parts — so a list
616    // failure flips `passed = false` (a `ListPrefixError`), rather than the
617    // old behaviour where per-part HEAD still "verified" parts a failed
618    // listing couldn't enumerate.  Every Rivet destination backend offers
619    // strong read-after-write list consistency, so the happy path is one call.
620    //
621    // Graded depth: `Light` skips this `list_prefix` entirely — no part
622    // reconcile, no `ListPrefixError`, `parts_verified` stays 0, and section 5
623    // (untracked) is a no-op since `reconciliation` is `None`.  `Sample` and
624    // `Full` run it.  A `Light` pass therefore certifies only that the
625    // manifest reads, is self-consistent, and `_SUCCESS` matches — never that
626    // the parts are physically present.
627    let reconciliation = if depth.runs_part_reconcile() {
628        match dest.list_prefix(manifest_dir) {
629            Ok(listing) => Some(reconcile_manifest_against_listing(
630                &manifest,
631                &listing,
632                manifest_dir,
633            )),
634            Err(e) => {
635                out.failures.push(Failure::ListPrefixError {
636                    detail: format!("{e:#}"),
637                });
638                None
639            }
640        }
641    } else {
642        None
643    };
644    if let Some(rec) = &reconciliation {
645        for check in &rec.per_part {
646            match &check.presence {
647                PartPresence::Present { md5_verified } => {
648                    out.parts_verified += 1;
649                    if *md5_verified {
650                        out.parts_md5_verified += 1;
651                    }
652                }
653                PartPresence::SizeMismatch { expected, actual } => {
654                    out.parts_failed += 1;
655                    out.failures.push(Failure::PartSizeMismatch {
656                        part_id: check.part_id,
657                        path: check.path.clone(),
658                        expected: *expected,
659                        actual: *actual,
660                    });
661                }
662                PartPresence::Missing => {
663                    out.parts_failed += 1;
664                    out.failures.push(Failure::PartMissing {
665                        part_id: check.part_id,
666                        path: check.path.clone(),
667                    });
668                }
669                PartPresence::ChecksumMismatch { expected, actual } => {
670                    out.parts_failed += 1;
671                    out.failures.push(Failure::PartChecksumMismatch {
672                        part_id: check.part_id,
673                        path: check.path.clone(),
674                        expected: expected.clone(),
675                        actual: actual.clone(),
676                    });
677                }
678            }
679        }
680    }
681
682    // ── 4. _SUCCESS marker consistency ─────────────────────────────────
683    //
684    // Same error-consistency contract as step 1: head/read failures become
685    // `Failure::SuccessMarkerReadError`, not bubbled `Err`.  Absent marker
686    // (Ok(None)) stays informational, not a failure (M2: only successful
687    // runs land _SUCCESS, so its absence on a failed manifest is correct).
688    let success_head = match dest.head(&success_key) {
689        Ok(h) => h,
690        Err(e) => {
691            out.failures.push(Failure::SuccessMarkerReadError {
692                detail: format!("_SUCCESS head failed: {e:#}"),
693            });
694            out.recompute_passed();
695            return Ok(out);
696        }
697    };
698    match success_head {
699        None => {
700            // Absent _SUCCESS is informational, not a failure: per ADR-0012
701            // M2, only successful runs land it.  A failed-then-rewritten
702            // manifest legitimately lacks _SUCCESS.  Leave
703            // `success_marker_consistent = false` (this is a "no signal"
704            // bool, not a "broken" bool) and let the caller decide.
705        }
706        Some(head) if head.size_bytes > SUCCESS_MARKER_MAX_BYTES => {
707            // Refuse to materialise an oversized _SUCCESS: a bare uncapped
708            // dest.read of a multi-GB planted marker OOMs the validate/resume/repair
709            // process (the asymmetry with step 1's manifest.json cap this closes).
710            // success_head already carries the size — no extra round-trip.
711            out.failures.push(Failure::SuccessMarkerMalformed {
712                body_preview: format!(
713                    "(oversized: {} bytes exceeds the {SUCCESS_MARKER_MAX_BYTES}-byte _SUCCESS cap; not read)",
714                    head.size_bytes
715                ),
716            });
717            out.recompute_passed();
718            return Ok(out);
719        }
720        Some(_) => match dest.read(&success_key) {
721            Err(e) => {
722                out.failures.push(Failure::SuccessMarkerReadError {
723                    detail: format!("{e:#}"),
724                });
725            }
726            Ok(body) => {
727                let body_str = match std::str::from_utf8(&body) {
728                    Ok(s) => s,
729                    Err(_) => {
730                        out.failures.push(Failure::SuccessMarkerMalformed {
731                            body_preview: format!("(non-utf8, {} bytes)", body.len()),
732                        });
733                        out.recompute_passed();
734                        return Ok(out);
735                    }
736                };
737                match parse_success_marker(body_str) {
738                    None => {
739                        out.failures.push(Failure::SuccessMarkerMalformed {
740                            body_preview: preview(body_str),
741                        });
742                    }
743                    Some(marker_fp) => {
744                        let manifest_fp = success_marker_body(&manifest_bytes);
745                        // success_marker_body returns the trailing `\n`
746                        // form; trim before comparing to the parsed marker
747                        // (which already trims).
748                        let manifest_fp_trimmed = manifest_fp.trim_end_matches('\n');
749                        if marker_fp == manifest_fp_trimmed {
750                            out.success_marker_consistent = true;
751                        } else {
752                            out.failures.push(Failure::SuccessMarkerStale {
753                                marker_fingerprint: marker_fp.to_string(),
754                                manifest_fingerprint: manifest_fp_trimmed.to_string(),
755                            });
756                        }
757                    }
758                }
759            }
760        },
761    }
762
763    // ── 5. Untracked surplus ───────────────────────────────────────────
764    //
765    // Already computed by the step-3 reconciliation (sidecars, quarantine,
766    // and the doctor probe are filtered there).  Emit it last so the failure
767    // ordering stays parts → marker → untracked.  A list failure left
768    // `reconciliation = None` and already flipped `passed` above.
769    if let Some(rec) = reconciliation {
770        for obj in rec.untracked {
771            out.failures.push(Failure::UntrackedObject {
772                key: obj.key,
773                size_bytes: obj.size_bytes,
774            });
775        }
776    }
777
778    out.recompute_passed();
779    Ok(out)
780}
781
782/// Truncate `s` to a small printable preview for error messages.
783fn preview(s: &str) -> String {
784    let trimmed: String = s.chars().take(40).collect();
785    if s.chars().count() > 40 {
786        format!("{trimmed}…")
787    } else {
788        trimmed
789    }
790}
791
792#[cfg(test)]
793mod tests {
794    use super::*;
795    use crate::config::{DestinationConfig, DestinationType};
796    use crate::destination::local::LocalDestination;
797    use crate::manifest::{
798        MANIFEST_VERSION, ManifestDestination, ManifestPart, ManifestSource, ManifestStatus,
799        PartStatus, RunManifest,
800    };
801    use std::path::Path;
802
803    fn local_dest(base: &Path) -> LocalDestination {
804        LocalDestination::new(&DestinationConfig {
805            destination_type: DestinationType::Local,
806            path: Some(base.to_string_lossy().into_owned()),
807            ..Default::default()
808        })
809        .unwrap()
810    }
811
812    fn part(part_id: u32, rows: i64, size: u64, fp: &str) -> ManifestPart {
813        ManifestPart {
814            part_id,
815            path: format!("part-{part_id:06}.parquet"),
816            rows,
817            size_bytes: size,
818            content_fingerprint: fp.into(),
819            content_md5: String::new(),
820            status: PartStatus::Committed,
821        }
822    }
823
824    fn build_manifest(parts: Vec<ManifestPart>, status: ManifestStatus) -> RunManifest {
825        let row_count: i64 = parts
826            .iter()
827            .filter(|p| p.status == PartStatus::Committed)
828            .map(|p| p.rows)
829            .sum();
830        let part_count = parts
831            .iter()
832            .filter(|p| p.status == PartStatus::Committed)
833            .count() as u32;
834        RunManifest {
835            mode: "batch".to_string(),
836            manifest_version: MANIFEST_VERSION,
837            run_id: "r".into(),
838            export_name: "public.orders".into(),
839            started_at: "2026-05-21T12:00:00Z".into(),
840            finished_at: "2026-05-21T12:01:00Z".into(),
841            status,
842            source: ManifestSource {
843                engine: "postgres".into(),
844                schema: Some("public".into()),
845                table: Some("orders".into()),
846                extraction: None,
847            },
848            destination: ManifestDestination {
849                kind: "local".into(),
850                uri: "file:///tmp/out".into(),
851            },
852            format: "parquet".into(),
853            compression: "zstd".into(),
854            schema_fingerprint: "xxh3:0123456789abcdef".into(),
855            row_count,
856            part_count,
857            parts,
858            column_checksums: None,
859            checksum_key_column: None,
860        }
861    }
862
863    /// Lay out a clean dataset with manifest + _SUCCESS at the root.
864    fn write_dataset(dir: &Path, m: &RunManifest, parts_with_bytes: &[(&str, &[u8])]) {
865        for (name, bytes) in parts_with_bytes {
866            std::fs::write(dir.join(name), bytes).unwrap();
867        }
868        let body = serde_json::to_vec_pretty(m).unwrap();
869        std::fs::write(dir.join(MANIFEST_FILENAME), &body).unwrap();
870        if matches!(m.status, ManifestStatus::Success) {
871            std::fs::write(dir.join(SUCCESS_FILENAME), success_marker_body(&body)).unwrap();
872        }
873    }
874
875    // ── happy path ───────────────────────────────────────────────────────
876
877    #[test]
878    fn happy_path_verifies_all_parts_and_success_marker() {
879        let dir = tempfile::tempdir().unwrap();
880        let m = build_manifest(
881            vec![
882                part(1, 10, 4, "xxh3:1111111111111111"),
883                part(2, 20, 5, "xxh3:2222222222222222"),
884            ],
885            ManifestStatus::Success,
886        );
887        write_dataset(
888            dir.path(),
889            &m,
890            &[
891                ("part-000001.parquet", b"AAAA"),
892                ("part-000002.parquet", b"BBBBB"),
893            ],
894        );
895        let dest = local_dest(dir.path());
896
897        let v = verify_at_destination(&dest, "", ValidateDepth::Full).unwrap();
898        assert!(v.manifest_found);
899        assert!(!v.legacy_run);
900        assert_eq!(v.parts_verified, 2);
901        assert_eq!(v.parts_failed, 0);
902        assert!(v.success_marker_consistent);
903        assert!(v.manifest_self_consistent);
904        assert!(v.passed);
905        assert!(v.failures.is_empty());
906    }
907
908    // ── M6 legacy run ───────────────────────────────────────────────────
909
910    #[test]
911    fn no_manifest_returns_legacy_run_label() {
912        // Empty prefix — no manifest, no parts.
913        let dir = tempfile::tempdir().unwrap();
914        let dest = local_dest(dir.path());
915        let v = verify_at_destination(&dest, "", ValidateDepth::Full).unwrap();
916        assert!(!v.manifest_found);
917        assert!(v.legacy_run);
918        assert_eq!(v.parts_verified, 0);
919        assert!(!v.passed);
920        assert!(v.failures.is_empty(), "no failures, just a legacy label");
921    }
922
923    // ── M5 part-presence failures ───────────────────────────────────────
924
925    #[test]
926    fn missing_part_is_flagged_with_part_id_and_path() {
927        let dir = tempfile::tempdir().unwrap();
928        let m = build_manifest(
929            vec![
930                part(1, 10, 4, "xxh3:1111111111111111"),
931                part(2, 20, 5, "xxh3:2222222222222222"),
932            ],
933            ManifestStatus::Success,
934        );
935        write_dataset(
936            dir.path(),
937            &m,
938            &[("part-000001.parquet", b"AAAA")], // part 2 missing
939        );
940        let dest = local_dest(dir.path());
941
942        let v = verify_at_destination(&dest, "", ValidateDepth::Full).unwrap();
943        assert_eq!(v.parts_verified, 1);
944        assert_eq!(v.parts_failed, 1);
945        assert!(!v.passed);
946        assert!(
947            v.failures
948                .iter()
949                .any(|f| matches!(f, Failure::PartMissing { part_id: 2, .. }))
950        );
951    }
952
953    #[test]
954    fn part_size_mismatch_is_flagged_with_expected_and_actual() {
955        let dir = tempfile::tempdir().unwrap();
956        let m = build_manifest(
957            vec![part(1, 10, 4, "xxh3:1111111111111111")],
958            ManifestStatus::Success,
959        );
960        // Manifest claims 4 bytes; we write 6.
961        write_dataset(dir.path(), &m, &[("part-000001.parquet", b"OOPSIE")]);
962        let dest = local_dest(dir.path());
963
964        let v = verify_at_destination(&dest, "", ValidateDepth::Full).unwrap();
965        assert!(!v.passed);
966        let mismatch = v
967            .failures
968            .iter()
969            .find_map(|f| match f {
970                Failure::PartSizeMismatch {
971                    part_id,
972                    expected,
973                    actual,
974                    ..
975                } => Some((*part_id, *expected, *actual)),
976                _ => None,
977            })
978            .expect("must surface the size mismatch");
979        assert_eq!(mismatch, (1, 4, 6));
980    }
981
982    // ── _SUCCESS marker integrity ───────────────────────────────────────
983
984    #[test]
985    fn stale_success_marker_is_flagged_as_inconsistent() {
986        // Write a manifest, then overwrite _SUCCESS with the marker for a
987        // *different* manifest body — simulating an orchestrator that
988        // mishandled a re-run.
989        let dir = tempfile::tempdir().unwrap();
990        let m = build_manifest(
991            vec![part(1, 10, 4, "xxh3:1111111111111111")],
992            ManifestStatus::Success,
993        );
994        write_dataset(dir.path(), &m, &[("part-000001.parquet", b"AAAA")]);
995        std::fs::write(
996            dir.path().join(SUCCESS_FILENAME),
997            success_marker_body(b"different manifest body"),
998        )
999        .unwrap();
1000        let dest = local_dest(dir.path());
1001
1002        let v = verify_at_destination(&dest, "", ValidateDepth::Full).unwrap();
1003        assert!(!v.success_marker_consistent);
1004        assert!(!v.passed);
1005        assert!(
1006            v.failures
1007                .iter()
1008                .any(|f| matches!(f, Failure::SuccessMarkerStale { .. }))
1009        );
1010    }
1011
1012    #[test]
1013    fn malformed_success_marker_body_is_flagged() {
1014        let dir = tempfile::tempdir().unwrap();
1015        let m = build_manifest(
1016            vec![part(1, 10, 4, "xxh3:1111111111111111")],
1017            ManifestStatus::Success,
1018        );
1019        write_dataset(dir.path(), &m, &[("part-000001.parquet", b"AAAA")]);
1020        std::fs::write(dir.path().join(SUCCESS_FILENAME), b"not even xxh3 shaped").unwrap();
1021        let dest = local_dest(dir.path());
1022
1023        let v = verify_at_destination(&dest, "", ValidateDepth::Full).unwrap();
1024        assert!(!v.passed);
1025        assert!(
1026            v.failures
1027                .iter()
1028                .any(|f| matches!(f, Failure::SuccessMarkerMalformed { .. }))
1029        );
1030    }
1031
1032    #[test]
1033    fn absent_success_marker_does_not_fail_validation_alone() {
1034        // ADR-0012 M2: only successful runs land _SUCCESS.  A failed-then-
1035        // rewritten manifest legitimately lacks one — verification must
1036        // not flip `passed` just for that.
1037        let dir = tempfile::tempdir().unwrap();
1038        let m = build_manifest(
1039            vec![part(1, 10, 4, "xxh3:1111111111111111")],
1040            ManifestStatus::Failed,
1041        );
1042        write_dataset(dir.path(), &m, &[("part-000001.parquet", b"AAAA")]);
1043        // Note: write_dataset only writes _SUCCESS for status == Success,
1044        // so no marker exists here.
1045        assert!(!dir.path().join(SUCCESS_FILENAME).exists());
1046        let dest = local_dest(dir.path());
1047
1048        let v = verify_at_destination(&dest, "", ValidateDepth::Full).unwrap();
1049        assert!(v.manifest_found);
1050        assert!(
1051            !v.success_marker_consistent,
1052            "no marker => false (no signal)"
1053        );
1054        // The parts still verified, so passed = true.
1055        assert!(v.passed);
1056        assert!(v.failures.is_empty());
1057    }
1058
1059    // ── self-consistency ────────────────────────────────────────────────
1060
1061    #[test]
1062    fn self_inconsistent_manifest_is_flagged_but_part_check_still_runs() {
1063        let dir = tempfile::tempdir().unwrap();
1064        let mut m = build_manifest(
1065            vec![part(1, 10, 4, "xxh3:1111111111111111")],
1066            ManifestStatus::Success,
1067        );
1068        m.row_count = 9999; // lie
1069
1070        let body = serde_json::to_vec_pretty(&m).unwrap();
1071        std::fs::write(dir.path().join("part-000001.parquet"), b"AAAA").unwrap();
1072        std::fs::write(dir.path().join(MANIFEST_FILENAME), &body).unwrap();
1073        std::fs::write(
1074            dir.path().join(SUCCESS_FILENAME),
1075            success_marker_body(&body),
1076        )
1077        .unwrap();
1078        let dest = local_dest(dir.path());
1079
1080        let v = verify_at_destination(&dest, "", ValidateDepth::Full).unwrap();
1081        assert!(v.manifest_found);
1082        assert!(!v.manifest_self_consistent);
1083        assert!(!v.passed);
1084        // Parts that are physically present still get their `parts_verified`
1085        // counter bumped — both signals are independently useful.
1086        assert_eq!(v.parts_verified, 1);
1087        assert!(
1088            v.failures
1089                .iter()
1090                .any(|f| matches!(f, Failure::ManifestSelfInconsistent { .. }))
1091        );
1092    }
1093
1094    // ── untracked objects ───────────────────────────────────────────────
1095
1096    #[test]
1097    fn verify_counters_track_present_and_failed_parts() {
1098        // Mutation-tier2 gap: the verdict-shaping fields (manifest_found /
1099        // passed / failures) and the per-part counters (parts_verified /
1100        // parts_failed) had no assertion — `+= -> -=` survived. One present
1101        // part + one missing part pin both counters and the verdict.
1102        let dir = tempfile::tempdir().unwrap();
1103        let m = build_manifest(
1104            vec![
1105                part(1, 10, 4, "xxh3:1111111111111111"),
1106                part(2, 10, 4, "xxh3:2222222222222222"),
1107            ],
1108            ManifestStatus::Success,
1109        );
1110        // Only part 1 exists at the destination.
1111        write_dataset(dir.path(), &m, &[("part-000001.parquet", b"AAAA")]);
1112        let dest = local_dest(dir.path());
1113
1114        let v = verify_at_destination(&dest, "", ValidateDepth::Full).unwrap();
1115        assert!(v.manifest_found, "manifest is at the prefix");
1116        assert_eq!(v.parts_verified, 1, "part 1 is present at its size");
1117        assert_eq!(v.parts_failed, 1, "part 2 is missing");
1118        assert!(
1119            v.failures
1120                .iter()
1121                .any(|f| matches!(f, Failure::PartMissing { part_id: 2, .. })),
1122            "the missing part is named in failures: {:?}",
1123            v.failures
1124        );
1125        assert!(!v.passed, "a missing part must fail the verdict");
1126    }
1127
1128    #[test]
1129    fn read_capped_boundary_is_exact() {
1130        // `size > max` (not >=): a body exactly AT the cap must load; one
1131        // byte over must be refused before materialising.
1132        let dir = tempfile::tempdir().unwrap();
1133        std::fs::write(dir.path().join("at-cap.bin"), vec![0u8; 8]).unwrap();
1134        std::fs::write(dir.path().join("over-cap.bin"), vec![0u8; 9]).unwrap();
1135        let dest = local_dest(dir.path());
1136        assert_eq!(
1137            read_capped(&dest, "at-cap.bin", 8)
1138                .expect("exactly at cap loads")
1139                .len(),
1140            8
1141        );
1142        let err = read_capped(&dest, "over-cap.bin", 8).expect_err("over cap refuses");
1143        assert!(
1144            err.to_string().contains("read cap"),
1145            "actionable message: {err:#}"
1146        );
1147    }
1148
1149    #[test]
1150    fn preview_truncates_only_past_forty_chars() {
1151        let s39: String = "x".repeat(39);
1152        let s40: String = "x".repeat(40);
1153        let s41: String = "x".repeat(41);
1154        assert_eq!(preview(&s39), s39, "under the limit: unchanged");
1155        assert_eq!(
1156            preview(&s40),
1157            s40,
1158            "exactly at the limit: unchanged (`>` not `>=`)"
1159        );
1160        assert_eq!(
1161            preview(&s41),
1162            format!("{s40}\u{2026}"),
1163            "past the limit: 40 chars + ellipsis"
1164        );
1165    }
1166
1167    #[test]
1168    fn untracked_object_under_prefix_is_flagged() {
1169        let dir = tempfile::tempdir().unwrap();
1170        let m = build_manifest(
1171            vec![part(1, 10, 4, "xxh3:1111111111111111")],
1172            ManifestStatus::Success,
1173        );
1174        write_dataset(dir.path(), &m, &[("part-000001.parquet", b"AAAA")]);
1175        std::fs::write(dir.path().join("rogue.parquet"), b"XX").unwrap();
1176        let dest = local_dest(dir.path());
1177
1178        let v = verify_at_destination(&dest, "", ValidateDepth::Full).unwrap();
1179        assert!(
1180            v.failures.iter().any(
1181                |f| matches!(f, Failure::UntrackedObject { key, .. } if key == "rogue.parquet")
1182            )
1183        );
1184        // Untracked objects are surfaced but do NOT flip `passed` — that
1185        // is the resume-side decision (M9).  Parts and marker are fine,
1186        // so passed remains true.
1187        assert!(v.passed);
1188    }
1189
1190    #[test]
1191    fn quarantine_prefix_objects_are_silently_ignored() {
1192        let dir = tempfile::tempdir().unwrap();
1193        let m = build_manifest(
1194            vec![part(1, 10, 4, "xxh3:1111111111111111")],
1195            ManifestStatus::Success,
1196        );
1197        write_dataset(dir.path(), &m, &[("part-000001.parquet", b"AAAA")]);
1198        std::fs::create_dir_all(dir.path().join(crate::manifest::QUARANTINE_PREFIX)).unwrap();
1199        std::fs::write(
1200            dir.path()
1201                .join(crate::manifest::QUARANTINE_PREFIX)
1202                .join("old.parquet"),
1203            b"OO",
1204        )
1205        .unwrap();
1206        let dest = local_dest(dir.path());
1207
1208        let v = verify_at_destination(&dest, "", ValidateDepth::Full).unwrap();
1209        assert!(v.passed);
1210        assert!(
1211            !v.failures
1212                .iter()
1213                .any(|f| matches!(f, Failure::UntrackedObject { .. })),
1214            "quarantine_prefix is the legitimate home for these — must not flag"
1215        );
1216    }
1217
1218    #[test]
1219    fn doctor_probe_is_not_flagged_as_untracked() {
1220        // Regression: `rivet doctor` writes `.rivet_doctor_probe` at the
1221        // destination prefix and never removes it.  A subsequent
1222        // `rivet run --validate` against the same prefix must treat it as a
1223        // Rivet sidecar, not foreign data — otherwise `has_failures()` trips
1224        // and the run's `validated` flag is downgraded to FAIL.
1225        let dir = tempfile::tempdir().unwrap();
1226        let m = build_manifest(
1227            vec![part(1, 10, 4, "xxh3:1111111111111111")],
1228            ManifestStatus::Success,
1229        );
1230        write_dataset(dir.path(), &m, &[("part-000001.parquet", b"AAAA")]);
1231        std::fs::write(
1232            dir.path().join(crate::manifest::DOCTOR_PROBE_FILENAME),
1233            b"ok",
1234        )
1235        .unwrap();
1236        let dest = local_dest(dir.path());
1237
1238        let v = verify_at_destination(&dest, "", ValidateDepth::Full).unwrap();
1239        assert!(
1240            !v.has_failures(),
1241            "doctor probe must not surface as a failure: {:?}",
1242            v.failures
1243        );
1244        assert!(v.passed);
1245    }
1246
1247    // ── manifest_dir join semantics ─────────────────────────────────────
1248
1249    #[test]
1250    fn verifies_in_subdirectory_when_manifest_dir_is_non_empty() {
1251        let outer = tempfile::tempdir().unwrap();
1252        std::fs::create_dir_all(outer.path().join("sub/run")).unwrap();
1253        let m = build_manifest(
1254            vec![part(1, 10, 4, "xxh3:1111111111111111")],
1255            ManifestStatus::Success,
1256        );
1257        let body = serde_json::to_vec_pretty(&m).unwrap();
1258        std::fs::write(outer.path().join("sub/run/part-000001.parquet"), b"AAAA").unwrap();
1259        std::fs::write(outer.path().join("sub/run").join(MANIFEST_FILENAME), &body).unwrap();
1260        std::fs::write(
1261            outer.path().join("sub/run").join(SUCCESS_FILENAME),
1262            success_marker_body(&body),
1263        )
1264        .unwrap();
1265        let dest = local_dest(outer.path());
1266
1267        let v = verify_at_destination(&dest, "sub/run", ValidateDepth::Full).unwrap();
1268        assert!(v.passed);
1269        assert_eq!(v.parts_verified, 1);
1270
1271        // Trailing slash is normalised — same outcome.
1272        let v2 = verify_at_destination(&dest, "sub/run/", ValidateDepth::Full).unwrap();
1273        assert!(v2.passed);
1274    }
1275
1276    // ── list-failure semantics (presence now rides the listing) ──────────
1277
1278    /// Wraps a real `LocalDestination` but fails every `list_prefix`. Used to
1279    /// pin the post-refactor contract: presence is derived from the listing,
1280    /// so a listing we cannot read means the audit cannot certify the parts.
1281    struct ListFails(LocalDestination);
1282    impl crate::destination::Destination for ListFails {
1283        fn write(&self, p: &Path, k: &str) -> Result<crate::destination::WriteOutcome> {
1284            self.0.write(p, k)
1285        }
1286        fn capabilities(&self) -> crate::destination::DestinationCapabilities {
1287            self.0.capabilities()
1288        }
1289        fn head(&self, k: &str) -> Result<Option<crate::destination::ObjectMeta>> {
1290            self.0.head(k)
1291        }
1292        fn read(&self, k: &str) -> Result<Vec<u8>> {
1293            self.0.read(k)
1294        }
1295        fn list_prefix(&self, _: &str) -> Result<Vec<crate::destination::ObjectMeta>> {
1296            anyhow::bail!("listing unavailable")
1297        }
1298    }
1299
1300    #[test]
1301    fn list_failure_cannot_certify_parts_and_fails_the_audit() {
1302        let dir = tempfile::tempdir().unwrap();
1303        let m = build_manifest(vec![part(0, 3, 3, "xxh3:0")], ManifestStatus::Success);
1304        write_dataset(dir.path(), &m, &[("part-000000.parquet", b"abc")]);
1305        let dest = ListFails(local_dest(dir.path()));
1306
1307        let v = verify_at_destination(&dest, "", ValidateDepth::Full).unwrap();
1308        // The manifest itself reads + parses fine (HEAD/read still work)…
1309        assert!(v.manifest_found);
1310        assert!(v.manifest_self_consistent);
1311        // …but with no listing we verify zero parts and refuse to pass.
1312        assert!(
1313            !v.passed,
1314            "an audit that cannot list the prefix must not pass"
1315        );
1316        assert_eq!(v.parts_verified, 0);
1317        assert!(
1318            v.failures
1319                .iter()
1320                .any(|f| matches!(f, Failure::ListPrefixError { .. })),
1321            "expected a ListPrefixError, got: {:?}",
1322            v.failures
1323        );
1324    }
1325
1326    // ── manifest read-error semantics (explicit failure, not legacy) ─────
1327
1328    /// Wraps a real `LocalDestination` but fails reading `manifest.json`
1329    /// (head still sees it) — EACCES or a transient store error on a
1330    /// manifest that exists.
1331    struct ManifestReadFails(LocalDestination);
1332    impl crate::destination::Destination for ManifestReadFails {
1333        fn write(&self, p: &Path, k: &str) -> Result<crate::destination::WriteOutcome> {
1334            self.0.write(p, k)
1335        }
1336        fn capabilities(&self) -> crate::destination::DestinationCapabilities {
1337            self.0.capabilities()
1338        }
1339        fn head(&self, k: &str) -> Result<Option<crate::destination::ObjectMeta>> {
1340            self.0.head(k)
1341        }
1342        fn read(&self, k: &str) -> Result<Vec<u8>> {
1343            if k.ends_with(MANIFEST_FILENAME) {
1344                anyhow::bail!("permission denied (simulated)")
1345            }
1346            self.0.read(k)
1347        }
1348        fn list_prefix(&self, p: &str) -> Result<Vec<crate::destination::ObjectMeta>> {
1349            self.0.list_prefix(p)
1350        }
1351    }
1352
1353    #[test]
1354    fn unreadable_manifest_is_explicit_failure_not_legacy() {
1355        // The exit gates (`rivet validate`, run finalize) key off this exact
1356        // shape: `manifest_found: false` but `has_failures()` — distinct
1357        // from M6 legacy (`legacy_run: true`, no failures, exit 0).
1358        let dir = tempfile::tempdir().unwrap();
1359        let m = build_manifest(
1360            vec![part(1, 10, 4, "xxh3:1111111111111111")],
1361            ManifestStatus::Success,
1362        );
1363        write_dataset(dir.path(), &m, &[("part-000001.parquet", b"AAAA")]);
1364        let dest = ManifestReadFails(local_dest(dir.path()));
1365
1366        let v = verify_at_destination(&dest, "", ValidateDepth::Full).unwrap();
1367        assert!(!v.manifest_found);
1368        assert!(!v.legacy_run, "a read error is not the M6 legacy label");
1369        assert!(!v.passed);
1370        assert!(v.has_failures(), "orchestrators need a reason to refuse");
1371        assert!(
1372            matches!(v.failures.as_slice(), [Failure::ManifestReadError { .. }]),
1373            "expected exactly one ManifestReadError, got: {:?}",
1374            v.failures
1375        );
1376    }
1377
1378    /// Same contract when `head` itself errors (cannot even stat the
1379    /// manifest): symmetric `ManifestReadError`, never the legacy label.
1380    struct ManifestHeadFails(LocalDestination);
1381    impl crate::destination::Destination for ManifestHeadFails {
1382        fn write(&self, p: &Path, k: &str) -> Result<crate::destination::WriteOutcome> {
1383            self.0.write(p, k)
1384        }
1385        fn capabilities(&self) -> crate::destination::DestinationCapabilities {
1386            self.0.capabilities()
1387        }
1388        fn head(&self, k: &str) -> Result<Option<crate::destination::ObjectMeta>> {
1389            if k.ends_with(MANIFEST_FILENAME) {
1390                anyhow::bail!("io timeout (simulated)")
1391            }
1392            self.0.head(k)
1393        }
1394        fn read(&self, k: &str) -> Result<Vec<u8>> {
1395            self.0.read(k)
1396        }
1397        fn list_prefix(&self, p: &str) -> Result<Vec<crate::destination::ObjectMeta>> {
1398            self.0.list_prefix(p)
1399        }
1400    }
1401
1402    #[test]
1403    fn manifest_head_error_is_explicit_failure_not_legacy() {
1404        let dir = tempfile::tempdir().unwrap();
1405        let m = build_manifest(
1406            vec![part(1, 10, 4, "xxh3:1111111111111111")],
1407            ManifestStatus::Success,
1408        );
1409        write_dataset(dir.path(), &m, &[("part-000001.parquet", b"AAAA")]);
1410        let dest = ManifestHeadFails(local_dest(dir.path()));
1411
1412        let v = verify_at_destination(&dest, "", ValidateDepth::Full).unwrap();
1413        assert!(!v.manifest_found);
1414        assert!(!v.legacy_run);
1415        assert!(!v.passed);
1416        assert!(
1417            matches!(
1418                v.failures.as_slice(),
1419                [Failure::ManifestReadError { detail }] if detail.contains("manifest head failed")
1420            ),
1421            "expected one ManifestReadError naming the head step, got: {:?}",
1422            v.failures
1423        );
1424    }
1425
1426    // #5: a _SUCCESS whose head-reported size exceeds the cap must be flagged
1427    // WITHOUT being read — a bare uncapped read of a multi-GB planted marker OOMs
1428    // the validate/resume process (asymmetric with the manifest.json cap). The mock
1429    // PANICS if read(_SUCCESS) is called, so the test passing proves the read was
1430    // short-circuited by the size check.
1431    struct SuccessMarkerOversized(LocalDestination);
1432    impl crate::destination::Destination for SuccessMarkerOversized {
1433        fn write(&self, p: &Path, k: &str) -> Result<crate::destination::WriteOutcome> {
1434            self.0.write(p, k)
1435        }
1436        fn capabilities(&self) -> crate::destination::DestinationCapabilities {
1437            self.0.capabilities()
1438        }
1439        fn head(&self, k: &str) -> Result<Option<crate::destination::ObjectMeta>> {
1440            if k.ends_with(crate::manifest::SUCCESS_FILENAME) {
1441                return Ok(Some(crate::destination::ObjectMeta {
1442                    key: k.to_string(),
1443                    size_bytes: SUCCESS_MARKER_MAX_BYTES * 4,
1444                    content_md5: None,
1445                }));
1446            }
1447            self.0.head(k)
1448        }
1449        fn read(&self, k: &str) -> Result<Vec<u8>> {
1450            assert!(
1451                !k.ends_with(crate::manifest::SUCCESS_FILENAME),
1452                "verify must NOT read an oversized _SUCCESS — the size cap must short-circuit \
1453                 before materialising it into memory (the OOM this guards)"
1454            );
1455            self.0.read(k)
1456        }
1457        fn list_prefix(&self, p: &str) -> Result<Vec<crate::destination::ObjectMeta>> {
1458            self.0.list_prefix(p)
1459        }
1460    }
1461
1462    #[test]
1463    fn oversized_success_marker_is_malformed_and_never_read() {
1464        let dir = tempfile::tempdir().unwrap();
1465        let m = build_manifest(
1466            vec![part(1, 10, 4, "xxh3:1111111111111111")],
1467            ManifestStatus::Success,
1468        );
1469        write_dataset(dir.path(), &m, &[("part-000001.parquet", b"AAAA")]);
1470        let dest = SuccessMarkerOversized(local_dest(dir.path()));
1471
1472        let v = verify_at_destination(&dest, "", ValidateDepth::Full).unwrap();
1473        assert!(
1474            v.failures.iter().any(|f| matches!(
1475                f,
1476                Failure::SuccessMarkerMalformed { body_preview } if body_preview.contains("oversized")
1477            )),
1478            "an oversized _SUCCESS must yield SuccessMarkerMalformed(oversized) without reading it, got: {:?}",
1479            v.failures
1480        );
1481    }
1482
1483    #[test]
1484    fn passed_is_derived_advisory_failures_do_not_fail() {
1485        // An advisory failure (untracked surplus) keeps the verdict passing…
1486        let mut v = ManifestVerification {
1487            manifest_found: true,
1488            ..ManifestVerification::empty()
1489        };
1490        v.failures.push(Failure::UntrackedObject {
1491            key: "stray.parquet".into(),
1492            size_bytes: 9,
1493        });
1494        v.recompute_passed();
1495        assert!(v.passed, "untracked surplus is advisory, not fatal");
1496
1497        // …while any fatal failure flips it.
1498        v.failures.push(Failure::PartMissing {
1499            part_id: 1,
1500            path: "part-000001.parquet".into(),
1501        });
1502        v.recompute_passed();
1503        assert!(!v.passed, "a missing part is fatal");
1504
1505        // No manifest → never passes regardless of failures.
1506        let mut legacy = ManifestVerification::empty();
1507        legacy.recompute_passed();
1508        assert!(!legacy.passed, "no manifest found → cannot certify");
1509    }
1510
1511    #[test]
1512    fn verify_content_policy_fails_only_size_only_parts() {
1513        // 3 parts, 2 content-checked, 1 size-only.
1514        let base = ManifestVerification {
1515            manifest_found: true,
1516            parts_verified: 3,
1517            parts_md5_verified: 2,
1518            ..ManifestVerification::empty()
1519        };
1520        // verify: size → size-only is acceptable, passes.
1521        let mut sz = base.clone();
1522        sz.recompute_passed();
1523        sz.enforce_content_policy(false);
1524        assert!(sz.passed, "size-only OK under verify: size");
1525
1526        // verify: content → the 1 size-only part is a fatal failure.
1527        let mut ct = base.clone();
1528        ct.recompute_passed();
1529        ct.enforce_content_policy(true);
1530        assert!(!ct.passed, "a size-only part fails verify: content");
1531        assert!(
1532            ct.failures.iter().any(|f| matches!(
1533                f,
1534                Failure::ContentVerificationUnmet {
1535                    size_only: 1,
1536                    total: 3
1537                }
1538            )),
1539            "expected ContentVerificationUnmet, got: {:?}",
1540            ct.failures
1541        );
1542
1543        // verify: content with every part md5-checked → satisfied.
1544        let mut all = ManifestVerification {
1545            parts_md5_verified: 3,
1546            ..base
1547        };
1548        all.recompute_passed();
1549        all.enforce_content_policy(true);
1550        assert!(
1551            all.passed && all.failures.is_empty(),
1552            "all md5 meets verify: content"
1553        );
1554    }
1555
1556    // ── require_manifest_present (finding #20: operator-pinned --prefix) ──────
1557
1558    #[test]
1559    fn require_manifest_escalates_legacy_to_fatal_absent() {
1560        // The exact shape `verify_at_destination` returns for an absent manifest
1561        // (`legacy()`): no manifest, no other failure. With a pinned `--prefix`
1562        // this is escalated to a fatal `ManifestRequiredButAbsent` so the exit
1563        // gate refuses it instead of passing as a benign legacy run.
1564        let mut v = ManifestVerification::legacy();
1565        assert!(v.legacy_run && !v.has_failures());
1566
1567        v.require_manifest_present("exports/2026-06-09/orders/");
1568
1569        assert!(!v.legacy_run, "no longer the benign legacy-run label");
1570        assert!(!v.passed, "an absent-but-required manifest cannot pass");
1571        assert!(
1572            matches!(
1573                v.failures.as_slice(),
1574                [Failure::ManifestRequiredButAbsent { prefix }]
1575                    if prefix == "exports/2026-06-09/orders/"
1576            ),
1577            "expected one ManifestRequiredButAbsent naming the prefix, got: {:?}",
1578            v.failures
1579        );
1580    }
1581
1582    #[test]
1583    fn require_manifest_is_noop_on_a_real_passing_manifest() {
1584        // A found, passing verdict is untouched — `--prefix` plus real data is
1585        // the normal "validate this exact prefix" case and must still pass.
1586        let mut v = ManifestVerification {
1587            manifest_found: true,
1588            manifest_self_consistent: true,
1589            parts_verified: 1,
1590            passed: true,
1591            ..ManifestVerification::empty()
1592        };
1593        v.require_manifest_present("exports/orders/");
1594        assert!(
1595            v.passed && v.failures.is_empty(),
1596            "real dataset still passes"
1597        );
1598    }
1599
1600    #[test]
1601    fn require_manifest_does_not_double_flag_a_read_error() {
1602        // An absent manifest that already carries a `ManifestReadError` (head /
1603        // read failed) is already a fatal, classified failure — requiring a
1604        // manifest here must not add a second, redundant failure.
1605        let mut v = ManifestVerification::legacy();
1606        v.legacy_run = false;
1607        v.failures.push(Failure::ManifestReadError {
1608            detail: "permission denied".into(),
1609        });
1610        v.recompute_passed();
1611
1612        v.require_manifest_present("exports/orders/");
1613
1614        assert!(
1615            matches!(v.failures.as_slice(), [Failure::ManifestReadError { .. }]),
1616            "must leave the existing read-error verdict alone, got: {:?}",
1617            v.failures
1618        );
1619    }
1620
1621    // ── graded verify layer (--depth) ───────────────────────────────────
1622
1623    #[test]
1624    fn light_depth_skips_part_reconcile_even_when_a_part_is_missing() {
1625        // A manifest declaring a part that is NOT on disk. At `Full`/`Sample`
1626        // this is a fatal `PartMissing`; at `Light` the `list_prefix` reconcile
1627        // is skipped entirely, so `parts_verified == 0`, no `ListPrefixError`,
1628        // and — with `_SUCCESS` consistent and the manifest self-consistent —
1629        // the verdict still passes. Light certifies the manifest + marker, not
1630        // the parts.
1631        let dir = tempfile::tempdir().unwrap();
1632        let m = build_manifest(
1633            vec![
1634                part(1, 10, 4, "xxh3:1111111111111111"),
1635                part(2, 20, 5, "xxh3:2222222222222222"),
1636            ],
1637            ManifestStatus::Success,
1638        );
1639        // Deliberately write NEITHER part — only manifest.json + _SUCCESS.
1640        write_dataset(dir.path(), &m, &[]);
1641        let dest = local_dest(dir.path());
1642
1643        let v = verify_at_destination(&dest, "", ValidateDepth::Light).unwrap();
1644        assert_eq!(v.depth_level, "light");
1645        assert_eq!(
1646            v.parts_verified, 0,
1647            "light skips the listing — no part is ever verified"
1648        );
1649        assert_eq!(
1650            v.parts_failed, 0,
1651            "no part reconcile means no part failures"
1652        );
1653        assert!(
1654            !v.failures.iter().any(|f| matches!(
1655                f,
1656                Failure::PartMissing { .. } | Failure::ListPrefixError { .. }
1657            )),
1658            "light must not surface part or list failures, got: {:?}",
1659            v.failures
1660        );
1661        assert!(
1662            v.success_marker_consistent,
1663            "_SUCCESS is still checked at light depth"
1664        );
1665        assert!(v.manifest_self_consistent);
1666        assert!(
1667            v.passed,
1668            "manifest + _SUCCESS are consistent, so a light pass certifies it"
1669        );
1670    }
1671
1672    #[test]
1673    fn light_depth_never_lists_so_a_list_failure_cannot_trip() {
1674        // Even with a destination whose `list_prefix` always errors, a light
1675        // pass succeeds: it never calls `list_prefix`, so no `ListPrefixError`.
1676        // This is the direct contrast to `list_failure_cannot_certify_parts…`
1677        // (which runs at Full and *does* fail on the list error).
1678        let dir = tempfile::tempdir().unwrap();
1679        let m = build_manifest(vec![part(0, 3, 3, "xxh3:0")], ManifestStatus::Success);
1680        write_dataset(dir.path(), &m, &[("part-000000.parquet", b"abc")]);
1681        let dest = ListFails(local_dest(dir.path()));
1682
1683        let v = verify_at_destination(&dest, "", ValidateDepth::Light).unwrap();
1684        assert_eq!(v.depth_level, "light");
1685        assert!(
1686            !v.failures
1687                .iter()
1688                .any(|f| matches!(f, Failure::ListPrefixError { .. })),
1689            "light never lists, so a failing list_prefix cannot surface, got: {:?}",
1690            v.failures
1691        );
1692        assert_eq!(v.parts_verified, 0);
1693        assert!(v.passed, "manifest + _SUCCESS consistent → light passes");
1694    }
1695
1696    #[test]
1697    fn sample_depth_runs_part_reconcile_like_full() {
1698        // `Sample` runs every section `verify_at_destination` owns (1-5) — the
1699        // Form B value re-read it skips lives in the *caller*, not here. So a
1700        // missing part is a fatal `PartMissing` at Sample, identical to Full.
1701        let dir = tempfile::tempdir().unwrap();
1702        let m = build_manifest(
1703            vec![
1704                part(1, 10, 4, "xxh3:1111111111111111"),
1705                part(2, 20, 5, "xxh3:2222222222222222"),
1706            ],
1707            ManifestStatus::Success,
1708        );
1709        write_dataset(dir.path(), &m, &[("part-000001.parquet", b"AAAA")]); // part 2 missing
1710        let dest = local_dest(dir.path());
1711
1712        let v = verify_at_destination(&dest, "", ValidateDepth::Sample).unwrap();
1713        assert_eq!(v.depth_level, "sample");
1714        assert_eq!(v.parts_verified, 1);
1715        assert_eq!(v.parts_failed, 1);
1716        assert!(!v.passed);
1717        assert!(
1718            v.failures
1719                .iter()
1720                .any(|f| matches!(f, Failure::PartMissing { part_id: 2, .. })),
1721            "sample reconciles parts just like full, got: {:?}",
1722            v.failures
1723        );
1724    }
1725
1726    #[test]
1727    fn depth_level_is_stamped_on_every_verdict_shape() {
1728        // The depth label rides the verdict even on the early-return shapes
1729        // (legacy / no manifest), so a consumer always sees how deep the pass
1730        // went.
1731        let dir = tempfile::tempdir().unwrap();
1732        let dest = local_dest(dir.path()); // empty prefix → legacy
1733        for depth in [
1734            ValidateDepth::Light,
1735            ValidateDepth::Sample,
1736            ValidateDepth::Full,
1737        ] {
1738            let v = verify_at_destination(&dest, "", depth).unwrap();
1739            assert!(v.legacy_run, "empty prefix is the legacy shape");
1740            assert_eq!(
1741                v.depth_level,
1742                depth.label(),
1743                "legacy verdict must still carry its depth label"
1744            );
1745        }
1746    }
1747
1748    #[test]
1749    fn error_code_is_stable_and_distinct_per_variant() {
1750        // Each variant maps to its documented `RIVET_VERIFY_*` code. A
1751        // regression guard: renaming a code is a silent break for any CI gate
1752        // keying off it.
1753        let cases: &[(Failure, &str)] = &[
1754            (
1755                Failure::PartMissing {
1756                    part_id: 1,
1757                    path: "p".into(),
1758                },
1759                "RIVET_VERIFY_PART_MISSING",
1760            ),
1761            (
1762                Failure::PartSizeMismatch {
1763                    part_id: 1,
1764                    path: "p".into(),
1765                    expected: 1,
1766                    actual: 2,
1767                },
1768                "RIVET_VERIFY_PART_SIZE_MISMATCH",
1769            ),
1770            (
1771                Failure::PartChecksumMismatch {
1772                    part_id: 1,
1773                    path: "p".into(),
1774                    expected: "a".into(),
1775                    actual: "b".into(),
1776                },
1777                "RIVET_VERIFY_PART_CHECKSUM_MISMATCH",
1778            ),
1779            (
1780                Failure::SuccessMarkerMalformed {
1781                    body_preview: "x".into(),
1782                },
1783                "RIVET_VERIFY_SUCCESS_MALFORMED",
1784            ),
1785            (
1786                Failure::SuccessMarkerStale {
1787                    marker_fingerprint: "a".into(),
1788                    manifest_fingerprint: "b".into(),
1789                },
1790                "RIVET_VERIFY_SUCCESS_STALE",
1791            ),
1792            (
1793                Failure::ManifestSelfInconsistent { detail: "d".into() },
1794                "RIVET_VERIFY_MANIFEST_INCONSISTENT",
1795            ),
1796            (
1797                Failure::ManifestReadError { detail: "d".into() },
1798                "RIVET_VERIFY_MANIFEST_READ_ERROR",
1799            ),
1800            (
1801                Failure::SuccessMarkerReadError { detail: "d".into() },
1802                "RIVET_VERIFY_SUCCESS_READ_ERROR",
1803            ),
1804            (
1805                Failure::ListPrefixError { detail: "d".into() },
1806                "RIVET_VERIFY_LIST_ERROR",
1807            ),
1808            (
1809                Failure::UntrackedObject {
1810                    key: "k".into(),
1811                    size_bytes: 1,
1812                },
1813                "RIVET_VERIFY_UNTRACKED_OBJECT",
1814            ),
1815            (
1816                Failure::ContentVerificationUnmet {
1817                    size_only: 1,
1818                    total: 2,
1819                },
1820                "RIVET_VERIFY_CONTENT_UNMET",
1821            ),
1822            (
1823                Failure::ManifestRequiredButAbsent { prefix: "p".into() },
1824                "RIVET_VERIFY_MANIFEST_REQUIRED",
1825            ),
1826        ];
1827        for (failure, code) in cases {
1828            assert_eq!(&failure.error_code(), code, "code for {failure:?}");
1829            assert!(
1830                failure.error_code().starts_with("RIVET_VERIFY_"),
1831                "every code shares the RIVET_VERIFY_ prefix"
1832            );
1833        }
1834    }
1835}