Skip to main content

schedr_master/scheduler/
backfill.rs

1//! Creating a backfill (decisions 363, 364, 400-404; see archive/PROJECT.md, Runs: manual
2//! runs, backfill and pausing): one `backfill` run per fire time of the range with no
3//! successful, queued or running run (every one with `--all`), each for one schedule period,
4//! all created at once with the backfill, queued oldest first behind the other kinds. A paused
5//! DAG's backfill runs start too (decision 401).
6
7use jiff::Timestamp;
8use schedr_db::backfills::NewBackfill;
9use schedr_model::{DagId, RunKind, RunState};
10
11use super::{Scheduler, SchedulerError, new_run, run_params};
12use crate::fire_times::FireTimes;
13use crate::planning::{Plan, RunTimes};
14use crate::quiet::WakeReason;
15
16/// The most fire times a backfill's range may have unless `[backfill] max_runs` says
17/// otherwise, those already run included: a year of a daily DAG, a month of an hourly one.
18pub const DEFAULT_MAX_RUNS: u32 = 1000;
19
20/// What a backfill is asked for.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub struct BackfillAsk<'a> {
23    /// The range's first moment.
24    pub from: Timestamp,
25    /// Its last moment; now if not given (a later one ends at now).
26    pub to: Option<Timestamp>,
27    /// A run for every fire time, not only those missing one (`--all`).
28    pub all: bool,
29    /// The runs' parameters, over the DAG's defaults, checked once.
30    pub params: Option<&'a serde_json::Map<String, serde_json::Value>>,
31    /// Count only: nothing is created (`--dry-run`).
32    pub dry_run: bool,
33}
34
35/// What a backfill found, or created.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct BackfillCount {
38    /// The fire times of its range.
39    pub fire_times: u32,
40    /// How many got a run (or would).
41    pub created: u32,
42    /// How many were skipped: a run of theirs succeeded or hasn't finished.
43    pub skipped: u32,
44    /// The backfill's ID; `None` for a dry run or one with nothing to create.
45    pub backfill_id: Option<String>,
46}
47
48impl Scheduler {
49    /// Creates a backfill of `dag_id` as `ask` says, with the ID `id` (a command's: a command
50    /// applied again finds it stored), its runs by `user`, its range of at most `max_runs` fire
51    /// times.
52    ///
53    /// # Errors
54    ///
55    /// [`SchedulerError::NotRunnable`] or [`SchedulerError::Held`] as for a manual run;
56    /// [`SchedulerError::Backfill`] for a DAG without fire times, a range with none or more
57    /// than `max_runs` fire times, a range ending before it starts; [`SchedulerError::Params`]
58    /// for parameters refused; what storing it fails with.
59    pub async fn backfill(
60        &self,
61        id: &str,
62        dag_id: &DagId,
63        ask: BackfillAsk<'_>,
64        (user, max_runs): (&str, u32),
65        now: Timestamp,
66    ) -> Result<BackfillCount, SchedulerError> {
67        let refused = |why: String| SchedulerError::Backfill {
68            dag_id: dag_id.clone(),
69            why,
70        };
71        let active = self
72            .db
73            .active_dags()
74            .await?
75            .into_iter()
76            .find(|d| &d.dag.id == dag_id)
77            .ok_or_else(|| SchedulerError::NotRunnable(dag_id.clone()))?;
78        if let Some(held) = active.held {
79            return Err(SchedulerError::Held {
80                dag_id: dag_id.clone(),
81                held,
82            });
83        }
84        let fire_times =
85            FireTimes::new(&active.dag.trigger).map_err(|error| SchedulerError::FireTimes {
86                dag_id: dag_id.clone(),
87                error,
88            })?;
89        if matches!(fire_times, FireTimes::None) {
90            return Err(refused(
91                "its trigger has no fire times (a backfill takes `Cron`, `Every` or `Once`); \
92                 start a run with `schedr runs trigger` instead"
93                    .to_owned(),
94            ));
95        }
96        let to = ask.to.map_or(now, |to| to.min(now));
97        if to < ask.from {
98            return Err(refused(format!(
99                "the range ends ({to}) before it starts ({}); a range ending later than now ends now",
100                ask.from
101            )));
102        }
103        let times = fire_times_in(&fire_times, ask.from, to, max_runs);
104        let Some(times) = times else {
105            return Err(refused(format!(
106                "its range has more than {max_runs} fire times, over `[backfill] max_runs`: \
107                 split it"
108            )));
109        };
110        if times.is_empty() {
111            return Err(refused(format!("no fire time from {} to {to}", ask.from)));
112        }
113        // Checked once, before anything is created.
114        let params = run_params(&active, ask.params)?;
115        let covered = if ask.all {
116            std::collections::BTreeSet::new()
117        } else {
118            self.db.covered_times(dag_id, ask.from, to).await?
119        };
120        let missing: Vec<Timestamp> = times
121            .iter()
122            .copied()
123            .filter(|t| !covered.contains(t))
124            .collect();
125        let count = |backfill_id| BackfillCount {
126            fire_times: u32::try_from(times.len()).unwrap_or(u32::MAX),
127            created: u32::try_from(missing.len()).unwrap_or(u32::MAX),
128            skipped: u32::try_from(times.len() - missing.len()).unwrap_or(u32::MAX),
129            backfill_id,
130        };
131        if ask.dry_run || missing.is_empty() {
132            return Ok(count(None));
133        }
134        let backfill = NewBackfill {
135            id,
136            dag_id,
137            range_from: ask.from,
138            range_to: to,
139            all_fire_times: ask.all,
140            requested_by: user,
141            created_at: now,
142            fire_times: count(None).fire_times,
143            created_runs: count(None).created,
144        };
145        self.store(
146            &active,
147            &fire_times,
148            &backfill,
149            (&times, &missing, &params),
150            now,
151        )
152        .await?;
153        Ok(count(Some(id.to_owned())))
154    }
155
156    /// Stores `backfill` and a queued run per `missing` fire time (of the range's `times`), in
157    /// one transaction, then starts those that fit `max_active_runs`.
158    async fn store(
159        &self,
160        active: &schedr_db::runs::ActiveDag,
161        fire_times: &FireTimes,
162        backfill: &NewBackfill<'_>,
163        (times, missing, params): (&[Timestamp], &[Timestamp], &serde_json::Value),
164        now: Timestamp,
165    ) -> Result<(), SchedulerError> {
166        let plan = Plan {
167            dag: &active.dag,
168            fire_times,
169            first_seen: active.first_seen,
170            limits: self.plan_limits,
171        };
172        let sinces: std::collections::BTreeMap<Timestamp, Timestamp> = times
173            .iter()
174            .copied()
175            .zip(plan.fire_time_sinces(times))
176            .collect();
177        let db = self.db.clone();
178        // The backfill and its runs together: all of them or none.
179        Box::pin(db.atomically(async {
180            if !self.db.insert_backfill(backfill).await? {
181                // Created by this command already (its round failed after the commit).
182                return Ok::<(), SchedulerError>(());
183            }
184            for planned_for in missing {
185                let window = RunTimes {
186                    planned_for: *planned_for,
187                    since: sinces
188                        .get(planned_for)
189                        .copied()
190                        .unwrap_or_else(|| plan.fire_time_since(*planned_for)),
191                };
192                let by = backfill.requested_by;
193                let mut new = new_run(active, RunKind::Backfill, window, now, by, params);
194                new.state = RunState::Queued;
195                new.backfill_id = Some(backfill.id);
196                let run_id = uuid::Uuid::now_v7().to_string();
197                self.db.insert_run_as(&run_id, &new).await?;
198            }
199            Ok(())
200        }))
201        .await?;
202        self.wakes.wake(backfill.dag_id, WakeReason::RunQueued);
203        let running = self.db.running_count(backfill.dag_id).await?;
204        let queued = self.db.queued_runs(backfill.dag_id).await?;
205        self.start_queued(&queued, &plan, running, now).await?;
206        Ok(())
207    }
208}
209
210/// The fire times in `[from, to]`, oldest first; `None` if there are more than `max`.
211fn fire_times_in(
212    fire_times: &FireTimes,
213    from: Timestamp,
214    to: Timestamp,
215    max: u32,
216) -> Option<Vec<Timestamp>> {
217    fire_times.between(from, to, usize::try_from(max).unwrap_or(usize::MAX))
218}