Skip to main content

schedr_db/
reads.rs

1//! What the webserver reads: runs, their task instances and attempts, as shown to people.
2//!
3//! The webserver reads the database directly (with a read-only role in production) and never
4//! writes scheduling state; actions are command rows (see archive/PROJECT.md, Web UI and CLI).
5
6use std::collections::BTreeMap;
7
8use jiff::Timestamp;
9use schedr_model::{
10    AttemptStatus, CleanupResult, DagId, RunKind, RunState, TaskId, TaskInstanceState,
11};
12
13use crate::database::{Database, DbError};
14use crate::query::{
15    db_time, from_json, from_name, on_pool, optional_time, parse_time, sql, to_json,
16};
17
18#[cfg(test)]
19mod tests;
20
21/// How many runs, tasks and workers are in each state (the master's gauges).
22#[derive(Debug, Clone, Default, PartialEq, Eq)]
23pub struct StateCounts {
24    /// Runs by state and kind: `(state, kind, count)`.
25    pub runs: Vec<(String, String, i64)>,
26    /// Task instances of unfinished runs, by state.
27    pub tasks: Vec<(String, i64)>,
28    /// Workers in the registry, by state.
29    pub workers: Vec<(String, i64)>,
30}
31
32/// The most runs one list returns.
33pub const MAX_RUNS: u32 = 500;
34
35/// A run, as listed.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct RunRecord {
38    /// Its ID.
39    pub id: String,
40    /// The DAG.
41    pub dag_id: DagId,
42    /// Who or what created it.
43    pub kind: RunKind,
44    /// Where it stands.
45    pub state: RunState,
46    /// The moment it is for.
47    pub planned_for: Timestamp,
48    /// The start of its window.
49    pub since: Timestamp,
50    /// When it was created.
51    pub triggered_at: Timestamp,
52    /// `scheduler`, a user name, the parent run, or `trigger`.
53    pub triggered_by: String,
54    /// When it started running.
55    pub started_at: Option<Timestamp>,
56    /// When it finished.
57    pub ended_at: Option<Timestamp>,
58    /// Why it turned a yellow success after its end (decision 309): `late_cleanup_failed`.
59    pub late_failure: Option<String>,
60    /// The run whose `TriggerDagOperator` started it (a `chained` run), or whose success started
61    /// it (a `RunOf` trigger's).
62    pub parent_run_id: Option<String>,
63    /// Its backfill and its place in it (a `backfill` run).
64    pub backfill: Option<BackfillPlace>,
65}
66
67/// A backfill run's backfill, and its place among the backfill's runs, oldest first
68/// (`backfill 3/31`, decision 403).
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct BackfillPlace {
71    /// The backfill's ID.
72    pub id: String,
73    /// Its place, from 1.
74    pub index: u32,
75    /// How many runs the backfill has.
76    pub total: u32,
77}
78
79/// A task instance, as shown.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct InstanceRecord {
82    /// The task.
83    pub task_id: TaskId,
84    /// Its place among a mapped task's instances; -1 for an unmapped task, and for a mapped
85    /// task as a whole.
86    pub map_index: i32,
87    /// Why it ended without an attempt (a mapped task that couldn't expand).
88    pub reason: Option<String>,
89    /// Its state.
90    pub state: TaskInstanceState,
91    /// Its outcome, on success.
92    pub outcome: Option<String>,
93    /// Attempts made.
94    pub try_number: u32,
95    /// Why it is waiting or unschedulable.
96    pub queued_reason: Option<String>,
97    /// How its cleanups ended: the last, unless one failed; `None` for a task without one, or
98    /// before its first cleanup ends.
99    pub cleanup_result: Option<CleanupResult>,
100    /// When it last changed.
101    pub updated_at: Timestamp,
102}
103
104/// An attempt's cleanup, as shown.
105#[derive(Debug, Clone, PartialEq, Eq, Default)]
106pub struct CleanupRecord {
107    /// How it ended; `None` while it hasn't (or for a task without one).
108    pub result: Option<CleanupResult>,
109    /// The tries it made.
110    pub tries: Option<u32>,
111    /// How long its tries ran, measured by the worker.
112    pub duration_ms: Option<u64>,
113    /// The error kind of its last failed try.
114    pub error_kind: Option<String>,
115    /// The structured error summary of its last failed try (JSON text).
116    pub error_summary: Option<String>,
117    /// How many times it moved to another worker (`cleanup_anywhere`).
118    pub moves: u32,
119    /// The handles the attempt registered, each as JSON text (masked), in order.
120    pub handles: Vec<String>,
121}
122
123impl CleanupRecord {
124    /// Whether there is anything to show: a task without a cleanup has nothing.
125    #[must_use]
126    pub fn is_empty(&self) -> bool {
127        *self == Self::default()
128    }
129}
130
131/// An attempt, as shown.
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct AttemptRecord {
134    /// Its ID.
135    pub id: String,
136    /// Its try number.
137    pub try_number: u32,
138    /// The worker it ran on.
139    pub worker_id: Option<String>,
140    /// How it ended; `None` while it runs.
141    pub status: Option<AttemptStatus>,
142    /// The process's exit code.
143    pub exit_code: Option<i32>,
144    /// The error kind schedr recognised.
145    pub error_kind: Option<String>,
146    /// The structured error summary (JSON text).
147    pub error_summary: Option<String>,
148    /// When it was assigned.
149    pub assigned_at: Timestamp,
150    /// When the worker started it.
151    pub started_at: Option<Timestamp>,
152    /// When it ended.
153    pub ended_at: Option<Timestamp>,
154    /// How long it ran, measured by the worker (see [`crate::attempts::AttemptEnd`]).
155    pub duration_ms: Option<u64>,
156    /// The peak memory of its process group, sampled by the worker's watchdog.
157    pub peak_memory_bytes: Option<u64>,
158    /// How the worker started its process (`spawn` or `fork`); `None` until it started.
159    pub start_method: Option<String>,
160    /// What its process used (its parent's view at its exit), if the worker read it.
161    pub usage: Option<schedr_model::runner::ProcessUsage>,
162    /// Whether its process dumped core.
163    pub core_dumped: bool,
164    /// Its cleanup (empty for a task without one).
165    pub cleanup: CleanupRecord,
166    /// The run a `TriggerDagOperator`'s attempt started (no worker runs it).
167    pub chained_run_id: Option<String>,
168}
169
170type RunRow = (
171    String,
172    String,
173    String,
174    String,
175    String,
176    String,
177    String,
178    String,
179    Option<String>,
180    Option<String>,
181    Option<String>,
182    Option<String>,
183    Option<String>,
184    i64,
185    i64,
186);
187
188type InstanceRow = (
189    String,
190    String,
191    Option<String>,
192    i32,
193    Option<String>,
194    String,
195    i32,
196    Option<String>,
197    Option<String>,
198);
199
200type CleanupRow = (
201    String,
202    Option<String>,
203    Option<i32>,
204    Option<i64>,
205    Option<String>,
206    Option<String>,
207    i32,
208);
209
210type AttemptRow = (
211    String,
212    i32,
213    Option<String>,
214    Option<String>,
215    Option<i32>,
216    Option<String>,
217    Option<String>,
218    String,
219    Option<String>,
220    Option<String>,
221    Option<i64>,
222    Option<i64>,
223    Option<String>,
224    Option<String>,
225    bool,
226    Option<String>,
227);
228
229const RUN_COLUMNS_ONE: &str = "SELECT id{text}, dag_id, kind, state, {ts<}planned_for{>ts}, \
230    {ts<}since{>ts}, {ts<}triggered_at{>ts}, triggered_by, {ts<}started_at{>ts}, \
231    {ts<}ended_at{>ts}, late_failure, parent_run_id{text}, backfill_id{text}, \
232    (SELECT COUNT(*) FROM runs b WHERE b.backfill_id = runs.backfill_id \
233     AND (b.planned_for < runs.planned_for OR (b.planned_for = runs.planned_for AND b.id <= runs.id))), \
234    (SELECT COUNT(*) FROM runs b WHERE b.backfill_id = runs.backfill_id) FROM runs WHERE id = $1{uuid}";
235
236const RUN_COLUMNS_OF_DAG: &str = "SELECT id{text}, dag_id, kind, state, {ts<}planned_for{>ts}, \
237    {ts<}since{>ts}, {ts<}triggered_at{>ts}, triggered_by, {ts<}started_at{>ts}, \
238    {ts<}ended_at{>ts}, late_failure, parent_run_id{text}, backfill_id{text}, \
239    (SELECT COUNT(*) FROM runs b WHERE b.backfill_id = runs.backfill_id \
240     AND (b.planned_for < runs.planned_for OR (b.planned_for = runs.planned_for AND b.id <= runs.id))), \
241    (SELECT COUNT(*) FROM runs b WHERE b.backfill_id = runs.backfill_id) FROM runs WHERE dag_id = $1 AND ($2{ts} IS NULL OR planned_for = $2{ts}) \
242    ORDER BY planned_for DESC, triggered_at DESC, id DESC LIMIT $3";
243
244/// The runs listed newest triggered first, filtered by `$dag` (an SQL condition on `dag_id`),
245/// the state and the page's cursor. The page's runs are chosen first, then each one's place in
246/// its backfill counted: counted before the `LIMIT`, every matching run of a large backfill was
247/// counted (quadratic; Codex's review of D500: 4.3 s over 4,000 runs of one backfill).
248macro_rules! runs_listed {
249    ($dag:literal) => {
250        concat!(
251            "SELECT id{text}, dag_id, kind, state, {ts<}planned_for{>ts}, \
252    {ts<}since{>ts}, {ts<}triggered_at{>ts}, triggered_by, {ts<}started_at{>ts}, \
253    {ts<}ended_at{>ts}, late_failure, parent_run_id{text}, backfill_id{text}, \
254    (SELECT COUNT(*) FROM runs b WHERE b.backfill_id = runs.backfill_id \
255     AND (b.planned_for < runs.planned_for OR (b.planned_for = runs.planned_for AND b.id <= runs.id))), \
256    (SELECT COUNT(*) FROM runs b WHERE b.backfill_id = runs.backfill_id) FROM runs \
257    WHERE runs.id IN (SELECT id FROM runs WHERE ",
258            $dag,
259            " AND ($2 IS NULL OR state = $2) AND ($3{ts} IS NULL OR triggered_at < $3{ts} \
260    OR ($5{uuid} IS NOT NULL AND triggered_at = $3{ts} AND id < $5{uuid})) \
261    ORDER BY triggered_at DESC, id DESC LIMIT $4) \
262    ORDER BY triggered_at DESC, runs.id DESC"
263        )
264    };
265}
266
267const RUNS_FILTERED: &str = runs_listed!("($1 IS NULL OR dag_id = $1)");
268
269/// The DAG IDs holding a part (`$1`, a [`contains_pattern`]), from `dags`: every DAG ID a run
270/// has, removed ones too.
271const DAGS_HOLDING: &str = "SELECT dag_id FROM dags WHERE LOWER(dag_id) LIKE $1 ESCAPE '\\'";
272
273/// The runs of the DAGs in `$6` ([`DAGS_HOLDING`]'s answer), by `runs_by_dag_trigger`; on
274/// SQLite a JSON list. The DAGs are read first: in one statement Postgres planned the subquery
275/// as a join and walked every run by trigger time even when no DAG matched (Codex's review of
276/// D500: 96 ms over 250,000 runs; none matched now asks nothing).
277const RUNS_OF_DAGS_SQLITE: &str =
278    runs_listed!("($1 IS NULL OR dag_id = $1) AND dag_id IN (SELECT value FROM json_each($6))");
279
280/// As [`RUNS_OF_DAGS_SQLITE`], `$6` the IDs joined by commas (no DAG ID holds one): an array
281/// the planner sees, not a JSON list it can't count (measured with `runs_by_dag_trigger`, 250,000
282/// runs: no match 0.16 ms against 144 ms, a rare DAG 0.4 ms against 57 ms).
283const RUNS_OF_DAGS_POSTGRES: &str =
284    runs_listed!("($1 IS NULL OR dag_id = $1) AND dag_id = ANY(string_to_array($6{text}, ','))");
285
286/// A `LIKE` pattern matching any text holding `part`, in any case: lower-cased, its `%`, `_`
287/// and `\` escaped (with `ESCAPE '\'`).
288fn contains_pattern(part: &str) -> String {
289    let mut pattern = String::from("%");
290    for c in part.to_lowercase().chars() {
291        if matches!(c, '%' | '_' | '\\') {
292            pattern.push('\\');
293        }
294        pattern.push(c);
295    }
296    pattern.push('%');
297    pattern
298}
299
300/// Which runs [`Database::runs`] lists.
301#[derive(Debug, Clone, Default, PartialEq, Eq)]
302pub struct RunFilter {
303    /// Only this DAG's.
304    pub dag_id: Option<DagId>,
305    /// Only the DAGs whose ID holds this, in any case (the Runs page's DAG field).
306    pub dag_contains: Option<String>,
307    /// Only runs in this state.
308    pub state: Option<RunState>,
309    /// Only runs listed after this point: triggered before this moment, or at it with a
310    /// lower ID than `before_run` (the next page: the last run shown's `triggered_at` and ID;
311    /// a scheduler round triggers its runs at the same moment).
312    pub before: Option<Timestamp>,
313    /// The last run shown, with `before` (ignored without it).
314    pub before_run: Option<String>,
315    /// At most this many (capped at [`MAX_RUNS`]).
316    pub limit: u32,
317}
318
319impl Database {
320    /// Runs of every DAG (or one), newest triggered first, filtered by `filter`.
321    ///
322    /// # Errors
323    ///
324    /// [`DbError`] if the query fails or stored data doesn't read.
325    pub async fn runs(&self, filter: &RunFilter) -> Result<Vec<RunRecord>, DbError> {
326        let dags = match filter.dag_contains.as_deref() {
327            Some(part) => {
328                let dags: Vec<String> = on_pool!(self, |pool, backend| {
329                    sqlx::query_scalar(sql(backend, DAGS_HOLDING))
330                        .bind(contains_pattern(part))
331                        .fetch_all(pool)
332                        .await?
333                });
334                if dags.is_empty() {
335                    return Ok(Vec::new());
336                }
337                Some(dags)
338            }
339            None => None,
340        };
341        let rows: Vec<RunRow> = on_pool!(self, |pool, backend| {
342            let postgres = matches!(backend, crate::backend::Backend::Postgres);
343            let query = sqlx::query_as(sql(
344                backend,
345                match (&dags, postgres) {
346                    (None, _) => RUNS_FILTERED,
347                    (Some(_), false) => RUNS_OF_DAGS_SQLITE,
348                    (Some(_), true) => RUNS_OF_DAGS_POSTGRES,
349                },
350            ))
351            .bind(filter.dag_id.as_ref().map(DagId::as_str))
352            .bind(filter.state.map(|s| s.to_string()))
353            .bind(filter.before.map(db_time))
354            .bind(i64::from(filter.limit.min(MAX_RUNS)))
355            .bind(filter.before_run.as_deref());
356            match &dags {
357                Some(dags) => {
358                    let list = if postgres {
359                        dags.join(",")
360                    } else {
361                        to_json(dags)
362                    };
363                    query.bind(list).fetch_all(pool).await?
364                }
365                None => query.fetch_all(pool).await?,
366            }
367        });
368        rows.into_iter().map(run_record).collect()
369    }
370
371    /// The DAG JSON of the version a run ran with (its graph); `None` for an unknown run.
372    ///
373    /// # Errors
374    ///
375    /// [`DbError`] if the query fails or the stored JSON doesn't read.
376    pub async fn run_dag_json(&self, run_id: &str) -> Result<Option<serde_json::Value>, DbError> {
377        const DAG: &str = "SELECT v.dag_json{text} FROM runs r \
378            JOIN dag_versions v ON v.id = r.dag_version_id WHERE r.id = $1{uuid}";
379        let row: Option<(String,)> = on_pool!(self, |pool, backend| {
380            sqlx::query_as(sql(backend, DAG))
381                .bind(run_id)
382                .fetch_optional(pool)
383                .await?
384        });
385        row.map(|(json,)| from_json("dag_versions.dag_json", &json))
386            .transpose()
387    }
388
389    /// The DAG a run runs, parsed once per version (the cache's, see
390    /// [`Database::dag_version`]); `None` for no such run (B137: each task read parsed it).
391    ///
392    /// # Errors
393    ///
394    /// [`DbError`] if the query fails or the stored DAG doesn't read.
395    pub async fn run_dag(
396        &self,
397        run_id: &str,
398    ) -> Result<Option<std::sync::Arc<schedr_model::Dag>>, DbError> {
399        const VERSION: &str = "SELECT dag_version_id{text} FROM runs WHERE id = $1{uuid}";
400        let version: Option<String> = on_pool!(self, |pool, backend| {
401            sqlx::query_scalar(sql(backend, VERSION))
402                .bind(run_id)
403                .fetch_optional(pool)
404                .await?
405        });
406        match version {
407            Some(version) => Ok(Some(self.dag_version(&version).await?)),
408            None => Ok(None),
409        }
410    }
411
412    /// The DAG of each of `run_ids` that exists, by run (M5.1d: a group's wait steps cleared
413    /// with one read, where [`Self::run_dag`] reads a run's DAG whole).
414    ///
415    /// # Errors
416    ///
417    /// [`DbError`] if the query fails.
418    pub async fn run_dag_ids(&self, run_ids: &[&str]) -> Result<BTreeMap<String, String>, DbError> {
419        const DAGS: &str = "SELECT id{text}, dag_id FROM runs \
420            WHERE id IN (SELECT value{uuid} FROM {json_each}($1{json}))";
421        if run_ids.is_empty() {
422            return Ok(BTreeMap::new());
423        }
424        let list = to_json(&run_ids);
425        let rows: Vec<(String, String)> = on_pool!(self, |pool, backend| {
426            sqlx::query_as(sql(backend, DAGS))
427                .bind(&list)
428                .fetch_all(pool)
429                .await?
430        });
431        Ok(rows.into_iter().collect())
432    }
433
434    /// How many instances mapped task `task_id` has in a run (its whole row not counted).
435    ///
436    /// # Errors
437    ///
438    /// [`DbError`] if the query fails.
439    pub async fn mapped_instances(&self, run_id: &str, task_id: &TaskId) -> Result<usize, DbError> {
440        const COUNT: &str = "SELECT COUNT(*) FROM task_instances \
441            WHERE run_id = $1{uuid} AND task_id = $2 AND map_index >= 0";
442        let count: i64 = on_pool!(self, |pool, backend| {
443            sqlx::query_scalar(sql(backend, COUNT))
444                .bind(run_id)
445                .bind(task_id.as_str())
446                .fetch_one(pool)
447                .await?
448        });
449        Ok(usize::try_from(count).unwrap_or(0))
450    }
451
452    /// A task's stored output in a run, with its outcome; `None` when it has none (yet).
453    ///
454    /// # Errors
455    ///
456    /// [`DbError`] if the query fails or the stored value doesn't read.
457    pub async fn run_task_output(
458        &self,
459        run_id: &str,
460        task_id: &TaskId,
461    ) -> Result<Option<(String, serde_json::Value)>, DbError> {
462        self.instance_output(run_id, task_id, -1).await
463    }
464
465    /// One task instance's stored output in a run, with its outcome; `None` when it has none
466    /// (yet).
467    ///
468    /// # Errors
469    ///
470    /// [`DbError`] if the query fails or the stored value doesn't read.
471    pub async fn instance_output(
472        &self,
473        run_id: &str,
474        task_id: &TaskId,
475        map_index: i32,
476    ) -> Result<Option<(String, serde_json::Value)>, DbError> {
477        const OUTPUT: &str = "SELECT o.outcome, o.value{text} FROM outputs o \
478            JOIN task_instances t ON t.id = o.task_instance_id \
479            WHERE t.run_id = $1{uuid} AND t.task_id = $2 AND t.map_index = $3";
480        let row: Option<(String, String)> = on_pool!(self, |pool, backend| {
481            sqlx::query_as(sql(backend, OUTPUT))
482                .bind(run_id)
483                .bind(task_id.as_str())
484                .bind(map_index)
485                .fetch_optional(pool)
486                .await?
487        });
488        row.map(|(outcome, value)| Ok((outcome, from_json("outputs.value", &value)?)))
489            .transpose()
490    }
491
492    /// Whether `[retention] outputs` deleted run `run_id`'s outputs (decision 435).
493    ///
494    /// # Errors
495    ///
496    /// [`DbError::Sqlx`] if the query fails.
497    pub async fn outputs_deleted(&self, run_id: &str) -> Result<bool, DbError> {
498        const DELETED: &str = "SELECT 1 FROM runs WHERE id = $1{uuid} \
499            AND outputs_deleted_at IS NOT NULL";
500        let found: Option<i32> = on_pool!(self, |pool, backend| {
501            sqlx::query_scalar(sql(backend, DELETED))
502                .bind(run_id)
503                .fetch_optional(pool)
504                .await?
505        });
506        Ok(found.is_some())
507    }
508
509    /// A DAG's runs, newest `planned_for` first, at most `limit` (capped at [`MAX_RUNS`]);
510    /// only those for `planned_for` when given.
511    ///
512    /// # Errors
513    ///
514    /// [`DbError`] if the query fails or stored data doesn't read.
515    pub async fn dag_runs(
516        &self,
517        dag_id: &DagId,
518        planned_for: Option<Timestamp>,
519        limit: u32,
520    ) -> Result<Vec<RunRecord>, DbError> {
521        let rows: Vec<RunRow> = on_pool!(self, |pool, backend| {
522            sqlx::query_as(sql(backend, RUN_COLUMNS_OF_DAG))
523                .bind(dag_id.as_str())
524                .bind(planned_for.map(db_time))
525                .bind(i64::from(limit.min(MAX_RUNS)))
526                .fetch_all(pool)
527                .await?
528        });
529        rows.into_iter().map(run_record).collect()
530    }
531
532    /// A run by ID.
533    ///
534    /// # Errors
535    ///
536    /// [`DbError`] if the query fails or stored data doesn't read.
537    pub async fn run_record(&self, run_id: &str) -> Result<Option<RunRecord>, DbError> {
538        let row: Option<RunRow> = on_pool!(self, |pool, backend| {
539            sqlx::query_as(sql(backend, RUN_COLUMNS_ONE))
540                .bind(run_id)
541                .fetch_optional(pool)
542                .await?
543        });
544        row.map(run_record).transpose()
545    }
546
547    /// A run's task instances, in task ID order, then `map_index` order (a mapped task as a
548    /// whole first).
549    ///
550    /// # Errors
551    ///
552    /// [`DbError`] if the query fails or stored data doesn't read.
553    pub async fn run_instances(&self, run_id: &str) -> Result<Vec<InstanceRecord>, DbError> {
554        const INSTANCES: &str = "SELECT task_id, state, outcome, try_number, queued_reason, \
555            {ts<}updated_at{>ts}, map_index, reason, cleanup_result FROM task_instances \
556            WHERE run_id = $1{uuid} ORDER BY task_id, map_index";
557        let rows: Vec<InstanceRow> = on_pool!(self, |pool, backend| {
558            sqlx::query_as(sql(backend, INSTANCES))
559                .bind(run_id)
560                .fetch_all(pool)
561                .await?
562        });
563        rows.into_iter()
564            .map(
565                |(
566                    task_id,
567                    state,
568                    outcome,
569                    try_number,
570                    queued_reason,
571                    updated_at,
572                    map_index,
573                    reason,
574                    cleanup_result,
575                )| {
576                    Ok(InstanceRecord {
577                        task_id: task_id_of(task_id)?,
578                        map_index,
579                        reason,
580                        state: from_name("task_instances.state", state)?,
581                        outcome,
582                        try_number: u32::try_from(try_number).unwrap_or(0),
583                        queued_reason,
584                        cleanup_result: cleanup_result
585                            .map(|name| from_name("task_instances.cleanup_result", name))
586                            .transpose()?,
587                        updated_at: parse_time("task_instances.updated_at", &updated_at)?,
588                    })
589                },
590            )
591            .collect()
592    }
593
594    /// The code hashes a run's attempts ran with, in the order first used (more than one:
595    /// its tasks ran on different code).
596    ///
597    /// # Errors
598    ///
599    /// [`DbError::Sqlx`] if the query fails.
600    pub async fn run_code_hashes(&self, run_id: &str) -> Result<Vec<String>, DbError> {
601        const HASHES: &str = "SELECT a.code_hash FROM attempts a \
602            JOIN task_instances t ON t.id = a.task_instance_id \
603            WHERE t.run_id = $1{uuid} AND a.code_hash IS NOT NULL AND a.code_hash <> '' \
604            GROUP BY a.code_hash ORDER BY MIN(COALESCE(a.started_at, a.assigned_at)), a.code_hash";
605        let hashes = on_pool!(self, |pool, backend| {
606            sqlx::query_scalar(sql(backend, HASHES))
607                .bind(run_id)
608                .fetch_all(pool)
609                .await?
610        });
611        Ok(hashes)
612    }
613
614    /// How many runs (by state and kind), task instances of unfinished runs and workers (by
615    /// state) there are.
616    ///
617    /// # Errors
618    ///
619    /// [`DbError::Sqlx`] if a query fails.
620    pub async fn state_counts(&self) -> Result<StateCounts, DbError> {
621        const RUNS: &str =
622            "SELECT state, kind, COUNT(*) FROM runs GROUP BY state, kind ORDER BY state, kind";
623        const TASKS: &str = "SELECT t.state, COUNT(*) FROM task_instances t \
624            JOIN runs r ON r.id = t.run_id WHERE r.state IN ('queued', 'running') \
625            GROUP BY t.state ORDER BY t.state";
626        const WORKERS: &str = "SELECT state, COUNT(*) FROM workers GROUP BY state ORDER BY state";
627        let (runs, tasks, workers) = on_pool!(self, |pool, backend| {
628            (
629                sqlx::query_as(sql(backend, RUNS))
630                    .fetch_all(&mut *pool)
631                    .await?,
632                sqlx::query_as(sql(backend, TASKS))
633                    .fetch_all(&mut *pool)
634                    .await?,
635                sqlx::query_as(sql(backend, WORKERS))
636                    .fetch_all(&mut *pool)
637                    .await?,
638            )
639        });
640        Ok(StateCounts {
641            runs,
642            tasks,
643            workers,
644        })
645    }
646
647    /// The attempts of a run's task, oldest first.
648    ///
649    /// # Errors
650    ///
651    /// [`DbError`] if the query fails or stored data doesn't read.
652    pub async fn task_attempts(
653        &self,
654        run_id: &str,
655        task_id: &TaskId,
656    ) -> Result<Vec<AttemptRecord>, DbError> {
657        self.instance_attempts(run_id, task_id, -1).await
658    }
659
660    /// The attempts of one task instance of a run, oldest first.
661    ///
662    /// # Errors
663    ///
664    /// [`DbError`] if the query fails or stored data doesn't read.
665    pub async fn instance_attempts(
666        &self,
667        run_id: &str,
668        task_id: &TaskId,
669        map_index: i32,
670    ) -> Result<Vec<AttemptRecord>, DbError> {
671        const ATTEMPTS: &str = "SELECT a.id{text}, a.try_number, a.worker_id, a.status, \
672            a.exit_code, a.error_kind, a.error_summary{text}, {ts<}a.assigned_at{>ts}, \
673            {ts<}a.started_at{>ts}, {ts<}a.ended_at{>ts}, a.duration_ms, a.peak_memory_bytes, \
674            a.start_method, a.usage{text}, a.core_dumped, a.chained_run_id{text} FROM attempts a \
675            JOIN task_instances t ON t.id = a.task_instance_id \
676            WHERE t.run_id = $1{uuid} AND t.task_id = $2 AND t.map_index = $3 \
677            ORDER BY a.try_number";
678        const CLEANUPS: &str = "SELECT a.id{text}, a.cleanup_result, a.cleanup_tries, \
679            a.cleanup_duration_ms, a.cleanup_error_kind, a.cleanup_error_summary{text}, \
680            a.cleanup_moves FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
681            WHERE t.run_id = $1{uuid} AND t.task_id = $2 AND t.map_index = $3";
682        const HANDLES: &str = "SELECT h.attempt_id{text}, h.handle FROM cleanup_handles h \
683            JOIN attempts a ON a.id = h.attempt_id \
684            JOIN task_instances t ON t.id = a.task_instance_id \
685            WHERE t.run_id = $1{uuid} AND t.task_id = $2 AND t.map_index = $3 \
686            ORDER BY h.attempt_id, h.position";
687        let (rows, cleanups, handles): (Vec<AttemptRow>, Vec<CleanupRow>, Vec<(String, String)>) =
688            on_pool!(self, |pool, backend| {
689                (
690                    sqlx::query_as(sql(backend, ATTEMPTS))
691                        .bind(run_id)
692                        .bind(task_id.as_str())
693                        .bind(map_index)
694                        .fetch_all(&mut *pool)
695                        .await?,
696                    sqlx::query_as(sql(backend, CLEANUPS))
697                        .bind(run_id)
698                        .bind(task_id.as_str())
699                        .bind(map_index)
700                        .fetch_all(&mut *pool)
701                        .await?,
702                    sqlx::query_as(sql(backend, HANDLES))
703                        .bind(run_id)
704                        .bind(task_id.as_str())
705                        .bind(map_index)
706                        .fetch_all(&mut *pool)
707                        .await?,
708                )
709            });
710        let mut by_attempt: BTreeMap<String, CleanupRecord> = BTreeMap::new();
711        for (id, result, tries, duration_ms, error_kind, error_summary, moves) in cleanups {
712            by_attempt.insert(
713                id,
714                CleanupRecord {
715                    result: result
716                        .map(|name| from_name("attempts.cleanup_result", name))
717                        .transpose()?,
718                    tries: tries.and_then(|n| u32::try_from(n).ok()),
719                    duration_ms: duration_ms.and_then(|ms| u64::try_from(ms).ok()),
720                    error_kind,
721                    error_summary,
722                    moves: u32::try_from(moves).unwrap_or(0),
723                    handles: Vec::new(),
724                },
725            );
726        }
727        for (id, handle) in handles {
728            by_attempt.entry(id).or_default().handles.push(handle);
729        }
730        rows.into_iter()
731            .map(|row| {
732                let mut record = attempt_record(row)?;
733                record.cleanup = by_attempt.remove(&record.id).unwrap_or_default();
734                Ok(record)
735            })
736            .collect()
737    }
738}
739
740fn task_id_of(text: String) -> Result<TaskId, DbError> {
741    TaskId::new(text).map_err(|e| DbError::InvalidData {
742        what: "task_instances.task_id",
743        reason: e.to_string(),
744    })
745}
746
747fn run_record(row: RunRow) -> Result<RunRecord, DbError> {
748    let (
749        id,
750        dag_id,
751        kind,
752        state,
753        planned_for,
754        since,
755        triggered_at,
756        triggered_by,
757        started,
758        ended,
759        late_failure,
760        parent_run_id,
761        backfill_id,
762        backfill_index,
763        backfill_total,
764    ) = row;
765    Ok(RunRecord {
766        id,
767        dag_id: DagId::new(dag_id).map_err(|e| DbError::InvalidData {
768            what: "runs.dag_id",
769            reason: e.to_string(),
770        })?,
771        kind: from_name("runs.kind", kind)?,
772        state: from_name("runs.state", state)?,
773        planned_for: parse_time("runs.planned_for", &planned_for)?,
774        since: parse_time("runs.since", &since)?,
775        triggered_at: parse_time("runs.triggered_at", &triggered_at)?,
776        triggered_by,
777        started_at: optional_time("runs.started_at", started)?,
778        ended_at: optional_time("runs.ended_at", ended)?,
779        late_failure,
780        parent_run_id,
781        backfill: backfill_id.map(|id| BackfillPlace {
782            id,
783            index: u32::try_from(backfill_index).unwrap_or(0),
784            total: u32::try_from(backfill_total).unwrap_or(0),
785        }),
786    })
787}
788
789fn attempt_record(row: AttemptRow) -> Result<AttemptRecord, DbError> {
790    let (
791        id,
792        try_number,
793        worker_id,
794        status,
795        exit_code,
796        error_kind,
797        error_summary,
798        assigned,
799        started,
800        ended,
801        duration_ms,
802        peak_memory,
803        start_method,
804        usage,
805        core_dumped,
806        chained_run_id,
807    ) = row;
808    Ok(AttemptRecord {
809        id,
810        try_number: u32::try_from(try_number).unwrap_or(0),
811        worker_id,
812        status: status
813            .map(|s| from_name("attempts.status", s))
814            .transpose()?,
815        exit_code,
816        error_kind,
817        error_summary,
818        assigned_at: parse_time("attempts.assigned_at", &assigned)?,
819        started_at: optional_time("attempts.started_at", started)?,
820        ended_at: optional_time("attempts.ended_at", ended)?,
821        duration_ms: duration_ms.and_then(|ms| u64::try_from(ms).ok()),
822        peak_memory_bytes: peak_memory.and_then(|bytes| u64::try_from(bytes).ok()),
823        start_method,
824        usage: usage
825            .map(|json| from_json("attempts.usage", &json))
826            .transpose()?,
827        core_dumped,
828        cleanup: CleanupRecord::default(),
829        chained_run_id,
830    })
831}