Skip to main content

schedr_master/
scheduler.rs

1//! The scheduler pass: new scheduled runs, queued runs started, and manual runs.
2//!
3//! Each pass looks at the DAGs that can run (not removed, not in conflict, with a version) that
4//! it visits: an unpaused DAG gets runs for its due fire times ([`Plan::scheduled_runs`]), then queued
5//! runs take the places left ([`runs_to_start`]). Pausing stops only the first part. Runs are
6//! stored before anything else happens to them, and a scheduled run is unique per
7//! `planned_for`, so a pass repeated after a crash creates nothing twice.
8//!
9//! Which DAGs a pass looks at is [`QuietDags`]'s choice (decision 485): every DAG, or those the
10//! database finds due (a scheduled DAG's stored next fire time come or unknown, a queued run)
11//! and those marked. After each visit a scheduled DAG's next fire time is stored when it
12//! changed: the visit's own time while due runs wait (held, at `max_active_runs`, past the
13//! round's share), else its next fire time, [`NO_FIRE`] when it has none.
14
15use std::collections::{BTreeSet, HashMap, HashSet};
16use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
17
18use jiff::Timestamp;
19use schedr_db::dags::NO_FIRE;
20use schedr_db::runs::{ActiveDag, Held, NewRun, QueuedRun};
21use schedr_db::{Database, DbError};
22use schedr_model::{DagId, RunKind, RunState};
23
24use crate::fire_times::{FireTimes, FireTimesError};
25use crate::metrics::MasterMetrics;
26use crate::planning::{ManualRunError, Plan, RunTimes, manual_planned_for, runs_to_start};
27use crate::quiet::{QuietDags, QuietSettings, Visit, Visited, WakeReason, Wakes};
28
29/// The most scheduled runs a round creates for one DAG: a DAG catching up after a long pause
30/// goes over a few rounds, the earliest first (B18).
31pub const SCHEDULED_PER_ROUND: usize = 10;
32
33pub mod backfill;
34
35#[cfg(test)]
36mod tests;
37
38/// Who created scheduled runs, as recorded in `triggered_by`.
39pub const SCHEDULER: &str = "scheduler";
40
41/// Why a scheduler operation failed.
42#[derive(Debug, thiserror::Error)]
43pub enum SchedulerError {
44    /// The database failed.
45    #[error(transparent)]
46    Db(#[from] DbError),
47    /// The DAG doesn't exist, was removed, is in conflict or has no version.
48    #[error("DAG `{0}` can't run: it doesn't exist, was removed or is in conflict")]
49    NotRunnable(DagId),
50    /// The DAG's file fails to import in its root's current parse (decision 72): no run is
51    /// created until it imports again.
52    #[error("{}", held.reason(dag_id.as_str()))]
53    Held {
54        /// The DAG.
55        dag_id: DagId,
56        /// Why.
57        held: Held,
58    },
59    /// An event trigger starts its runs, and the run asked for brings no event.
60    #[error(
61        "DAG `{0}`: its runs start from events, so this one needs an event (`--event <key>` for one \
62         it found, or `--event-key` and `--event-data`)"
63    )]
64    NeedsEvent(DagId),
65    /// A run brings an event, and no event trigger starts the DAG's runs.
66    #[error("DAG `{0}`: no event trigger starts its runs, so its tasks read no event")]
67    NoEventTrigger(DagId),
68    /// A `TriggerDagOperator`'s target isn't started by other DAGs, or not by this one
69    /// (decision 398).
70    #[error(
71        "DAG `{dag_id}` can't be started by a TriggerDagOperator of `{by}`: {}",
72        if *chained {
73            "its `trigger=Chained(by=[...])` doesn't name that DAG"
74        } else {
75            "only a DAG with `trigger=Chained()` is started by other DAGs (its own trigger, or \
76             none, says how it runs)"
77        }
78    )]
79    NotChained {
80        /// The target.
81        dag_id: DagId,
82        /// The DAG whose operator would start it.
83        by: DagId,
84        /// Whether it is `Chained`, naming other DAGs.
85        chained: bool,
86    },
87    /// A `TriggerDagOperator`'s target is paused: its trigger, `Chained`, is switched off, as a
88    /// schedule is (decision 398).
89    #[error(
90        "DAG `{0}` is paused, so no TriggerDagOperator starts its runs until it is resumed \
91         (`schedr dags unpause {0}`)"
92    )]
93    ChainedPaused(DagId),
94    /// A backfill that can't be created (decisions 363, 404).
95    #[error("DAG `{dag_id}`: no backfill: {why}")]
96    Backfill {
97        /// The DAG.
98        dag_id: DagId,
99        /// Why not.
100        why: String,
101    },
102    /// A manual run's time isn't allowed.
103    #[error(transparent)]
104    ManualRun(#[from] ManualRunError),
105    /// The run's parameters are refused (decision 133): the reason is shown.
106    #[error("DAG `{dag_id}`: {reason}")]
107    Params {
108        /// The DAG.
109        dag_id: DagId,
110        /// Why.
111        reason: String,
112    },
113    /// The fire times of the DAG's stored trigger can't be evaluated (it passed validation
114    /// with another version of the master).
115    #[error("DAG `{dag_id}`: {error}")]
116    FireTimes {
117        /// The DAG.
118        dag_id: DagId,
119        /// Why.
120        error: FireTimesError,
121    },
122}
123
124/// A run created by the scheduler or a person.
125#[derive(Debug, Clone, PartialEq, Eq)]
126pub struct CreatedRun {
127    /// The DAG.
128    pub dag_id: DagId,
129    /// The run's ID.
130    pub run_id: String,
131    /// Its kind.
132    pub kind: RunKind,
133    /// Its time and window.
134    pub times: RunTimes,
135}
136
137/// What a pass did.
138#[derive(Debug, Default)]
139pub struct Pass {
140    /// Scheduled runs created.
141    pub created: Vec<CreatedRun>,
142    /// Queued runs started, by ID.
143    pub started: Vec<String>,
144    /// DAGs skipped because their schedule can't be evaluated or their defaults are refused.
145    pub skipped: Vec<SchedulerError>,
146    /// Those of them logged by this pass: skipped for the first time, or for another reason
147    /// (B154: each once, not every round it stays skipped).
148    pub newly_skipped: Vec<DagId>,
149}
150
151/// The scheduler over a database (cheap to clone; clones share which DAGs are quiet).
152#[derive(Debug, Clone)]
153pub struct Scheduler {
154    db: Database,
155    quiet: Arc<Mutex<QuietDags>>,
156    wakes: Wakes,
157    /// The DAGs skipped, with why, as last logged; one that passes again is forgotten.
158    skipped: Arc<Mutex<HashMap<DagId, String>>>,
159    /// The most scheduled runs a round creates for one DAG (decision 493).
160    scheduled_per_round: usize,
161    /// Each DAG's plan's bounds.
162    plan_limits: crate::planning::PlanLimits,
163}
164
165impl Scheduler {
166    /// A scheduler storing runs in `db`, with the default quiet DAG settings.
167    #[must_use]
168    pub fn new(db: Database) -> Self {
169        Self::with_quiet(db, QuietSettings::default(), Wakes::default())
170    }
171
172    /// A scheduler storing runs in `db`, skipping quiet DAGs as `settings` say, woken by
173    /// `wakes` (shared with what changes runs).
174    #[must_use]
175    pub fn with_quiet(db: Database, settings: QuietSettings, wakes: Wakes) -> Self {
176        Self {
177            db,
178            quiet: Arc::new(Mutex::new(QuietDags::new(settings, wakes.clone()))),
179            wakes,
180            skipped: Arc::default(),
181            scheduled_per_round: SCHEDULED_PER_ROUND,
182            plan_limits: crate::planning::PlanLimits::default(),
183        }
184    }
185
186    /// The scheduler with the master's bounds (decision 493).
187    #[must_use]
188    pub fn with_limits(
189        mut self,
190        rounds: &crate::core::RoundLimits,
191        for_tolerance: std::time::Duration,
192    ) -> Self {
193        self.scheduled_per_round = rounds.scheduled_runs;
194        self.plan_limits = crate::planning::PlanLimits {
195            runs_per_pass: rounds.planning_pass_runs,
196            for_tolerance: jiff::SignedDuration::try_from(for_tolerance)
197                .unwrap_or(jiff::SignedDuration::MAX),
198        };
199        self
200    }
201
202    /// `error` skips `dag_id` in `pass`: logged when it is new for that DAG.
203    fn skip(&self, pass: &mut Pass, dag_id: &DagId, error: SchedulerError) {
204        let reason = error.to_string();
205        let mut skipped = self.skipped.lock().unwrap_or_else(PoisonError::into_inner);
206        if skipped.get(dag_id) != Some(&reason) {
207            tracing::warn!(
208                %dag_id,
209                %error,
210                "the scheduler skips the DAG: no scheduled run is created until this is fixed"
211            );
212            skipped.insert(dag_id.clone(), reason);
213            pass.newly_skipped.push(dag_id.clone());
214        }
215        pass.skipped.push(error);
216    }
217
218    /// `dag_id` went through a pass unskipped: a later skip is logged again.
219    fn passed(&self, dag_id: &DagId) {
220        self.skipped
221            .lock()
222            .unwrap_or_else(PoisonError::into_inner)
223            .remove(dag_id);
224    }
225
226    /// Counts busy and quiet DAGs, and wakes, in `metrics`.
227    pub fn set_metrics(&self, metrics: MasterMetrics) {
228        self.quiet().set_metrics(metrics);
229    }
230
231    /// The marks that wake quiet DAGs.
232    #[must_use]
233    pub const fn wakes(&self) -> &Wakes {
234        &self.wakes
235    }
236
237    fn quiet(&self) -> MutexGuard<'_, QuietDags> {
238        self.quiet.lock().unwrap_or_else(PoisonError::into_inner)
239    }
240
241    /// One pass at `now` over the DAGs that can run: every one, or the busy ones and the
242    /// quiet ones woken.
243    ///
244    /// # Errors
245    ///
246    /// [`SchedulerError::Db`] if the database fails (the pass stops; what was stored stays).
247    pub async fn pass(&self, now: Timestamp) -> Result<Pass, SchedulerError> {
248        // What the database finds due (decision 485), whatever stored it: a queued run, a
249        // scheduled DAG whose stored next fire time has come or isn't known. Both through the
250        // round's probe: an idle round reads neither.
251        let mut due = Vec::new();
252        let mut stored = HashMap::new();
253        if self.quiet().enabled() {
254            for dag in self.db.dags_with_queued_runs().await? {
255                due.push((dag, WakeReason::RunQueued));
256            }
257            for (dag, at) in self.db.scheduled_due(now).await? {
258                let reason = if at.is_some() {
259                    WakeReason::Timer
260                } else {
261                    WakeReason::Unknown
262                };
263                due.push((dag.clone(), reason));
264                stored.insert(dag, at);
265            }
266        }
267        let visit = self.quiet().round(due);
268        let result = self.visit(visit, stored, now).await;
269        if result.is_err() {
270            // Nothing the round would have changed is kept: the next one retries it.
271            self.quiet().round_failed();
272        }
273        result
274    }
275
276    /// The round's work: the DAGs `visit` names visited at `now`; `stored`, the next fire times
277    /// stored of those the database found due (read for the others when it visits all).
278    async fn visit(
279        &self,
280        visit: Visit,
281        mut stored: HashMap<DagId, Option<Timestamp>>,
282        now: Timestamp,
283    ) -> Result<Pass, SchedulerError> {
284        let mut pass = Pass::default();
285        match &visit {
286            // Nothing due: nothing read.
287            Visit::Some(dags) if dags.is_empty() => {
288                self.quiet().round_done(&visit, &HashSet::new());
289                return Ok(pass);
290            }
291            Visit::All => stored = self.db.next_fires().await?,
292            Visit::Some(_) => {}
293        }
294        // The DAGs' runs at once: a round costs a few queries, not three per DAG (B12), and
295        // reads only the DAGs it visits.
296        let (overview, active_dags) = match &visit {
297            Visit::All => (self.db.run_overview().await?, self.db.active_dags().await?),
298            Visit::Some(dags) => {
299                let dags: Vec<&DagId> = dags.iter().collect();
300                (
301                    self.db.run_overview_of(&dags).await?,
302                    self.db.active_dags_of(&dags).await?,
303                )
304            }
305        };
306        let mut seen = HashSet::with_capacity(active_dags.len());
307        for active in active_dags {
308            seen.insert(active.dag.id.clone());
309            let fire_times = match FireTimes::new(&active.dag.trigger) {
310                Ok(fire_times) => fire_times,
311                Err(error) => {
312                    let error = SchedulerError::FireTimes {
313                        dag_id: active.dag.id.clone(),
314                        error,
315                    };
316                    self.skip(&mut pass, &active.dag.id, error);
317                    continue;
318                }
319            };
320            let plan = Plan {
321                dag: &active.dag,
322                fire_times: &fire_times,
323                first_seen: active.first_seen,
324                limits: self.plan_limits,
325            };
326            let mut running = overview.running(&active.dag.id);
327            let mut waiting = None;
328            let queued = overview.queued(&active.dag.id);
329            let mut skipped = false;
330            // Held (decision 72): its fire times create nothing (missed, as when paused) and
331            // its queued runs wait.
332            let held = active.held.as_ref();
333            if !active.paused && held.is_none() {
334                let last = overview.last_scheduled(&active.dag.id);
335                (waiting, skipped) = self
336                    .create_due(&mut pass, &active, &plan, last, &mut running, now)
337                    .await?;
338            }
339            if !skipped {
340                self.passed(&active.dag.id);
341            }
342            if held.is_none() {
343                pass.started
344                    .extend(self.start_queued(queued, &plan, running, now).await?);
345            }
346            let why = held.map(|h| h.reason(active.dag.id.as_str()));
347            // When to visit it next, stored when it changed (decision 485): while due runs wait,
348            // the first of them, and while it is held (to see the hold lift), a time come
349            // already, so each round visits it again with no write; else its next fire time.
350            // A paused one isn't due until unpausing clears it.
351            if active.dag.trigger.kind() == Some("schedule") && !active.paused {
352                let stored_at = stored.get(&active.dag.id).copied().flatten();
353                let next = if held.is_some() {
354                    stored_at.filter(|at| *at <= now).unwrap_or(now)
355                } else if let Some(first) = waiting {
356                    first.min(now)
357                } else {
358                    plan.next_fire_after(now).unwrap_or(NO_FIRE)
359                };
360                if stored.get(&active.dag.id) != Some(&Some(next)) {
361                    self.db.set_next_fire(&active.dag.id, next).await?;
362                }
363            }
364            self.quiet().visited(
365                &active.dag.id,
366                Visited {
367                    held: why.as_deref(),
368                },
369            );
370        }
371        self.quiet().round_done(&visit, &seen);
372        Ok(pass)
373    }
374
375    /// Creates `active`'s due scheduled runs at `now` (at most [`SCHEDULED_PER_ROUND`]), `last`
376    /// its last scheduled one; `running` counts those created. Returns the first fire time
377    /// still waiting, if any, and whether the DAG was skipped (its defaults).
378    async fn create_due(
379        &self,
380        pass: &mut Pass,
381        active: &ActiveDag,
382        plan: &Plan<'_>,
383        last: Option<Timestamp>,
384        running: &mut u32,
385        now: Timestamp,
386    ) -> Result<(Option<Timestamp>, bool), SchedulerError> {
387        let due = self.due_runs(plan, last, *running, now).await?;
388        let capped = due.len() > self.scheduled_per_round;
389        let mut last_created = last;
390        // At most so many a DAG a round: a long catch-up goes over a few (B18).
391        for times in due.into_iter().take(self.scheduled_per_round) {
392            // The defaults, checked when the DAG was validated.
393            let params = match run_params(active, None) {
394                Ok(params) => params,
395                Err(error) => {
396                    self.skip(pass, &active.dag.id, error);
397                    return Ok((None, true));
398                }
399            };
400            last_created = last_created.max(Some(times.planned_for));
401            let new = new_run(active, RunKind::Scheduled, times, now, SCHEDULER, &params);
402            if let Some(run_id) = self.db.insert_run(&new).await? {
403                *running += 1;
404                pass.created
405                    .push(created(active, run_id, RunKind::Scheduled, times));
406            }
407        }
408        // Due runs that wait (decision 485): past the round's share, or a fire time still due,
409        // for a free place or behind a run of another kind that may yet fail (one that
410        // succeeded takes it for good). A DAG skipped for its defaults waits for new code
411        // instead.
412        let waiting = match plan.first_waiting(last_created, now, &BTreeSet::new()) {
413            Some(first) if capped => Some(first),
414            None => None,
415            Some(first) => {
416                let done = self.db.succeeded_times(&active.dag.id, first, now).await?;
417                plan.first_waiting(last_created, now, &done)
418            }
419        };
420        Ok((waiting, false))
421    }
422
423    /// Creates a manual run for `requested` (`--for`) or now, by `user`; it starts at once
424    /// if the DAG has a free place, and waits as `queued` otherwise. A paused DAG's manual
425    /// runs run normally.
426    ///
427    /// # Errors
428    ///
429    /// [`SchedulerError::NotRunnable`], [`SchedulerError::Held`] while its file fails to
430    /// import, [`SchedulerError::ManualRun`] for a time in the future,
431    /// [`SchedulerError::FireTimes`] or [`SchedulerError::Db`].
432    ///
433    pub async fn trigger(
434        &self,
435        dag_id: &DagId,
436        requested: Option<Timestamp>,
437        user: &str,
438        now: Timestamp,
439    ) -> Result<CreatedRun, SchedulerError> {
440        self.trigger_as(None, dag_id, requested, (None, None), user, now)
441            .await
442    }
443
444    /// As [`Self::trigger`], the run's ID given (`trigger_run` passes its command's): a run
445    /// with that ID already there (the command applied before its decision was stored) is
446    /// the one returned, not created again (B7). `params`: the values given for the run's
447    /// parameters, over the DAG's defaults.
448    ///
449    /// # Errors
450    ///
451    /// As [`Self::trigger`], and [`SchedulerError::Params`] for parameters refused.
452    pub async fn trigger_as(
453        &self,
454        run_id: Option<&str>,
455        dag_id: &DagId,
456        requested: Option<Timestamp>,
457        (params, event): (
458            Option<&serde_json::Map<String, serde_json::Value>>,
459            Option<&schedr_model::RunEvent>,
460        ),
461        user: &str,
462        now: Timestamp,
463    ) -> Result<CreatedRun, SchedulerError> {
464        self.create_run(
465            run_id,
466            dag_id,
467            requested,
468            (params, event),
469            (RunKind::Manual, user, None),
470            now,
471        )
472        .await
473    }
474
475    /// Creates a `chained` run of `dag_id` (a `TriggerDagOperator`'s, decisions 357-362): as a
476    /// manual run, with its ID given, `parent_run_id` as its parent and `triggered_by`, if the
477    /// DAG is `trigger=Chained()` letting `parent_dag` start it, and not paused (decision 398).
478    ///
479    /// # Errors
480    ///
481    /// As [`Self::trigger_as`].
482    pub async fn trigger_chained(
483        &self,
484        run_id: &str,
485        dag_id: &DagId,
486        planned_for: Timestamp,
487        params: Option<&serde_json::Map<String, serde_json::Value>>,
488        (parent_run_id, parent_dag): (&str, &DagId),
489        now: Timestamp,
490    ) -> Result<CreatedRun, SchedulerError> {
491        self.create_run(
492            Some(run_id),
493            dag_id,
494            Some(planned_for),
495            (params, None),
496            (
497                RunKind::Chained,
498                parent_run_id,
499                Some((parent_run_id, parent_dag)),
500            ),
501            now,
502        )
503        .await
504    }
505
506    async fn create_run(
507        &self,
508        run_id: Option<&str>,
509        dag_id: &DagId,
510        requested: Option<Timestamp>,
511        (params, event): (
512            Option<&serde_json::Map<String, serde_json::Value>>,
513            Option<&schedr_model::RunEvent>,
514        ),
515        (kind, user, parent): (RunKind, &str, Option<(&str, &DagId)>),
516        now: Timestamp,
517    ) -> Result<CreatedRun, SchedulerError> {
518        // Its own DAG only, not every active one (decision 483).
519        let active = self
520            .db
521            .active_dags_of(&[dag_id])
522            .await?
523            .into_iter()
524            .find(|d| &d.dag.id == dag_id)
525            .ok_or_else(|| SchedulerError::NotRunnable(dag_id.clone()))?;
526        if let Some(held) = active.held {
527            return Err(SchedulerError::Held {
528                dag_id: dag_id.clone(),
529                held,
530            });
531        }
532        if let Some((_, by)) = parent {
533            if !active.dag.trigger.chained_from(by) {
534                return Err(SchedulerError::NotChained {
535                    dag_id: dag_id.clone(),
536                    by: by.clone(),
537                    chained: matches!(active.dag.trigger, schedr_model::Trigger::Chained { .. }),
538                });
539            }
540            if active.paused {
541                return Err(SchedulerError::ChainedPaused(dag_id.clone()));
542            }
543        }
544        if active.dag.trigger.brings_event() != event.is_some() {
545            return Err(if event.is_some() {
546                SchedulerError::NoEventTrigger(dag_id.clone())
547            } else {
548                SchedulerError::NeedsEvent(dag_id.clone())
549            });
550        }
551        let fire_times =
552            FireTimes::new(&active.dag.trigger).map_err(|error| SchedulerError::FireTimes {
553                dag_id: dag_id.clone(),
554                error,
555            })?;
556        let plan = Plan {
557            dag: &active.dag,
558            fire_times: &fire_times,
559            first_seen: active.first_seen,
560            limits: self.plan_limits,
561        };
562        let planned_for = manual_planned_for(requested, now);
563        let nearest = self.db.nearest_earlier_run(dag_id, planned_for).await?;
564        let times = plan.manual_times(requested, now, nearest)?;
565        let params = run_params(&active, params)?;
566        let mut new = new_run(&active, kind, times, now, user, &params);
567        new.state = RunState::Queued;
568        new.event = event;
569        new.parent_run_id = parent.map(|(run, _)| run);
570        self.wakes.wake(dag_id, WakeReason::RunQueued);
571        // Only scheduled runs are unique per `planned_for`: a manual one is stored unless a
572        // run with its given ID is there already, and then that one is it.
573        let run_id = run_id.map_or_else(|| uuid::Uuid::now_v7().to_string(), str::to_owned);
574        self.db.insert_run_as(&run_id, &new).await?;
575        let running = self.db.running_count(dag_id).await?;
576        let queued = self.db.queued_runs(dag_id).await?;
577        self.start_queued(&queued, &plan, running, now).await?;
578        Ok(created(&active, run_id, kind, times))
579    }
580
581    /// Stores what a DAG's trigger found: a key not seen before queues a run, as a manual one
582    /// (`since` is the previous event's `planned_for`), a repeat moves the bookmark only. Gives
583    /// the run's ID, `None` for a repeat.
584    ///
585    /// # Errors
586    ///
587    /// [`SchedulerError::Params`] for parameters refused, and what storing it fails with.
588    pub async fn event_run(
589        &self,
590        active: &ActiveDag,
591        event: &schedr_model::RunEvent,
592        since: Option<Timestamp>,
593        now: Timestamp,
594    ) -> Result<Option<String>, SchedulerError> {
595        let planned_for = event.at.unwrap_or(now);
596        // An event may be for a moment before the last one's (a late webhook, a backfill): its
597        // window is then empty, never inverted (Grok's review of M4.11e).
598        let times = RunTimes {
599            planned_for,
600            since: since
601                .filter(|since| *since <= planned_for)
602                .unwrap_or(planned_for),
603        };
604        let params = run_params(active, None)?;
605        let mut new = new_run(active, RunKind::Event, times, now, EVENT_USER, &params);
606        new.state = RunState::Queued;
607        new.event = Some(event);
608        // A `RunOf` trigger's run was caused by the run it names (its event's key): its parent,
609        // linked both ways as a chained run is.
610        if active.dag.trigger.is_run_of() {
611            new.parent_run_id = Some(&event.key);
612        }
613        let run_id = uuid::Uuid::now_v7().to_string();
614        let stored = self.db.store_event(&run_id, &new, event).await?;
615        if stored.is_some() {
616            self.wakes.wake(&active.dag.id, WakeReason::RunQueued);
617        }
618        Ok(stored)
619    }
620
621    /// Stores a batch a trigger found (decision 352): each item an event, a run for the new ones
622    /// only (B188), as [`Self::event_run`] does for one. Gives the run's ID, `None` when every
623    /// item was seen before.
624    ///
625    /// # Errors
626    ///
627    /// As [`Self::event_run`].
628    pub async fn batch_run(
629        &self,
630        active: &ActiveDag,
631        batch: &schedr_model::RunEvent,
632        items: &[(schedr_model::RunEvent, serde_json::Value)],
633        since: Option<Timestamp>,
634        now: Timestamp,
635    ) -> Result<Option<String>, SchedulerError> {
636        let planned_for = batch.at.unwrap_or(now);
637        let times = RunTimes {
638            planned_for,
639            since: since
640                .filter(|since| *since <= planned_for)
641                .unwrap_or(planned_for),
642        };
643        let params = run_params(active, None)?;
644        let mut new = new_run(active, RunKind::Event, times, now, EVENT_USER, &params);
645        new.state = RunState::Queued;
646        let run_id = uuid::Uuid::now_v7().to_string();
647        let stored = self
648            .db
649            .store_batch(&run_id, &new, &batch.key, items)
650            .await?;
651        if stored.is_some() {
652            self.wakes.wake(&active.dag.id, WakeReason::RunQueued);
653        }
654        Ok(stored)
655    }
656
657    /// Starts the DAG's `queued` runs that fit next to its `running` ones.
658    /// The scheduled runs `plan` has due at `now`, leaving out the fire times a run of another
659    /// kind covers (succeeded, queued or running: a backfill's, a manual one), so a period
660    /// isn't run twice; read only when something is due.
661    async fn due_runs(
662        &self,
663        plan: &Plan<'_>,
664        last: Option<Timestamp>,
665        running: u32,
666        now: Timestamp,
667    ) -> Result<Vec<RunTimes>, SchedulerError> {
668        let due = plan.scheduled_runs(last, running, now);
669        let Some(first) = due.first() else {
670            return Ok(due);
671        };
672        let covered = self
673            .db
674            .covered_times(&plan.dag.id, first.planned_for, now)
675            .await?;
676        if covered.is_empty() {
677            return Ok(due);
678        }
679        Ok(plan.scheduled_runs_except(last, running, now, &covered))
680    }
681
682    async fn start_queued(
683        &self,
684        queued: &[QueuedRun],
685        plan: &Plan<'_>,
686        running: u32,
687        now: Timestamp,
688    ) -> Result<Vec<String>, SchedulerError> {
689        let mut started = Vec::new();
690        for run in runs_to_start(queued, plan.free_places(running)) {
691            self.db.start_run(&run.id, now).await?;
692            started.push(run.id.clone());
693        }
694        Ok(started)
695    }
696}
697
698fn created(active: &ActiveDag, run_id: String, kind: RunKind, times: RunTimes) -> CreatedRun {
699    CreatedRun {
700        dag_id: active.dag.id.clone(),
701        run_id,
702        kind,
703        times,
704    }
705}
706
707/// A run's parameters: `given`'s over the DAG's defaults, checked (decision 133).
708fn run_params(
709    active: &ActiveDag,
710    given: Option<&serde_json::Map<String, serde_json::Value>>,
711) -> Result<serde_json::Value, SchedulerError> {
712    crate::params::run_params(active.dag.params.as_ref(), given).map_err(|reason| {
713        SchedulerError::Params {
714            dag_id: active.dag.id.clone(),
715            reason,
716        }
717    })
718}
719
720/// Who an event's run was started by.
721const EVENT_USER: &str = "trigger";
722
723fn new_run<'a>(
724    active: &'a ActiveDag,
725    kind: RunKind,
726    times: RunTimes,
727    now: Timestamp,
728    by: &'a str,
729    params: &'a serde_json::Value,
730) -> NewRun<'a> {
731    NewRun {
732        dag_id: &active.dag.id,
733        dag_version_id: &active.version_id,
734        kind,
735        state: RunState::Running,
736        planned_for: times.planned_for,
737        since: times.since,
738        triggered_at: now,
739        triggered_by: by,
740        params,
741        event: None,
742        parent_run_id: None,
743        backfill_id: None,
744    }
745}