Skip to main content

faucet_cli/commands/
schedule.rs

1//! `faucet schedule` — run a pipeline on a cron schedule in one long-running
2//! process. Reuses `expand` + `executor::run_expanded` per tick; keeps no state
3//! of its own (resumability rides the pipeline's per-page bookmark). See
4//! `docs/superpowers/specs/2026-05-30-faucet-schedule-design.md`.
5
6use crate::auth_catalog::{AuthCatalog, build_auth_catalog};
7use crate::cli::ScheduleArgs;
8use crate::config::PipelineConfig;
9use crate::error::{CliError, CliResult};
10use crate::executor::{ExecuteOptions, RunSummary, run_expanded};
11use crate::expand::{ExpandedNode, expand};
12use crate::schedule::compiled::CompiledSchedule;
13use crate::schedule::metrics as m;
14use crate::schedule::state::{AfterRun, RunOutcome, SchedulerState, TickAction};
15use chrono::{DateTime, Utc};
16use std::time::Duration;
17use tokio::task::JoinHandle;
18use tokio::time::Instant;
19use tracing::Instrument;
20
21/// An in-flight run.
22struct RunningRun {
23    handle: JoinHandle<CliResult<RunSummary>>,
24    started: Instant,
25}
26
27/// The data the loop needs after a run finishes.
28struct RunFinished {
29    outcome: RunOutcome,
30    duration: Duration,
31    detail: Option<String>,
32    /// Circuit-breaker re-entry cooldown when the run tripped the breaker.
33    cooldown: Option<Duration>,
34}
35
36/// Cross-platform shutdown-signal source, registered once.
37struct Shutdown {
38    #[cfg(unix)]
39    sigterm: tokio::signal::unix::Signal,
40}
41
42impl Shutdown {
43    fn new() -> CliResult<Self> {
44        #[cfg(unix)]
45        {
46            use tokio::signal::unix::{SignalKind, signal};
47            let sigterm = signal(SignalKind::terminate()).map_err(|e| {
48                CliError::Internal(format!("failed to install SIGTERM handler: {e}"))
49            })?;
50            Ok(Self { sigterm })
51        }
52        #[cfg(not(unix))]
53        {
54            Ok(Self {})
55        }
56    }
57
58    /// Resolve when SIGTERM (Unix) or Ctrl-C (any platform) is received.
59    async fn recv(&mut self) {
60        #[cfg(unix)]
61        {
62            tokio::select! {
63                _ = tokio::signal::ctrl_c() => {}
64                _ = self.sigterm.recv() => {}
65            }
66        }
67        #[cfg(not(unix))]
68        {
69            let _ = tokio::signal::ctrl_c().await;
70        }
71    }
72}
73
74/// Cross-platform hot-reload signal source (SIGHUP on Unix). On non-Unix
75/// platforms `recv()` never resolves, so the reload arm simply never fires.
76struct Reload {
77    #[cfg(unix)]
78    sighup: tokio::signal::unix::Signal,
79}
80
81impl Reload {
82    fn new() -> CliResult<Self> {
83        #[cfg(unix)]
84        {
85            use tokio::signal::unix::{SignalKind, signal};
86            let sighup = signal(SignalKind::hangup()).map_err(|e| {
87                CliError::Internal(format!("failed to install SIGHUP handler: {e}"))
88            })?;
89            Ok(Self { sighup })
90        }
91        #[cfg(not(unix))]
92        {
93            Ok(Self {})
94        }
95    }
96
97    /// Resolve when SIGHUP is received (Unix); never resolves elsewhere.
98    async fn recv(&mut self) {
99        #[cfg(unix)]
100        {
101            self.sighup.recv().await;
102        }
103        #[cfg(not(unix))]
104        {
105            std::future::pending::<()>().await;
106        }
107    }
108}
109
110/// The config-derived fields a hot reload (SIGHUP) swaps. Auth catalog, lineage
111/// emitter, notifier, and catalog handle are deliberately NOT reloaded — they
112/// hold pooled connections / cached tokens reused across ticks (reloading them
113/// would churn connections and could leak auth-catalog tokens).
114struct ReloadedBundle {
115    compiled: CompiledSchedule,
116    nodes: Vec<ExpandedNode>,
117    execution: Option<crate::config::ExecutionSpec>,
118    resilience: Option<faucet_core::ResiliencePolicy>,
119    sla: Option<crate::sla::SlaSpec>,
120    cron: String,
121    timezone: String,
122}
123
124/// Re-read + re-validate the config file and build a fresh [`ReloadedBundle`].
125/// Any error (parse, missing `schedule:`, invalid cron, expand failure) is
126/// returned so the caller can keep running on the previous config.
127async fn reload_bundle(path: &std::path::Path, profile: Option<&str>) -> CliResult<ReloadedBundle> {
128    let cfg = PipelineConfig::from_path_async(path, profile).await?;
129    let spec = cfg.schedule.as_ref().ok_or_else(|| {
130        CliError::Config("reload: config no longer has a `schedule:` block".into())
131    })?;
132    let compiled = CompiledSchedule::compile(spec)?;
133    let cron = spec.cron.clone();
134    let timezone = spec.timezone.clone();
135    let nodes = expand(&cfg)?;
136    let resilience = match &cfg.resilience {
137        Some(spec) => Some(spec.to_policy()?),
138        None => None,
139    };
140    Ok(ReloadedBundle {
141        compiled,
142        nodes,
143        execution: cfg.execution.clone(),
144        resilience,
145        sla: cfg.sla.clone(),
146        cron,
147        timezone,
148    })
149}
150
151/// Max time to sleep before re-reading the wall clock. Caps clock-step / DST
152/// drift to one chunk and keeps the heartbeat fresh.
153const MAX_SLEEP: Duration = Duration::from_secs(30);
154
155/// Execute the `schedule` subcommand.
156pub async fn run(args: ScheduleArgs) -> CliResult<()> {
157    let cwd = std::env::current_dir()?;
158    let env_path =
159        crate::env_loader::resolve_env_file(args.env_file.as_deref(), args.no_env_file, &cwd)?;
160    crate::env_loader::load_env_file_if_present(env_path.as_deref())?;
161    let path = match args.config {
162        Some(p) => p,
163        None => crate::env_loader::discover_config_path(&cwd).ok_or(CliError::NoConfigOrFromEnv)?,
164    };
165
166    let cfg = PipelineConfig::from_path_async(&path, args.profile.as_deref()).await?;
167    let spec = cfg.schedule.as_ref().ok_or_else(|| {
168        CliError::Config(
169            "no `schedule:` block in config — use `faucet run` for a one-shot run, or add a `schedule:` block"
170                .into(),
171        )
172    })?;
173    let compiled = CompiledSchedule::compile(spec)?;
174    let cron = spec.cron.clone();
175    let timezone = spec.timezone.clone();
176
177    crate::obs::install(&cfg)?;
178
179    let pipeline_name = cfg.name.clone().unwrap_or_else(|| {
180        path.file_stem()
181            .and_then(|s| s.to_str())
182            .unwrap_or("pipeline")
183            .to_owned()
184    });
185
186    let auth = build_auth_catalog(cfg.auth.as_ref())?;
187    // Build the shared OpenLineage emitter once; the `Arc` is cloned into each
188    // tick's `ExecuteOptions` so every run reuses the same transport/client.
189    #[cfg(feature = "lineage")]
190    let lineage = crate::lineage_glue::build_emitter(cfg.lineage.as_ref())
191        .map_err(|e| CliError::Config(format!("lineage: {e}")))?;
192    #[cfg(feature = "lineage")]
193    let lineage_cfg = cfg.lineage.clone();
194    // Build the notifier once; the `Arc` is cloned into each tick's options and
195    // reused for the scheduler-level `scheduler_stuck` signal.
196    #[cfg(feature = "notify")]
197    let notifier = crate::notify::Notifier::from_specs(&cfg.notifications)?;
198    // Connect the catalog store once; the handle (a pooled connection) is
199    // cloned into each tick's options so every run accumulates into it.
200    #[cfg(feature = "catalog")]
201    let catalog = match cfg.catalog.as_ref() {
202        Some(spec) => Some(crate::catalog::connect_from_spec(spec).await?),
203        None => None,
204    };
205    let nodes = expand(&cfg)?; // validate once; cloned per tick
206    let execution = cfg.execution.clone();
207    let resilience = match &cfg.resilience {
208        Some(spec) => Some(spec.to_policy()?),
209        None => None,
210    };
211
212    if args.once {
213        return run_once(
214            &nodes,
215            &auth,
216            &execution,
217            &compiled,
218            &pipeline_name,
219            &resilience,
220            &cfg.sla,
221            #[cfg(feature = "lineage")]
222            &lineage,
223            #[cfg(feature = "lineage")]
224            &lineage_cfg,
225            #[cfg(feature = "notify")]
226            &notifier,
227            #[cfg(feature = "catalog")]
228            &catalog,
229        )
230        .await;
231    }
232
233    run_loop(
234        compiled,
235        nodes,
236        auth,
237        execution,
238        pipeline_name,
239        cron,
240        timezone,
241        resilience,
242        cfg.sla.clone(),
243        path,
244        args.profile,
245        #[cfg(feature = "lineage")]
246        lineage,
247        #[cfg(feature = "lineage")]
248        lineage_cfg,
249        #[cfg(feature = "notify")]
250        notifier,
251        #[cfg(feature = "catalog")]
252        catalog,
253    )
254    .await
255}
256
257/// Build a fresh `ExecuteOptions` for one tick (connectors are rebuilt per run;
258/// the auth catalog is shared so cached tokens survive across ticks).
259#[allow(clippy::too_many_arguments)]
260fn make_opts(
261    pipeline_name: &str,
262    execution: &Option<crate::config::ExecutionSpec>,
263    auth: &AuthCatalog,
264    clock: chrono::DateTime<chrono::FixedOffset>,
265    resilience: &Option<faucet_core::ResiliencePolicy>,
266    sla: &Option<crate::sla::SlaSpec>,
267    #[cfg(feature = "lineage")] lineage: &Option<std::sync::Arc<faucet_lineage::LineageEmitter>>,
268    #[cfg(feature = "lineage")] lineage_cfg: &Option<faucet_lineage::LineageConfig>,
269    #[cfg(feature = "notify")] notifier: &Option<std::sync::Arc<crate::notify::Notifier>>,
270    #[cfg(feature = "catalog")] catalog: &Option<crate::catalog::CatalogHandle>,
271) -> ExecuteOptions {
272    ExecuteOptions {
273        pipeline_name: pipeline_name.to_string(),
274        execution: execution.clone(),
275        dry_run: false,
276        limit: None,
277        state_path_override: None,
278        shard: None,
279        auth: auth.clone(),
280        clock,
281        cancel: None,
282        resilience: resilience.clone(),
283        sla: sla.clone(),
284        #[cfg(feature = "lineage")]
285        lineage: lineage.clone(),
286        #[cfg(feature = "lineage")]
287        lineage_cfg: lineage_cfg.clone(),
288        #[cfg(feature = "notify")]
289        notifier: notifier.clone(),
290        #[cfg(feature = "catalog")]
291        catalog: catalog.clone(),
292    }
293}
294
295/// The per-run tracing span. Wraps the inner pipeline spans so a scheduled run
296/// is correlatable in distributed tracing. `scheduled_for` is the cron-intended
297/// instant; `tick` is when the run actually started.
298fn run_span(run_ordinal: u64, scheduled_for: DateTime<Utc>, tick: DateTime<Utc>) -> tracing::Span {
299    tracing::info_span!(
300        "faucet.schedule.run",
301        run_ordinal,
302        scheduled_for_unix_seconds = scheduled_for.timestamp(),
303        tick_unix_seconds = tick.timestamp(),
304    )
305}
306
307/// Spawn one pipeline run, wrapping it in the optional run timeout and the
308/// per-run span.
309fn spawn_run(
310    nodes: Vec<ExpandedNode>,
311    opts: ExecuteOptions,
312    timeout: Option<Duration>,
313    span: tracing::Span,
314) -> JoinHandle<CliResult<RunSummary>> {
315    tokio::spawn(
316        async move {
317            match timeout {
318                Some(d) => match tokio::time::timeout(d, run_expanded(nodes, opts)).await {
319                    Ok(r) => r,
320                    Err(_) => Err(CliError::Internal(format!(
321                        "scheduled run exceeded run_timeout_secs ({}s) and was aborted",
322                        d.as_secs()
323                    ))),
324                },
325                None => run_expanded(nodes, opts).await,
326            }
327        }
328        .instrument(span),
329    )
330}
331
332/// Display prefix of [`faucet_core::FaucetError::CircuitOpen`]. The per-invocation
333/// typed error is flattened to a string by the executor, so the scheduler matches
334/// on this stable prefix to detect a circuit-open run; the authoritative cooldown
335/// duration is recovered from the run's configured resilience policy (not parsed
336/// out of the message).
337const CIRCUIT_OPEN_PREFIX: &str = "Circuit open after";
338
339/// Classify a joined run task into a scheduler outcome + a log detail. When the
340/// run tripped the circuit breaker, `cooldown` is set to the policy's re-entry
341/// cooldown so the loop can delay the next tick.
342fn classify(
343    joined: Result<CliResult<RunSummary>, tokio::task::JoinError>,
344    breaker_cooldown: Option<Duration>,
345) -> RunFinished {
346    // Did any failure indicate a tripped circuit breaker?
347    let circuit_open = match &joined {
348        Ok(Ok(summary)) => summary
349            .invocations
350            .iter()
351            .filter_map(|i| i.error.as_deref())
352            .any(|e| e.starts_with(CIRCUIT_OPEN_PREFIX)),
353        Ok(Err(e)) => e.to_string().contains(CIRCUIT_OPEN_PREFIX),
354        Err(_) => false,
355    };
356    // Recover the typed cooldown through the pure decision helper, using the
357    // configured cooldown as the authoritative duration.
358    let cooldown = if circuit_open {
359        let reconstructed: Result<(), faucet_core::FaucetError> =
360            Err(faucet_core::FaucetError::CircuitOpen {
361                failures: 0,
362                cooldown: breaker_cooldown.unwrap_or(Duration::ZERO),
363            });
364        crate::schedule::state::cooldown_delay(&reconstructed).filter(|d| !d.is_zero())
365    } else {
366        None
367    };
368
369    let (outcome, detail) = match joined {
370        Ok(Ok(summary)) if summary.had_failures() => (
371            RunOutcome::Failure,
372            Some(format!("{} invocation(s) failed", summary.failure_count())),
373        ),
374        Ok(Ok(_)) => (RunOutcome::Success, None),
375        Ok(Err(e)) => (RunOutcome::Failure, Some(e.to_string())),
376        Err(je) => (
377            RunOutcome::Failure,
378            Some(format!("run task panicked: {je}")),
379        ),
380    };
381    RunFinished {
382        outcome,
383        duration: Duration::ZERO,
384        detail,
385        cooldown,
386    }
387}
388
389/// `--once`: run exactly one pipeline run now and map its result to an exit.
390#[allow(clippy::too_many_arguments)]
391async fn run_once(
392    nodes: &[ExpandedNode],
393    auth: &AuthCatalog,
394    execution: &Option<crate::config::ExecutionSpec>,
395    compiled: &CompiledSchedule,
396    pipeline_name: &str,
397    resilience: &Option<faucet_core::ResiliencePolicy>,
398    sla: &Option<crate::sla::SlaSpec>,
399    #[cfg(feature = "lineage")] lineage: &Option<std::sync::Arc<faucet_lineage::LineageEmitter>>,
400    #[cfg(feature = "lineage")] lineage_cfg: &Option<faucet_lineage::LineageConfig>,
401    #[cfg(feature = "notify")] notifier: &Option<std::sync::Arc<crate::notify::Notifier>>,
402    #[cfg(feature = "catalog")] catalog: &Option<crate::catalog::CatalogHandle>,
403) -> CliResult<()> {
404    tracing::info!(pipeline = %pipeline_name, "schedule --once: running one pipeline now");
405    let now = chrono::Utc::now();
406    let opts = make_opts(
407        pipeline_name,
408        execution,
409        auth,
410        compiled.clock_at(now),
411        resilience,
412        sla,
413        #[cfg(feature = "lineage")]
414        lineage,
415        #[cfg(feature = "lineage")]
416        lineage_cfg,
417        #[cfg(feature = "notify")]
418        notifier,
419        #[cfg(feature = "catalog")]
420        catalog,
421    );
422    let span = run_span(1, now, now);
423    let fut = run_expanded(nodes.to_vec(), opts).instrument(span);
424    let summary = match compiled.run_timeout {
425        Some(d) => tokio::time::timeout(d, fut).await.map_err(|_| {
426            CliError::Internal(format!(
427                "--once run exceeded run_timeout_secs ({}s)",
428                d.as_secs()
429            ))
430        })??,
431        None => fut.await?,
432    };
433    if summary.had_failures() {
434        return Err(CliError::PipelineHadFailures {
435            count: summary.failure_count(),
436        });
437    }
438    Ok(())
439}
440
441/// The scheduling loop.
442#[allow(clippy::too_many_arguments)]
443async fn run_loop(
444    mut compiled: CompiledSchedule,
445    mut nodes: Vec<ExpandedNode>,
446    auth: AuthCatalog,
447    mut execution: Option<crate::config::ExecutionSpec>,
448    pipeline_name: String,
449    mut cron: String,
450    mut timezone: String,
451    mut resilience: Option<faucet_core::ResiliencePolicy>,
452    mut sla: Option<crate::sla::SlaSpec>,
453    path: std::path::PathBuf,
454    profile: Option<String>,
455    #[cfg(feature = "lineage")] lineage: Option<std::sync::Arc<faucet_lineage::LineageEmitter>>,
456    #[cfg(feature = "lineage")] lineage_cfg: Option<faucet_lineage::LineageConfig>,
457    #[cfg(feature = "notify")] notifier: Option<std::sync::Arc<crate::notify::Notifier>>,
458    #[cfg(feature = "catalog")] catalog: Option<crate::catalog::CatalogHandle>,
459) -> CliResult<()> {
460    let mut state = SchedulerState::new(&compiled);
461    // The circuit-breaker re-entry cooldown, if a breaker is configured. Used to
462    // delay the next tick after a run trips the breaker. Recomputed on reload.
463    let mut breaker_cooldown = resilience
464        .as_ref()
465        .and_then(|r| r.circuit_breaker)
466        .map(|cb| cb.cooldown);
467    let mut shutdown = Shutdown::new()?;
468    let mut reload = Reload::new()?;
469    let mut running: Option<RunningRun> = None;
470    let mut pending_scheduled_for: Option<DateTime<Utc>> = None;
471    let mut run_ordinal: u64 = 0;
472
473    let mut next_due = if compiled.start_immediately {
474        Utc::now()
475    } else {
476        compiled
477            .next_after(Utc::now())
478            .ok_or_else(|| CliError::Config("schedule: no upcoming occurrence".into()))?
479    };
480
481    // Startup banner: cron, timezone, and the next few firing times so an
482    // operator can confirm at a glance the schedule is configured correctly.
483    let upcoming: Vec<String> = {
484        let mut t = Utc::now();
485        let mut v = Vec::with_capacity(3);
486        while v.len() < 3 {
487            match compiled.next_after(t) {
488                Some(n) => {
489                    v.push(n.to_rfc3339());
490                    t = n;
491                }
492                None => break,
493            }
494        }
495        v
496    };
497    tracing::info!(
498        pipeline = %pipeline_name,
499        cron = %cron,
500        timezone = %timezone,
501        next_occurrences = ?upcoming,
502        "scheduler started (Ctrl-C / SIGTERM to stop)"
503    );
504
505    // Register HELP text and pre-emit the two run-state gauges at 0 so both
506    // series exist in `/metrics` from t=0 — the `metrics` exporter only renders
507    // a series after its first emission, and these gauges are otherwise first
508    // touched mid/post-run, leaving a pre-first-run scrape blind to them
509    // (#146 R NIT).
510    m::describe();
511    m::in_flight(&pipeline_name, 0);
512    m::consecutive_failures(&pipeline_name, 0);
513
514    loop {
515        let now = Utc::now();
516
517        if now >= next_due {
518            match state.on_tick(running.is_some()) {
519                TickAction::Dispatch => {
520                    run_ordinal += 1;
521                    let opts = make_opts(
522                        &pipeline_name,
523                        &execution,
524                        &auth,
525                        compiled.clock_at(next_due),
526                        &resilience,
527                        &sla,
528                        #[cfg(feature = "lineage")]
529                        &lineage,
530                        #[cfg(feature = "lineage")]
531                        &lineage_cfg,
532                        #[cfg(feature = "notify")]
533                        &notifier,
534                        #[cfg(feature = "catalog")]
535                        &catalog,
536                    );
537                    let span = run_span(run_ordinal, next_due, now);
538                    let handle = spawn_run(nodes.clone(), opts, compiled.run_timeout, span);
539                    m::in_flight(&pipeline_name, 1);
540                    m::last_run_started(&pipeline_name, now);
541                    m::lateness(&pipeline_name, now - next_due);
542                    tracing::info!(pipeline = %pipeline_name, run_ordinal, scheduled_for = %next_due, "run started");
543                    running = Some(RunningRun {
544                        handle,
545                        started: Instant::now(),
546                    });
547                }
548                TickAction::Skip => {
549                    m::overlap(&pipeline_name, "skip");
550                    m::run_outcome(&pipeline_name, "skipped");
551                    tracing::warn!(pipeline = %pipeline_name, scheduled_for = %next_due, "tick skipped — previous run still in progress");
552                }
553                TickAction::Queue => {
554                    m::overlap(&pipeline_name, "queue");
555                    if pending_scheduled_for.is_none() {
556                        pending_scheduled_for = Some(next_due);
557                    }
558                    tracing::warn!(pipeline = %pipeline_name, scheduled_for = %next_due, "tick queued — will run after current run finishes");
559                }
560                TickAction::ForbidAbort => {
561                    m::overlap(&pipeline_name, "forbid");
562                    // A prior `Dispatch` set the in-flight gauge to 1; reset it
563                    // before we bail so `/metrics` doesn't read a stuck 1 after
564                    // the scheduler exits (#146 R LOW).
565                    m::in_flight(&pipeline_name, 0);
566                    return Err(CliError::ScheduleOverlapForbidden);
567                }
568            }
569            // Advance from the tick that just fired (`next_due`), not from the
570            // wall clock — so a sub-minute occurrence isn't skipped just because
571            // dispatch latency pushed `now` past it. A long backlog (suspension)
572            // is collapsed to a single catch-up inside `next_due_after_tick`.
573            next_due = match compiled.next_due_after_tick(next_due, Utc::now()) {
574                Some(t) => t,
575                None => {
576                    tracing::info!(pipeline = %pipeline_name, "no further scheduled occurrences; exiting");
577                    return Ok(());
578                }
579            };
580        }
581
582        let now2 = Utc::now();
583        m::heartbeat(&pipeline_name, now2);
584        m::next_tick(&pipeline_name, next_due);
585        let chunk = (next_due - now2)
586            .to_std()
587            .unwrap_or(Duration::ZERO)
588            .min(MAX_SLEEP);
589
590        tokio::select! {
591            biased;
592
593            _ = shutdown.recv() => {
594                tracing::info!(pipeline = %pipeline_name, "shutdown signal received; draining in-flight run");
595                graceful_shutdown(running.take(), compiled.shutdown_grace, &pipeline_name).await;
596                // Flush any buffered OTLP telemetry after the final run drains
597                // (no-op without the `otel` feature).
598                faucet_core::shutdown_otel();
599                return Ok(());
600            }
601
602            finished = wait_for_run(&mut running, breaker_cooldown) => {
603                let mut finished = finished;
604                if let Some(rr) = running.take() {
605                    finished.duration = rr.started.elapsed();
606                }
607                m::in_flight(&pipeline_name, 0);
608                let done_at = Utc::now();
609
610                // Circuit-breaker re-entry cooldown: if the run tripped the
611                // breaker, push the next tick out so AT LEAST `cooldown` elapses
612                // before re-entry. This composes with the cron schedule — it
613                // only delays `next_due` when the cooldown would land later than
614                // the next scheduled occurrence. The actual wait happens in the
615                // existing cancellation-aware `select!` below, so SIGTERM still
616                // interrupts it.
617                if let Some(d) = finished.cooldown
618                    && let Ok(delta) = chrono::Duration::from_std(d)
619                {
620                    let resume = done_at + delta;
621                    if resume > next_due {
622                        next_due = resume;
623                    }
624                    tracing::warn!(
625                        pipeline = %pipeline_name,
626                        cooldown_secs = d.as_secs(),
627                        next_due = %next_due,
628                        "circuit breaker opened; delaying re-entry by cooldown"
629                    );
630                }
631                m::last_run_completed(&pipeline_name, done_at);
632                m::last_run_duration(&pipeline_name, finished.duration);
633                m::run_outcome(&pipeline_name, match finished.outcome {
634                    RunOutcome::Success => "ok",
635                    RunOutcome::Failure => "err",
636                });
637                match finished.outcome {
638                    RunOutcome::Success => tracing::info!(
639                        pipeline = %pipeline_name, secs = finished.duration.as_secs_f64(), "run completed"
640                    ),
641                    RunOutcome::Failure => tracing::error!(
642                        pipeline = %pipeline_name, detail = finished.detail.as_deref().unwrap_or("unknown"),
643                        "run failed"
644                    ),
645                }
646
647                let after = state.on_run_finished(finished.outcome);
648                m::consecutive_failures(&pipeline_name, state.consecutive_failures());
649                match after {
650                    AfterRun::ExitOk => {
651                        tracing::info!(pipeline = %pipeline_name, "max_runs reached; exiting");
652                        return Ok(());
653                    }
654                    AfterRun::ExitFailure { consecutive } => {
655                        #[cfg(feature = "notify")]
656                        if let Some(n) = &notifier {
657                            n.emit(crate::notify::NotifyEvent::scheduler_stuck(
658                                &pipeline_name,
659                                format!(
660                                    "scheduler exiting after {consecutive} consecutive failures"
661                                ),
662                            ))
663                            .await;
664                        }
665                        return Err(CliError::PipelineHadFailures { count: consecutive as usize });
666                    }
667                    AfterRun::Continue { dispatch_pending } => {
668                        if dispatch_pending {
669                            run_ordinal += 1;
670                            let sched_for = pending_scheduled_for.take().unwrap_or(done_at);
671                            let opts = make_opts(
672                                &pipeline_name,
673                                &execution,
674                                &auth,
675                                compiled.clock_at(sched_for),
676                                &resilience,
677                                &sla,
678                                #[cfg(feature = "lineage")]
679                                &lineage,
680                                #[cfg(feature = "lineage")]
681                                &lineage_cfg,
682                                #[cfg(feature = "notify")]
683                                &notifier,
684                                #[cfg(feature = "catalog")]
685                                &catalog,
686                            );
687                            let span = run_span(run_ordinal, sched_for, done_at);
688                            let handle = spawn_run(nodes.clone(), opts, compiled.run_timeout, span);
689                            m::in_flight(&pipeline_name, 1);
690                            m::last_run_started(&pipeline_name, done_at);
691                            m::lateness(&pipeline_name, done_at - sched_for);
692                            tracing::info!(pipeline = %pipeline_name, run_ordinal, scheduled_for = %sched_for, "queued run started");
693                            running = Some(RunningRun { handle, started: Instant::now() });
694                        }
695                    }
696                }
697            }
698
699            _ = reload.recv() => {
700                // Hot config reload (SIGHUP): re-read + re-validate the config.
701                // On success, atomically swap the config-derived state and
702                // recompute the next tick; the scheduler's run counters and any
703                // in-flight run are untouched. On failure, keep the old config.
704                match reload_bundle(&path, profile.as_deref()).await {
705                    Ok(b) => {
706                        compiled = b.compiled;
707                        nodes = b.nodes;
708                        execution = b.execution;
709                        resilience = b.resilience;
710                        sla = b.sla;
711                        cron = b.cron;
712                        timezone = b.timezone;
713                        breaker_cooldown = resilience
714                            .as_ref()
715                            .and_then(|r| r.circuit_breaker)
716                            .map(|cb| cb.cooldown);
717                        next_due = if compiled.start_immediately {
718                            Utc::now()
719                        } else {
720                            compiled.next_after(Utc::now()).unwrap_or(next_due)
721                        };
722                        m::reload(&pipeline_name, "ok");
723                        tracing::info!(
724                            pipeline = %pipeline_name, cron = %cron, timezone = %timezone,
725                            next_due = %next_due, "config reloaded (SIGHUP)"
726                        );
727                    }
728                    Err(e) => {
729                        m::reload(&pipeline_name, "error");
730                        tracing::error!(
731                            pipeline = %pipeline_name, error = %e,
732                            "config reload failed; keeping the previous config"
733                        );
734                    }
735                }
736            }
737
738            _ = tokio::time::sleep(chunk) => { /* re-loop: re-read wall clock */ }
739        }
740    }
741}
742
743/// Await the in-flight run (or never resolve when idle). Returns the classified
744/// outcome; the caller fills in `duration` from the `RunningRun`.
745async fn wait_for_run(
746    running: &mut Option<RunningRun>,
747    breaker_cooldown: Option<Duration>,
748) -> RunFinished {
749    match running {
750        Some(rr) => classify((&mut rr.handle).await, breaker_cooldown),
751        None => std::future::pending().await,
752    }
753}
754
755/// On shutdown, await the in-flight run up to `grace`, then abort it.
756async fn graceful_shutdown(running: Option<RunningRun>, grace: Duration, pipeline_name: &str) {
757    if let Some(mut rr) = running {
758        match tokio::time::timeout(grace, &mut rr.handle).await {
759            Ok(_) => {
760                tracing::info!(pipeline = %pipeline_name, "in-flight run finished during shutdown grace")
761            }
762            Err(_) => {
763                rr.handle.abort();
764                tracing::warn!(
765                    pipeline = %pipeline_name,
766                    grace_secs = grace.as_secs(),
767                    "in-flight run exceeded shutdown grace; aborted (partial sink state possible; bookmark preserved for the next run)"
768                );
769            }
770        }
771        m::in_flight(pipeline_name, 0);
772    }
773}
774
775#[cfg(test)]
776mod tests {
777    use super::*;
778    use crate::schedule::spec::ScheduleSpec;
779
780    fn compiled(yaml: &str) -> CompiledSchedule {
781        let spec: ScheduleSpec = serde_yaml::from_str(yaml).unwrap();
782        CompiledSchedule::compile(&spec).unwrap()
783    }
784
785    // A valid scheduled config reloads into a fresh bundle; a config that lost
786    // its `schedule:` block (or is otherwise invalid) is rejected so the loop
787    // can keep the previous config.
788    #[tokio::test]
789    async fn reload_bundle_validates_and_builds() {
790        let dir = tempfile::tempdir().unwrap();
791        let good = dir.path().join("good.yaml");
792        std::fs::write(
793            &good,
794            "version: 1\nname: sch\npipeline:\n  source:\n    type: csv\n    config:\n      path: in.csv\n  sink:\n    type: jsonl\n    config:\n      path: out.jsonl\nschedule:\n  cron: \"*/5 * * * *\"\n  timezone: UTC\n",
795        )
796        .unwrap();
797        let b = reload_bundle(&good, None)
798            .await
799            .expect("valid config reloads");
800        assert_eq!(b.cron, "*/5 * * * *");
801        assert_eq!(b.timezone, "UTC");
802        assert_eq!(b.nodes.len(), 1);
803
804        // Missing `schedule:` → rejected.
805        let bad = dir.path().join("bad.yaml");
806        std::fs::write(
807            &bad,
808            "version: 1\npipeline:\n  source:\n    type: csv\n    config:\n      path: in.csv\n  sink:\n    type: jsonl\n    config:\n      path: out.jsonl\n",
809        )
810        .unwrap();
811        assert!(reload_bundle(&bad, None).await.is_err());
812    }
813
814    fn summary(failures: usize, total: usize) -> RunSummary {
815        let mut invocations = Vec::new();
816        for i in 0..total {
817            invocations.push(crate::executor::InvocationOutcome {
818                row_id: format!("r{i}"),
819                parent_record_key: None,
820                records_written: if i < failures { 0 } else { 3 },
821                error: if i < failures {
822                    Some("boom".into())
823                } else {
824                    None
825                },
826            });
827        }
828        RunSummary { invocations }
829    }
830
831    #[test]
832    fn classify_success_when_no_failures() {
833        let joined = Ok(Ok(summary(0, 2)));
834        let f = classify(joined, None);
835        assert_eq!(f.outcome, RunOutcome::Success);
836        assert!(f.detail.is_none());
837        assert!(f.cooldown.is_none());
838    }
839
840    #[test]
841    fn classify_failure_when_some_invocations_failed() {
842        let joined = Ok(Ok(summary(2, 5)));
843        let f = classify(joined, None);
844        assert_eq!(f.outcome, RunOutcome::Failure);
845        assert_eq!(f.detail.as_deref(), Some("2 invocation(s) failed"));
846        assert!(f.cooldown.is_none());
847    }
848
849    #[test]
850    fn classify_failure_when_run_errored() {
851        let joined: Result<CliResult<RunSummary>, tokio::task::JoinError> =
852            Ok(Err(CliError::Internal("disk full".into())));
853        let f = classify(joined, None);
854        assert_eq!(f.outcome, RunOutcome::Failure);
855        assert!(f.detail.as_deref().unwrap().contains("disk full"));
856    }
857
858    #[tokio::test]
859    async fn classify_failure_when_task_panicked() {
860        // Spawn a task that panics, then join it to obtain a real JoinError.
861        let handle = tokio::spawn(async { panic!("kaboom") });
862        let joined: Result<CliResult<RunSummary>, tokio::task::JoinError> = handle.await.map(Ok);
863        let f = classify(joined, None);
864        assert_eq!(f.outcome, RunOutcome::Failure);
865        assert!(
866            f.detail.as_deref().unwrap().contains("panicked"),
867            "{:?}",
868            f.detail
869        );
870    }
871
872    #[test]
873    fn classify_recovers_cooldown_from_circuit_open_invocation() {
874        // An invocation whose error is the flattened CircuitOpen Display string
875        // is detected; the cooldown is recovered from the configured policy.
876        let circuit_open_msg = faucet_core::FaucetError::CircuitOpen {
877            failures: 3,
878            cooldown: Duration::from_secs(60),
879        }
880        .to_string();
881        let invocations = vec![crate::executor::InvocationOutcome {
882            row_id: "r0".into(),
883            parent_record_key: None,
884            records_written: 0,
885            error: Some(circuit_open_msg),
886        }];
887        let joined = Ok(Ok(RunSummary { invocations }));
888        let f = classify(joined, Some(Duration::from_secs(45)));
889        assert_eq!(f.outcome, RunOutcome::Failure);
890        assert_eq!(f.cooldown, Some(Duration::from_secs(45)));
891    }
892
893    #[test]
894    fn classify_circuit_open_without_configured_cooldown_yields_none() {
895        // Defensive: a circuit-open run with no configured cooldown (zero)
896        // produces no delay rather than a spurious zero-length sleep.
897        let circuit_open_msg = faucet_core::FaucetError::CircuitOpen {
898            failures: 1,
899            cooldown: Duration::from_secs(10),
900        }
901        .to_string();
902        let invocations = vec![crate::executor::InvocationOutcome {
903            row_id: "r0".into(),
904            parent_record_key: None,
905            records_written: 0,
906            error: Some(circuit_open_msg),
907        }];
908        let joined = Ok(Ok(RunSummary { invocations }));
909        let f = classify(joined, None);
910        assert_eq!(f.outcome, RunOutcome::Failure);
911        assert!(f.cooldown.is_none());
912    }
913
914    #[test]
915    fn classify_no_cooldown_for_ordinary_failure() {
916        // A plain failing invocation must not trip the cooldown path even when a
917        // breaker cooldown is configured.
918        let joined = Ok(Ok(summary(1, 2)));
919        let f = classify(joined, Some(Duration::from_secs(30)));
920        assert_eq!(f.outcome, RunOutcome::Failure);
921        assert!(f.cooldown.is_none());
922    }
923
924    #[test]
925    fn run_span_carries_ordinal_and_times() {
926        let scheduled = Utc::now();
927        let tick = scheduled + chrono::Duration::seconds(3);
928        let span = run_span(7, scheduled, tick);
929        // The span exists and is enterable; field values are recorded on
930        // creation. We assert it has the expected metadata name.
931        assert_eq!(span.metadata().unwrap().name(), "faucet.schedule.run");
932    }
933
934    #[tokio::test]
935    async fn wait_for_run_returns_classified_outcome() {
936        let handle = tokio::spawn(async { Ok(summary(0, 1)) });
937        let mut running = Some(RunningRun {
938            handle,
939            started: Instant::now(),
940        });
941        let finished = wait_for_run(&mut running, None).await;
942        assert_eq!(finished.outcome, RunOutcome::Success);
943    }
944
945    #[tokio::test]
946    async fn spawn_run_times_out_into_internal_error() {
947        // The run "never finishes" (a long sleep) but the 1s timeout aborts it
948        // and maps to an Internal error mentioning run_timeout_secs.
949        let dir = tempfile::tempdir().unwrap();
950        let input = dir.path().join("in.csv");
951        let output = dir.path().join("out.jsonl");
952        std::fs::write(&input, "name\nx\n").unwrap();
953        // Build nodes from a tiny real config so the spawned future is genuine.
954        let yaml = format!(
955            "version: 1\npipeline:\n  source: {{ type: csv, config: {{ path: {input} }} }}\n  sink: {{ type: jsonl, config: {{ path: {output} }} }}\n",
956            input = input.display(),
957            output = output.display(),
958        );
959        let cfg = crate::config::parse_with_extension(&yaml, "yaml").unwrap();
960        let nodes = expand(&cfg).unwrap();
961        let auth = AuthCatalog::new();
962        let opts = make_opts(
963            "to",
964            &None,
965            &auth,
966            Utc::now().fixed_offset(),
967            &None,
968            &None,
969            #[cfg(feature = "lineage")]
970            &None,
971            #[cfg(feature = "lineage")]
972            &None,
973            #[cfg(feature = "notify")]
974            &None,
975            #[cfg(feature = "catalog")]
976            &None,
977        );
978        // A zero-ish timeout (1ns) virtually guarantees the timeout branch fires
979        // even though the pipeline is fast — the timeout races the spawn.
980        let handle = spawn_run(
981            nodes,
982            opts,
983            Some(Duration::from_nanos(1)),
984            run_span(1, Utc::now(), Utc::now()),
985        );
986        let joined = handle.await.unwrap();
987        // Either the run finished before the 1ns deadline (Ok) — unlikely — or
988        // it tripped the timeout into an Internal error. Accept both but assert
989        // the timeout message shape when it errors.
990        if let Err(CliError::Internal(msg)) = &joined {
991            assert!(msg.contains("run_timeout_secs"), "{msg}");
992        }
993    }
994
995    #[tokio::test]
996    async fn make_opts_disables_dry_run_limit_and_state_override() {
997        let auth = AuthCatalog::new();
998        let clock = Utc::now().fixed_offset();
999        let opts = make_opts(
1000            "p",
1001            &None,
1002            &auth,
1003            clock,
1004            &None,
1005            &None,
1006            #[cfg(feature = "lineage")]
1007            &None,
1008            #[cfg(feature = "lineage")]
1009            &None,
1010            #[cfg(feature = "notify")]
1011            &None,
1012            #[cfg(feature = "catalog")]
1013            &None,
1014        );
1015        assert_eq!(opts.pipeline_name, "p");
1016        assert!(!opts.dry_run);
1017        assert!(opts.limit.is_none());
1018        assert!(opts.state_path_override.is_none());
1019        assert!(opts.cancel.is_none());
1020        assert_eq!(opts.clock, clock);
1021    }
1022
1023    #[tokio::test]
1024    async fn graceful_shutdown_awaits_finished_run() {
1025        // A run that finishes immediately is awaited within the grace window.
1026        let c = compiled("cron: \"* * * * *\"\nshutdown_grace_secs: 5");
1027        let handle = tokio::spawn(async { Ok(summary(0, 1)) });
1028        let running = Some(RunningRun {
1029            handle,
1030            started: Instant::now(),
1031        });
1032        // Should return promptly without aborting (the run already completed).
1033        graceful_shutdown(running, c.shutdown_grace, "p").await;
1034    }
1035
1036    #[tokio::test]
1037    async fn graceful_shutdown_aborts_run_exceeding_grace() {
1038        // A run that never finishes is aborted once the (tiny) grace elapses.
1039        let handle = tokio::spawn(async {
1040            tokio::time::sleep(Duration::from_secs(3600)).await;
1041            Ok(summary(0, 1))
1042        });
1043        let running = Some(RunningRun {
1044            handle,
1045            started: Instant::now(),
1046        });
1047        // 50ms grace → the abort branch fires; the call must still return.
1048        graceful_shutdown(running, Duration::from_millis(50), "p").await;
1049    }
1050
1051    #[tokio::test]
1052    async fn graceful_shutdown_noop_when_idle() {
1053        // No in-flight run → returns immediately.
1054        graceful_shutdown(None, Duration::from_secs(1), "p").await;
1055    }
1056}