Skip to main content

rivet/pipeline/
mod.rs

1//! **Layer: Coordinator** (planning → execution → persistence/observability)
2//!
3//! `pipeline/mod.rs` is the only module allowed to bridge all three layers.
4//! It reads a resolved plan (planning), dispatches to execution modules, then
5//! records metrics and sends notifications (persistence/observability).
6//!
7//! See `docs/adr/0003-layer-classification.md` for the full module taxonomy.
8
9mod aggregate;
10mod apply_cmd;
11mod cdc_job;
12pub(crate) mod chunked;
13mod cli;
14pub(crate) mod commit;
15mod finalize;
16pub(crate) mod ipc;
17mod job;
18mod keyset;
19mod manifest_reconcile;
20pub(crate) mod manifest_writer;
21mod parallel_children;
22pub(crate) mod parent_ui;
23mod partition_expand;
24mod plan_cmd;
25pub(crate) mod progress;
26mod reconcile_cmd;
27mod repair_cmd;
28pub(crate) mod report;
29mod resume_decisions;
30// `pub(crate)` so `error::classify_exit` can reach `retry::classify_error`
31// (transient → exit-code 2) without routing through the test-only re-export.
32pub(crate) mod retry;
33// The `rivet run` orchestrator (~290 LOC) lives next door so this facade
34// stays a thin re-export layer.  Module name shadows `pub fn run` below;
35// the duplicate is resolved by Rust's namespace rules (modules live in
36// the type namespace, fns in the value namespace) and unambiguous at
37// every call site (`pipeline::run(...)` is the function).
38mod run;
39mod run_store;
40mod schema_drift;
41mod single;
42mod sink;
43mod summary;
44mod validate;
45mod validate_cmd;
46mod validate_manifest;
47
48// ── Public API surface (consumed by `src/cli/dispatch.rs` + binaries) ──────
49//
50// These items are the contract the binary depends on.  Adding to this list
51// is an API change that requires a release-note entry; removing or
52// renaming requires a deprecation cycle.
53
54pub use apply_cmd::run_apply_command;
55pub use cli::{
56    reset_chunk_checkpoint, reset_chunk_checkpoints_stuck, reset_state, show_chunk_checkpoint,
57    show_files, show_journal, show_metrics, show_progression, show_state,
58};
59pub use plan_cmd::{PlanOutputFormat, run_plan_command};
60pub use reconcile_cmd::{ReconcileOutputFormat, run_reconcile_command};
61pub use repair_cmd::{RepairOutputFormat, RepairReportSource, run_repair_command};
62pub use validate_cmd::{ValidateOutputFormat, ValidateTarget, run_validate_command};
63
64// `RunSummary` is consumed by `notify::*` (via the Coordinator path) plus
65// integration-test fixtures.  It is the canonical observability struct so
66// it stays in the regular public surface.
67pub use summary::RunSummary;
68
69// ── Crate-internal cross-module use ────────────────────────────────────────
70
71pub(crate) use job::run_export_job_with_chunk_source;
72#[cfg(test)]
73#[allow(unused_imports)]
74pub(crate) use retry::is_transient;
75
76// ── Test-only surface ──────────────────────────────────────────────────────
77//
78// The integration tests in `tests/*.rs` exercise the trust-contract writers,
79// readers, and decision logic without spinning up a full pipeline.  These
80// items are NOT part of the public CLI contract — operators get them only
81// transitively (via `summary.json`, `manifest.json`, `--validate`, etc.).
82//
83// Hidden behind `#[doc(hidden)] pub mod for_tests` so they don't pollute
84// the rendered crate docs and so a renaming refactor here is a clear
85// "test-only" change rather than appearing as a public API break.
86//
87// Convention matches the existing `destination_for_tests` window in
88// `lib.rs`: tests reach these via `rivet::pipeline::for_tests::*`.
89
90#[doc(hidden)]
91pub mod for_tests {
92    pub use super::chunked::generate_chunks;
93    pub use super::manifest_writer::{ManifestBuilder, WriteOutcome, write_manifest};
94    pub use super::report::{RunReport, report_dir, write_run_report};
95    pub use super::resume_decisions::{
96        PartDecision, QuarantineReason, ResumeDecision, ResumePlan, UntrackedDecision,
97        build_resume_plan,
98    };
99    pub use super::retry::{RetryClass, classify_error};
100    pub use super::validate::validate_output;
101    pub use super::validate_manifest::{
102        Failure as ManifestVerificationFailure, ManifestVerification, verify_at_destination,
103    };
104    pub use crate::plan::build_time_window_query;
105}
106
107// Backwards-compat re-exports at the crate root so existing test files
108// keep compiling without a sweeping import-site update.  Each is delegated
109// to `for_tests::*`; new test code should import from `for_tests` directly.
110//
111// `#[allow(unused_imports)]` because the bin target's dead-code analysis
112// doesn't see the integration tests that consume these — same situation
113// as `RunSummary::stub_for_testing`.
114#[doc(hidden)]
115#[allow(unused_imports)]
116pub use for_tests::{
117    ManifestBuilder, ManifestVerification, ManifestVerificationFailure, PartDecision,
118    QuarantineReason, ResumeDecision, ResumePlan, RetryClass, RunReport, UntrackedDecision,
119    WriteOutcome, build_resume_plan, build_time_window_query, classify_error, generate_chunks,
120    report_dir, validate_output, verify_at_destination, write_manifest, write_run_report,
121};
122
123// The orchestrator and its `RunOptions` live in `run.rs`.  Re-exported
124// here so external call sites keep using `pipeline::run(...)` and
125// `pipeline::RunOptions`.  Multi-export render-mode flags ride along
126// because `RunSummary::print` and the in-place card renderer read them.
127pub use run::{RunOptions, run};
128#[allow(unused_imports)] // `multi_export_concurrent` is wired for future use
129pub(crate) use run::{multi_export_concurrent, multi_export_mode};
130
131pub(crate) fn format_bytes(b: u64) -> String {
132    if b >= 1_073_741_824 {
133        format!("{:.1} GB", b as f64 / 1_073_741_824.0)
134    } else if b >= 1_048_576 {
135        format!("{:.1} MB", b as f64 / 1_048_576.0)
136    } else if b >= 1024 {
137        format!("{:.1} KB", b as f64 / 1024.0)
138    } else {
139        format!("{} B", b)
140    }
141}
142
143/// Strip the trailing recovery-hint portion of a chunked-pipeline error
144/// message produced by `pipeline::chunked`.  Returns the cause prefix and
145/// whether a chunked-checkpoint hint was detected.
146///
147/// Hints emitted by `pipeline::chunked` always follow the pattern
148/// `<cause>; <connector> \`rivet …\` …`, so we cut at the first `; ` whose
149/// remainder contains a backtick-quoted `rivet` invocation.
150///
151/// Used by both the per-export card renderer (`parent_ui`) and the run
152/// aggregator (`aggregate`) so the long inline command doesn't wrap, distort
153/// the in-place card layout, and doesn't repeat the consolidated recovery
154/// block printed by the aggregator.
155pub(crate) fn strip_chunked_recovery_hint(msg: &str) -> (&str, bool) {
156    let mut pos = 0;
157    while let Some(off) = msg[pos..].find("; ") {
158        let abs = pos + off;
159        let tail = &msg[abs + 2..];
160        if tail.contains("`rivet ") {
161            return (&msg[..abs], true);
162        }
163        pos = abs + 2;
164    }
165    (msg, false)
166}
167
168/// Truncate `s` to at most `max_chars` Unicode characters, appending `…`
169/// when truncated.  Returns `s` unchanged if already short enough.  Used by
170/// the in-place card renderer to keep every line within the chosen
171/// terminal width — line wrapping breaks the cursor-up redraw math and
172/// causes cards to drift down the screen.
173pub(crate) fn clamp_line(s: &str, max_chars: usize) -> String {
174    if max_chars == 0 {
175        return String::new();
176    }
177    if s.chars().count() <= max_chars {
178        return s.to_string();
179    }
180    let keep = max_chars.saturating_sub(1);
181    let mut out: String = s.chars().take(keep).collect();
182    out.push('…');
183    out
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189    use crate::config::{SourceConfig, SourceType};
190    use crate::plan::{
191        CompressionType, DestinationConfig, DestinationType, DiagnosticLevel, ExtractionStrategy,
192        FormatType, MetaColumns, ResolvedRunPlan, validate_plan,
193    };
194    use crate::tuning::SourceTuning;
195
196    #[test]
197    fn test_format_bytes() {
198        assert_eq!(format_bytes(500), "500 B");
199        assert_eq!(format_bytes(1024), "1.0 KB");
200        assert_eq!(format_bytes(1536), "1.5 KB");
201        assert_eq!(format_bytes(1_048_576), "1.0 MB");
202        assert_eq!(format_bytes(1_073_741_824), "1.0 GB");
203        assert_eq!(format_bytes(2_684_354_560), "2.5 GB");
204    }
205
206    #[test]
207    fn strip_chunked_recovery_hint_strips_use_form() {
208        let m = "export 'users': chunk checkpoint run 'users_x' still in progress; \
209                 use `rivet run --config foo.yaml --export users --resume` or \
210                 `rivet state reset-chunks --config foo.yaml --export users`";
211        let (cause, hinted) = strip_chunked_recovery_hint(m);
212        assert!(hinted);
213        assert_eq!(
214            cause,
215            "export 'users': chunk checkpoint run 'users_x' still in progress"
216        );
217    }
218
219    #[test]
220    fn strip_chunked_recovery_hint_strips_fix_errors_form() {
221        let m = "export 'a': chunk checkpoint incomplete (3 tasks not completed); \
222                 fix errors and `rivet run --config c.yaml --export a --resume` or \
223                 `rivet state reset-chunks --config c.yaml --export a`";
224        let (cause, hinted) = strip_chunked_recovery_hint(m);
225        assert!(hinted);
226        assert_eq!(
227            cause,
228            "export 'a': chunk checkpoint incomplete (3 tasks not completed)"
229        );
230    }
231
232    #[test]
233    fn strip_chunked_recovery_hint_passthrough_when_no_hint() {
234        let m = "export 'q': source connection refused; retry exhausted";
235        let (cause, hinted) = strip_chunked_recovery_hint(m);
236        assert!(!hinted);
237        assert_eq!(cause, m);
238    }
239
240    #[test]
241    fn clamp_line_truncates_with_ellipsis() {
242        assert_eq!(clamp_line("short", 80), "short");
243        assert_eq!(clamp_line("hello world", 8), "hello w…");
244        let s = "αβγδ".repeat(50);
245        let out = clamp_line(&s, 10);
246        assert_eq!(out.chars().count(), 10);
247        assert!(out.ends_with('…'));
248    }
249
250    #[test]
251    fn format_bytes_boundary_values() {
252        assert_eq!(format_bytes(0), "0 B");
253        assert_eq!(format_bytes(1), "1 B");
254        assert_eq!(format_bytes(1023), "1023 B");
255        assert_eq!(format_bytes(1024), "1.0 KB");
256        assert_eq!(format_bytes(1025), "1.0 KB");
257        assert_eq!(format_bytes(1_048_575), "1024.0 KB");
258        assert_eq!(format_bytes(1_048_576), "1.0 MB");
259        assert_eq!(format_bytes(1_073_741_823), "1024.0 MB");
260        assert_eq!(format_bytes(1_073_741_824), "1.0 GB");
261    }
262
263    fn minimal_plan() -> ResolvedRunPlan {
264        ResolvedRunPlan {
265            export_name: "test_export".into(),
266            base_query: "SELECT 1".into(),
267            strategy: ExtractionStrategy::Snapshot,
268            format: FormatType::Parquet,
269            compression: CompressionType::default(),
270            compression_level: None,
271            max_file_size_bytes: None,
272            skip_empty: false,
273            meta_columns: MetaColumns::default(),
274            destination: DestinationConfig {
275                destination_type: DestinationType::Local,
276                path: Some("./out".into()),
277                ..Default::default()
278            },
279            quality: None,
280            tuning: SourceTuning::from_config(None),
281            tuning_profile_label: "balanced (default)".into(),
282            validate: false,
283            reconcile: false,
284            resume: false,
285            source: SourceConfig {
286                source_type: SourceType::Postgres,
287                url: Some("postgresql://localhost/test".into()),
288                url_env: None,
289                url_file: None,
290                host: None,
291                port: None,
292                user: None,
293                password: None,
294                password_env: None,
295                database: None,
296                environment: None,
297                tuning: None,
298                tls: None,
299            },
300            column_overrides: Default::default(),
301            verify: crate::config::VerifyMode::Size,
302            schema_drift_policy: Default::default(),
303            shape_drift_warn_factor: 2.0,
304            parquet: None,
305        }
306    }
307
308    #[test]
309    fn test_run_summary_fields() {
310        let plan = minimal_plan();
311        let summary = RunSummary::new(&plan);
312        assert_eq!(summary.export_name, "test_export");
313        assert_eq!(summary.status, "running");
314        assert_eq!(summary.total_rows, 0);
315        assert_eq!(summary.files_produced, 0);
316        assert_eq!(summary.tuning_profile, "balanced (default)");
317        assert_eq!(summary.batch_size, 10_000);
318        assert_eq!(summary.format, "parquet");
319        assert_eq!(summary.mode, "full");
320        assert!(
321            summary.run_id.starts_with("test_export_"),
322            "run_id should start with export name, got: {}",
323            summary.run_id
324        );
325    }
326
327    // ─── RunSummary::new() journal invariants ────────────────────────────────
328
329    /// `RunSummary::new()` must immediately record a `PlanResolved` event as the
330    /// first journal entry.  This satisfies the "what was planned?" query from ADR-0001.
331    #[test]
332    fn run_summary_new_records_plan_resolved_as_first_event() {
333        let plan = minimal_plan();
334        let summary = RunSummary::new(&plan);
335
336        assert!(
337            !summary.journal.entries.is_empty(),
338            "journal must have at least one entry after RunSummary::new()"
339        );
340        assert!(
341            matches!(
342                summary.journal.entries[0].event,
343                crate::journal::RunEvent::PlanResolved(_)
344            ),
345            "first journal event must be PlanResolved, got: {:?}",
346            summary.journal.entries[0].event
347        );
348    }
349
350    /// The `PlanSnapshot` recorded inside `PlanResolved` must faithfully capture
351    /// key fields from the `ResolvedRunPlan`.
352    #[test]
353    fn run_summary_plan_snapshot_matches_plan_fields() {
354        let plan = minimal_plan();
355        let summary = RunSummary::new(&plan);
356
357        let snap = summary
358            .journal
359            .plan_snapshot()
360            .expect("plan_snapshot() must be Some after RunSummary::new()");
361
362        assert_eq!(snap.export_name, plan.export_name);
363        assert_eq!(snap.validate, plan.validate);
364        assert_eq!(snap.reconcile, plan.reconcile);
365        assert_eq!(snap.resume, plan.resume);
366        assert_eq!(snap.batch_size, plan.tuning.batch_size);
367    }
368
369    /// The journal's `run_id` must match the `RunSummary`'s `run_id`.
370    #[test]
371    fn run_summary_journal_run_id_matches_summary_run_id() {
372        let plan = minimal_plan();
373        let summary = RunSummary::new(&plan);
374        assert_eq!(
375            summary.journal.run_id, summary.run_id,
376            "journal run_id must match summary run_id"
377        );
378    }
379
380    // ─── Rejected plan gate ──────────────────────────────────────────────────
381
382    /// Gap 7 — `run_export_job` bails before execution when `validate_plan` returns
383    /// a `Rejected` diagnostic.  The wiring is in `run_export_job` (this file,
384    /// ~line 210): if `rejected` is non-empty, the function returns `anyhow::bail!`.
385    ///
386    /// This test verifies the *condition* that triggers the bail: that `validate_plan`
387    /// does in fact produce a `Rejected` diagnostic for the stdout+split combination.
388    /// The gate itself (`run_export_job`) cannot be called directly in tests because
389    /// it requires a live database connection and config; we test its precondition here.
390    #[test]
391    fn rejected_plan_produces_rejected_diagnostic_blocking_run_export_job() {
392        let mut plan = minimal_plan();
393        // stdout + max_file_size triggers check_stdout_split → Rejected.
394        plan.destination.destination_type = DestinationType::Stdout;
395        plan.max_file_size_bytes = Some(10 * 1024 * 1024);
396
397        let diags = validate_plan(&plan);
398        let rejected_count = diags
399            .iter()
400            .filter(|d| d.level == DiagnosticLevel::Rejected)
401            .count();
402
403        assert!(
404            rejected_count > 0,
405            "stdout + max_file_size must produce a Rejected diagnostic so that \
406             run_export_job bails before calling run_with_reconnect; got: {:?}",
407            diags
408                .iter()
409                .map(|d| (&d.rule, &d.level))
410                .collect::<Vec<_>>()
411        );
412    }
413
414    /// stdout + chunked strategy also triggers a Rejected diagnostic (check_stdout_chunked).
415    #[test]
416    fn rejected_plan_stdout_chunked_blocks_run_export_job() {
417        use crate::plan::ChunkedPlan;
418        let mut plan = minimal_plan();
419        plan.destination.destination_type = DestinationType::Stdout;
420        plan.strategy = ExtractionStrategy::Chunked(ChunkedPlan {
421            column: "id".into(),
422            chunk_size: 1000,
423            chunk_count: None,
424            parallel: 1,
425            dense: false,
426            by_days: None,
427            max_attempts: 3,
428            checkpoint: false,
429        });
430
431        let diags = validate_plan(&plan);
432        assert!(
433            diags.iter().any(|d| d.level == DiagnosticLevel::Rejected),
434            "stdout + chunked must produce a Rejected diagnostic"
435        );
436    }
437
438    // ─── synthetic_failed_summary ────────────────────────────────────────────
439
440    /// Pre-`RunSummary::new` failures (plan-build error, plan-validation
441    /// rejection) still need to be aggregated.  `synthetic_failed_summary`
442    /// produces a minimally-populated summary that aggregation can consume
443    /// without panicking.
444    #[test]
445    fn synthetic_failed_summary_carries_error_and_status() {
446        let err = anyhow::anyhow!("could not connect to source: timeout");
447        let s = job::synthetic_failed_summary("orders", &err);
448        assert_eq!(s.export_name, "orders");
449        assert_eq!(s.status, "failed");
450        assert_eq!(
451            s.error_message.as_deref(),
452            Some("could not connect to source: timeout")
453        );
454        assert!(
455            s.run_id.starts_with("orders_"),
456            "run_id must be derived from export name, got {}",
457            s.run_id
458        );
459        // Aggregation reads these fields directly — they must default to zero.
460        assert_eq!(s.total_rows, 0);
461        assert_eq!(s.files_produced, 0);
462        assert_eq!(s.bytes_written, 0);
463        assert_eq!(s.duration_ms, 0);
464    }
465
466    /// `entry_from_summary` must faithfully copy fields the aggregate cares
467    /// about.  This guards against silent drift if `RunAggregateEntry` or
468    /// `RunSummary` gain new fields.
469    #[test]
470    fn aggregate_entry_from_summary_copies_observable_fields() {
471        let plan = minimal_plan();
472        let mut summary = RunSummary::new(&plan);
473        summary.status = "success".into();
474        summary.total_rows = 12_345;
475        summary.files_produced = 3;
476        summary.bytes_written = 9_876_543;
477        summary.duration_ms = 5_000;
478
479        let entry = aggregate::entry_from_summary(&summary);
480        assert_eq!(entry.export_name, summary.export_name);
481        assert_eq!(entry.status, "success");
482        assert_eq!(entry.run_id, summary.run_id);
483        assert_eq!(entry.rows, 12_345);
484        assert_eq!(entry.files, 3);
485        assert_eq!(entry.bytes, 9_876_543);
486        assert_eq!(entry.duration_ms, 5_000);
487        assert_eq!(entry.mode, summary.mode);
488        assert_eq!(entry.error_message, None);
489    }
490}