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