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    // Record the config snapshot for `faucet plan --diff` after a clean tick
439    // (best-effort; #374). Repeated identical ticks upsert harmlessly.
440    #[cfg(feature = "catalog")]
441    crate::catalog::snapshot::record_if_ok(
442        catalog.as_ref(),
443        pipeline_name,
444        crate::catalog::snapshot::on_error_str(execution),
445        nodes,
446        true,
447        chrono::Utc::now(),
448    )
449    .await;
450    Ok(())
451}
452
453/// The scheduling loop.
454#[allow(clippy::too_many_arguments)]
455async fn run_loop(
456    mut compiled: CompiledSchedule,
457    mut nodes: Vec<ExpandedNode>,
458    auth: AuthCatalog,
459    mut execution: Option<crate::config::ExecutionSpec>,
460    pipeline_name: String,
461    mut cron: String,
462    mut timezone: String,
463    mut resilience: Option<faucet_core::ResiliencePolicy>,
464    mut sla: Option<crate::sla::SlaSpec>,
465    path: std::path::PathBuf,
466    profile: Option<String>,
467    #[cfg(feature = "lineage")] lineage: Option<std::sync::Arc<faucet_lineage::LineageEmitter>>,
468    #[cfg(feature = "lineage")] lineage_cfg: Option<faucet_lineage::LineageConfig>,
469    #[cfg(feature = "notify")] notifier: Option<std::sync::Arc<crate::notify::Notifier>>,
470    #[cfg(feature = "catalog")] catalog: Option<crate::catalog::CatalogHandle>,
471) -> CliResult<()> {
472    let mut state = SchedulerState::new(&compiled);
473    // The circuit-breaker re-entry cooldown, if a breaker is configured. Used to
474    // delay the next tick after a run trips the breaker. Recomputed on reload.
475    let mut breaker_cooldown = resilience
476        .as_ref()
477        .and_then(|r| r.circuit_breaker)
478        .map(|cb| cb.cooldown);
479    let mut shutdown = Shutdown::new()?;
480    let mut reload = Reload::new()?;
481    let mut running: Option<RunningRun> = None;
482    let mut pending_scheduled_for: Option<DateTime<Utc>> = None;
483    let mut run_ordinal: u64 = 0;
484
485    let mut next_due = if compiled.start_immediately {
486        Utc::now()
487    } else {
488        compiled
489            .next_after(Utc::now())
490            .ok_or_else(|| CliError::Config("schedule: no upcoming occurrence".into()))?
491    };
492
493    // Startup banner: cron, timezone, and the next few firing times so an
494    // operator can confirm at a glance the schedule is configured correctly.
495    let upcoming: Vec<String> = {
496        let mut t = Utc::now();
497        let mut v = Vec::with_capacity(3);
498        while v.len() < 3 {
499            match compiled.next_after(t) {
500                Some(n) => {
501                    v.push(n.to_rfc3339());
502                    t = n;
503                }
504                None => break,
505            }
506        }
507        v
508    };
509    tracing::info!(
510        pipeline = %pipeline_name,
511        cron = %cron,
512        timezone = %timezone,
513        next_occurrences = ?upcoming,
514        "scheduler started (Ctrl-C / SIGTERM to stop)"
515    );
516
517    // Register HELP text and pre-emit the two run-state gauges at 0 so both
518    // series exist in `/metrics` from t=0 — the `metrics` exporter only renders
519    // a series after its first emission, and these gauges are otherwise first
520    // touched mid/post-run, leaving a pre-first-run scrape blind to them
521    // (#146 R NIT).
522    m::describe();
523    m::in_flight(&pipeline_name, 0);
524    m::consecutive_failures(&pipeline_name, 0);
525
526    loop {
527        let now = Utc::now();
528
529        if now >= next_due {
530            match state.on_tick(running.is_some()) {
531                TickAction::Dispatch => {
532                    run_ordinal += 1;
533                    let opts = make_opts(
534                        &pipeline_name,
535                        &execution,
536                        &auth,
537                        compiled.clock_at(next_due),
538                        &resilience,
539                        &sla,
540                        #[cfg(feature = "lineage")]
541                        &lineage,
542                        #[cfg(feature = "lineage")]
543                        &lineage_cfg,
544                        #[cfg(feature = "notify")]
545                        &notifier,
546                        #[cfg(feature = "catalog")]
547                        &catalog,
548                    );
549                    let span = run_span(run_ordinal, next_due, now);
550                    let handle = spawn_run(nodes.clone(), opts, compiled.run_timeout, span);
551                    m::in_flight(&pipeline_name, 1);
552                    m::last_run_started(&pipeline_name, now);
553                    m::lateness(&pipeline_name, now - next_due);
554                    tracing::info!(pipeline = %pipeline_name, run_ordinal, scheduled_for = %next_due, "run started");
555                    running = Some(RunningRun {
556                        handle,
557                        started: Instant::now(),
558                    });
559                }
560                TickAction::Skip => {
561                    m::overlap(&pipeline_name, "skip");
562                    m::run_outcome(&pipeline_name, "skipped");
563                    tracing::warn!(pipeline = %pipeline_name, scheduled_for = %next_due, "tick skipped — previous run still in progress");
564                }
565                TickAction::Queue => {
566                    m::overlap(&pipeline_name, "queue");
567                    if pending_scheduled_for.is_none() {
568                        pending_scheduled_for = Some(next_due);
569                    }
570                    tracing::warn!(pipeline = %pipeline_name, scheduled_for = %next_due, "tick queued — will run after current run finishes");
571                }
572                TickAction::ForbidAbort => {
573                    m::overlap(&pipeline_name, "forbid");
574                    // A prior `Dispatch` set the in-flight gauge to 1; reset it
575                    // before we bail so `/metrics` doesn't read a stuck 1 after
576                    // the scheduler exits (#146 R LOW).
577                    m::in_flight(&pipeline_name, 0);
578                    return Err(CliError::ScheduleOverlapForbidden);
579                }
580            }
581            // Advance from the tick that just fired (`next_due`), not from the
582            // wall clock — so a sub-minute occurrence isn't skipped just because
583            // dispatch latency pushed `now` past it. A long backlog (suspension)
584            // is collapsed to a single catch-up inside `next_due_after_tick`.
585            next_due = match compiled.next_due_after_tick(next_due, Utc::now()) {
586                Some(t) => t,
587                None => {
588                    tracing::info!(pipeline = %pipeline_name, "no further scheduled occurrences; exiting");
589                    return Ok(());
590                }
591            };
592        }
593
594        let now2 = Utc::now();
595        m::heartbeat(&pipeline_name, now2);
596        m::next_tick(&pipeline_name, next_due);
597        let chunk = (next_due - now2)
598            .to_std()
599            .unwrap_or(Duration::ZERO)
600            .min(MAX_SLEEP);
601
602        tokio::select! {
603            biased;
604
605            _ = shutdown.recv() => {
606                tracing::info!(pipeline = %pipeline_name, "shutdown signal received; draining in-flight run");
607                graceful_shutdown(running.take(), compiled.shutdown_grace, &pipeline_name).await;
608                // Flush any buffered OTLP telemetry after the final run drains
609                // (no-op without the `otel` feature).
610                faucet_core::shutdown_otel();
611                return Ok(());
612            }
613
614            finished = wait_for_run(&mut running, breaker_cooldown) => {
615                let mut finished = finished;
616                if let Some(rr) = running.take() {
617                    finished.duration = rr.started.elapsed();
618                }
619                m::in_flight(&pipeline_name, 0);
620                let done_at = Utc::now();
621
622                // Circuit-breaker re-entry cooldown: if the run tripped the
623                // breaker, push the next tick out so AT LEAST `cooldown` elapses
624                // before re-entry. This composes with the cron schedule — it
625                // only delays `next_due` when the cooldown would land later than
626                // the next scheduled occurrence. The actual wait happens in the
627                // existing cancellation-aware `select!` below, so SIGTERM still
628                // interrupts it.
629                if let Some(d) = finished.cooldown
630                    && let Ok(delta) = chrono::Duration::from_std(d)
631                {
632                    let resume = done_at + delta;
633                    if resume > next_due {
634                        next_due = resume;
635                    }
636                    tracing::warn!(
637                        pipeline = %pipeline_name,
638                        cooldown_secs = d.as_secs(),
639                        next_due = %next_due,
640                        "circuit breaker opened; delaying re-entry by cooldown"
641                    );
642                }
643                m::last_run_completed(&pipeline_name, done_at);
644                m::last_run_duration(&pipeline_name, finished.duration);
645                m::run_outcome(&pipeline_name, match finished.outcome {
646                    RunOutcome::Success => "ok",
647                    RunOutcome::Failure => "err",
648                });
649                match finished.outcome {
650                    RunOutcome::Success => tracing::info!(
651                        pipeline = %pipeline_name, secs = finished.duration.as_secs_f64(), "run completed"
652                    ),
653                    RunOutcome::Failure => tracing::error!(
654                        pipeline = %pipeline_name, detail = finished.detail.as_deref().unwrap_or("unknown"),
655                        "run failed"
656                    ),
657                }
658
659                let after = state.on_run_finished(finished.outcome);
660                m::consecutive_failures(&pipeline_name, state.consecutive_failures());
661                match after {
662                    AfterRun::ExitOk => {
663                        tracing::info!(pipeline = %pipeline_name, "max_runs reached; exiting");
664                        return Ok(());
665                    }
666                    AfterRun::ExitFailure { consecutive } => {
667                        #[cfg(feature = "notify")]
668                        if let Some(n) = &notifier {
669                            n.emit(crate::notify::NotifyEvent::scheduler_stuck(
670                                &pipeline_name,
671                                format!(
672                                    "scheduler exiting after {consecutive} consecutive failures"
673                                ),
674                            ))
675                            .await;
676                        }
677                        return Err(CliError::PipelineHadFailures { count: consecutive as usize });
678                    }
679                    AfterRun::Continue { dispatch_pending } => {
680                        if dispatch_pending {
681                            run_ordinal += 1;
682                            let sched_for = pending_scheduled_for.take().unwrap_or(done_at);
683                            let opts = make_opts(
684                                &pipeline_name,
685                                &execution,
686                                &auth,
687                                compiled.clock_at(sched_for),
688                                &resilience,
689                                &sla,
690                                #[cfg(feature = "lineage")]
691                                &lineage,
692                                #[cfg(feature = "lineage")]
693                                &lineage_cfg,
694                                #[cfg(feature = "notify")]
695                                &notifier,
696                                #[cfg(feature = "catalog")]
697                                &catalog,
698                            );
699                            let span = run_span(run_ordinal, sched_for, done_at);
700                            let handle = spawn_run(nodes.clone(), opts, compiled.run_timeout, span);
701                            m::in_flight(&pipeline_name, 1);
702                            m::last_run_started(&pipeline_name, done_at);
703                            m::lateness(&pipeline_name, done_at - sched_for);
704                            tracing::info!(pipeline = %pipeline_name, run_ordinal, scheduled_for = %sched_for, "queued run started");
705                            running = Some(RunningRun { handle, started: Instant::now() });
706                        }
707                    }
708                }
709            }
710
711            _ = reload.recv() => {
712                // Hot config reload (SIGHUP): re-read + re-validate the config.
713                // On success, atomically swap the config-derived state and
714                // recompute the next tick; the scheduler's run counters and any
715                // in-flight run are untouched. On failure, keep the old config.
716                match reload_bundle(&path, profile.as_deref()).await {
717                    Ok(b) => {
718                        compiled = b.compiled;
719                        nodes = b.nodes;
720                        execution = b.execution;
721                        resilience = b.resilience;
722                        sla = b.sla;
723                        cron = b.cron;
724                        timezone = b.timezone;
725                        breaker_cooldown = resilience
726                            .as_ref()
727                            .and_then(|r| r.circuit_breaker)
728                            .map(|cb| cb.cooldown);
729                        next_due = if compiled.start_immediately {
730                            Utc::now()
731                        } else {
732                            compiled.next_after(Utc::now()).unwrap_or(next_due)
733                        };
734                        m::reload(&pipeline_name, "ok");
735                        tracing::info!(
736                            pipeline = %pipeline_name, cron = %cron, timezone = %timezone,
737                            next_due = %next_due, "config reloaded (SIGHUP)"
738                        );
739                    }
740                    Err(e) => {
741                        m::reload(&pipeline_name, "error");
742                        tracing::error!(
743                            pipeline = %pipeline_name, error = %e,
744                            "config reload failed; keeping the previous config"
745                        );
746                    }
747                }
748            }
749
750            _ = tokio::time::sleep(chunk) => { /* re-loop: re-read wall clock */ }
751        }
752    }
753}
754
755/// Await the in-flight run (or never resolve when idle). Returns the classified
756/// outcome; the caller fills in `duration` from the `RunningRun`.
757async fn wait_for_run(
758    running: &mut Option<RunningRun>,
759    breaker_cooldown: Option<Duration>,
760) -> RunFinished {
761    match running {
762        Some(rr) => classify((&mut rr.handle).await, breaker_cooldown),
763        None => std::future::pending().await,
764    }
765}
766
767/// On shutdown, await the in-flight run up to `grace`, then abort it.
768async fn graceful_shutdown(running: Option<RunningRun>, grace: Duration, pipeline_name: &str) {
769    if let Some(mut rr) = running {
770        match tokio::time::timeout(grace, &mut rr.handle).await {
771            Ok(_) => {
772                tracing::info!(pipeline = %pipeline_name, "in-flight run finished during shutdown grace")
773            }
774            Err(_) => {
775                rr.handle.abort();
776                tracing::warn!(
777                    pipeline = %pipeline_name,
778                    grace_secs = grace.as_secs(),
779                    "in-flight run exceeded shutdown grace; aborted (partial sink state possible; bookmark preserved for the next run)"
780                );
781            }
782        }
783        m::in_flight(pipeline_name, 0);
784    }
785}
786
787#[cfg(test)]
788mod tests {
789    use super::*;
790    use crate::schedule::spec::ScheduleSpec;
791
792    fn compiled(yaml: &str) -> CompiledSchedule {
793        let spec: ScheduleSpec = serde_yaml::from_str(yaml).unwrap();
794        CompiledSchedule::compile(&spec).unwrap()
795    }
796
797    // A valid scheduled config reloads into a fresh bundle; a config that lost
798    // its `schedule:` block (or is otherwise invalid) is rejected so the loop
799    // can keep the previous config.
800    #[tokio::test]
801    async fn reload_bundle_validates_and_builds() {
802        let dir = tempfile::tempdir().unwrap();
803        let good = dir.path().join("good.yaml");
804        std::fs::write(
805            &good,
806            "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",
807        )
808        .unwrap();
809        let b = reload_bundle(&good, None)
810            .await
811            .expect("valid config reloads");
812        assert_eq!(b.cron, "*/5 * * * *");
813        assert_eq!(b.timezone, "UTC");
814        assert_eq!(b.nodes.len(), 1);
815
816        // Missing `schedule:` → rejected.
817        let bad = dir.path().join("bad.yaml");
818        std::fs::write(
819            &bad,
820            "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",
821        )
822        .unwrap();
823        assert!(reload_bundle(&bad, None).await.is_err());
824    }
825
826    fn summary(failures: usize, total: usize) -> RunSummary {
827        let mut invocations = Vec::new();
828        for i in 0..total {
829            invocations.push(crate::executor::InvocationOutcome {
830                row_id: format!("r{i}"),
831                parent_record_key: None,
832                records_written: if i < failures { 0 } else { 3 },
833                error: if i < failures {
834                    Some("boom".into())
835                } else {
836                    None
837                },
838                metrics: None,
839            });
840        }
841        RunSummary { invocations }
842    }
843
844    #[test]
845    fn classify_success_when_no_failures() {
846        let joined = Ok(Ok(summary(0, 2)));
847        let f = classify(joined, None);
848        assert_eq!(f.outcome, RunOutcome::Success);
849        assert!(f.detail.is_none());
850        assert!(f.cooldown.is_none());
851    }
852
853    #[test]
854    fn classify_failure_when_some_invocations_failed() {
855        let joined = Ok(Ok(summary(2, 5)));
856        let f = classify(joined, None);
857        assert_eq!(f.outcome, RunOutcome::Failure);
858        assert_eq!(f.detail.as_deref(), Some("2 invocation(s) failed"));
859        assert!(f.cooldown.is_none());
860    }
861
862    #[test]
863    fn classify_failure_when_run_errored() {
864        let joined: Result<CliResult<RunSummary>, tokio::task::JoinError> =
865            Ok(Err(CliError::Internal("disk full".into())));
866        let f = classify(joined, None);
867        assert_eq!(f.outcome, RunOutcome::Failure);
868        assert!(f.detail.as_deref().unwrap().contains("disk full"));
869    }
870
871    #[tokio::test]
872    async fn classify_failure_when_task_panicked() {
873        // Spawn a task that panics, then join it to obtain a real JoinError.
874        let handle = tokio::spawn(async { panic!("kaboom") });
875        let joined: Result<CliResult<RunSummary>, tokio::task::JoinError> = handle.await.map(Ok);
876        let f = classify(joined, None);
877        assert_eq!(f.outcome, RunOutcome::Failure);
878        assert!(
879            f.detail.as_deref().unwrap().contains("panicked"),
880            "{:?}",
881            f.detail
882        );
883    }
884
885    #[test]
886    fn classify_recovers_cooldown_from_circuit_open_invocation() {
887        // An invocation whose error is the flattened CircuitOpen Display string
888        // is detected; the cooldown is recovered from the configured policy.
889        let circuit_open_msg = faucet_core::FaucetError::CircuitOpen {
890            failures: 3,
891            cooldown: Duration::from_secs(60),
892        }
893        .to_string();
894        let invocations = vec![crate::executor::InvocationOutcome {
895            row_id: "r0".into(),
896            parent_record_key: None,
897            records_written: 0,
898            error: Some(circuit_open_msg),
899            metrics: None,
900        }];
901        let joined = Ok(Ok(RunSummary { invocations }));
902        let f = classify(joined, Some(Duration::from_secs(45)));
903        assert_eq!(f.outcome, RunOutcome::Failure);
904        assert_eq!(f.cooldown, Some(Duration::from_secs(45)));
905    }
906
907    #[test]
908    fn classify_circuit_open_without_configured_cooldown_yields_none() {
909        // Defensive: a circuit-open run with no configured cooldown (zero)
910        // produces no delay rather than a spurious zero-length sleep.
911        let circuit_open_msg = faucet_core::FaucetError::CircuitOpen {
912            failures: 1,
913            cooldown: Duration::from_secs(10),
914        }
915        .to_string();
916        let invocations = vec![crate::executor::InvocationOutcome {
917            row_id: "r0".into(),
918            parent_record_key: None,
919            records_written: 0,
920            error: Some(circuit_open_msg),
921            metrics: None,
922        }];
923        let joined = Ok(Ok(RunSummary { invocations }));
924        let f = classify(joined, None);
925        assert_eq!(f.outcome, RunOutcome::Failure);
926        assert!(f.cooldown.is_none());
927    }
928
929    #[test]
930    fn classify_no_cooldown_for_ordinary_failure() {
931        // A plain failing invocation must not trip the cooldown path even when a
932        // breaker cooldown is configured.
933        let joined = Ok(Ok(summary(1, 2)));
934        let f = classify(joined, Some(Duration::from_secs(30)));
935        assert_eq!(f.outcome, RunOutcome::Failure);
936        assert!(f.cooldown.is_none());
937    }
938
939    #[test]
940    fn run_span_carries_ordinal_and_times() {
941        let scheduled = Utc::now();
942        let tick = scheduled + chrono::Duration::seconds(3);
943        let span = run_span(7, scheduled, tick);
944        // The span exists and is enterable; field values are recorded on
945        // creation. We assert it has the expected metadata name.
946        assert_eq!(span.metadata().unwrap().name(), "faucet.schedule.run");
947    }
948
949    #[tokio::test]
950    async fn wait_for_run_returns_classified_outcome() {
951        let handle = tokio::spawn(async { Ok(summary(0, 1)) });
952        let mut running = Some(RunningRun {
953            handle,
954            started: Instant::now(),
955        });
956        let finished = wait_for_run(&mut running, None).await;
957        assert_eq!(finished.outcome, RunOutcome::Success);
958    }
959
960    #[tokio::test]
961    async fn spawn_run_times_out_into_internal_error() {
962        // The run "never finishes" (a long sleep) but the 1s timeout aborts it
963        // and maps to an Internal error mentioning run_timeout_secs.
964        let dir = tempfile::tempdir().unwrap();
965        let input = dir.path().join("in.csv");
966        let output = dir.path().join("out.jsonl");
967        std::fs::write(&input, "name\nx\n").unwrap();
968        // Build nodes from a tiny real config so the spawned future is genuine.
969        let yaml = format!(
970            "version: 1\npipeline:\n  source: {{ type: csv, config: {{ path: {input} }} }}\n  sink: {{ type: jsonl, config: {{ path: {output} }} }}\n",
971            input = input.display(),
972            output = output.display(),
973        );
974        let cfg = crate::config::parse_with_extension(&yaml, "yaml").unwrap();
975        let nodes = expand(&cfg).unwrap();
976        let auth = AuthCatalog::new();
977        let opts = make_opts(
978            "to",
979            &None,
980            &auth,
981            Utc::now().fixed_offset(),
982            &None,
983            &None,
984            #[cfg(feature = "lineage")]
985            &None,
986            #[cfg(feature = "lineage")]
987            &None,
988            #[cfg(feature = "notify")]
989            &None,
990            #[cfg(feature = "catalog")]
991            &None,
992        );
993        // A zero-ish timeout (1ns) virtually guarantees the timeout branch fires
994        // even though the pipeline is fast — the timeout races the spawn.
995        let handle = spawn_run(
996            nodes,
997            opts,
998            Some(Duration::from_nanos(1)),
999            run_span(1, Utc::now(), Utc::now()),
1000        );
1001        let joined = handle.await.unwrap();
1002        // Either the run finished before the 1ns deadline (Ok) — unlikely — or
1003        // it tripped the timeout into an Internal error. Accept both but assert
1004        // the timeout message shape when it errors.
1005        if let Err(CliError::Internal(msg)) = &joined {
1006            assert!(msg.contains("run_timeout_secs"), "{msg}");
1007        }
1008    }
1009
1010    #[tokio::test]
1011    async fn make_opts_disables_dry_run_limit_and_state_override() {
1012        let auth = AuthCatalog::new();
1013        let clock = Utc::now().fixed_offset();
1014        let opts = make_opts(
1015            "p",
1016            &None,
1017            &auth,
1018            clock,
1019            &None,
1020            &None,
1021            #[cfg(feature = "lineage")]
1022            &None,
1023            #[cfg(feature = "lineage")]
1024            &None,
1025            #[cfg(feature = "notify")]
1026            &None,
1027            #[cfg(feature = "catalog")]
1028            &None,
1029        );
1030        assert_eq!(opts.pipeline_name, "p");
1031        assert!(!opts.dry_run);
1032        assert!(opts.limit.is_none());
1033        assert!(opts.state_path_override.is_none());
1034        assert!(opts.cancel.is_none());
1035        assert_eq!(opts.clock, clock);
1036    }
1037
1038    #[tokio::test]
1039    async fn graceful_shutdown_awaits_finished_run() {
1040        // A run that finishes immediately is awaited within the grace window.
1041        let c = compiled("cron: \"* * * * *\"\nshutdown_grace_secs: 5");
1042        let handle = tokio::spawn(async { Ok(summary(0, 1)) });
1043        let running = Some(RunningRun {
1044            handle,
1045            started: Instant::now(),
1046        });
1047        // Should return promptly without aborting (the run already completed).
1048        graceful_shutdown(running, c.shutdown_grace, "p").await;
1049    }
1050
1051    #[tokio::test]
1052    async fn graceful_shutdown_aborts_run_exceeding_grace() {
1053        // A run that never finishes is aborted once the (tiny) grace elapses.
1054        let handle = tokio::spawn(async {
1055            tokio::time::sleep(Duration::from_secs(3600)).await;
1056            Ok(summary(0, 1))
1057        });
1058        let running = Some(RunningRun {
1059            handle,
1060            started: Instant::now(),
1061        });
1062        // 50ms grace → the abort branch fires; the call must still return.
1063        graceful_shutdown(running, Duration::from_millis(50), "p").await;
1064    }
1065
1066    #[tokio::test]
1067    async fn graceful_shutdown_noop_when_idle() {
1068        // No in-flight run → returns immediately.
1069        graceful_shutdown(None, Duration::from_secs(1), "p").await;
1070    }
1071}