Skip to main content

rivet/pipeline/
run.rs

1//! **Layer: Coordinator entrypoint** — the `rivet run` orchestrator.
2//!
3//! Single bridge between planning, execution, and persistence/observability.
4//! Owns the multi-export render-mode flags, decides between sequential vs
5//! thread-parallel vs process-parallel, and produces the run aggregate at
6//! the end.
7//!
8//! Lives in its own file so [`crate::pipeline`] (which is read as a facade
9//! by every other module) stays a thin re-export layer rather than a
10//! ~300-LOC orchestrator wrapped in mod-level declarations.
11
12use std::path::Path;
13use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
14
15use crate::config::{Config, ExportConfig};
16use crate::error::Result;
17use crate::state::StateStore;
18
19use super::summary::RunSummary;
20use super::{aggregate, ipc, job, parallel_children, parent_ui};
21
22/// Per-run configuration flags passed from the CLI to the pipeline.
23///
24/// Replaces the previous pattern of threading 4+ positional `bool` arguments
25/// through `run`, `run_export_job`, and child-process invocations.  Named fields
26/// prevent silent argument transposition (e.g., `validate` and `reconcile`
27/// swapped).
28#[derive(Debug, Clone, Copy)]
29pub struct RunOptions<'a> {
30    pub validate: bool,
31    pub reconcile: bool,
32    pub resume: bool,
33    /// Override safety gates that would otherwise refuse to start the run.
34    ///
35    /// Currently used by ADR-0012 M8 — `--resume` against a prefix whose
36    /// `_SUCCESS` marker is present is refused unless `--force` is given,
37    /// so an operator cannot accidentally re-export over a verified
38    /// dataset.  Other gates may share the same flag in the future
39    /// (per ADR-0013: one `--force`, scoped to whichever gate it overrides).
40    pub force: bool,
41    pub params: Option<&'a std::collections::HashMap<String, String>>,
42}
43
44/// True when the current process is running more than one export in this
45/// `rivet run` invocation (sequential or `--parallel-exports`).  Per-export
46/// renderers (`RunSummary::print`, `ChunkProgress`) read this to switch to
47/// the compact one-line format and to suppress the indicatif chunk bar
48/// respectively, so 15 exports take 15 lines instead of 100+ and threads
49/// don't stack progress bars on top of each other.
50///
51/// Children of `--parallel-export-processes` always have `exports.len() == 1`
52/// in their own process so this flag stays `false` for them; the parent
53/// renders cards itself via `parent_ui`.
54pub(crate) static MULTI_EXPORT_MODE: AtomicBool = AtomicBool::new(false);
55
56/// True only when multiple exports run **concurrently** in the current
57/// process (i.e. `--parallel-exports`, threads).  Used to suppress
58/// per-export `indicatif` chunk progress bars whose terminal writes
59/// otherwise interleave across threads and corrupt each other.
60pub(crate) static MULTI_EXPORT_CONCURRENT: AtomicBool = AtomicBool::new(false);
61
62pub(crate) fn multi_export_mode() -> bool {
63    MULTI_EXPORT_MODE.load(AtomicOrdering::Relaxed)
64}
65
66#[allow(dead_code)] // kept for future renderers; flag is still set in `run` below.
67pub(crate) fn multi_export_concurrent() -> bool {
68    MULTI_EXPORT_CONCURRENT.load(AtomicOrdering::Relaxed)
69}
70
71fn print_json_summary(agg: &crate::state::RunAggregate) {
72    match serde_json::to_string_pretty(agg) {
73        Ok(json) => println!("{json}"),
74        Err(e) => eprintln!(
75            "rivet: error: failed to serialize run summary as JSON: {:#}",
76            e
77        ),
78    }
79}
80
81#[allow(clippy::too_many_arguments)] // CLI fan-in; surface stays stable per ADR-0013
82pub fn run(
83    config_path: &str,
84    export_name: Option<&str>,
85    validate: bool,
86    reconcile: bool,
87    resume: bool,
88    force: bool,
89    params: Option<&std::collections::HashMap<String, String>>,
90    parallel_exports_cli: bool,
91    parallel_export_processes_cli: bool,
92    summary_output: Option<&Path>,
93    json_output: bool,
94) -> Result<()> {
95    // F-NEW-B (0.7.5 audit): `--force` is scoped to whichever gate it
96    // overrides (today: the `_SUCCESS`-already-present refusal on
97    // resume).  When the operator passes `--force` without `--resume`,
98    // the flag is a no-op — surface that explicitly so a typo or
99    // copy-paste mistake does not pass silently.
100    if force && !resume {
101        log::warn!(
102            "--force without --resume is a no-op today (force only overrides the resume safety \
103             gate against a destination prefix whose _SUCCESS is already present)"
104        );
105    }
106    let config = Config::load_with_params(config_path, params)?;
107
108    let config_dir = Path::new(config_path)
109        .parent()
110        .unwrap_or(Path::new("."))
111        .to_path_buf();
112
113    let exports: Vec<&ExportConfig> = if let Some(name) = export_name {
114        let e = config
115            .exports
116            .iter()
117            .find(|e| e.name == name)
118            .ok_or_else(|| anyhow::anyhow!("export '{}' not found in config", name))?;
119        vec![e]
120    } else {
121        config.exports.iter().collect()
122    };
123
124    let opts = RunOptions {
125        validate,
126        reconcile,
127        resume,
128        force,
129        params,
130    };
131
132    let run_parallel_processes = (parallel_export_processes_cli
133        || config.parallel_export_processes)
134        && export_name.is_none()
135        && exports.len() > 1;
136
137    let started_at = chrono::Utc::now();
138
139    if run_parallel_processes {
140        // Run schema migrations once in the parent BEFORE forking children.
141        // Otherwise N children race for the exclusive write lock on a
142        // brand-new `.rivet_state.db` and `busy_timeout` is not enough to
143        // serialise them — most fail with `migration v1 failed: database is
144        // locked`.  After this open succeeds the schema is at the latest
145        // version and children's `StateStore::open` calls become idempotent
146        // (the `MIGRATIONS` loop is a no-op when `ver <= current`).
147        if let Err(e) = StateStore::open(config_path) {
148            return Err(anyhow::anyhow!(
149                "state: failed to initialize state DB before spawning children: {:#}",
150                e
151            ));
152        }
153
154        let (result, child_failures, stderr_dump) =
155            parallel_children::run_exports_as_child_processes(
156                config_path,
157                &exports,
158                validate,
159                reconcile,
160                resume,
161                force,
162                params,
163            );
164        let finished_at = chrono::Utc::now();
165        // Best-effort aggregate: open the state DB read-only-ish and reconstruct
166        // entries from the per-child `record_metric` rows.  Failure to open the
167        // DB here only suppresses the aggregate, not the run itself.
168        match StateStore::open(config_path) {
169            Ok(state) => {
170                let entries =
171                    aggregate::collect_child_entries(&state, &exports, started_at, &child_failures);
172                let agg = aggregate::build(
173                    entries,
174                    started_at,
175                    finished_at,
176                    Some(config_path),
177                    "parallel-processes",
178                );
179                aggregate::print(&agg);
180                aggregate::persist(&state, &agg, summary_output);
181                if json_output {
182                    print_json_summary(&agg);
183                }
184            }
185            Err(e) => log::warn!(
186                "aggregate: cannot open state DB to record run aggregate: {:#}",
187                e
188            ),
189        }
190        // Captured child stderr is printed AFTER the aggregate so the run
191        // summary stays immediately under the card stack — verbose log
192        // output sits below for triage when needed.
193        if !stderr_dump.is_empty() {
194            use std::io::Write;
195            let mut h = std::io::stderr().lock();
196            let _ = h.write_all(stderr_dump.as_bytes());
197            let _ = h.flush();
198        }
199        return result;
200    }
201
202    let run_parallel = (parallel_exports_cli || config.parallel_exports)
203        && export_name.is_none()
204        && exports.len() > 1;
205
206    // Compact-rendering hints for the per-export renderers.  Set once here so
207    // every code path below — sequential, `--parallel-exports`, the apply
208    // path, etc. — sees a consistent mode.  Restored at the end of the run
209    // so subsequent invocations within the same process (tests, library
210    // callers) start with a clean slate.
211    let multi_export = export_name.is_none() && exports.len() > 1;
212    let prev_multi = MULTI_EXPORT_MODE.swap(multi_export, AtomicOrdering::Relaxed);
213    let prev_concurrent = MULTI_EXPORT_CONCURRENT.swap(run_parallel, AtomicOrdering::Relaxed);
214    struct ResetMultiExport(bool, bool);
215    impl Drop for ResetMultiExport {
216        fn drop(&mut self) {
217            MULTI_EXPORT_MODE.store(self.0, AtomicOrdering::Relaxed);
218            MULTI_EXPORT_CONCURRENT.store(self.1, AtomicOrdering::Relaxed);
219        }
220    }
221    let _reset_multi = ResetMultiExport(prev_multi, prev_concurrent);
222
223    let mut summaries: Vec<RunSummary> = Vec::with_capacity(exports.len());
224    let mut failures: Vec<String> = Vec::new();
225
226    if run_parallel {
227        log::info!(
228            "running {} exports in parallel (separate state DB connection per export)",
229            exports.len()
230        );
231
232        // In threads mode every export emits the same `ChildEvent` stream
233        // that `--parallel-export-processes` children emit, but routed
234        // through an in-process `mpsc` channel.  A single UI thread (the
235        // same `parent_ui::run_ui` used for the process-mode parent) owns
236        // stderr and renders one card line per export — no indicatif, no
237        // multi-bar coordination headache, no scrollback artefacts from
238        // concurrent redraws.  Ensure stderr is also pre-migrated so child
239        // threads opening their own `StateStore` don't race on schema DDL.
240        if let Err(e) = StateStore::open(config_path) {
241            return Err(anyhow::anyhow!(
242                "state: failed to initialize state DB before spawning export threads: {:#}",
243                e
244            ));
245        }
246        let (tx, rx) = std::sync::mpsc::channel::<parent_ui::UiMessage>();
247        ipc::install_in_process_tx(tx);
248        let ui_thread = std::thread::Builder::new()
249            .name("rivet-ui".to_string())
250            .spawn(move || parent_ui::run_ui(rx))
251            .ok();
252
253        let collected: std::sync::Mutex<Vec<(Result<()>, RunSummary)>> =
254            std::sync::Mutex::new(Vec::with_capacity(exports.len()));
255        std::thread::scope(|s| {
256            let mut handles = Vec::new();
257            for &export in &exports {
258                handles.push(s.spawn(|| {
259                    let state = match StateStore::open(config_path) {
260                        Ok(s) => s,
261                        Err(e) => {
262                            let err = anyhow::anyhow!(
263                                "export '{}': failed to open state database: {:#}",
264                                export.name,
265                                e
266                            );
267                            let summary = job::synthetic_failed_summary(&export.name, &err);
268                            return (Err(err), summary);
269                        }
270                    };
271                    job::run_export_job(config_path, &config, export, &state, &config_dir, &opts)
272                }));
273            }
274            for h in handles {
275                match h.join() {
276                    Ok(pair) => collected.lock().unwrap().push(pair),
277                    Err(payload) => std::panic::resume_unwind(payload),
278                }
279            }
280        });
281
282        // All exports are done → drop the sender so `parent_ui::run_ui`
283        // sees the channel close and exits cleanly (committing the final
284        // card stack to scrollback).  Joining is best-effort: even if the
285        // UI thread is wedged we still want to print the run aggregate
286        // below.
287        ipc::clear_in_process_tx();
288        if let Some(t) = ui_thread {
289            let _ = t.join();
290        }
291
292        for (res, summary) in collected.into_inner().unwrap() {
293            if let Err(e) = res {
294                failures.push(format!("{e:#}"));
295            }
296            summaries.push(summary);
297        }
298    } else {
299        let state = StateStore::open(config_path)?;
300
301        // Always route through `parent_ui` — same as `--parallel-exports`.
302        // Gating on `is_attended()` left VHS/ttyd on indicatif when the
303        // attended bit is unset; `run_ui` already falls back to linear
304        // mode for piped stderr.
305        let (tx, rx) = std::sync::mpsc::channel::<parent_ui::UiMessage>();
306        ipc::install_in_process_tx(tx);
307        let ui_thread = std::thread::Builder::new()
308            .name("rivet-ui".to_string())
309            .spawn(move || parent_ui::run_ui(rx))
310            .ok();
311
312        for export in &exports {
313            let (res, summary) =
314                job::run_export_job(config_path, &config, export, &state, &config_dir, &opts);
315            if let Err(e) = res {
316                failures.push(format!("{e:#}"));
317            }
318            summaries.push(summary);
319        }
320
321        ipc::clear_in_process_tx();
322        if let Some(t) = ui_thread {
323            let _ = t.join();
324        }
325        // Single-export sequential runs still emit the detailed block after
326        // the card commits to scrollback.
327        if exports.len() == 1
328            && let Some(summary) = summaries.last()
329        {
330            summary.print_stderr_block();
331        }
332    }
333
334    let finished_at = chrono::Utc::now();
335    // Skip the aggregate for single-export runs.  Two cases this catches:
336    //   1) `rivet run --export X` (manual one-off): the per-export block
337    //      already says everything, an aggregate of one row is just noise.
338    //   2) Children spawned by `--parallel-export-processes`: each child
339    //      enters this code path with exports.len() == 1.  The parent
340    //      (parallel_processes branch above) builds the run-wide aggregate
341    //      from every child's `export_metrics` row, so a child-level
342    //      aggregate would just write a duplicate into `run_aggregate`.
343    // Force-write the JSON file even when skipping, so `--summary-output`
344    // remains useful for one-off runs.
345    if exports.len() > 1 {
346        let parallel_mode = if run_parallel {
347            "parallel-threads"
348        } else {
349            "sequential"
350        };
351        let entries: Vec<_> = summaries
352            .iter()
353            .map(aggregate::entry_from_summary)
354            .collect();
355        let agg = aggregate::build(
356            entries,
357            started_at,
358            finished_at,
359            Some(config_path),
360            parallel_mode,
361        );
362        aggregate::print(&agg);
363        // Open a fresh state handle for persisting the aggregate so we don't
364        // assume which thread owned the per-export `StateStore` above.
365        match StateStore::open(config_path) {
366            Ok(state) => aggregate::persist(&state, &agg, summary_output),
367            Err(e) => log::warn!(
368                "aggregate: cannot open state DB to record run aggregate: {:#}",
369                e
370            ),
371        }
372        if json_output {
373            print_json_summary(&agg);
374        }
375    } else if summary_output.is_some() || json_output {
376        // One export, but the user asked for a summary file and/or JSON stdout —
377        // honour both without polluting the DB or stderr.
378        let entries: Vec<_> = summaries
379            .iter()
380            .map(aggregate::entry_from_summary)
381            .collect();
382        let agg = aggregate::build(
383            entries,
384            started_at,
385            finished_at,
386            Some(config_path),
387            "sequential",
388        );
389        if let Some(out) = summary_output
390            && let Err(e) =
391                std::fs::write(out, serde_json::to_string_pretty(&agg).unwrap_or_default())
392        {
393            log::warn!(
394                "aggregate: failed to write summary JSON to {}: {:#}",
395                out.display(),
396                e
397            );
398        }
399        if json_output {
400            print_json_summary(&agg);
401        }
402    }
403
404    if !failures.is_empty() {
405        anyhow::bail!("{}", failures.join("; "));
406    }
407
408    Ok(())
409}