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