Skip to main content

rivet/
manifest.rs

1//! **Layer: Trust contract**
2//!
3//! Public JSON manifest written next to every cloud-or-local-file run's
4//! output.  Defines the wire schema and the in-memory builder; the actual
5//! writer (atomic rename / atomic PUT) lives next to the destination
6//! implementations.
7//!
8//! Invariants are documented in [`docs/adr/0012-cloud-manifest-contract.md`].
9//! This module owns *only* the data types and a tiny set of pure helpers —
10//! ordering, atomicity, and `_SUCCESS` semantics belong to the writer.
11//!
12//! The manifest is read by:
13//! - `--resume` (decision matrix M8: skip / rewrite / quarantine)
14//! - `--validate` (M5: every listed part exists at recorded size)
15//! - `--reconcile` (manifest row counts vs source `COUNT(*)`)
16//! - the run report (informational; not a verdict source)
17//!
18//! Forward compatibility: callers MUST ignore unknown fields when reading.
19//! Field additions are non-breaking; field removals or type changes require
20//! a [`MANIFEST_VERSION`] bump.
21
22// The wire types (RunManifest, ManifestPart, ...) and the writer-side
23// helpers (success_marker_body) are already wired into the pipeline; the
24// reader-side helpers (validate_self_consistency, committed_rows,
25// committed_part_count, parse_success_marker, ManifestInconsistency) ship
26// next when `--validate` / `--reconcile` learn to inspect the manifest.
27// Mark the whole module as dead-code-tolerant until then so the bin crate
28// (which doesn't compile tests) stays clean.
29#![allow(dead_code)]
30
31use serde::{Deserialize, Serialize};
32
33/// Current manifest schema version.  See ADR-0012 §Manifest schema.
34pub const MANIFEST_VERSION: u32 = 1;
35
36/// File name of the manifest at the destination prefix.
37pub const MANIFEST_FILENAME: &str = "manifest.json";
38
39/// File name of the success marker.  Written *after* the manifest per M2;
40/// its presence implies M5 (every listed part exists at recorded size).
41pub const SUCCESS_FILENAME: &str = "_SUCCESS";
42
43/// Prefix under which untracked / corrupt parts are moved on resume (M9).
44/// Layout: `<prefix>/_quarantine/<run_id>/<original-name>`.
45pub const QUARANTINE_PREFIX: &str = "_quarantine";
46
47/// `manifest-<sanitized run_id>.json` — the immutable per-run COPY written
48/// beside the canonical [`MANIFEST_FILENAME`]. The canonical name is
49/// last-writer-wins (a pointer to the latest run); consecutive runs into one
50/// prefix would clobber it, so this copy preserves EACH run's manifest for a
51/// consumer that sums row counts across runs. Same run-token sanitizer the
52/// parts use: an RFC3339 run id carries `:`/`+` (illegal on Windows), so map
53/// anything outside `[A-Za-z0-9._-]` to `-`.
54pub fn run_unique_manifest_name(run_id: &str) -> String {
55    let token: String = run_id
56        .chars()
57        .map(|c| {
58            if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
59                c
60            } else {
61                '-'
62            }
63        })
64        .collect();
65    format!("manifest-{token}.json")
66}
67
68/// True if `name` (a final path segment) is a [`run_unique_manifest_name`] copy
69/// — a Rivet-internal sidecar the validate/reconcile paths must NOT flag as an
70/// untracked foreign object. Excludes the canonical `manifest.json` (`manifest.`
71/// prefix, not `manifest-`).
72pub fn is_run_unique_manifest_name(name: &str) -> bool {
73    name.starts_with("manifest-") && name.ends_with(".json")
74}
75
76/// Writability probe `rivet doctor` drops at the destination prefix.  It is a
77/// Rivet-internal sidecar (like [`MANIFEST_FILENAME`] / [`SUCCESS_FILENAME`]),
78/// so the manifest-aware `--validate` pass must not flag it as an untracked
79/// foreign object when a run follows a `doctor` against the same prefix.
80pub const DOCTOR_PROBE_FILENAME: &str = ".rivet_doctor_probe";
81
82/// Join a manifest-relative key (e.g. a part `path`, [`MANIFEST_FILENAME`])
83/// onto a destination sub-directory.  An empty `dir` returns `key` unchanged
84/// — the common case, since production callers pass `""` (the manifest lives
85/// at the prefix root).  Shared by the destination-verification and
86/// resume-reconciliation paths so both speak the same key namespace.
87pub fn join_key(dir: &str, key: &str) -> String {
88    let dir = dir.trim_end_matches('/');
89    if dir.is_empty() {
90        key.to_string()
91    } else {
92        format!("{dir}/{key}")
93    }
94}
95
96/// Compute the body of the `_SUCCESS` marker for a given serialized manifest.
97///
98/// Format: a single line `"xxh3:<16-hex>\n"`.  ADR-0012 M2 — `_SUCCESS`
99/// carries the manifest fingerprint so an orchestrator can detect manifest
100/// changes (rerun, resume that completed, repair) with a cheap `GET _SUCCESS`
101/// instead of refetching the full manifest body.
102///
103/// `manifest_bytes` must be the exact bytes that were written to `manifest.json`
104/// — usually the result of `serde_json::to_vec_pretty(&RunManifest)`.  The
105/// caller is responsible for using the same bytes for both writes; computing
106/// the fingerprint from a re-serialized struct would risk encoding drift
107/// (key ordering, whitespace) producing a different hash.
108pub fn success_marker_body(manifest_bytes: &[u8]) -> String {
109    use xxhash_rust::xxh3::xxh3_64;
110    format!("xxh3:{:016x}\n", xxh3_64(manifest_bytes))
111}
112
113/// Parse the fingerprint out of a `_SUCCESS` marker body.
114///
115/// Returns `Some("xxh3:<hex>")` on a well-formed marker, `None` on anything
116/// else (empty file, missing prefix, wrong length, non-hex body).  Trailing
117/// whitespace and newlines are tolerated to match the on-wire shape produced
118/// by [`success_marker_body`].
119///
120/// Used by `--validate` and by external polling consumers (Airflow sensors,
121/// CI checks) to decide whether a cached manifest is still current.
122pub fn parse_success_marker(body: &str) -> Option<&str> {
123    let trimmed = body.trim_end_matches(|c: char| c.is_ascii_whitespace());
124    // `strip_prefix` + a BYTE-length check, NOT `split_at`: split_at panics on a
125    // non-char-boundary index, so a crafted 21-byte valid-UTF-8 `_SUCCESS` body with
126    // a multibyte codepoint straddling byte 5 (`"aaa" + U+0800 + …`) passed the old
127    // length gate and aborted the whole `validate`/`--resume`/repair process under
128    // the release `panic=abort` profile — a DoS of the trust oracle via a
129    // destination-writable planted file (the same threat surface the manifest.json
130    // byte-cap already defends). strip_prefix + byte-len never touch a char boundary.
131    let hex = trimmed.strip_prefix("xxh3:")?;
132    if hex.len() != 16 {
133        return None;
134    }
135    if !hex
136        .chars()
137        .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
138    {
139        return None;
140    }
141    Some(trimmed)
142}
143
144/// One per-column Form B checksum, keyed by column **name** (not position) so a
145/// column reorder between export and validate can never silently misalign the
146/// comparison (the positional `Vec<String>` it replaced could). `checksum` is the
147/// per-column xxh3, XOR-combined over the whole export, as a decimal string
148/// (JSON-stable).
149#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
150pub struct ColumnChecksum {
151    pub name: String,
152    pub checksum: String,
153}
154
155/// Public, stable JSON shape for the run manifest.
156///
157/// One manifest is written per `run_id` per export.  See ADR-0012 M4
158/// (Append-Only Per Run) for the resume-across-interruption story.
159#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
160pub struct RunManifest {
161    pub manifest_version: u32,
162    pub run_id: String,
163    pub export_name: String,
164    /// Which pipeline shape wrote this manifest — `batch` or `cdc`. Guards a
165    /// prefix against silent cross-shape clobbering (finding #44: a CDC run
166    /// overwrote a batch export's manifest at a shared prefix, orphaning its
167    /// parts from `rivet validate`). Defaults to `batch` for manifests
168    /// written before this field existed.
169    #[serde(default = "default_manifest_mode")]
170    pub mode: String,
171    pub started_at: String,
172    pub finished_at: String,
173    pub status: ManifestStatus,
174    pub source: ManifestSource,
175    pub destination: ManifestDestination,
176    pub format: String,
177    pub compression: String,
178    /// xxh3 fingerprint of the column schema; see [`crate::state::schema_fingerprint`].
179    pub schema_fingerprint: String,
180    pub row_count: i64,
181    pub part_count: u32,
182    pub parts: Vec<ManifestPart>,
183    /// Per-column value checksum over the whole export (Form B), keyed by column
184    /// name — the per-column xxh3 XOR-combined over the run. `rivet validate`
185    /// re-reads the parts and recomputes this to catch an `Arrow→Parquet` encode
186    /// fault or post-write corruption — the step the in-process Form A check
187    /// cannot see. Optional for back-compat: older manifests omit it (no
188    /// `MANIFEST_VERSION` bump), newer readers tolerate its absence.
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub column_checksums: Option<Vec<ColumnChecksum>>,
191    /// The column the Form B checksum is keyed to (`xxh3(key ‖ value)`, the
192    /// export's cursor/key column) so `validate` re-keys identically. `None` ⇒
193    /// un-keyed (a full export with no cursor). See [`ColumnChecksum`].
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub checksum_key_column: Option<String>,
196}
197
198/// Terminal status of the run *as recorded by the writer*.
199///
200/// `success` is only written when M2 (Manifest Before SUCCESS) is satisfied
201/// — i.e. when the writer is about to drop the `_SUCCESS` marker.
202/// `failed` and `interrupted` manifests serve as audit trails and as input
203/// to resume; they do NOT trigger `_SUCCESS`.
204#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
205#[serde(rename_all = "snake_case")]
206pub enum ManifestStatus {
207    Success,
208    Failed,
209    Interrupted,
210}
211
212#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
213pub struct ManifestSource {
214    pub engine: String,
215    pub schema: Option<String>,
216    pub table: Option<String>,
217    /// The extraction contract this run fulfilled — strategy, cursor identity,
218    /// and the cursor RANGE this extract covered. Ported from the
219    /// pip_db_replicator meta-catalog idea: cursor metadata travels WITH the
220    /// extract so a downstream warehouse can reconcile continuity
221    /// (`run N+1.cursor_low` must follow `run N.cursor_high` — a gap is a
222    /// silently-skipped range) without querying rivet's private state.
223    /// `None` on manifests written before this field existed, and on paths
224    /// that carry no cursor (a full snapshot records only the strategy).
225    #[serde(default, skip_serializing_if = "Option::is_none")]
226    pub extraction: Option<ExtractionMetadata>,
227}
228
229/// Cursor/strategy metadata shipped in the manifest for warehouse-side
230/// reconciliation. Cursor bounds are STRING-encoded and type-tagged: a lexical
231/// order lies on numbers (the same trap as a binlog `__pos` string), so the
232/// consumer compares by `cursor_type`, not by raw string order.
233#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
234pub struct ExtractionMetadata {
235    /// `full` / `incremental` / `chunked` / `keyset` / `timewindow`.
236    pub strategy: String,
237    /// Resolved cursor/key column, when the strategy has one.
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub cursor_column: Option<String>,
240    /// Source type of the cursor column (for typed range comparison).
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub cursor_type: Option<String>,
243    /// Lowest cursor value covered by THIS extract (the prior run's high, or
244    /// the min seen this run). `None` for a full snapshot / first run.
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub cursor_low: Option<String>,
247    /// Highest cursor value covered — the value the NEXT run must resume from.
248    #[serde(default, skip_serializing_if = "Option::is_none")]
249    pub cursor_high: Option<String>,
250    /// Source-side row count at extraction time, when cheaply known — distinct
251    /// from the manifest's `row_count` (rows EXTRACTED). A divergence is the
252    /// reconciliation signal. `None` when not probed.
253    #[serde(default, skip_serializing_if = "Option::is_none")]
254    pub source_row_count: Option<i64>,
255}
256
257#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
258pub struct ManifestDestination {
259    pub kind: String,
260    pub uri: String,
261}
262
263/// One committed (or quarantined) output part.
264///
265/// `path` is **relative to the destination prefix** (ADR-0012 §Manifest
266/// schema) so the manifest is portable across copies of the dataset.
267#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
268pub struct ManifestPart {
269    pub part_id: u32,
270    pub path: String,
271    pub rows: i64,
272    pub size_bytes: u64,
273    /// xxh3 fingerprint of the part body.  Format mirrors [`crate::state::schema_fingerprint`]:
274    /// `"xxh3:<16-hex>"`.  Algorithm prefix MUST be checked before interpreting
275    /// the hex body (sha256/blake3 reserved for future hashers).
276    pub content_fingerprint: String,
277    /// Base64 MD5 of the part body, in GCS's `md5Hash` encoding — lets
278    /// destination verification compare against the object's listing metadata
279    /// with **no download** (GCS/S3/Azure surface this; the comparison rides
280    /// the listing `--validate` already does).  Empty for legacy manifests and
281    /// for parts whose MD5 could not be computed; the check then degrades to
282    /// size-only.  `#[serde(default)]` keeps pre-0.7.x manifests parseable.
283    #[serde(default)]
284    pub content_md5: String,
285    pub status: PartStatus,
286}
287
288#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
289#[serde(rename_all = "snake_case")]
290pub enum PartStatus {
291    /// Listed in the active manifest at the destination.
292    Committed,
293    /// Found in a prior manifest but rejected on resume (M9); retained for audit.
294    Quarantined,
295}
296
297impl RunManifest {
298    /// Sum of `rows` across `Committed` parts.  Used by M5 sanity checks and
299    /// by `--reconcile` to compare against source `COUNT(*)`.
300    pub fn committed_rows(&self) -> i64 {
301        self.parts
302            .iter()
303            .filter(|p| p.status == PartStatus::Committed)
304            .map(|p| p.rows)
305            .sum()
306    }
307
308    /// Number of `Committed` parts.
309    pub fn committed_part_count(&self) -> usize {
310        self.parts
311            .iter()
312            .filter(|p| p.status == PartStatus::Committed)
313            .count()
314    }
315
316    /// Verify that the recorded aggregates (`row_count`, `part_count`) match
317    /// the actual `Committed` parts in `parts`.  A mismatch is a writer bug;
318    /// callers should refuse to act on the manifest until investigated.
319    pub fn validate_self_consistency(&self) -> std::result::Result<(), ManifestInconsistency> {
320        if self.manifest_version != MANIFEST_VERSION {
321            return Err(ManifestInconsistency::UnsupportedVersion {
322                found: self.manifest_version,
323                supported: MANIFEST_VERSION,
324            });
325        }
326        let actual_parts = self.committed_part_count();
327        if actual_parts != self.part_count as usize {
328            return Err(ManifestInconsistency::PartCountMismatch {
329                declared: self.part_count,
330                actual: actual_parts,
331            });
332        }
333        let actual_rows = self.committed_rows();
334        if actual_rows != self.row_count {
335            return Err(ManifestInconsistency::RowCountMismatch {
336                declared: self.row_count,
337                actual: actual_rows,
338            });
339        }
340        // Part IDs must be unique within a manifest.
341        let mut ids: Vec<u32> = self.parts.iter().map(|p| p.part_id).collect();
342        ids.sort_unstable();
343        for w in ids.windows(2) {
344            if w[0] == w[1] {
345                return Err(ManifestInconsistency::DuplicatePartId(w[0]));
346            }
347        }
348        Ok(())
349    }
350}
351
352/// Self-consistency failures detected by [`RunManifest::validate_self_consistency`].
353///
354/// These represent writer bugs, not destination drift; M5 destination-state
355/// checks live in the validate command path.
356#[derive(Debug, PartialEq)]
357pub enum ManifestInconsistency {
358    UnsupportedVersion { found: u32, supported: u32 },
359    PartCountMismatch { declared: u32, actual: usize },
360    RowCountMismatch { declared: i64, actual: i64 },
361    DuplicatePartId(u32),
362}
363
364impl std::fmt::Display for ManifestInconsistency {
365    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
366        match self {
367            Self::UnsupportedVersion { found, supported } => write!(
368                f,
369                "manifest_version {found} is not supported by this build (expected {supported})"
370            ),
371            Self::PartCountMismatch { declared, actual } => write!(
372                f,
373                "part_count declares {declared} parts but {actual} committed parts found"
374            ),
375            Self::RowCountMismatch { declared, actual } => write!(
376                f,
377                "row_count declares {declared} rows but committed parts sum to {actual}"
378            ),
379            Self::DuplicatePartId(id) => {
380                write!(f, "duplicate part_id {id} in manifest.parts")
381            }
382        }
383    }
384}
385
386impl std::error::Error for ManifestInconsistency {}
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391
392    fn part(id: u32, rows: i64, size: u64) -> ManifestPart {
393        ManifestPart {
394            part_id: id,
395            path: format!("part-{id:06}.parquet"),
396            rows,
397            size_bytes: size,
398            content_fingerprint: format!("xxh3:{:016x}", id as u64),
399            content_md5: String::new(),
400            status: PartStatus::Committed,
401        }
402    }
403
404    fn manifest_with_parts(parts: Vec<ManifestPart>) -> RunManifest {
405        let row_count = parts
406            .iter()
407            .filter(|p| p.status == PartStatus::Committed)
408            .map(|p| p.rows)
409            .sum();
410        let part_count = parts
411            .iter()
412            .filter(|p| p.status == PartStatus::Committed)
413            .count() as u32;
414        RunManifest {
415            mode: "batch".to_string(),
416            manifest_version: MANIFEST_VERSION,
417            run_id: "orders_20260521T120000.000".into(),
418            export_name: "public.orders".into(),
419            started_at: "2026-05-21T12:00:00Z".into(),
420            finished_at: "2026-05-21T12:14:33Z".into(),
421            status: ManifestStatus::Success,
422            source: ManifestSource {
423                engine: "postgres".into(),
424                schema: Some("public".into()),
425                table: Some("orders".into()),
426                extraction: None,
427            },
428            destination: ManifestDestination {
429                kind: "gcs".into(),
430                uri: "gs://rivet-exports/public.orders/run/".into(),
431            },
432            format: "parquet".into(),
433            compression: "zstd".into(),
434            schema_fingerprint: "xxh3:0123456789abcdef".into(),
435            row_count,
436            part_count,
437            parts,
438            column_checksums: None,
439            checksum_key_column: None,
440        }
441    }
442
443    // ── constants ───────────────────────────────────────────────────────────
444
445    #[test]
446    fn manifest_version_is_one() {
447        assert_eq!(MANIFEST_VERSION, 1);
448    }
449
450    #[test]
451    fn filenames_are_stable() {
452        assert_eq!(MANIFEST_FILENAME, "manifest.json");
453        assert_eq!(SUCCESS_FILENAME, "_SUCCESS");
454        assert_eq!(QUARANTINE_PREFIX, "_quarantine");
455    }
456
457    #[test]
458    fn run_unique_manifest_name_sanitizes_and_is_recognised() {
459        // A real CLI run id is RFC3339 — `:` and `+` are not filename-safe (`:`
460        // is illegal on Windows), so they map to `-`.
461        let n = run_unique_manifest_name("orders_2026-07-13T12:00:00+00:00");
462        assert_eq!(n, "manifest-orders_2026-07-13T12-00-00-00-00.json");
463        assert!(is_run_unique_manifest_name(&n));
464        // The canonical pointer is NOT a per-run copy (its stem is `manifest.`,
465        // not `manifest-`), so validate/reconcile still treat it distinctly.
466        assert!(!is_run_unique_manifest_name(MANIFEST_FILENAME));
467    }
468
469    // ── self-consistency ────────────────────────────────────────────────────
470
471    #[test]
472    fn self_consistent_manifest_validates() {
473        let m = manifest_with_parts(vec![part(1, 100, 4096), part(2, 200, 8192)]);
474        assert_eq!(m.validate_self_consistency(), Ok(()));
475    }
476
477    #[test]
478    fn rejects_part_count_mismatch() {
479        let mut m = manifest_with_parts(vec![part(1, 100, 4096)]);
480        m.part_count = 5;
481        assert!(matches!(
482            m.validate_self_consistency(),
483            Err(ManifestInconsistency::PartCountMismatch {
484                declared: 5,
485                actual: 1
486            })
487        ));
488    }
489
490    #[test]
491    fn rejects_row_count_mismatch() {
492        let mut m = manifest_with_parts(vec![part(1, 100, 4096)]);
493        m.row_count = 999;
494        assert!(matches!(
495            m.validate_self_consistency(),
496            Err(ManifestInconsistency::RowCountMismatch {
497                declared: 999,
498                actual: 100
499            })
500        ));
501    }
502
503    #[test]
504    fn rejects_duplicate_part_id() {
505        let m = manifest_with_parts(vec![part(1, 100, 4096), part(1, 200, 8192)]);
506        let err = m.validate_self_consistency().unwrap_err();
507        assert_eq!(err, ManifestInconsistency::DuplicatePartId(1));
508    }
509
510    #[test]
511    fn rejects_unsupported_version() {
512        let mut m = manifest_with_parts(vec![]);
513        m.manifest_version = 999;
514        m.part_count = 0;
515        m.row_count = 0;
516        assert!(matches!(
517            m.validate_self_consistency(),
518            Err(ManifestInconsistency::UnsupportedVersion {
519                found: 999,
520                supported: 1
521            })
522        ));
523    }
524
525    // ── quarantined parts ──────────────────────────────────────────────────
526
527    #[test]
528    fn quarantined_parts_do_not_count_toward_row_or_part_totals() {
529        let mut p_q = part(2, 999, 8192);
530        p_q.status = PartStatus::Quarantined;
531        let m = manifest_with_parts(vec![part(1, 100, 4096), p_q]);
532
533        // The factory only counts committed; manifest must validate.
534        assert_eq!(m.validate_self_consistency(), Ok(()));
535        assert_eq!(m.committed_rows(), 100);
536        assert_eq!(m.committed_part_count(), 1);
537    }
538
539    // ── serde roundtrip ────────────────────────────────────────────────────
540
541    #[test]
542    fn json_roundtrip_preserves_fields() {
543        let m = manifest_with_parts(vec![part(1, 100, 4096), part(2, 200, 8192)]);
544        let json = serde_json::to_string_pretty(&m).unwrap();
545        let parsed: RunManifest = serde_json::from_str(&json).unwrap();
546        assert_eq!(m, parsed);
547    }
548
549    #[test]
550    fn status_serializes_as_snake_case() {
551        let m = manifest_with_parts(vec![]);
552        // Force part_count=0 so the empty-parts manifest still validates self-consistency,
553        // then check the wire form.  (This test cares about the enum encoding, not totals.)
554        let mut m = m;
555        m.part_count = 0;
556        m.row_count = 0;
557        let json = serde_json::to_string(&m).unwrap();
558        assert!(json.contains("\"status\":\"success\""));
559
560        m.status = ManifestStatus::Interrupted;
561        let json = serde_json::to_string(&m).unwrap();
562        assert!(json.contains("\"status\":\"interrupted\""));
563    }
564
565    // ── success marker ─────────────────────────────────────────────────────
566
567    #[test]
568    fn success_marker_body_is_xxh3_prefix_plus_16_hex_plus_newline() {
569        let body = success_marker_body(b"some manifest bytes");
570        assert!(body.starts_with("xxh3:"), "body = {body:?}");
571        assert!(body.ends_with('\n'), "body = {body:?}");
572        let trimmed = body.trim_end();
573        let hex = &trimmed["xxh3:".len()..];
574        assert_eq!(hex.len(), 16, "body = {body:?}");
575        assert!(
576            hex.chars()
577                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
578        );
579    }
580
581    #[test]
582    fn success_marker_body_is_deterministic_for_same_input() {
583        let a = success_marker_body(b"hello");
584        let b = success_marker_body(b"hello");
585        assert_eq!(a, b);
586    }
587
588    #[test]
589    fn success_marker_body_differs_for_different_manifest_bytes() {
590        let a = success_marker_body(b"manifest one");
591        let b = success_marker_body(b"manifest two");
592        assert_ne!(a, b);
593    }
594
595    #[test]
596    fn parse_success_marker_roundtrips_with_writer() {
597        let body = success_marker_body(b"some manifest bytes");
598        let fp = parse_success_marker(&body).expect("must parse");
599        assert!(fp.starts_with("xxh3:"));
600        assert_eq!(fp.len(), "xxh3:".len() + 16);
601    }
602
603    #[test]
604    fn parse_success_marker_rejects_malformed_bodies() {
605        assert_eq!(parse_success_marker(""), None);
606        assert_eq!(parse_success_marker("\n"), None);
607        assert_eq!(parse_success_marker("sha256:0123456789abcdef"), None);
608        // Wrong hex length:
609        assert_eq!(parse_success_marker("xxh3:0123\n"), None);
610        // Uppercase hex (we emit lowercase; reject to keep the format strict):
611        assert_eq!(parse_success_marker("xxh3:0123456789ABCDEF\n"), None);
612        // Non-hex body:
613        assert_eq!(parse_success_marker("xxh3:zzzzzzzzzzzzzzzz\n"), None);
614        // Missing prefix:
615        assert_eq!(parse_success_marker("0123456789abcdef\n"), None);
616        // A crafted 21-byte (== the valid length) body with a MULTIBYTE codepoint
617        // straddling byte 5: passes the byte-length gate, and the old `split_at(5)`
618        // panicked on the non-char-boundary → a DoS of the trust oracle under
619        // panic=abort (a destination-writable planted `_SUCCESS`). Must be `None`,
620        // never a panic. ("aaa" + U+0800 [bytes 3..6] + 15×'a' = 21 bytes.)
621        assert_eq!(parse_success_marker("aaa\u{0800}aaaaaaaaaaaaaaa"), None);
622    }
623
624    #[test]
625    fn parse_success_marker_tolerates_trailing_whitespace() {
626        let body = "xxh3:0123456789abcdef\n";
627        assert_eq!(parse_success_marker(body), Some("xxh3:0123456789abcdef"));
628        // CRLF on Windows, double newline, trailing spaces — all fine.
629        let body = "xxh3:0123456789abcdef\r\n";
630        assert_eq!(parse_success_marker(body), Some("xxh3:0123456789abcdef"));
631    }
632
633    #[test]
634    fn unknown_fields_are_ignored_by_reader() {
635        // ADR-0012 forward-compatibility contract: a reader compiled against
636        // v1 must tolerate v2-style fields that it doesn't recognise.
637        let json = r#"{
638            "manifest_version": 1,
639            "run_id": "r1",
640            "export_name": "t",
641            "started_at": "2026-01-01T00:00:00Z",
642            "finished_at": "2026-01-01T00:01:00Z",
643            "status": "success",
644            "source": {"engine": "postgres"},
645            "destination": {"kind": "local", "uri": "file:///tmp/out/"},
646            "format": "parquet",
647            "compression": "zstd",
648            "schema_fingerprint": "xxh3:0000000000000000",
649            "row_count": 0,
650            "part_count": 0,
651            "parts": [],
652            "future_field_added_in_v2": {"nested": true}
653        }"#;
654        let parsed: RunManifest = serde_json::from_str(json).unwrap();
655        assert_eq!(parsed.run_id, "r1");
656        assert_eq!(parsed.validate_self_consistency(), Ok(()));
657    }
658}
659
660fn default_manifest_mode() -> String {
661    "batch".to_string()
662}
663
664/// Finding #44 guard: refuse to overwrite a manifest written by the OTHER
665/// pipeline shape. Same-shape overwrites stay allowed (a batch full re-run
666/// replaces its own manifest by design; CDC extends its own). A missing or
667/// unreadable manifest is not this guard's business — corruption surfaces in
668/// `rivet validate`, and first runs must not require a read round-trip.
669pub fn guard_manifest_mode(
670    dest: &dyn crate::destination::Destination,
671    new_mode: &str,
672) -> anyhow::Result<()> {
673    let Ok(bytes) = dest.read("manifest.json") else {
674        return Ok(());
675    };
676    let Ok(existing) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
677        return Ok(());
678    };
679    // A manifest WITHOUT the field predates 0.16.6 — every live CDC
680    // deployment's prefix looks like that after an upgrade, and refusing it
681    // would brick their own resume. Absent mode ⇒ unknown ⇒ allow; only an
682    // EXPLICIT cross-shape mismatch refuses.
683    let Some(existing_mode) = existing.get("mode").and_then(|m| m.as_str()) else {
684        return Ok(());
685    };
686    if existing_mode != new_mode {
687        anyhow::bail!(
688            "destination already holds a '{existing_mode}' manifest (run_id {run}); refusing to \
689             overwrite it with a '{new_mode}' manifest — a batch export and a CDC export sharing \
690             one prefix silently destroy each other's audit trail. Give this export its own \
691             prefix (the scaffold now uses exports/<table>/cdc/ for CDC).",
692            run = existing
693                .get("run_id")
694                .and_then(|r| r.as_str())
695                .unwrap_or("unknown"),
696        );
697    }
698    Ok(())
699}
700
701#[cfg(test)]
702mod mode_guard_tests {
703    use super::*;
704
705    #[test]
706    fn pre_extraction_manifests_parse_with_none() {
707        // Manifests written before the extraction section (the real v0.16
708        // fixture) must parse — the field is opt-in.
709        let old = std::fs::read_to_string(
710            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
711                .join("tests/fixtures/compat/v0.16/cdc_manifest.json"),
712        )
713        .expect("compat fixture");
714        let m: RunManifest = serde_json::from_str(&old).expect("parses");
715        assert!(m.source.extraction.is_none());
716    }
717
718    #[test]
719    fn extraction_roundtrips_and_omits_none_fields() {
720        let ex = ExtractionMetadata {
721            strategy: "incremental".into(),
722            cursor_column: Some("id".into()),
723            cursor_type: None,
724            cursor_low: Some("1000".into()),
725            cursor_high: Some("2000".into()),
726            source_row_count: None,
727        };
728        let j = serde_json::to_string(&ex).unwrap();
729        // skip_serializing_if omits the None fields entirely.
730        assert!(!j.contains("cursor_type"), "None fields omitted: {j}");
731        assert!(!j.contains("source_row_count"), "{j}");
732        assert!(j.contains("\"cursor_low\":\"1000\""), "{j}");
733        let back: ExtractionMetadata = serde_json::from_str(&j).unwrap();
734        assert_eq!(back, ex);
735    }
736
737    #[test]
738    fn pre_mode_manifests_default_to_batch() {
739        // The REAL committed v0.16 manifest (compat fixture) predates the
740        // `mode` field — it must parse and read as batch.
741        let old = std::fs::read_to_string(
742            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
743                .join("tests/fixtures/compat/v0.16/cdc_manifest.json"),
744        )
745        .expect("compat fixture");
746        let m: RunManifest = serde_json::from_str(&old).expect("old manifests parse");
747        assert_eq!(m.mode, "batch");
748    }
749
750    #[test]
751    fn cross_shape_overwrite_is_refused_same_shape_allowed() {
752        let d = tempfile::tempdir().unwrap();
753        let dest = crate::destination::create_destination(&crate::config::DestinationConfig {
754            destination_type: crate::config::DestinationType::Local,
755            path: Some(d.path().to_str().unwrap().to_string()),
756            ..Default::default()
757        })
758        .unwrap();
759        // empty prefix: any mode fine
760        guard_manifest_mode(dest.as_ref(), "batch").unwrap();
761        std::fs::write(
762            d.path().join("manifest.json"),
763            r#"{"mode":"batch","run_id":"r1"}"#,
764        )
765        .unwrap();
766        guard_manifest_mode(dest.as_ref(), "batch").expect("same shape re-run allowed");
767        let err = guard_manifest_mode(dest.as_ref(), "cdc")
768            .unwrap_err()
769            .to_string();
770        assert!(err.contains("refusing to"), "loud refusal: {err}");
771        assert!(
772            err.contains("exports/<table>/cdc/"),
773            "carries the recovery: {err}"
774        );
775        // A pre-0.16.6 manifest (no mode field) must be ALLOWED — every live
776        // CDC deployment's prefix looks like that right after an upgrade, and
777        // refusing would brick their own resume. Unknown ⇒ pass.
778        std::fs::write(d.path().join("manifest.json"), r#"{"run_id":"legacy"}"#).unwrap();
779        guard_manifest_mode(dest.as_ref(), "cdc").expect("legacy prefixes must keep resuming");
780        guard_manifest_mode(dest.as_ref(), "batch").expect("in either direction");
781    }
782}