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