Skip to main content

schedr_db/
runs.rs

1//! DAG runs: creating them, and what the scheduler reads to decide on new ones.
2//!
3//! A scheduled run is unique per (DAG, `planned_for`) (a partial unique index), so a master
4//! that crashes after creating one can't create it twice; manual, backfill, chained and event runs
5//! are exempt (see archive/PROJECT.md, Runs: manual runs, backfill and pausing).
6
7use std::collections::{BTreeMap, HashMap};
8use std::sync::Arc;
9
10use jiff::Timestamp;
11use schedr_model::{Dag, DagId, RunKind, RunState};
12use uuid::Uuid;
13
14use crate::database::{Database, DbError};
15use crate::query::{db_time, from_name, in_tx, on_pool, parse_time, sql, sql_text};
16
17/// The rows of queued runs: the read's `FROM ... WHERE` and its probe check's (decision 485).
18macro_rules! queued_from {
19    () => {
20        "FROM runs WHERE state = 'queued'"
21    };
22}
23pub(crate) use queued_from;
24
25#[cfg(test)]
26mod tests;
27
28/// The most DAG IDs one query names (well under both databases' parameter limits).
29const DAGS_PER_QUERY: usize = 500;
30
31/// ` AND <column> IN ($1, …, $count)`, or nothing for no IDs.
32fn among(column: &str, count: usize) -> String {
33    if count == 0 {
34        return String::new();
35    }
36    let wanted: Vec<String> = (1..=count).map(|n| format!("${n}")).collect();
37    format!(" AND {column} IN ({})", wanted.join(", "))
38}
39
40/// Each DAG's latest scheduled run, of `count` DAGs (every DAG when 0), `NULL` for none: one
41/// index lookup per DAG, not its whole scheduled history (`MAX ... GROUP BY` read every
42/// scheduled run of each DAG every round, B120). The `NULL`s are left to the caller: a filter
43/// on the lookup's value ran it a second time (B130).
44fn last_scheduled_query(count: usize) -> String {
45    let among = among("d.dag_id", count);
46    format!(
47        "SELECT d.dag_id, {{ts<}}(SELECT MAX(r.planned_for) FROM runs r \
48          WHERE r.kind = 'scheduled' AND r.dag_id = d.dag_id){{>ts}} \
49         FROM dags d WHERE TRUE{among}"
50    )
51}
52
53pub(crate) fn dag_id_of(text: String) -> Result<DagId, DbError> {
54    DagId::new(text).map_err(|e| DbError::InvalidData {
55        what: "dag_id",
56        reason: e.to_string(),
57    })
58}
59
60/// A run to create.
61#[derive(Debug, Clone)]
62pub struct NewRun<'a> {
63    /// The DAG.
64    pub dag_id: &'a DagId,
65    /// The DAG version it runs.
66    pub dag_version_id: &'a str,
67    /// Who or what created it.
68    pub kind: RunKind,
69    /// `running`, or `queued` to wait for `max_active_runs`.
70    pub state: RunState,
71    /// The moment it is for.
72    pub planned_for: Timestamp,
73    /// The start of its window.
74    pub since: Timestamp,
75    /// When it was created.
76    pub triggered_at: Timestamp,
77    /// `scheduler`, a user name, or the parent run.
78    pub triggered_by: &'a str,
79    /// Its parameters, as stored JSON (decision 138); `{}` for a DAG that takes none.
80    pub params: &'a serde_json::Value,
81    /// The event that started it.
82    pub event: Option<&'a schedr_model::RunEvent>,
83    /// The run whose `TriggerDagOperator` started it (a `chained` run), or whose success started
84    /// it (a `RunOf` trigger's).
85    pub parent_run_id: Option<&'a str>,
86    /// The backfill it belongs to (a `backfill` run).
87    pub backfill_id: Option<&'a str>,
88}
89
90/// The parameters of a run of a DAG that takes none.
91pub static NO_PARAMS: std::sync::LazyLock<serde_json::Value> =
92    std::sync::LazyLock::new(|| serde_json::Value::Object(serde_json::Map::new()));
93
94/// A run waiting for `max_active_runs`.
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct QueuedRun {
97    /// The run's ID.
98    pub id: String,
99    /// Its kind (which decides who gets a freed place first).
100    pub kind: RunKind,
101    /// When it was created.
102    pub triggered_at: Timestamp,
103    /// The moment it is for (a backfill's runs, created at once, start oldest first).
104    pub planned_for: Timestamp,
105}
106
107/// What the scheduler needs of every DAG's runs, read at once for a whole round
108/// ([`Database::run_overview`]): a few queries, however many DAGs there are (B12).
109#[derive(Debug, Clone, Default, PartialEq, Eq)]
110pub struct RunOverview {
111    /// Running runs, per DAG.
112    pub running: BTreeMap<String, u32>,
113    /// The latest scheduled run's `planned_for`, per DAG.
114    pub last_scheduled: BTreeMap<String, Timestamp>,
115    /// Queued runs, per DAG, oldest first.
116    pub queued: BTreeMap<String, Vec<QueuedRun>>,
117}
118
119impl RunOverview {
120    /// `dag_id`'s running runs (0 if none).
121    #[must_use]
122    pub fn running(&self, dag_id: &DagId) -> u32 {
123        self.running.get(dag_id.as_str()).copied().unwrap_or(0)
124    }
125
126    /// `dag_id`'s latest scheduled `planned_for`, if it has a scheduled run.
127    #[must_use]
128    pub fn last_scheduled(&self, dag_id: &DagId) -> Option<Timestamp> {
129        self.last_scheduled.get(dag_id.as_str()).copied()
130    }
131
132    /// `dag_id`'s queued runs, oldest first.
133    #[must_use]
134    pub fn queued(&self, dag_id: &DagId) -> &[QueuedRun] {
135        self.queued.get(dag_id.as_str()).map_or(&[], Vec::as_slice)
136    }
137}
138
139/// A DAG the scheduler looks at: not removed, not in conflict, with a current version.
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct ActiveDag {
142    /// Whether its trigger is paused (no new scheduled runs; queued runs still start), or it
143    /// has none (decision 459).
144    pub paused: bool,
145    /// Why it is held, when the file defining it fails to import in its root's current parse
146    /// (decision 72): no run is created or started, and manual triggers are refused.
147    pub held: Option<Held>,
148    /// When the master first stored it.
149    pub first_seen: Timestamp,
150    /// Its current version's ID.
151    pub version_id: String,
152    /// Its current version.
153    pub dag: Arc<Dag>,
154}
155
156/// Why a DAG is held: its file's import error in its root's current parse (decision 72).
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct Held {
159    /// The file, relative to its root.
160    pub path: String,
161    /// The error's exception class name.
162    pub exception: String,
163    /// The error's message.
164    pub message: String,
165    /// The schedr version of the parse that failed (`0.2.0`): after an upgrade, the reason
166    /// says the file stopped importing with it, the code being the same (decision 441).
167    pub schedr_version: String,
168}
169
170impl Held {
171    /// Why `dag_id` gets no runs, for people (the API, the UI, a refused trigger, the log):
172    /// it is the DAG's **file** that failed, so every DAG of the file is held, and what to do
173    /// about it (decisions 72, 72.3).
174    #[must_use]
175    pub fn reason(&self, dag_id: &str) -> String {
176        use schedr_model::runner::{
177            INVALID_DAG_EXCEPTION, INVALID_PATH_EXCEPTION, PARSE_RESULT_TOO_LARGE_EXCEPTION,
178        };
179        let path = &self.path;
180        let message = &self.message;
181        let what = match self.exception.as_str() {
182            PARSE_RESULT_TOO_LARGE_EXCEPTION => format!(
183                "the parse result of its file `{path}` (the JSON of all the file's DAGs \
184                 together, not of `{dag_id}` alone) is too large for the master: {message}. \
185                 Every DAG of the file is held until it fits: move large DAGs to files of their \
186                 own, keep large data out of the DAGs' arguments (load it when the task runs), \
187                 or raise [grpc] max_message_size"
188            ),
189            INVALID_DAG_EXCEPTION => format!(
190                "its file `{path}` imports, but defines a DAG the master's checks refuse \
191                 ({message}). Every DAG of the file is held while one is invalid: fix that DAG, \
192                 or move it to a file of its own"
193            ),
194            INVALID_PATH_EXCEPTION => format!(
195                "its file `{path}` isn't inside its root ({message}). Every DAG of the file is \
196                 held until it is"
197            ),
198            exception => format!(
199                "its file `{path}` fails to import with schedr {} ({exception}: {message}), so \
200                 its tasks couldn't run. Every DAG of the file is held until it imports: fix \
201                 the file, or, if it stopped importing when schedr was upgraded, roll back",
202                self.schedr_version
203            ),
204        };
205        format!("DAG `{dag_id}` is held, no runs are created and it can't be triggered: {what}")
206    }
207    /// The current parses' import errors by (root, path), the files whose DAGs are held: a
208    /// transient error (a timeout, a runner that died) holds nothing, since the file is parsed
209    /// again and its DAGs keep their last good version meanwhile (decision 72.2).
210    #[must_use]
211    pub fn by_file(errors: &[crate::dags::ImportErrorRecord]) -> HashMap<(String, String), Self> {
212        errors
213            .iter()
214            .filter(|e| !e.error.is_transient())
215            .map(|e| {
216                let held = Self {
217                    path: e.path.clone(),
218                    exception: e.error.exception.clone(),
219                    message: e.error.message.clone(),
220                    schedr_version: e.schedr_version.clone(),
221                };
222                ((e.root.clone(), e.path.clone()), held)
223            })
224            .collect()
225    }
226
227    /// Whether `dag`'s file is among `held` files, and why.
228    #[must_use]
229    pub fn of(dag: &Dag, held: &HashMap<(String, String), Self>) -> Option<Self> {
230        held.get(&(dag.location.root.clone(), dag.location.path.clone()))
231            .cloned()
232    }
233}
234
235impl Database {
236    /// Creates a run and returns its ID; `None` if it is a scheduled run for a `planned_for`
237    /// that already has one.
238    ///
239    /// # Errors
240    ///
241    /// [`DbError::Sqlx`] if the statement fails.
242    pub async fn insert_run(&self, run: &NewRun<'_>) -> Result<Option<String>, DbError> {
243        self.insert_run_as(&Uuid::now_v7().to_string(), run).await
244    }
245
246    /// As [`Self::insert_run`], with the run's ID given (a command's, so applying it again
247    /// finds the run it made); `None` also when a run with this ID exists.
248    ///
249    /// # Errors
250    ///
251    /// [`DbError::Sqlx`] if the statement fails.
252    pub async fn insert_run_as(
253        &self,
254        id: &str,
255        run: &NewRun<'_>,
256    ) -> Result<Option<String>, DbError> {
257        const INSERT: &str = "INSERT INTO runs \
258            (id, dag_id, dag_version_id, kind, state, planned_for, since, triggered_at, \
259             triggered_by, started_at, params, event, parent_run_id, backfill_id) \
260            VALUES ($1{uuid}, $2, $3{uuid}, $4, $5, $6{ts}, $7{ts}, $8{ts}, $9, $10{ts}, \
261             $11{json}, $12{json}, $13{uuid}, $14{uuid}) ON CONFLICT DO NOTHING";
262        let started_at = (run.state == RunState::Running).then(|| db_time(run.triggered_at));
263        let inserted = in_tx!(self, |tx, backend| {
264            sqlx::query(sql(backend, INSERT))
265                .bind(id)
266                .bind(run.dag_id.as_str())
267                .bind(run.dag_version_id)
268                .bind(run.kind.to_string())
269                .bind(run.state.to_string())
270                .bind(db_time(run.planned_for))
271                .bind(db_time(run.since))
272                .bind(db_time(run.triggered_at))
273                .bind(run.triggered_by)
274                .bind(started_at)
275                .bind(run.params.to_string())
276                .bind(run.event.map(crate::query::to_json))
277                .bind(run.parent_run_id)
278                .bind(run.backfill_id)
279                .execute(&mut *tx)
280                .await?
281                .rows_affected()
282        });
283        Ok((inserted == 1).then(|| id.to_owned()))
284    }
285
286    /// A run's parameters, as stored JSON (decision 138); `None` for an unknown run.
287    ///
288    /// # Errors
289    ///
290    /// [`DbError`] if the query fails or the stored JSON doesn't read.
291    pub async fn run_params(&self, run_id: &str) -> Result<Option<serde_json::Value>, DbError> {
292        const PARAMS: &str = "SELECT params{text} FROM runs WHERE id = $1{uuid}";
293        let text: Option<String> = on_pool!(self, |pool, backend| {
294            sqlx::query_scalar(sql(backend, PARAMS))
295                .bind(run_id)
296                .fetch_optional(pool)
297                .await?
298        });
299        text.map(|t| crate::query::from_json("runs.params", &t))
300            .transpose()
301    }
302
303    /// The latest `planned_for` of the DAG's scheduled runs: the scheduler's bookkeeping,
304    /// which manual and backfill runs never change.
305    ///
306    /// # Errors
307    ///
308    /// [`DbError`] if the query fails or the stored time doesn't read.
309    pub async fn last_scheduled_for(&self, dag_id: &DagId) -> Result<Option<Timestamp>, DbError> {
310        const LAST: &str = "SELECT {ts<}MAX(planned_for){>ts} FROM runs \
311            WHERE dag_id = $1 AND kind = 'scheduled'";
312        self.optional_time(LAST, dag_id, None).await
313    }
314
315    /// The `planned_for` of the DAG's run nearest before `before`, of any kind.
316    ///
317    /// # Errors
318    ///
319    /// [`DbError`] if the query fails or the stored time doesn't read.
320    pub async fn nearest_earlier_run(
321        &self,
322        dag_id: &DagId,
323        before: Timestamp,
324    ) -> Result<Option<Timestamp>, DbError> {
325        const NEAREST: &str = "SELECT {ts<}MAX(planned_for){>ts} FROM runs \
326            WHERE dag_id = $1 AND planned_for < $2{ts}";
327        self.optional_time(NEAREST, dag_id, Some(before)).await
328    }
329
330    async fn optional_time(
331        &self,
332        query: &'static str,
333        dag_id: &DagId,
334        at: Option<Timestamp>,
335    ) -> Result<Option<Timestamp>, DbError> {
336        let text: Option<String> = on_pool!(self, |pool, backend| {
337            let mut q = sqlx::query_scalar(sql(backend, query)).bind(dag_id.as_str());
338            if let Some(at) = at {
339                q = q.bind(db_time(at));
340            }
341            q.fetch_one(pool).await?
342        });
343        text.map(|t| parse_time("runs.planned_for", &t)).transpose()
344    }
345
346    /// How many of the DAG's runs are running (what `max_active_runs` limits).
347    ///
348    /// # Errors
349    ///
350    /// [`DbError::Sqlx`] if the query fails.
351    pub async fn running_count(&self, dag_id: &DagId) -> Result<u32, DbError> {
352        const COUNT: &str = "SELECT COUNT(*) FROM runs WHERE dag_id = $1 AND state = 'running'";
353        let count: i64 = on_pool!(self, |pool, backend| {
354            sqlx::query_scalar(sql(backend, COUNT))
355                .bind(dag_id.as_str())
356                .fetch_one(pool)
357                .await?
358        });
359        Ok(u32::try_from(count).unwrap_or(u32::MAX))
360    }
361
362    /// The DAG's queued runs, oldest first.
363    ///
364    /// # Errors
365    ///
366    /// [`DbError`] if the query fails or a stored value doesn't read.
367    pub async fn queued_runs(&self, dag_id: &DagId) -> Result<Vec<QueuedRun>, DbError> {
368        const QUEUED: &str = "SELECT id{text}, kind, {ts<}triggered_at{>ts}, \
369            {ts<}planned_for{>ts} FROM runs \
370            WHERE dag_id = $1 AND state = 'queued' ORDER BY triggered_at, planned_for, id";
371        let rows: Vec<(String, String, String, String)> = on_pool!(self, |pool, backend| {
372            sqlx::query_as(sql(backend, QUEUED))
373                .bind(dag_id.as_str())
374                .fetch_all(pool)
375                .await?
376        });
377        rows.into_iter()
378            .map(|(id, kind, triggered_at, planned_for)| {
379                Ok(QueuedRun {
380                    id,
381                    kind: from_name("runs.kind", kind)?,
382                    triggered_at: parse_time("runs.triggered_at", &triggered_at)?,
383                    planned_for: parse_time("runs.planned_for", &planned_for)?,
384                })
385            })
386            .collect()
387    }
388
389    /// Every DAG's running count, latest scheduled `planned_for` and queued runs, in three
390    /// queries: what a scheduler round reads, instead of three queries per DAG (B12). The
391    /// master is the only writer of runs, so the round can work from it until it ends.
392    ///
393    /// # Errors
394    ///
395    /// [`DbError`] if a query fails or a stored value doesn't read.
396    pub async fn run_overview(&self) -> Result<RunOverview, DbError> {
397        let mut overview = RunOverview::default();
398        self.overview_into(&mut overview, &[]).await?;
399        Ok(overview)
400    }
401
402    /// As [`Self::run_overview`], for `dags` only (a round visiting some DAGs, see
403    /// archive/PROJECT.md, "Quiet DAGs"): its cost follows them, not every DAG. Nothing for no
404    /// DAGs.
405    ///
406    /// # Errors
407    ///
408    /// [`DbError`] if a query fails or a stored value doesn't read.
409    pub async fn run_overview_of(&self, dags: &[&DagId]) -> Result<RunOverview, DbError> {
410        let mut overview = RunOverview::default();
411        for chunk in dags.chunks(DAGS_PER_QUERY) {
412            self.overview_into(&mut overview, chunk).await?;
413        }
414        Ok(overview)
415    }
416
417    /// Adds the overview of `dags` (every DAG when empty) to `overview`.
418    async fn overview_into(
419        &self,
420        overview: &mut RunOverview,
421        dags: &[&DagId],
422    ) -> Result<(), DbError> {
423        type Rows = (
424            Vec<(String, i64)>,
425            Vec<(String, Option<String>)>,
426            Vec<(String, String, String, String, String)>,
427        );
428        let among = among("dag_id", dags.len());
429        let running = format!(
430            "SELECT dag_id, COUNT(*) FROM runs WHERE state = 'running'{among} GROUP BY dag_id"
431        );
432        let last = last_scheduled_query(dags.len());
433        let queued = format!(
434            "SELECT dag_id, id{{text}}, kind, {{ts<}}triggered_at{{>ts}}, \
435             {{ts<}}planned_for{{>ts}} FROM runs \
436             WHERE state = 'queued'{among} ORDER BY dag_id, triggered_at, planned_for, id"
437        );
438        // One connection, one time limit, for all three.
439        let (running, last, queued): Rows = on_pool!(self, |pool, backend| {
440            let mut running_query = sqlx::query_as(sql_text(backend, &running));
441            let mut last_query = sqlx::query_as(sql_text(backend, &last));
442            let mut queued_query = sqlx::query_as(sql_text(backend, &queued));
443            for dag in dags {
444                running_query = running_query.bind(dag.as_str());
445                last_query = last_query.bind(dag.as_str());
446                queued_query = queued_query.bind(dag.as_str());
447            }
448            (
449                running_query.fetch_all(&mut *pool).await?,
450                last_query.fetch_all(&mut *pool).await?,
451                queued_query.fetch_all(&mut *pool).await?,
452            )
453        });
454        for (dag, count) in running {
455            overview
456                .running
457                .insert(dag, u32::try_from(count).unwrap_or(u32::MAX));
458        }
459        for (dag, at) in last {
460            // A DAG without a scheduled run has none.
461            let Some(at) = at else { continue };
462            overview
463                .last_scheduled
464                .insert(dag, parse_time("runs.planned_for", &at)?);
465        }
466        for (dag, id, kind, triggered_at, planned_for) in queued {
467            overview.queued.entry(dag).or_default().push(QueuedRun {
468                id,
469                kind: from_name("runs.kind", kind)?,
470                triggered_at: parse_time("runs.triggered_at", &triggered_at)?,
471                planned_for: parse_time("runs.planned_for", &planned_for)?,
472            });
473        }
474        Ok(())
475    }
476
477    /// The DAG's runs not finished (`queued` or `running`), oldest first.
478    ///
479    /// # Errors
480    ///
481    /// [`DbError::Sqlx`] if the query fails.
482    pub async fn runs_in_progress(&self, dag_id: &DagId) -> Result<Vec<String>, DbError> {
483        const IN_PROGRESS: &str = "SELECT id{text} FROM runs \
484            WHERE dag_id = $1 AND state IN ('queued', 'running') ORDER BY triggered_at, id";
485        let ids: Vec<String> = on_pool!(self, |pool, backend| {
486            sqlx::query_scalar(sql(backend, IN_PROGRESS))
487                .bind(dag_id.as_str())
488                .fetch_all(pool)
489                .await?
490        });
491        Ok(ids)
492    }
493
494    /// Marks a run that ended `success` as a yellow success (decision 309), once, with why
495    /// (`late_cleanup_failed`). Returns its DAG when this call marked it; `None` if it isn't
496    /// an ended success or is marked already.
497    ///
498    /// # Errors
499    ///
500    /// [`DbError::Sqlx`] if the statement fails.
501    pub async fn mark_late_failure(
502        &self,
503        run_id: &str,
504        reason: &str,
505    ) -> Result<Option<String>, DbError> {
506        const MARK: &str = "UPDATE runs SET late_failure = $1 \
507            WHERE id = $2{uuid} AND state = 'success' AND late_failure IS NULL RETURNING dag_id";
508        let marked: Option<(String,)> = in_tx!(self, |tx, backend| {
509            sqlx::query_as(sql(backend, MARK))
510                .bind(reason)
511                .bind(run_id)
512                .fetch_optional(&mut *tx)
513                .await?
514        });
515        Ok(marked.map(|(dag_id,)| dag_id))
516    }
517
518    /// Starts a queued run: it becomes `running`.
519    ///
520    /// # Errors
521    ///
522    /// [`DbError::Sqlx`] if the statement fails.
523    pub async fn start_run(&self, run_id: &str, now: Timestamp) -> Result<(), DbError> {
524        const START: &str = "UPDATE runs SET state = 'running', started_at = $1{ts} \
525            WHERE id = $2{uuid} AND state = 'queued'";
526        in_tx!(self, |tx, backend| {
527            sqlx::query(sql(backend, START))
528                .bind(db_time(now))
529                .bind(run_id)
530                .execute(&mut *tx)
531                .await?;
532        });
533        Ok(())
534    }
535
536    /// The DAGs the scheduler looks at: not removed, not in conflict, with a current
537    /// version; in DAG ID order.
538    ///
539    /// # Errors
540    ///
541    /// [`DbError`] if the query fails or stored data doesn't read.
542    pub async fn active_dags(&self) -> Result<Vec<ActiveDag>, DbError> {
543        let mut active = Vec::new();
544        self.active_into(&mut active, &[]).await?;
545        Ok(active)
546    }
547
548    /// The DAGs with queued runs (from any source: manual, chained, event, backfill), by the
549    /// partial index of unfinished runs: what wakes a quiet DAG whatever stored the run.
550    ///
551    /// # Errors
552    ///
553    /// [`DbError`] if the query fails or a stored DAG ID doesn't read.
554    pub async fn dags_with_queued_runs(&self) -> Result<Vec<DagId>, DbError> {
555        const QUEUED: &str = concat!("SELECT DISTINCT dag_id ", queued_from!());
556        if self.skipped(crate::probe::Check::QueuedRuns).await? {
557            return Ok(Vec::new());
558        }
559        let rows: Vec<String> = on_pool!(self, |pool, backend| {
560            sqlx::query_scalar(sql(backend, QUEUED))
561                .fetch_all(pool)
562                .await?
563        });
564        rows.into_iter().map(dag_id_of).collect()
565    }
566
567    /// The ID and current version of every DAG the scheduler looks at (as
568    /// [`Self::active_dags`], without their definitions): one small query, for the quiet DAGs'
569    /// check against memory.
570    ///
571    /// # Errors
572    ///
573    /// [`DbError`] if the query fails or a stored DAG ID doesn't read.
574    pub async fn active_dag_versions(&self) -> Result<Vec<(DagId, String)>, DbError> {
575        const VERSIONS: &str = "SELECT dag_id, current_version_id{text} FROM dags \
576            WHERE current_version_id IS NOT NULL AND removed_at IS NULL AND conflict IS NULL \
577            ORDER BY dag_id";
578        let rows: Vec<(String, String)> = on_pool!(self, |pool, backend| {
579            sqlx::query_as(sql(backend, VERSIONS))
580                .fetch_all(pool)
581                .await?
582        });
583        rows.into_iter()
584            .map(|(dag, version)| Ok((dag_id_of(dag)?, version)))
585            .collect()
586    }
587
588    /// As [`Self::active_dags`], for `dags` only: those of them that can run.
589    ///
590    /// # Errors
591    ///
592    /// [`DbError`] if the query fails or stored data doesn't read.
593    pub async fn active_dags_of(&self, dags: &[&DagId]) -> Result<Vec<ActiveDag>, DbError> {
594        let mut active = Vec::new();
595        for chunk in dags.chunks(DAGS_PER_QUERY) {
596            self.active_into(&mut active, chunk).await?;
597        }
598        active.sort_by(|a, b| a.dag.id.cmp(&b.dag.id));
599        Ok(active)
600    }
601
602    /// Adds the active DAGs among `dags` (every DAG when empty) to `active`.
603    async fn active_into(
604        &self,
605        active: &mut Vec<ActiveDag>,
606        dags: &[&DagId],
607    ) -> Result<(), DbError> {
608        let text = format!(
609            "SELECT COALESCE(t.paused, TRUE), {{ts<}}d.first_seen_at{{>ts}}, \
610             d.current_version_id{{text}} \
611             FROM dags d LEFT JOIN dag_triggers t ON t.dag_id = d.dag_id \
612             WHERE d.current_version_id IS NOT NULL \
613             AND d.removed_at IS NULL AND d.conflict IS NULL{} ORDER BY d.dag_id",
614            among("d.dag_id", dags.len())
615        );
616        let rows: Vec<(bool, String, String)> = on_pool!(self, |pool, backend| {
617            let mut query = sqlx::query_as(sql_text(backend, &text));
618            for dag in dags {
619                query = query.bind(dag.as_str());
620            }
621            query.fetch_all(pool).await?
622        });
623        active.reserve(rows.len());
624        // Usually none: a small query, once a round (decision 72).
625        let held = Held::by_file(&self.current_import_errors().await?);
626        for (paused, first_seen, version_id) in rows {
627            // The definition from the cache: parsed once per version, not every round (B13).
628            let dag = self.dag_version(&version_id).await?;
629            active.push(ActiveDag {
630                paused,
631                held: Held::of(&dag, &held),
632                first_seen: parse_time("dags.first_seen_at", &first_seen)?,
633                version_id,
634                dag,
635            });
636        }
637        Ok(())
638    }
639}