Skip to main content

schedr_master/
planning.rs

1//! The rules for run times and new runs (see archive/PROJECT.md, Native API: run time semantics,
2//! and Runs: manual runs, backfill and pausing).
3//!
4//! - A run on a **fire time** covers one schedule period: `since` is the previous fire time,
5//!   or `initial_since` on the DAG's first fire time at or after `start`.
6//! - A **manual run** not on a fire time covers what happened since the nearest earlier run
7//!   of any kind.
8//! - The **scheduler** creates runs for fire times in `(last scheduled run, now]`, from `start`
9//!   (the moment the DAG was first stored, without one) up to `end`. With `catchup` off only
10//!   the most recent such fire time gets a run; with it on every one does, in order. Either
11//!   way at most `max_active_runs` runs run at a time; a fire time that finds no place is
12//!   missed, and the same rules decide when a place frees up.
13//! - **Queued runs** (manual, chained, event, backfill) take the places left: manual, chained
14//!   and event runs first, then backfill, oldest first within each.
15
16use std::collections::BTreeSet;
17
18use jiff::{SignedDuration, Timestamp};
19use schedr_db::runs::QueuedRun;
20use schedr_model::{Dag, RunKind};
21
22use crate::fire_times::FireTimes;
23
24#[cfg(test)]
25mod tests;
26
27/// How far in the future `--for` may be, for clock skew between the CLI and the master.
28pub const FOR_TOLERANCE: SignedDuration = SignedDuration::from_mins(1);
29
30/// The most runs the scheduler creates for one DAG in one pass (a `catchup` backlog with no
31/// `max_active_runs` limit continues in the next pass).
32pub const MAX_RUNS_PER_PASS: usize = 100;
33
34/// A run's time and window: it covers `(since, planned_for]`.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct RunTimes {
37    /// The moment the run is for.
38    pub planned_for: Timestamp,
39    /// The start of its window.
40    pub since: Timestamp,
41}
42
43/// A manual run that can't be created.
44#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
45pub enum ManualRunError {
46    /// `--for` is in the future.
47    #[error("`--for` must not be in the future ({planned_for} is after now, {now})")]
48    InFuture {
49        /// The requested time.
50        planned_for: Timestamp,
51        /// The master's clock.
52        now: Timestamp,
53    },
54}
55
56/// A DAG's time trigger with what its rules need.
57#[derive(Debug, Clone)]
58pub struct Plan<'a> {
59    /// The DAG.
60    pub dag: &'a Dag,
61    /// Its fire times.
62    pub fire_times: &'a FireTimes,
63    /// When the master first stored it (its start, without `start`).
64    pub first_seen: Timestamp,
65    /// How much it may create at once, and how far ahead a `--for` may be.
66    pub limits: PlanLimits,
67}
68
69/// A plan's bounds (decision 493).
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub struct PlanLimits {
72    /// The most runs one pass creates for the DAG (`SCHEDR_HIDDEN__MASTER__RUNS_PER_PLANNING_PASS`).
73    pub runs_per_pass: usize,
74    /// How far ahead of now `--for` may be (`SCHEDR_HIDDEN__MASTER__FOR_FUTURE_TOLERANCE`).
75    pub for_tolerance: SignedDuration,
76}
77
78impl Default for PlanLimits {
79    /// [`MAX_RUNS_PER_PASS`] and [`FOR_TOLERANCE`].
80    fn default() -> Self {
81        Self {
82            runs_per_pass: MAX_RUNS_PER_PASS,
83            for_tolerance: FOR_TOLERANCE,
84        }
85    }
86}
87
88impl Plan<'_> {
89    /// The moment scheduled runs start from: `start`, or when the DAG was first stored.
90    #[must_use]
91    pub fn effective_start(&self) -> Timestamp {
92        self.dag.trigger.start().unwrap_or(self.first_seen)
93    }
94
95    /// The DAG's next fire time after `now` (from its start, if that is later), within its
96    /// end; `None` when it has no more.
97    #[must_use]
98    pub fn next_fire_after(&self, now: Timestamp) -> Option<Timestamp> {
99        let start = self.effective_start();
100        let next = if start > now {
101            self.fire_times.next_at_or_after(start)
102        } else {
103            self.fire_times.next_after(now)
104        };
105        next.filter(|t| self.dag.trigger.end().is_none_or(|end| *t <= end))
106    }
107
108    /// The window of a run on a fire time: one schedule period.
109    #[must_use]
110    pub fn fire_time_since(&self, planned_for: Timestamp) -> Timestamp {
111        if let Some(initial) = self.dag.initial_since
112            && self.fire_times.next_at_or_after(self.effective_start()) == Some(planned_for)
113        {
114            return initial;
115        }
116        self.fire_times
117            .previous_before(planned_for)
118            .or(self.dag.initial_since)
119            .unwrap_or(planned_for)
120    }
121
122    /// [`Self::fire_time_since`] of each of `times`, consecutive fire times oldest first (a
123    /// backfill's range): each window starts at the fire time before it, so the range costs
124    /// one lookup, not one per fire time, which near a daylight-saving change walks hours of a
125    /// sub-minute cron's matches each (B199).
126    #[must_use]
127    pub fn fire_time_sinces(&self, times: &[Timestamp]) -> Vec<Timestamp> {
128        let first_fire = self
129            .dag
130            .initial_since
131            .and_then(|_| self.fire_times.next_at_or_after(self.effective_start()));
132        times
133            .iter()
134            .enumerate()
135            .map(|(i, t)| match (self.dag.initial_since, i.checked_sub(1)) {
136                (Some(initial), _) if first_fire == Some(*t) => initial,
137                (_, Some(before)) => times[before],
138                (_, None) => self.fire_time_since(*t),
139            })
140            .collect()
141    }
142
143    /// The times of a manual run: for `requested` (`--for`) or `now`. On a fire time it gets
144    /// one schedule period; otherwise it covers what happened since `nearest_earlier` (the
145    /// `planned_for` of the nearest earlier run of any kind, before [`manual_planned_for`]),
146    /// else since `initial_since`, else since the previous fire time; with none of these its
147    /// window is empty.
148    ///
149    /// # Errors
150    ///
151    /// [`ManualRunError::InFuture`] if `requested` is after now (beyond its `for_tolerance`).
152    pub fn manual_times(
153        &self,
154        requested: Option<Timestamp>,
155        now: Timestamp,
156        nearest_earlier: Option<Timestamp>,
157    ) -> Result<RunTimes, ManualRunError> {
158        let planned_for = manual_planned_for(requested, now);
159        if now
160            .checked_add(self.limits.for_tolerance)
161            .is_ok_and(|limit| planned_for > limit)
162        {
163            return Err(ManualRunError::InFuture { planned_for, now });
164        }
165        let since = if self.fire_times.is_fire_time(planned_for) {
166            self.fire_time_since(planned_for)
167        } else {
168            nearest_earlier
169                .or(self.dag.initial_since)
170                .or_else(|| self.fire_times.previous_before(planned_for))
171                .unwrap_or(planned_for)
172        };
173        Ok(RunTimes { planned_for, since })
174    }
175
176    /// The scheduled runs to create at `now`, given the latest `planned_for` of the DAG's
177    /// scheduled runs and how many of its runs are running. A paused DAG creates none (its
178    /// fire times are missed); the caller checks that.
179    #[must_use]
180    pub fn scheduled_runs(
181        &self,
182        last_scheduled: Option<Timestamp>,
183        running: u32,
184        now: Timestamp,
185    ) -> Vec<RunTimes> {
186        self.scheduled_runs_except(last_scheduled, running, now, &BTreeSet::new())
187    }
188
189    /// As [`Self::scheduled_runs`], leaving out the fire times in `covered`: those with a
190    /// successful, queued or running run of another kind (a backfill's, a manual one), which
191    /// get no scheduled run and take no place. With `catchup` the ones after them follow.
192    #[must_use]
193    pub fn scheduled_runs_except(
194        &self,
195        last_scheduled: Option<Timestamp>,
196        running: u32,
197        now: Timestamp,
198        covered: &BTreeSet<Timestamp>,
199    ) -> Vec<RunTimes> {
200        let free = self.free_places(running).min(self.limits.runs_per_pass);
201        self.due_times(last_scheduled, free, now, covered)
202            .into_iter()
203            .map(|planned_for| RunTimes {
204                planned_for,
205                since: self.fire_time_since(planned_for),
206            })
207            .collect()
208    }
209
210    /// The first fire time still due at `now` after `last_scheduled`, whatever the places
211    /// free, leaving out `covered` (decision 485: the scheduler visits the DAG again while
212    /// one waits).
213    #[must_use]
214    pub fn first_waiting(
215        &self,
216        last_scheduled: Option<Timestamp>,
217        now: Timestamp,
218        covered: &BTreeSet<Timestamp>,
219    ) -> Option<Timestamp> {
220        self.due_times(last_scheduled, 1, now, covered)
221            .into_iter()
222            .next()
223    }
224
225    /// The fire times due at `now` after `last_scheduled`, at most `free`, leaving out
226    /// `covered`.
227    fn due_times(
228        &self,
229        last_scheduled: Option<Timestamp>,
230        free: usize,
231        now: Timestamp,
232        covered: &BTreeSet<Timestamp>,
233    ) -> Vec<Timestamp> {
234        if free == 0 {
235            return Vec::new();
236        }
237        let upper = self.dag.trigger.end().map_or(now, |end| end.min(now));
238        let start = self.effective_start();
239        let after = |t: Timestamp| t >= start && last_scheduled.is_none_or(|last| t > last);
240        let mut due = Vec::new();
241        if self.dag.trigger.catchup() {
242            let from = match last_scheduled {
243                Some(last) if last >= start => self.fire_times.next_after(last),
244                _ => self.fire_times.next_at_or_after(start),
245            };
246            let mut next = from;
247            while let Some(t) = next.filter(|t| *t <= upper && due.len() < free) {
248                if !covered.contains(&t) {
249                    due.push(t);
250                }
251                next = self.fire_times.next_after(t);
252            }
253        } else if let Some(latest) = self
254            .fire_times
255            .last_at_or_before(upper)
256            .filter(|t| after(*t) && !covered.contains(t))
257        {
258            due.push(latest);
259        }
260        due
261    }
262
263    /// How many more runs may run (`usize::MAX` without a limit).
264    #[must_use]
265    pub fn free_places(&self, running: u32) -> usize {
266        self.dag.max_active_runs.map_or(usize::MAX, |limit| {
267            usize::try_from(limit.saturating_sub(running)).unwrap_or(usize::MAX)
268        })
269    }
270}
271
272/// The moment a manual run is for: `requested` (`--for`), or `now`.
273#[must_use]
274pub fn manual_planned_for(requested: Option<Timestamp>, now: Timestamp) -> Timestamp {
275    requested.unwrap_or(now)
276}
277
278/// The queued runs to start with `free` places: manual, chained and event runs first, then
279/// backfill, oldest first within each.
280#[must_use]
281pub fn runs_to_start(queued: &[QueuedRun], free: usize) -> Vec<&QueuedRun> {
282    let mut ordered: Vec<&QueuedRun> = queued.iter().collect();
283    ordered.sort_by_key(|run| {
284        (
285            priority(run.kind),
286            run.triggered_at,
287            run.planned_for,
288            run.id.clone(),
289        )
290    });
291    ordered.truncate(free);
292    ordered
293}
294
295const fn priority(kind: RunKind) -> u8 {
296    match kind {
297        RunKind::Scheduled => 0,
298        RunKind::Manual | RunKind::Chained | RunKind::Event => 1,
299        RunKind::Backfill => 2,
300    }
301}