Skip to main content

schedr_db/
attempts.rs

1//! Attempts: one try of a task instance on a worker.
2//!
3//! An assignment is stored **before** `AssignTask` is sent: the task instance becomes
4//! `running` and its try number goes up, in one transaction that only succeeds while it is
5//! `queued` (two passes can't assign it twice). An attempt's first end wins: delivery is at
6//! least once, so a repeated `Finished` changes nothing (see archive/PROJECT.md, Task assignment).
7
8use std::collections::{BTreeMap, BTreeSet};
9use std::sync::Arc;
10
11use jiff::Timestamp;
12use schedr_model::{AttemptStatus, CleanupResult, Dag, DagId, RunKind, TaskId, TaskInstanceState};
13use uuid::Uuid;
14
15use crate::database::{Database, DbError};
16use crate::query::{db_time, from_json, from_name, in_tx, on_pool, parse_time, sql, sql_text};
17
18/// The rows of open assignments not started yet, whenever and wherever (the read's cutoff and
19/// workers left out: its check says yes more often, never less; decision 485).
20macro_rules! unstarted_any_time_from {
21    () => {
22        "FROM attempts a WHERE a.status IS NULL AND a.chained_run_id IS NULL AND a.started_at IS NULL"
23    };
24}
25pub(crate) use unstarted_any_time_from;
26
27/// The rows of moved cleanups not started yet, whenever and wherever (as above).
28macro_rules! unstarted_cleanups_any_time_from {
29    () => {
30        "FROM attempts a WHERE a.status IS NULL AND a.chained_run_id IS NULL AND a.moved_at IS NOT NULL"
31    };
32}
33pub(crate) use unstarted_cleanups_any_time_from;
34
35/// The rows of a replaced incarnation's open attempts: the read's `FROM ... WHERE` and its probe check's (decision 485).
36macro_rules! replaced_from {
37    () => {
38        "FROM attempts WHERE status IS NULL AND replaced_at IS NOT NULL"
39    };
40}
41pub(crate) use replaced_from;
42
43/// The rows of unschedulable instances of running runs: the read's `FROM ... WHERE` and its probe check's (decision 485).
44macro_rules! unschedulable_from {
45    () => {
46        "FROM task_instances t JOIN runs r ON r.id = t.run_id WHERE t.state = 'unschedulable' AND r.state = 'running'"
47    };
48}
49pub(crate) use unschedulable_from;
50
51/// The rows of open `TriggerDagOperator` attempts: the read's `FROM ... WHERE` and its probe check's (decision 485).
52macro_rules! chained_from {
53    () => {
54        "FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id JOIN runs r ON r.id = t.run_id LEFT JOIN runs c ON c.id = a.chained_run_id WHERE a.status IS NULL AND a.chained_run_id IS NOT NULL"
55    };
56}
57pub(crate) use chained_from;
58
59/// The rows queued for assignment at `$1`: the read's `FROM ... WHERE` and its probe check's (decision 485).
60macro_rules! ready_from {
61    () => {
62        "FROM task_instances t JOIN runs r ON r.id = t.run_id JOIN dag_versions v ON v.id = r.dag_version_id JOIN parse_results p ON p.id = v.parse_result_id WHERE t.state = 'queued' AND t.ready_at <= $1{ts} AND (t.look_at IS NULL OR t.look_at <= $1{ts}) AND r.state = 'running' AND t.cancel_requested_at IS NULL"
63    };
64}
65pub(crate) use ready_from;
66
67/// The rows of moved cleanups waiting for a worker, whenever they may go: the read's `FROM ... WHERE` and its probe check's (decision 485).
68macro_rules! waiting_cleanups_any_time_from {
69    () => {
70        "FROM attempts a WHERE a.status IS NULL AND a.worker_id IS NULL AND a.chained_run_id IS NULL"
71    };
72}
73pub(crate) use waiting_cleanups_any_time_from;
74
75/// The most tasks one query reads the outputs of.
76const OUTPUTS_PER_QUERY: usize = 500;
77
78/// The most instances claimed by one statement (and attempts inserted, four parameters each).
79const CLAIMS_PER_STATEMENT: usize = 200;
80
81#[cfg(test)]
82mod tests;
83
84/// A task instance of a running run waiting for a worker (`unschedulable`).
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct Unschedulable {
87    /// The run's ID.
88    pub run_id: String,
89    /// The task.
90    pub task_id: TaskId,
91    /// Its place among a mapped task's instances; -1 for an unmapped task.
92    pub map_index: i32,
93    /// The DAG version the run runs.
94    pub dag: Arc<Dag>,
95    /// Since when it is `unschedulable`.
96    pub since: Timestamp,
97}
98
99/// An open `TriggerDagOperator` attempt (see [`Database::chained_attempts`]).
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct ChainedAttempt {
102    /// The attempt's ID.
103    pub id: String,
104    /// Its task instance's ID.
105    pub instance_id: String,
106    /// The run it belongs to (the parent of the run it starts).
107    pub run_id: String,
108    /// Its task.
109    pub task_id: TaskId,
110    /// Its instance (-1: the whole task).
111    pub map_index: i32,
112    /// When it started.
113    pub started_at: Timestamp,
114    /// The run it starts.
115    pub chained_run_id: String,
116    /// That run's state; `None` while it isn't created.
117    pub chained_state: Option<schedr_model::RunState>,
118    /// When that run ended, if it has.
119    pub chained_ended_at: Option<Timestamp>,
120    /// The parent run's DAG.
121    pub dag: Arc<Dag>,
122    /// Whether the parent run, or this task of it, is being cancelled.
123    pub cancel_requested: bool,
124    /// The parent run's kind.
125    pub run_kind: RunKind,
126    /// The parent run's `planned_for`.
127    pub planned_for: Timestamp,
128    /// The parent run's `since`.
129    pub since: Timestamp,
130}
131
132/// A queued task instance of a running run, ready to be assigned.
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct ReadyInstance {
135    /// The task instance's ID.
136    pub instance_id: String,
137    /// The run's ID.
138    pub run_id: String,
139    /// The task.
140    pub task_id: TaskId,
141    /// Its try number so far (the next attempt is this plus one).
142    pub try_number: u32,
143    /// The run's kind.
144    pub run_kind: RunKind,
145    /// The moment the run is for.
146    pub planned_for: Timestamp,
147    /// The start of the run's window.
148    pub since: Timestamp,
149    /// The DAG version the run runs (shared: the cache's, see [`Database::dag_version`]).
150    pub dag: Arc<Dag>,
151    /// That version's ID.
152    pub version_id: String,
153    /// The content hash of the code that version was parsed from (the worker reports what it
154    /// actually ran).
155    pub content_hash: String,
156    /// Why it waits, as shown.
157    pub queued_reason: Option<String>,
158    /// The schedr version of the parse its DAG version came from: workers older than this
159    /// don't get it.
160    pub parse_version: String,
161    /// Its place among a mapped task's instances; -1 for an unmapped task.
162    pub map_index: i32,
163}
164
165/// An open attempt, as the concurrency limits count it.
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct ActiveAttempt {
168    /// The attempt's ID.
169    pub attempt_id: String,
170    /// Its run's DAG.
171    pub dag_id: DagId,
172    /// Its run.
173    pub run_id: String,
174    /// Its task.
175    pub task_id: TaskId,
176}
177
178/// One instance of a mapped task, as its downstream tasks see it.
179#[derive(Debug, Clone, PartialEq)]
180pub struct InstanceResult {
181    /// Its place, from 0.
182    pub map_index: i32,
183    /// Its state.
184    pub state: TaskInstanceState,
185    /// Its outcome, once it succeeded.
186    pub outcome: Option<String>,
187    /// Its output (stored JSON), once it succeeded.
188    pub output: Option<serde_json::Value>,
189}
190
191/// A stored attempt.
192#[derive(Debug, Clone, PartialEq, Eq)]
193pub struct StoredAttempt {
194    /// Its ID.
195    pub id: String,
196    /// Its task instance.
197    pub instance_id: String,
198    /// The run.
199    pub run_id: String,
200    /// The task.
201    pub task_id: TaskId,
202    /// Its try number.
203    pub try_number: u32,
204    /// The worker it was assigned to.
205    pub worker_id: String,
206    /// How it ended; `None` while it runs.
207    pub status: Option<AttemptStatus>,
208    /// Whether the worker reported `Started`.
209    pub started: bool,
210    /// Its task instance's place among a mapped task's instances; -1 for an unmapped task.
211    pub map_index: i32,
212    /// Whether the task's result is kept while its cleanup runs.
213    pub result_kept: bool,
214    /// How many times its cleanup moved to another worker.
215    pub cleanup_moves: u32,
216    /// Whether its moved cleanup was assigned, and hasn't been started yet.
217    pub moving: bool,
218}
219
220/// How an attempt ended.
221#[derive(Debug, Clone, PartialEq, Eq)]
222pub struct AttemptEnd {
223    /// Its status.
224    pub status: AttemptStatus,
225    /// The process's exit code, if it exited.
226    pub exit_code: Option<i32>,
227    /// The signal that killed it, if one did.
228    pub signal: Option<i32>,
229    /// The peak memory of its process tree.
230    pub peak_memory_bytes: Option<u64>,
231    /// What its process used (its parent's view at its exit), if the worker read it.
232    pub usage: Option<schedr_model::runner::ProcessUsage>,
233    /// Whether its process dumped core.
234    pub core_dumped: bool,
235    /// How long it ran, measured by the worker with a monotonic clock (the start and end
236    /// timestamps come from the master's wall clock, which can step).
237    pub duration_ms: Option<u64>,
238    /// The error kind schedr recognised.
239    pub error_kind: Option<String>,
240    /// The structured error summary, as JSON text.
241    pub error_summary: Option<String>,
242    /// The content hash the code ran with.
243    pub code_hash: Option<String>,
244    /// How its cleanup ended; `None` for a task without one.
245    pub cleanup: Option<CleanupEnd>,
246}
247
248/// How an attempt's cleanup ended.
249#[derive(Debug, Clone, PartialEq, Eq)]
250pub struct CleanupEnd {
251    /// Its result.
252    pub result: CleanupResult,
253    /// How many tries it took.
254    pub tries: u32,
255    /// How long its tries ran, in milliseconds.
256    pub duration_ms: u64,
257    /// The error kind of its last try.
258    pub error_kind: Option<String>,
259    /// The error summary of its last try, as JSON text.
260    pub error_summary: Option<String>,
261}
262
263impl AttemptEnd {
264    /// An end decided by the master (`lost`, `assignment_expired`): only a status.
265    #[must_use]
266    pub const fn by_master(status: AttemptStatus) -> Self {
267        Self {
268            status,
269            exit_code: None,
270            signal: None,
271            peak_memory_bytes: None,
272            usage: None,
273            core_dumped: false,
274            duration_ms: None,
275            error_kind: None,
276            error_summary: None,
277            code_hash: None,
278            cleanup: None,
279        }
280    }
281}
282
283type ReadyRow = (
284    String,
285    String,
286    String,
287    i32,
288    String,
289    String,
290    String,
291    String,
292    String,
293    Option<String>,
294    String,
295    i32,
296    bool,
297);
298type AttemptRow = (
299    String,
300    String,
301    String,
302    String,
303    i32,
304    Option<String>,
305    Option<String>,
306    bool,
307    i32,
308    bool,
309    i32,
310    bool,
311);
312
313/// The attempt queries (sqlx needs `'static` text, so the shared columns are written out).
314/// The most attempt ends one statement records (16 parameters each: well under either
315/// database's limit).
316pub const ENDS_PER_STATEMENT: usize = 100;
317
318const ATTEMPT_BY_ID: &str = "SELECT a.id{text}, a.task_instance_id{text}, t.run_id{text}, \
319    t.task_id, a.try_number, a.worker_id, a.status, a.started_at IS NOT NULL, \
320    t.map_index, a.task_result IS NOT NULL, a.cleanup_moves, \
321    a.moved_at IS NOT NULL FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
322    WHERE a.id = $1{uuid}";
323const OPEN_ATTEMPTS: &str = "SELECT a.id{text}, a.task_instance_id{text}, t.run_id{text}, \
324    t.task_id, a.try_number, a.worker_id, a.status, a.started_at IS NOT NULL, \
325    t.map_index, a.task_result IS NOT NULL, a.cleanup_moves, \
326    a.moved_at IS NOT NULL FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
327    WHERE a.status IS NULL AND a.chained_run_id IS NULL AND ($1 IS NULL OR a.worker_id = $1) \
328    ORDER BY a.assigned_at, a.id";
329const UNSTARTED_CLEANUPS: &str = "SELECT a.id{text}, a.task_instance_id{text}, t.run_id{text}, \
330    t.task_id, a.try_number, a.worker_id, a.status, a.started_at IS NOT NULL, \
331    t.map_index, a.task_result IS NOT NULL, a.cleanup_moves, \
332    a.moved_at IS NOT NULL FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
333    WHERE a.status IS NULL AND a.chained_run_id IS NULL AND a.moved_at < $1{ts} \
334    AND a.worker_id NOT IN (SELECT value FROM {json_each}($3{json})) \
335    ORDER BY a.moved_at LIMIT $2";
336const ACTIVE_ATTEMPTS: &str = "SELECT a.id{text}, r.dag_id, t.run_id{text}, t.task_id \
337    FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
338    JOIN runs r ON r.id = t.run_id WHERE a.status IS NULL AND a.chained_run_id IS NULL \
339    ORDER BY a.id";
340const UNSTARTED_ATTEMPTS: &str = "SELECT a.id{text}, a.task_instance_id{text}, t.run_id{text}, \
341    t.task_id, a.try_number, a.worker_id, a.status, a.started_at IS NOT NULL, \
342    t.map_index, a.task_result IS NOT NULL, a.cleanup_moves, \
343    a.moved_at IS NOT NULL FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
344    WHERE a.status IS NULL AND a.chained_run_id IS NULL AND a.started_at IS NULL \
345    AND a.assigned_at < $1{ts} \
346    AND a.worker_id NOT IN (SELECT value FROM {json_each}($3{json})) \
347    ORDER BY a.assigned_at, a.id LIMIT $2";
348
349impl Database {
350    /// Queued task instances of running runs not being cancelled, ready at `now`: resources'
351    /// cleanups first (a cancelled run's too, decision 277), then oldest ready first.
352    ///
353    /// # Errors
354    ///
355    /// [`DbError`] if the query fails or stored data doesn't read.
356    pub async fn ready_instances(&self, now: Timestamp) -> Result<Vec<ReadyInstance>, DbError> {
357        const READY: &str = concat!(
358            "SELECT t.id{text}, r.id{text}, t.task_id, t.try_number, r.kind, \
359            {ts<}r.planned_for{>ts}, {ts<}r.since{>ts}, r.dag_version_id{text}, p.content_hash, \
360            t.queued_reason, p.schedr_version, t.map_index, r.cancel_requested_at IS NOT NULL ",
361            ready_from!(),
362            " ORDER BY t.ready_at, t.id"
363        );
364        if self.skipped_at(crate::probe::Check::Ready, now).await? {
365            return Ok(Vec::new());
366        }
367        let rows: Vec<ReadyRow> = on_pool!(self, |pool, backend| {
368            sqlx::query_as(sql(backend, READY))
369                .bind(db_time(now))
370                .fetch_all(pool)
371                .await?
372        });
373        // Each run's DAG from the cache, by version: a row no longer brings the whole
374        // definition along, once per ready task (B13).
375        let mut ready_list = Vec::with_capacity(rows.len());
376        for row in rows {
377            let run_cancelling = row.12;
378            let dag = self.dag_version(&row.7).await?;
379            let cleanup = dag
380                .resource_of_cleanup(&task_id_of(row.2.clone())?)
381                .is_some();
382            // A cancelled run's tasks don't start, but its resources' cleanups do (decision 277).
383            if run_cancelling && !cleanup {
384                continue;
385            }
386            ready_list.push((cleanup, ready(row, dag)?));
387        }
388        // Cleanups first, a paid cluster going before queued work (decision 225); the sort is
389        // stable, so the oldest first among each.
390        ready_list.sort_by_key(|(cleanup, _)| !*cleanup);
391        Ok(ready_list.into_iter().map(|(_, r)| r).collect())
392    }
393
394    /// Assigns a queued task instance to a worker: it becomes `running` with a new attempt.
395    /// Returns the attempt's ID and try number; `None` if the instance isn't queued any more.
396    ///
397    /// # Errors
398    ///
399    /// [`DbError::Sqlx`] if a statement fails (nothing is stored then).
400    pub async fn assign_attempt(
401        &self,
402        instance_id: &str,
403        worker_id: &str,
404        now: Timestamp,
405    ) -> Result<Option<(String, u32)>, DbError> {
406        const CLAIM: &str = "UPDATE task_instances SET state = 'running', \
407            try_number = try_number + 1, ready_at = NULL, queued_reason = NULL, updated_at = $1{ts} \
408            WHERE id = $2{uuid} AND state = 'queued'";
409        const TRY: &str = "SELECT try_number FROM task_instances WHERE id = $1{uuid}";
410        const INSERT: &str = "INSERT INTO attempts \
411            (id, task_instance_id, try_number, worker_id, assigned_at) \
412            VALUES ($1{uuid}, $2{uuid}, $3, $4, $5{ts})";
413        let id = Uuid::now_v7().to_string();
414        let now = db_time(now);
415        let try_number: Option<i32> = in_tx!(self, |tx, backend| {
416            let claimed = sqlx::query(sql(backend, CLAIM))
417                .bind(&now)
418                .bind(instance_id)
419                .execute(&mut *tx)
420                .await?
421                .rows_affected();
422            if claimed == 1 {
423                let try_number: i32 = sqlx::query_scalar(sql(backend, TRY))
424                    .bind(instance_id)
425                    .fetch_one(&mut *tx)
426                    .await?;
427                sqlx::query(sql(backend, INSERT))
428                    .bind(&id)
429                    .bind(instance_id)
430                    .bind(try_number)
431                    .bind(worker_id)
432                    .bind(&now)
433                    .execute(&mut *tx)
434                    .await?;
435                Some(try_number)
436            } else {
437                None
438            }
439        });
440        Ok(try_number.map(|n| (id, u32::try_from(n).unwrap_or(0))))
441    }
442
443    /// [`Self::assign_attempt`] for a round's whole batch (decision 482): each
444    /// `(instance, worker, attempt)` whose instance is still queued becomes `running` with that
445    /// new attempt, in two statements over many rows (the claim, then the attempts). Returns the
446    /// try number of each instance claimed; one no longer queued is left out.
447    ///
448    /// # Errors
449    ///
450    /// [`DbError::Sqlx`] if a statement fails (nothing is stored then).
451    pub async fn claim_attempts(
452        &self,
453        claims: &[(&str, &str, &str)],
454        now: Timestamp,
455    ) -> Result<BTreeMap<String, u32>, DbError> {
456        // One transaction for every chunk (Grok's review): never part of a batch stored.
457        Box::pin(self.atomically(self.claim_chunks(claims, now))).await
458    }
459
460    async fn claim_chunks(
461        &self,
462        claims: &[(&str, &str, &str)],
463        now: Timestamp,
464    ) -> Result<BTreeMap<String, u32>, DbError> {
465        let now = db_time(now);
466        let mut tries: BTreeMap<String, u32> = BTreeMap::new();
467        for chunk in claims.chunks(CLAIMS_PER_STATEMENT) {
468            let ids: Vec<String> = (2..chunk.len() + 2)
469                .map(|n| format!("${n}{{uuid}}"))
470                .collect();
471            let claim = format!(
472                "UPDATE task_instances SET state = 'running', try_number = try_number + 1, \
473                 ready_at = NULL, queued_reason = NULL, updated_at = $1{{ts}} \
474                 WHERE state = 'queued' AND id IN ({}) RETURNING id{{text}}, try_number",
475                ids.join(", ")
476            );
477            // The claim and its attempts in one transaction: never one without the other.
478            let claimed: BTreeMap<String, u32> = in_tx!(self, |tx, backend| {
479                let mut query =
480                    sqlx::query_as::<_, (String, i32)>(sql_text(backend, &claim)).bind(&now);
481                for (instance, _, _) in chunk {
482                    query = query.bind(*instance);
483                }
484                let claimed: BTreeMap<String, u32> = query
485                    .fetch_all(&mut *tx)
486                    .await?
487                    .into_iter()
488                    .map(|(id, n)| (id, u32::try_from(n).unwrap_or(0)))
489                    .collect();
490                let rows: Vec<&(&str, &str, &str)> = chunk
491                    .iter()
492                    .filter(|(instance, _, _)| claimed.contains_key(*instance))
493                    .collect();
494                if !rows.is_empty() {
495                    let values: Vec<String> = (0..rows.len())
496                        .map(|i| {
497                            let n = i * 4 + 2;
498                            format!(
499                                "(${n}{{uuid}}, ${}{{uuid}}, ${}, ${}, $1{{ts}})",
500                                n + 1,
501                                n + 2,
502                                n + 3
503                            )
504                        })
505                        .collect();
506                    let insert = format!(
507                        "INSERT INTO attempts (id, task_instance_id, try_number, worker_id, \
508                         assigned_at) VALUES {}",
509                        values.join(", ")
510                    );
511                    let mut query = sqlx::query(sql_text(backend, &insert)).bind(&now);
512                    for (instance, worker, attempt) in &rows {
513                        let try_number = i32::try_from(claimed[*instance]).unwrap_or(i32::MAX);
514                        query = query
515                            .bind(*attempt)
516                            .bind(*instance)
517                            .bind(try_number)
518                            .bind(*worker);
519                    }
520                    query.execute(&mut *tx).await?;
521                }
522                claimed
523            });
524            tries.extend(claimed);
525        }
526        Ok(tries)
527    }
528
529    /// Starts a `TriggerDagOperator`'s attempt (decisions 361, 380): the queued instance becomes
530    /// `running` with a new attempt that no worker runs, started at once, recording the run it
531    /// starts (`chained_run_id`) before that run is created. Returns the attempt's ID and try
532    /// number; `None` if the instance isn't queued any more.
533    ///
534    /// # Errors
535    ///
536    /// [`DbError::Sqlx`] if a statement fails (nothing is stored then).
537    pub async fn start_chained_attempt(
538        &self,
539        instance_id: &str,
540        chained_run_id: &str,
541        now: Timestamp,
542    ) -> Result<Option<(String, u32)>, DbError> {
543        const CLAIM: &str = "UPDATE task_instances SET state = 'running', \
544            try_number = try_number + 1, ready_at = NULL, queued_reason = NULL, updated_at = $1{ts} \
545            WHERE id = $2{uuid} AND state = 'queued'";
546        const TRY: &str = "SELECT try_number FROM task_instances WHERE id = $1{uuid}";
547        const INSERT: &str = "INSERT INTO attempts \
548            (id, task_instance_id, try_number, assigned_at, started_at, chained_run_id) \
549            VALUES ($1{uuid}, $2{uuid}, $3, $4{ts}, $4{ts}, $5{uuid})";
550        let id = Uuid::now_v7().to_string();
551        let now = db_time(now);
552        let try_number: Option<i32> = in_tx!(self, |tx, backend| {
553            let claimed = sqlx::query(sql(backend, CLAIM))
554                .bind(&now)
555                .bind(instance_id)
556                .execute(&mut *tx)
557                .await?
558                .rows_affected();
559            if claimed == 1 {
560                let try_number: i32 = sqlx::query_scalar(sql(backend, TRY))
561                    .bind(instance_id)
562                    .fetch_one(&mut *tx)
563                    .await?;
564                sqlx::query(sql(backend, INSERT))
565                    .bind(&id)
566                    .bind(instance_id)
567                    .bind(try_number)
568                    .bind(&now)
569                    .bind(chained_run_id)
570                    .execute(&mut *tx)
571                    .await?;
572                Some(try_number)
573            } else {
574                None
575            }
576        });
577        Ok(try_number.map(|n| (id, u32::try_from(n).unwrap_or(0))))
578    }
579
580    /// The `TriggerDagOperator` attempts still open (decision 361), each with the run it
581    /// started (`None` while that run isn't created yet: a master stopped in between) and its
582    /// parent run's state.
583    ///
584    /// # Errors
585    ///
586    /// [`DbError`] if the query fails or a row doesn't read.
587    pub async fn chained_attempts(&self) -> Result<Vec<ChainedAttempt>, DbError> {
588        const OPEN: &str = concat!(
589            "SELECT a.id{text}, t.id{text}, t.run_id{text}, t.task_id, \
590            t.map_index, {ts<}a.assigned_at{>ts}, a.chained_run_id{text}, c.state, \
591            r.dag_version_id{text}, \
592            (r.cancel_requested_at IS NOT NULL OR t.cancel_requested_at IS NOT NULL), \
593            r.kind, {ts<}r.planned_for{>ts}, {ts<}r.since{>ts}, {ts<}c.ended_at{>ts} ",
594            chained_from!(),
595            " ORDER BY a.assigned_at, a.id"
596        );
597        type Row = (
598            String,
599            String,
600            String,
601            String,
602            i32,
603            String,
604            String,
605            Option<String>,
606            String,
607            bool,
608            String,
609            String,
610            String,
611            Option<String>,
612        );
613        if self.skipped(crate::probe::Check::ChainedAttempts).await? {
614            return Ok(Vec::new());
615        }
616        let rows: Vec<Row> = on_pool!(self, |pool, backend| {
617            sqlx::query_as(sql(backend, OPEN)).fetch_all(pool).await?
618        });
619        let mut found = Vec::with_capacity(rows.len());
620        for row in rows {
621            let (id, instance_id, run_id, task_id, map_index, at, chained, state, version, cancel) = (
622                row.0, row.1, row.2, row.3, row.4, row.5, row.6, row.7, row.8, row.9,
623            );
624            found.push(ChainedAttempt {
625                id,
626                instance_id,
627                run_id,
628                task_id: TaskId::new(&task_id).map_err(|e| DbError::InvalidData {
629                    what: "task_instances.task_id",
630                    reason: e.to_string(),
631                })?,
632                map_index,
633                started_at: parse_time("attempts.assigned_at", &at)?,
634                chained_run_id: chained,
635                chained_state: state.map(|s| from_name("runs.state", s)).transpose()?,
636                dag: self.dag_version(&version).await?,
637                cancel_requested: cancel,
638                run_kind: from_name("runs.kind", row.10)?,
639                planned_for: parse_time("runs.planned_for", &row.11)?,
640                since: parse_time("runs.since", &row.12)?,
641                chained_ended_at: row
642                    .13
643                    .map(|at| parse_time("runs.ended_at", &at))
644                    .transpose()?,
645            });
646        }
647        Ok(found)
648    }
649
650    /// Takes back an assignment the worker rejected: the attempt is deleted (a rejection is
651    /// not a try), the try number goes back, and the instance gets `state` (`queued`, ready at
652    /// `ready_at`, or `unschedulable`) with `reason` to show.
653    ///
654    /// # Errors
655    ///
656    /// [`DbError::Sqlx`] if a statement fails (nothing is stored then).
657    pub async fn undo_assignment(
658        &self,
659        attempt_id: &str,
660        state: TaskInstanceState,
661        ready_at: Option<Timestamp>,
662        reason: Option<&str>,
663        now: Timestamp,
664    ) -> Result<(), DbError> {
665        const RESET: &str = "UPDATE task_instances SET state = $1, ready_at = $2{ts}, \
666            queued_reason = $3, try_number = try_number - 1, updated_at = $4{ts} \
667            WHERE id = (SELECT task_instance_id FROM attempts WHERE id = $5{uuid}) \
668            AND state = 'running'";
669        const DELETE: &str = "DELETE FROM attempts WHERE id = $1{uuid} AND status IS NULL";
670        in_tx!(self, |tx, backend| {
671            sqlx::query(sql(backend, RESET))
672                .bind(state.to_string())
673                .bind(ready_at.map(db_time))
674                .bind(reason)
675                .bind(db_time(now))
676                .bind(attempt_id)
677                .execute(&mut *tx)
678                .await?;
679            sqlx::query(sql(backend, DELETE))
680                .bind(attempt_id)
681                .execute(&mut *tx)
682                .await?;
683        });
684        Ok(())
685    }
686
687    /// An attempt by ID.
688    ///
689    /// # Errors
690    ///
691    /// [`DbError`] if the query fails or stored data doesn't read.
692    /// When an instance's first attempt started: a wait step's `max_wait` runs from then
693    /// (decision 321).
694    ///
695    /// # Errors
696    ///
697    /// [`DbError`] if the statement fails or a time doesn't read.
698    pub async fn first_start(&self, instance_id: &str) -> Result<Option<Timestamp>, DbError> {
699        const FIRST: &str = "SELECT {ts<}started_at{>ts} FROM attempts \
700            WHERE task_instance_id = $1{uuid} AND started_at IS NOT NULL \
701            ORDER BY started_at LIMIT 1";
702        let first: Option<String> = on_pool!(self, |pool, backend| {
703            sqlx::query_scalar(sql(backend, FIRST))
704                .bind(instance_id)
705                .fetch_optional(pool)
706                .await?
707        });
708        first
709            .map(|at| parse_time("attempts.started_at", &at))
710            .transpose()
711    }
712
713    /// [`Self::first_start`] of each of `instance_ids` at once (a round's ready wait steps,
714    /// decision 482): the instances never started are absent.
715    ///
716    /// # Errors
717    ///
718    /// [`DbError`] if a statement fails or a time doesn't read.
719    pub async fn first_starts(
720        &self,
721        instance_ids: &[&str],
722    ) -> Result<BTreeMap<String, Timestamp>, DbError> {
723        let mut first = BTreeMap::new();
724        for chunk in instance_ids.chunks(OUTPUTS_PER_QUERY) {
725            let wanted: Vec<String> = (1..=chunk.len()).map(|n| format!("${n}{{uuid}}")).collect();
726            let text = format!(
727                "SELECT task_instance_id{{text}}, {{ts<}}MIN(started_at){{>ts}} FROM attempts \
728                 WHERE started_at IS NOT NULL AND task_instance_id IN ({}) \
729                 GROUP BY task_instance_id",
730                wanted.join(", ")
731            );
732            let rows: Vec<(String, String)> = on_pool!(self, |pool, backend| {
733                let mut query = sqlx::query_as(sql_text(backend, &text));
734                for id in chunk {
735                    query = query.bind(*id);
736                }
737                query.fetch_all(pool).await?
738            });
739            for (instance_id, at) in rows {
740                first.insert(instance_id, parse_time("attempts.started_at", &at)?);
741            }
742        }
743        Ok(first)
744    }
745
746    /// An attempt by its ID.
747    ///
748    /// # Errors
749    ///
750    /// [`DbError`] if the statement fails or a row doesn't read.
751    pub async fn attempt(&self, attempt_id: &str) -> Result<Option<StoredAttempt>, DbError> {
752        let query = ATTEMPT_BY_ID;
753        let row: Option<AttemptRow> = on_pool!(self, |pool, backend| {
754            sqlx::query_as(sql(backend, query))
755                .bind(attempt_id)
756                .fetch_optional(pool)
757                .await?
758        });
759        row.map(stored_attempt).transpose()
760    }
761
762    /// Attempts still running (no end recorded), of one worker or of every worker.
763    ///
764    /// # Errors
765    ///
766    /// [`DbError`] if the query fails or stored data doesn't read.
767    pub async fn open_attempts(
768        &self,
769        worker_id: Option<&str>,
770    ) -> Result<Vec<StoredAttempt>, DbError> {
771        let query = OPEN_ATTEMPTS;
772        let rows: Vec<AttemptRow> = on_pool!(self, |pool, backend| {
773            sqlx::query_as(sql(backend, query))
774                .bind(worker_id)
775                .fetch_all(pool)
776                .await?
777        });
778        rows.into_iter().map(stored_attempt).collect()
779    }
780
781    /// Marks open attempts as left behind by a replaced incarnation (decision 443): they end
782    /// `lost` once its lease is over. A mark already made stands.
783    ///
784    /// # Errors
785    ///
786    /// [`DbError`] if a write fails.
787    pub async fn mark_replaced(
788        &self,
789        attempt_ids: &[String],
790        now: Timestamp,
791    ) -> Result<(), DbError> {
792        const MARK: &str = "UPDATE attempts SET replaced_at = COALESCE(replaced_at, $1{ts}) \
793            WHERE id = $2{uuid} AND status IS NULL";
794        in_tx!(self, |tx, backend| {
795            for attempt_id in attempt_ids {
796                sqlx::query(sql(backend, MARK))
797                    .bind(db_time(now))
798                    .bind(attempt_id)
799                    .execute(&mut *tx)
800                    .await?;
801            }
802        });
803        Ok(())
804    }
805
806    /// Clears the marks of [`Self::mark_replaced`]: the hold did its work (ended or moved the
807    /// attempt), or a worker's journal reports it, alive (Grok's review of decision 443).
808    ///
809    /// # Errors
810    ///
811    /// [`DbError`] if a write fails.
812    pub async fn clear_replaced(&self, attempt_ids: &[String]) -> Result<(), DbError> {
813        const CLEAR: &str = "UPDATE attempts SET replaced_at = NULL \
814            WHERE id = $1{uuid} AND replaced_at IS NOT NULL";
815        in_tx!(self, |tx, backend| {
816            for attempt_id in attempt_ids {
817                sqlx::query(sql(backend, CLEAR))
818                    .bind(attempt_id)
819                    .execute(&mut *tx)
820                    .await?;
821            }
822        });
823        Ok(())
824    }
825
826    /// The open attempts a replaced incarnation left behind ([`Self::mark_replaced`]).
827    ///
828    /// # Errors
829    ///
830    /// [`DbError`] if the query fails.
831    pub async fn replaced_attempts(&self) -> Result<Vec<String>, DbError> {
832        const REPLACED: &str = concat!(
833            "SELECT id{text} ",
834            replaced_from!(),
835            " ORDER BY replaced_at, id"
836        );
837        if self.skipped(crate::probe::Check::ReplacedAttempts).await? {
838            return Ok(Vec::new());
839        }
840        Ok(on_pool!(self, |pool, backend| {
841            sqlx::query_scalar(sql(backend, REPLACED))
842                .fetch_all(pool)
843                .await?
844        }))
845    }
846
847    /// Keeps the task's result of an open attempt while its cleanup runs (decision 229).
848    ///
849    /// # Errors
850    ///
851    /// [`DbError`] if the write fails.
852    pub async fn set_task_result(&self, attempt_id: &str, result: &[u8]) -> Result<(), DbError> {
853        // The first stands: a cleanup that moved reports no result of its own.
854        const SET: &str = "UPDATE attempts SET task_result = $1 \
855            WHERE id = $2{uuid} AND status IS NULL AND task_result IS NULL";
856        in_tx!(self, |tx, backend| {
857            sqlx::query(sql(backend, SET))
858                .bind(result)
859                .bind(attempt_id)
860                .execute(&mut *tx)
861                .await?;
862        });
863        Ok(())
864    }
865
866    /// The task's result kept for an attempt, if its process's end was reported.
867    ///
868    /// # Errors
869    ///
870    /// [`DbError`] if the query fails.
871    pub async fn task_result(&self, attempt_id: &str) -> Result<Option<Vec<u8>>, DbError> {
872        const GET: &str = "SELECT task_result FROM attempts WHERE id = $1{uuid}";
873        let row: Option<(Option<Vec<u8>>,)> = on_pool!(self, |pool, backend| {
874            sqlx::query_as(sql(backend, GET))
875                .bind(attempt_id)
876                .fetch_optional(pool)
877                .await?
878        });
879        Ok(row.and_then(|(result,)| result))
880    }
881
882    /// Adds handles an attempt registered, from place `first` on, keeping what is there (they
883    /// are sent again after a reconnect), up to `limit` bytes in all. Returns whether all
884    /// fitted.
885    ///
886    /// # Errors
887    ///
888    /// [`DbError`] if a statement fails.
889    pub async fn add_cleanup_handles(
890        &self,
891        attempt_id: &str,
892        first: u32,
893        handles: &[String],
894        limit: usize,
895    ) -> Result<bool, DbError> {
896        const STORED: &str = "SELECT position, CAST(OCTET_LENGTH(handle) AS BIGINT) \
897            FROM cleanup_handles WHERE attempt_id = $1{uuid}";
898        const ADD: &str = "INSERT INTO cleanup_handles (attempt_id, position, handle) \
899            VALUES ($1{uuid}, $2, $3) ON CONFLICT (attempt_id, position) DO NOTHING";
900        let fitted = in_tx!(self, |tx, backend| {
901            let stored: Vec<(i32, i64)> = sqlx::query_as(sql(backend, STORED))
902                .bind(attempt_id)
903                .fetch_all(&mut *tx)
904                .await?;
905            let mut size = stored.iter().fold(0_usize, |size, (_, bytes)| {
906                size.saturating_add(usize::try_from(*bytes).unwrap_or(usize::MAX))
907            });
908            let taken: BTreeSet<i32> = stored.into_iter().map(|(position, _)| position).collect();
909            let mut fitted = true;
910            for (index, handle) in handles.iter().enumerate() {
911                // From a worker: `first` may be anything.
912                let index = u32::try_from(index).unwrap_or(u32::MAX);
913                let position = i32::try_from(first.saturating_add(index)).unwrap_or(i32::MAX);
914                // Sent again: what is kept counts once, and what follows it still fits.
915                if taken.contains(&position) {
916                    continue;
917                }
918                size = size.saturating_add(handle.len());
919                if size > limit {
920                    fitted = false;
921                    break;
922                }
923                sqlx::query(sql(backend, ADD))
924                    .bind(attempt_id)
925                    .bind(position)
926                    .bind(handle)
927                    .execute(&mut *tx)
928                    .await?;
929            }
930            fitted
931        });
932        Ok(fitted)
933    }
934
935    /// How many of an attempt's handles the master has from the first on without a gap: a
936    /// worker holding more cleans those after them (B169). One stored past a gap is cleaned
937    /// there again rather than one in the gap left behind (Codex's review of B169).
938    ///
939    /// # Errors
940    ///
941    /// [`DbError`] if the query fails.
942    pub async fn cleanup_handles_unbroken(&self, attempt_id: &str) -> Result<u32, DbError> {
943        const POSITIONS: &str = "SELECT position FROM cleanup_handles \
944            WHERE attempt_id = $1{uuid} ORDER BY position";
945        let rows: Vec<(i32,)> = on_pool!(self, |pool, backend| {
946            sqlx::query_as(sql(backend, POSITIONS))
947                .bind(attempt_id)
948                .fetch_all(pool)
949                .await?
950        });
951        let unbroken = rows
952            .iter()
953            .zip(0_i32..)
954            .take_while(|((position,), expected)| position == expected)
955            .count();
956        Ok(u32::try_from(unbroken).unwrap_or(u32::MAX))
957    }
958
959    /// An attempt's handles, each as JSON text, in registration order.
960    ///
961    /// # Errors
962    ///
963    /// [`DbError`] if the query fails.
964    pub async fn cleanup_handles(&self, attempt_id: &str) -> Result<Vec<String>, DbError> {
965        const HANDLES: &str = "SELECT handle FROM cleanup_handles WHERE attempt_id = $1{uuid} \
966            ORDER BY position";
967        let rows: Vec<(String,)> = on_pool!(self, |pool, backend| {
968            sqlx::query_as(sql(backend, HANDLES))
969                .bind(attempt_id)
970                .fetch_all(pool)
971                .await?
972        });
973        Ok(rows.into_iter().map(|(handle,)| handle).collect())
974    }
975
976    /// Takes an attempt's cleanup off its worker, to wait for another (decision 243), with
977    /// the task's result if none is kept yet, counting a move (decision 247).
978    ///
979    /// # Errors
980    ///
981    /// [`DbError`] if the write fails.
982    pub async fn move_cleanup(
983        &self,
984        attempt_id: &str,
985        result: &[u8],
986        not_before: Timestamp,
987    ) -> Result<(), DbError> {
988        const MOVE: &str = "UPDATE attempts SET moved_from = worker_id, worker_id = NULL, \
989            cleanup_origin = COALESCE(cleanup_origin, worker_id), \
990            moved_at = NULL, cleanup_moves = cleanup_moves + 1, \
991            task_result = COALESCE(task_result, $1), \
992            cleanup_not_before = $2{ts} WHERE id = $3{uuid} AND status IS NULL";
993        in_tx!(self, |tx, backend| {
994            sqlx::query(sql(backend, MOVE))
995                .bind(result)
996                .bind(db_time(not_before))
997                .bind(attempt_id)
998                .execute(&mut *tx)
999                .await?;
1000        });
1001        Ok(())
1002    }
1003
1004    /// Gives a cleanup waiting to move back to the worker it moved from, which came back
1005    /// holding handles the master never got (B169): the move is undone, and with
1006    /// `drop_result` the task's result the move kept goes too (the worker reports its own).
1007    /// `false` if it no longer waits for a worker, or moved from another.
1008    ///
1009    /// # Errors
1010    ///
1011    /// [`DbError::Sqlx`] if the statement fails.
1012    pub async fn take_back_cleanup(
1013        &self,
1014        attempt_id: &str,
1015        worker_id: &str,
1016        drop_result: bool,
1017    ) -> Result<bool, DbError> {
1018        const BACK: &str = "UPDATE attempts SET worker_id = $1, moved_from = NULL, \
1019            moved_at = NULL, cleanup_not_before = NULL, cleanup_moves = cleanup_moves - 1, \
1020            cleanup_origin = CASE WHEN cleanup_moves = 1 THEN NULL ELSE cleanup_origin END, \
1021            task_result = CASE WHEN $2 THEN NULL ELSE task_result END \
1022            WHERE id = $3{uuid} AND status IS NULL AND worker_id IS NULL AND moved_from = $1 \
1023            AND cleanup_moves > 0";
1024        let updated = in_tx!(self, |tx, backend| {
1025            sqlx::query(sql(backend, BACK))
1026                .bind(worker_id)
1027                .bind(drop_result)
1028                .bind(attempt_id)
1029                .execute(&mut *tx)
1030                .await?
1031                .rows_affected()
1032        });
1033        Ok(updated == 1)
1034    }
1035
1036    /// The worker an attempt's cleanup first moved from (the one that ran its task), while no
1037    /// rest of its cleanup was added (B169): handles it registered that the master never got
1038    /// are cleaned there. Moves after the first don't change it (Codex's review of B169).
1039    ///
1040    /// # Errors
1041    ///
1042    /// [`DbError`] if the read fails.
1043    pub async fn rest_owed_by(&self, attempt_id: &str) -> Result<Option<String>, DbError> {
1044        const FROM: &str = "SELECT cleanup_origin FROM attempts \
1045            WHERE id = $1{uuid} AND NOT rest_cleaned";
1046        let row: Option<(Option<String>,)> = on_pool!(self, |pool, backend| {
1047            sqlx::query_as(sql(backend, FROM))
1048                .bind(attempt_id)
1049                .fetch_optional(pool)
1050                .await?
1051        });
1052        Ok(row.and_then(|(from,)| from))
1053    }
1054
1055    /// The worker an open attempt's cleanup moved from, while it waits for another (no worker
1056    /// yet): that worker's late result still counts (decision 282).
1057    ///
1058    /// # Errors
1059    ///
1060    /// [`DbError`] if the read fails.
1061    pub async fn cleanup_moved_from(&self, attempt_id: &str) -> Result<Option<String>, DbError> {
1062        const FROM: &str = "SELECT moved_from FROM attempts \
1063            WHERE id = $1{uuid} AND status IS NULL AND worker_id IS NULL";
1064        let row: Option<(Option<String>,)> = on_pool!(self, |pool, backend| {
1065            sqlx::query_as(sql(backend, FROM))
1066                .bind(attempt_id)
1067                .fetch_optional(pool)
1068                .await?
1069        });
1070        Ok(row.and_then(|(from,)| from))
1071    }
1072
1073    /// Gives a moved cleanup to `worker_id`, if it still waits. Returns whether it did.
1074    ///
1075    /// # Errors
1076    ///
1077    /// [`DbError`] if the write fails.
1078    pub async fn assign_cleanup(
1079        &self,
1080        attempt_id: &str,
1081        worker_id: &str,
1082        now: Timestamp,
1083    ) -> Result<bool, DbError> {
1084        const ASSIGN: &str = "UPDATE attempts SET worker_id = $1, moved_at = $2{ts} \
1085            WHERE id = $3{uuid} AND status IS NULL AND worker_id IS NULL";
1086        const REASON: &str = "UPDATE task_instances SET queued_reason = NULL \
1087            WHERE id = (SELECT task_instance_id FROM attempts WHERE id = $1{uuid})";
1088        let updated = in_tx!(self, |tx, backend| {
1089            let updated = sqlx::query(sql(backend, ASSIGN))
1090                .bind(worker_id)
1091                .bind(db_time(now))
1092                .bind(attempt_id)
1093                .execute(&mut *tx)
1094                .await?
1095                .rows_affected();
1096            sqlx::query(sql(backend, REASON))
1097                .bind(attempt_id)
1098                .execute(&mut *tx)
1099                .await?;
1100            updated
1101        });
1102        Ok(updated == 1)
1103    }
1104
1105    /// Takes back a moved cleanup its worker refused or never started: it waits again, no
1106    /// move counted.
1107    ///
1108    /// # Errors
1109    ///
1110    /// [`DbError`] if the write fails.
1111    pub async fn unassign_cleanup(&self, attempt_id: &str) -> Result<(), DbError> {
1112        // Taken back, no worker runs it: no replaced incarnation's hold on it either.
1113        const BACK: &str = "UPDATE attempts SET worker_id = NULL, moved_at = NULL, \
1114            replaced_at = NULL WHERE id = $1{uuid} AND status IS NULL";
1115        in_tx!(self, |tx, backend| {
1116            sqlx::query(sql(backend, BACK))
1117                .bind(attempt_id)
1118                .execute(&mut *tx)
1119                .await?;
1120        });
1121        Ok(())
1122    }
1123
1124    /// The moved cleanups assigned before `cutoff` and not started, but those of
1125    /// `except_workers`.
1126    ///
1127    /// # Errors
1128    ///
1129    /// [`DbError`] if the query fails or stored data doesn't read.
1130    pub async fn unstarted_cleanups(
1131        &self,
1132        cutoff: Timestamp,
1133        except_workers: &[String],
1134        limit: u32,
1135    ) -> Result<Vec<StoredAttempt>, DbError> {
1136        if self.skipped(crate::probe::Check::UnstartedCleanups).await? {
1137            return Ok(Vec::new());
1138        }
1139        let except = serde_json::to_string(except_workers).unwrap_or_else(|_| "[]".to_owned());
1140        let query = UNSTARTED_CLEANUPS;
1141        let rows: Vec<AttemptRow> = on_pool!(self, |pool, backend| {
1142            sqlx::query_as(sql(backend, query))
1143                .bind(db_time(cutoff))
1144                .bind(i64::from(limit))
1145                .bind(&except)
1146                .fetch_all(pool)
1147                .await?
1148        });
1149        rows.into_iter().map(stored_attempt).collect()
1150    }
1151
1152    /// The moved cleanups waiting for a worker, oldest first: each attempt's ID, and what an
1153    /// assignment needs.
1154    ///
1155    /// # Errors
1156    ///
1157    /// [`DbError`] if the query fails or stored data doesn't read.
1158    pub async fn waiting_cleanups(
1159        &self,
1160        now: Timestamp,
1161    ) -> Result<Vec<(String, ReadyInstance)>, DbError> {
1162        const WAITING: &str = "SELECT t.id{text}, r.id{text}, t.task_id, t.try_number, r.kind, \
1163            {ts<}r.planned_for{>ts}, {ts<}r.since{>ts}, r.dag_version_id{text}, p.content_hash, \
1164            t.queued_reason, p.schedr_version, t.map_index, r.cancel_requested_at IS NOT NULL \
1165            FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
1166            JOIN runs r ON r.id = t.run_id \
1167            JOIN dag_versions v ON v.id = r.dag_version_id \
1168            JOIN parse_results p ON p.id = v.parse_result_id \
1169            WHERE a.status IS NULL AND a.worker_id IS NULL AND a.chained_run_id IS NULL \
1170            AND a.cleanup_not_before <= $1{ts} \
1171            ORDER BY a.assigned_at, a.id";
1172        const IDS: &str = concat!(
1173            "SELECT a.id{text}, a.task_instance_id{text} ",
1174            waiting_cleanups_any_time_from!()
1175        );
1176        if self.skipped(crate::probe::Check::WaitingCleanups).await? {
1177            return Ok(Vec::new());
1178        }
1179        let rows: Vec<ReadyRow> = on_pool!(self, |pool, backend| {
1180            sqlx::query_as(sql(backend, WAITING))
1181                .bind(db_time(now))
1182                .fetch_all(pool)
1183                .await?
1184        });
1185        if rows.is_empty() {
1186            return Ok(Vec::new());
1187        }
1188        let ids: Vec<(String, String)> = on_pool!(self, |pool, backend| {
1189            sqlx::query_as(sql(backend, IDS)).fetch_all(pool).await?
1190        });
1191        let mut waiting = Vec::with_capacity(rows.len());
1192        for row in rows {
1193            let dag = self.dag_version(&row.7).await?;
1194            let instance = ready(row, dag)?;
1195            if let Some((attempt, _)) = ids.iter().find(|(_, i)| *i == instance.instance_id) {
1196                waiting.push((attempt.clone(), instance));
1197            }
1198        }
1199        Ok(waiting)
1200    }
1201
1202    /// Every open attempt (no end recorded) with its DAG, run and task: what the concurrency
1203    /// limits count (decision 88A), read when the master starts dispatching.
1204    ///
1205    /// # Errors
1206    ///
1207    /// [`DbError`] if the query fails or stored data doesn't read.
1208    pub async fn active_attempts(&self) -> Result<Vec<ActiveAttempt>, DbError> {
1209        let query = ACTIVE_ATTEMPTS;
1210        let rows: Vec<(String, String, String, String)> = on_pool!(self, |pool, backend| {
1211            sqlx::query_as(sql(backend, query)).fetch_all(pool).await?
1212        });
1213        rows.into_iter()
1214            .map(|(attempt_id, dag_id, run_id, task_id)| {
1215                Ok(ActiveAttempt {
1216                    attempt_id,
1217                    dag_id: DagId::new(dag_id).map_err(|e| DbError::InvalidData {
1218                        what: "runs.dag_id",
1219                        reason: e.to_string(),
1220                    })?,
1221                    run_id,
1222                    task_id: task_id_of(task_id)?,
1223                })
1224            })
1225            .collect()
1226    }
1227
1228    /// The open attempts of `dag_id`'s runs, counted by run and task: `(run, task, count)`
1229    /// (the DAG page's limits with their counts, decision 96).
1230    ///
1231    /// # Errors
1232    ///
1233    /// [`DbError`] if the query fails or stored data doesn't read.
1234    pub async fn active_counts(
1235        &self,
1236        dag_id: &DagId,
1237    ) -> Result<Vec<(String, TaskId, u32)>, DbError> {
1238        const COUNTS: &str = "SELECT t.run_id{text}, t.task_id, COUNT(*) \
1239            FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
1240            JOIN runs r ON r.id = t.run_id WHERE a.status IS NULL AND a.chained_run_id IS NULL \
1241            AND r.dag_id = $1 \
1242            GROUP BY t.run_id, t.task_id ORDER BY t.run_id, t.task_id";
1243        let rows: Vec<(String, String, i64)> = on_pool!(self, |pool, backend| {
1244            sqlx::query_as(sql(backend, COUNTS))
1245                .bind(dag_id.as_str())
1246                .fetch_all(pool)
1247                .await?
1248        });
1249        rows.into_iter()
1250            .map(|(run, task, count)| {
1251                Ok((
1252                    run,
1253                    task_id_of(task)?,
1254                    u32::try_from(count).unwrap_or(u32::MAX),
1255                ))
1256            })
1257            .collect()
1258    }
1259
1260    /// The oldest `limit` attempts assigned before `cutoff` that never reported `Started`, but
1261    /// those of `except_workers` (workers that may come back: left out before the limit, so
1262    /// they can't fill it, F14's review),
1263    /// oldest assigned first (a backlog read a round's worth at a time, B52).
1264    ///
1265    /// # Errors
1266    ///
1267    /// [`DbError`] if the query fails or stored data doesn't read.
1268    pub async fn unstarted_attempts(
1269        &self,
1270        cutoff: Timestamp,
1271        except_workers: &[String],
1272        limit: u32,
1273    ) -> Result<Vec<StoredAttempt>, DbError> {
1274        if self.skipped(crate::probe::Check::Unstarted).await? {
1275            return Ok(Vec::new());
1276        }
1277        let except = serde_json::to_string(except_workers).unwrap_or_else(|_| "[]".to_owned());
1278        let query = UNSTARTED_ATTEMPTS;
1279        let rows: Vec<AttemptRow> = on_pool!(self, |pool, backend| {
1280            sqlx::query_as(sql(backend, query))
1281                .bind(db_time(cutoff))
1282                .bind(i64::from(limit))
1283                .bind(&except)
1284                .fetch_all(pool)
1285                .await?
1286        });
1287        rows.into_iter().map(stored_attempt).collect()
1288    }
1289
1290    /// Records `Started` for a running attempt, started `at` (the worker's start in master
1291    /// time, M5.1m, never before its assignment; a start already recorded is kept). Returns
1292    /// whether it is still running.
1293    ///
1294    /// # Errors
1295    ///
1296    /// [`DbError::Sqlx`] if the statement fails.
1297    pub async fn mark_started(
1298        &self,
1299        attempt_id: &str,
1300        start_method: &str,
1301        at: Timestamp,
1302    ) -> Result<bool, DbError> {
1303        const START: &str = "UPDATE attempts SET started_at = COALESCE(started_at, \
1304            CASE WHEN $1{ts} < assigned_at THEN assigned_at ELSE $1{ts} END), \
1305            start_method = $2, moved_at = NULL WHERE id = $3{uuid} AND status IS NULL";
1306        let now = at;
1307        let updated = in_tx!(self, |tx, backend| {
1308            sqlx::query(sql(backend, START))
1309                .bind(db_time(now))
1310                .bind(start_method)
1311                .bind(attempt_id)
1312                .execute(&mut *tx)
1313                .await?
1314                .rows_affected()
1315        });
1316        Ok(updated == 1)
1317    }
1318
1319    /// Records `Started` for several running attempts started by `start_method`, each `at` its
1320    /// own time, as [`Self::mark_started`] does each, in one statement (M5.1d, M5.1m). Returns
1321    /// the IDs still running.
1322    ///
1323    /// # Errors
1324    ///
1325    /// [`DbError::Sqlx`] if the statement fails.
1326    pub async fn mark_started_many(
1327        &self,
1328        starts: &[(&str, Timestamp)],
1329        start_method: &str,
1330    ) -> Result<BTreeSet<String>, DbError> {
1331        // Each start a pair `[id, time]` of a JSON list, read as rows on each database.
1332        const SQLITE: &str = "UPDATE attempts SET started_at = COALESCE(attempts.started_at, \
1333            CASE WHEN p.at < attempts.assigned_at THEN attempts.assigned_at ELSE p.at END), \
1334            start_method = $1, moved_at = NULL \
1335            FROM (SELECT json_extract(value, '$[0]') AS id, json_extract(value, '$[1]') AS at \
1336            FROM json_each($2)) p \
1337            WHERE attempts.id = p.id AND attempts.status IS NULL RETURNING attempts.id";
1338        const POSTGRES: &str = "UPDATE attempts a SET started_at = COALESCE(a.started_at, \
1339            CASE WHEN p.at < a.assigned_at THEN a.assigned_at ELSE p.at END), \
1340            start_method = $1, moved_at = NULL \
1341            FROM (SELECT (value->>0)::uuid AS id, (value->>1)::timestamptz AS at \
1342            FROM jsonb_array_elements($2::jsonb)) p \
1343            WHERE a.id = p.id AND a.status IS NULL RETURNING a.id::text";
1344        if starts.is_empty() {
1345            return Ok(BTreeSet::new());
1346        }
1347        let pairs: Vec<(&str, String)> =
1348            starts.iter().map(|(id, at)| (*id, db_time(*at))).collect();
1349        let list = crate::query::to_json(&pairs);
1350        let started: Vec<String> = in_tx!(self, |tx, backend| {
1351            let query = match backend {
1352                crate::backend::Backend::Sqlite => SQLITE,
1353                crate::backend::Backend::Postgres => POSTGRES,
1354            };
1355            sqlx::query_scalar(sql(backend, query))
1356                .bind(start_method)
1357                .bind(&list)
1358                .fetch_all(&mut *tx)
1359                .await?
1360        });
1361        Ok(started.into_iter().collect())
1362    }
1363
1364    /// Records that a running attempt has started, with no start method: its worker
1365    /// reconnected with it in its journal, its `Started` perhaps lost (B50). A start already
1366    /// recorded is kept.
1367    ///
1368    /// # Errors
1369    ///
1370    /// [`DbError::Sqlx`] if the statement fails.
1371    pub async fn mark_adopted(&self, attempt_id: &str, now: Timestamp) -> Result<(), DbError> {
1372        const START: &str = "UPDATE attempts SET started_at = COALESCE(started_at, $1{ts}), \
1373            moved_at = NULL WHERE id = $2{uuid} AND status IS NULL";
1374        in_tx!(self, |tx, backend| {
1375            sqlx::query(sql(backend, START))
1376                .bind(db_time(now))
1377                .bind(attempt_id)
1378                .execute(&mut *tx)
1379                .await?
1380                .rows_affected()
1381        });
1382        Ok(())
1383    }
1384
1385    /// Several attempts by ID (M4B.4: a turn's `Finished`s read in one query); those that
1386    /// don't exist are left out.
1387    ///
1388    /// # Errors
1389    ///
1390    /// [`DbError`] if the query fails or stored data doesn't read.
1391    pub async fn attempts_by_ids(&self, ids: &[&str]) -> Result<Vec<StoredAttempt>, DbError> {
1392        const BY_IDS: &str = "SELECT a.id{text}, a.task_instance_id{text}, t.run_id{text}, \
1393            t.task_id, a.try_number, a.worker_id, a.status, a.started_at IS NOT NULL, \
1394            t.map_index, a.task_result IS NOT NULL, a.cleanup_moves, \
1395            a.moved_at IS NOT NULL FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
1396            WHERE a.id IN (SELECT value{uuid} FROM {json_each}($1{json}))";
1397        if ids.is_empty() {
1398            return Ok(Vec::new());
1399        }
1400        let list = crate::query::to_json(&ids);
1401        let rows: Vec<AttemptRow> = on_pool!(self, |pool, backend| {
1402            sqlx::query_as(sql(backend, BY_IDS))
1403                .bind(&list)
1404                .fetch_all(pool)
1405                .await?
1406        });
1407        rows.into_iter().map(stored_attempt).collect()
1408    }
1409
1410    /// Records how several attempts ended, as [`Self::end_attempt`] does each, in statements of
1411    /// up to [`ENDS_PER_STATEMENT`] (M4B.4, B184). Returns the IDs whose end this call recorded
1412    /// (not those ended already). Each ID at most once.
1413    ///
1414    /// # Errors
1415    ///
1416    /// [`DbError::Sqlx`] if a statement fails.
1417    pub async fn end_attempts(
1418        &self,
1419        ends: &[(&str, &AttemptEnd)],
1420        now: Timestamp,
1421    ) -> Result<BTreeSet<String>, DbError> {
1422        let now = db_time(now);
1423        let mut recorded = BTreeSet::new();
1424        in_tx!(self, |tx, backend| {
1425            for chunk in ends.chunks(ENDS_PER_STATEMENT) {
1426                let rows: Vec<String> = (0..chunk.len())
1427                    .map(|i| {
1428                        let n = 1 + i * 16;
1429                        format!(
1430                            "(${}{{uuid}}, ${}, ${}, ${}, ${}, ${}, ${}{{json}}, ${}, ${}, \
1431                             ${}{{json}}, ${}, ${}, ${}, ${}, ${}, ${}{{json}})",
1432                            n + 1,
1433                            n + 2,
1434                            n + 3,
1435                            n + 4,
1436                            n + 5,
1437                            n + 6,
1438                            n + 7,
1439                            n + 8,
1440                            n + 9,
1441                            n + 10,
1442                            n + 11,
1443                            n + 12,
1444                            n + 13,
1445                            n + 14,
1446                            n + 15,
1447                            n + 16
1448                        )
1449                    })
1450                    .collect();
1451                // As `end_attempt`'s, joined to a list of values: `columnN` names them.
1452                let text = format!(
1453                    "UPDATE attempts AS t SET status = v.column2, exit_code = v.column3, \
1454                     signal = v.column4, peak_memory_bytes = v.column5, error_kind = v.column6, \
1455                     error_summary = v.column7, code_hash = v.column8, ended_at = $1{{ts}}, \
1456                     duration_ms = v.column9, usage = v.column10, core_dumped = v.column11, \
1457                     cleanup_result = CASE WHEN NOT t.rest_cleaned THEN v.column12 \
1458                         WHEN t.cleanup_result IN ('failed', 'worker_lost') THEN t.cleanup_result \
1459                         WHEN v.column12 IN ('failed', 'worker_lost') THEN v.column12 \
1460                         WHEN t.cleanup_result = 'ok' OR v.column12 = 'ok' THEN 'ok' \
1461                         ELSE COALESCE(v.column12, t.cleanup_result) END, \
1462                     cleanup_tries = CASE WHEN NOT t.rest_cleaned THEN v.column13 \
1463                         ELSE COALESCE(t.cleanup_tries, 0) + COALESCE(v.column13, 0) END, \
1464                     cleanup_duration_ms = CASE WHEN NOT t.rest_cleaned THEN v.column14 \
1465                         ELSE COALESCE(t.cleanup_duration_ms, 0) + COALESCE(v.column14, 0) END, \
1466                     cleanup_error_kind = CASE WHEN NOT t.rest_cleaned THEN v.column15 \
1467                         ELSE COALESCE(t.cleanup_error_kind, v.column15) END, \
1468                     cleanup_error_summary = CASE WHEN NOT t.rest_cleaned THEN v.column16 \
1469                         ELSE COALESCE(t.cleanup_error_summary, v.column16) END, \
1470                     task_result = NULL \
1471                     FROM (VALUES {}) AS v \
1472                     WHERE t.id = v.column1 AND t.status IS NULL RETURNING id{{text}}",
1473                    rows.join(", ")
1474                );
1475                let mut update =
1476                    sqlx::query_scalar::<_, String>(sql_text(backend, &text)).bind(&now);
1477                for (attempt_id, end) in chunk {
1478                    let cleanup = end.cleanup.as_ref();
1479                    update = update
1480                        .bind(*attempt_id)
1481                        .bind(end.status.to_string())
1482                        .bind(end.exit_code)
1483                        .bind(end.signal)
1484                        .bind(
1485                            end.peak_memory_bytes
1486                                .map(|b| i64::try_from(b).unwrap_or(i64::MAX)),
1487                        )
1488                        .bind(end.error_kind.as_deref())
1489                        .bind(end.error_summary.clone().map(crate::query::storable_json))
1490                        .bind(end.code_hash.as_deref())
1491                        .bind(
1492                            end.duration_ms
1493                                .map(|ms| i64::try_from(ms).unwrap_or(i64::MAX)),
1494                        )
1495                        .bind(end.usage.as_ref().map(crate::query::to_json))
1496                        .bind(end.core_dumped)
1497                        .bind(cleanup.map(|c| c.result.to_string()))
1498                        .bind(cleanup.map(|c| i64::from(c.tries)))
1499                        .bind(cleanup.map(|c| i64::try_from(c.duration_ms).unwrap_or(i64::MAX)))
1500                        .bind(cleanup.and_then(|c| c.error_kind.as_deref()))
1501                        .bind(
1502                            cleanup
1503                                .and_then(|c| c.error_summary.clone())
1504                                .map(crate::query::storable_json),
1505                        );
1506                }
1507                recorded.extend(update.fetch_all(&mut *tx).await?);
1508            }
1509        });
1510        Ok(recorded)
1511    }
1512
1513    /// Records how an attempt ended, unless an end is already recorded. Returns whether this
1514    /// call recorded it. A rest cleanup added before (B169, [`Self::add_rest_cleanup`]) is
1515    /// kept: the two cleanups' results combine as there.
1516    ///
1517    /// # Errors
1518    ///
1519    /// [`DbError::Sqlx`] if the statement fails.
1520    pub async fn end_attempt(
1521        &self,
1522        attempt_id: &str,
1523        end: &AttemptEnd,
1524        now: Timestamp,
1525    ) -> Result<bool, DbError> {
1526        const END: &str = "UPDATE attempts SET status = $1, exit_code = $2, signal = $3, \
1527            peak_memory_bytes = $4, error_kind = $5, error_summary = $6{json}, code_hash = $7, \
1528            ended_at = $8{ts}, duration_ms = $9, usage = $10{json}, core_dumped = $11, \
1529            cleanup_result = CASE WHEN NOT rest_cleaned THEN $12 \
1530                WHEN cleanup_result IN ('failed', 'worker_lost') THEN cleanup_result \
1531                WHEN $12 IN ('failed', 'worker_lost') THEN $12 \
1532                WHEN cleanup_result = 'ok' OR $12 = 'ok' THEN 'ok' \
1533                ELSE COALESCE($12, cleanup_result) END, \
1534            cleanup_tries = CASE WHEN NOT rest_cleaned THEN $13 \
1535                ELSE COALESCE(cleanup_tries, 0) + COALESCE($13, 0) END, \
1536            cleanup_duration_ms = CASE WHEN NOT rest_cleaned THEN $14 \
1537                ELSE COALESCE(cleanup_duration_ms, 0) + COALESCE($14, 0) END, \
1538            cleanup_error_kind = CASE WHEN NOT rest_cleaned THEN $15 \
1539                ELSE COALESCE(cleanup_error_kind, $15) END, \
1540            cleanup_error_summary = CASE WHEN NOT rest_cleaned THEN $16{json} \
1541                ELSE COALESCE(cleanup_error_summary, $16{json}) END, \
1542            task_result = NULL \
1543            WHERE id = $17{uuid} AND status IS NULL";
1544        let cleanup = end.cleanup.as_ref();
1545        let updated = in_tx!(self, |tx, backend| {
1546            sqlx::query(sql(backend, END))
1547                .bind(end.status.to_string())
1548                .bind(end.exit_code)
1549                .bind(end.signal)
1550                .bind(
1551                    end.peak_memory_bytes
1552                        .map(|b| i64::try_from(b).unwrap_or(i64::MAX)),
1553                )
1554                .bind(end.error_kind.as_deref())
1555                .bind(end.error_summary.clone().map(crate::query::storable_json))
1556                .bind(end.code_hash.as_deref())
1557                .bind(db_time(now))
1558                .bind(
1559                    end.duration_ms
1560                        .map(|ms| i64::try_from(ms).unwrap_or(i64::MAX)),
1561                )
1562                .bind(end.usage.as_ref().map(crate::query::to_json))
1563                .bind(end.core_dumped)
1564                .bind(cleanup.map(|c| c.result.to_string()))
1565                .bind(cleanup.map(|c| i64::from(c.tries)))
1566                .bind(cleanup.map(|c| i64::try_from(c.duration_ms).unwrap_or(i64::MAX)))
1567                .bind(cleanup.and_then(|c| c.error_kind.as_deref()))
1568                .bind(
1569                    cleanup
1570                        .and_then(|c| c.error_summary.clone())
1571                        .map(crate::query::storable_json),
1572                )
1573                .bind(attempt_id)
1574                .bind(true)
1575                .execute(&mut *tx)
1576                .await?
1577                .rows_affected()
1578        });
1579        Ok(updated == 1)
1580    }
1581
1582    /// Adds the cleanup of the handles a moved cleanup didn't have (B169: registered while
1583    /// the master couldn't hear the worker, which ran it on its return) to the attempt's: a
1584    /// failure of either (`failed`, `worker_lost`) is the result, else either's `ok`; tries and time add up, the rest's
1585    /// error is kept. Before the attempt ends, its end combines with it. Once only: `false`
1586    /// if a rest was added already.
1587    ///
1588    /// # Errors
1589    ///
1590    /// [`DbError::Sqlx`] if the statement fails.
1591    pub async fn add_rest_cleanup(
1592        &self,
1593        attempt_id: &str,
1594        rest: &CleanupEnd,
1595    ) -> Result<bool, DbError> {
1596        const ADD: &str = "UPDATE attempts SET \
1597            cleanup_result = CASE WHEN cleanup_result IN ('failed', 'worker_lost') \
1598                THEN cleanup_result \
1599                WHEN $1 IN ('failed', 'worker_lost') THEN $1 \
1600                WHEN cleanup_result = 'ok' OR $1 = 'ok' THEN 'ok' ELSE $1 END, \
1601            cleanup_tries = COALESCE(cleanup_tries, 0) + $2, \
1602            cleanup_duration_ms = COALESCE(cleanup_duration_ms, 0) + $3, \
1603            cleanup_error_kind = COALESCE($4, cleanup_error_kind), \
1604            cleanup_error_summary = COALESCE($5{json}, cleanup_error_summary), \
1605            rest_cleaned = $7 \
1606            WHERE id = $6{uuid} AND NOT rest_cleaned";
1607        let updated = in_tx!(self, |tx, backend| {
1608            sqlx::query(sql(backend, ADD))
1609                .bind(rest.result.to_string())
1610                .bind(i64::from(rest.tries))
1611                .bind(i64::try_from(rest.duration_ms).unwrap_or(i64::MAX))
1612                .bind(rest.error_kind.as_deref())
1613                .bind(rest.error_summary.clone().map(crate::query::storable_json))
1614                .bind(attempt_id)
1615                .bind(true)
1616                .execute(&mut *tx)
1617                .await?
1618                .rows_affected()
1619        });
1620        Ok(updated == 1)
1621    }
1622
1623    /// The outputs stored for a run's tasks, by task ID (what downstream tasks get as inputs).
1624    ///
1625    /// # Errors
1626    ///
1627    /// [`DbError`] if the query fails or stored data doesn't read.
1628    pub async fn run_outputs(
1629        &self,
1630        run_id: &str,
1631    ) -> Result<BTreeMap<TaskId, serde_json::Value>, DbError> {
1632        const OUTPUTS: &str = "SELECT t.task_id, o.value{text} FROM outputs o \
1633            JOIN task_instances t ON t.id = o.task_instance_id \
1634            WHERE t.run_id = $1{uuid} AND t.map_index = -1";
1635        let rows: Vec<(String, String)> = on_pool!(self, |pool, backend| {
1636            sqlx::query_as(sql(backend, OUTPUTS))
1637                .bind(run_id)
1638                .fetch_all(pool)
1639                .await?
1640        });
1641        rows.into_iter()
1642            .map(|(task_id, value)| Ok((task_id_of(task_id)?, from_json("outputs.value", &value)?)))
1643            .collect()
1644    }
1645
1646    /// What `tasks` of a run ended with, for a task that uses them: by task ID, the outcome
1647    /// of one that succeeded, `None` for one that was skipped (each of its edges counts as
1648    /// not taken). Tasks in any other state are left out.
1649    ///
1650    /// # Errors
1651    ///
1652    /// [`DbError`] if the query fails or stored data doesn't read.
1653    pub async fn upstream_outcomes(
1654        &self,
1655        run_id: &str,
1656        tasks: &[&TaskId],
1657    ) -> Result<BTreeMap<TaskId, Option<String>>, DbError> {
1658        let mut outcomes = BTreeMap::new();
1659        for chunk in tasks.chunks(OUTPUTS_PER_QUERY) {
1660            let wanted: Vec<String> = (2..chunk.len() + 2).map(|n| format!("${n}")).collect();
1661            let text = format!(
1662                "SELECT task_id, state, outcome FROM task_instances \
1663                 WHERE run_id = $1{{uuid}} AND state IN ('success', 'skipped') \
1664                 AND map_index = -1 AND task_id IN ({})",
1665                wanted.join(", ")
1666            );
1667            let rows: Vec<(String, String, Option<String>)> = on_pool!(self, |pool, backend| {
1668                let mut query = sqlx::query_as(sql_text(backend, &text)).bind(run_id);
1669                for task in chunk {
1670                    query = query.bind(task.as_str());
1671                }
1672                query.fetch_all(pool).await?
1673            });
1674            for (task_id, state, outcome) in rows {
1675                let outcome = (state == "success")
1676                    .then(|| outcome.unwrap_or_else(|| schedr_model::DEFAULT_OUTCOME.to_owned()));
1677                outcomes.insert(task_id_of(task_id)?, outcome);
1678            }
1679        }
1680        Ok(outcomes)
1681    }
1682
1683    /// The outputs stored for `tasks` of a run, by task ID: what one task gets as inputs,
1684    /// without reading every other task's (a wide DAG's assignment read the whole run's, B18).
1685    ///
1686    /// # Errors
1687    ///
1688    /// [`DbError`] if the query fails or stored data doesn't read.
1689    pub async fn outputs_of(
1690        &self,
1691        run_id: &str,
1692        tasks: &[&TaskId],
1693    ) -> Result<BTreeMap<TaskId, serde_json::Value>, DbError> {
1694        let mut outputs = BTreeMap::new();
1695        for chunk in tasks.chunks(OUTPUTS_PER_QUERY) {
1696            let wanted: Vec<String> = (2..chunk.len() + 2).map(|n| format!("${n}")).collect();
1697            let text = format!(
1698                "SELECT t.task_id, o.value{{text}} FROM outputs o \
1699                 JOIN task_instances t ON t.id = o.task_instance_id \
1700                 WHERE t.run_id = $1{{uuid}} AND t.map_index = -1 AND t.task_id IN ({})",
1701                wanted.join(", ")
1702            );
1703            let rows: Vec<(String, String)> = on_pool!(self, |pool, backend| {
1704                let mut query = sqlx::query_as(sql_text(backend, &text)).bind(run_id);
1705                for task in chunk {
1706                    query = query.bind(task.as_str());
1707                }
1708                query.fetch_all(pool).await?
1709            });
1710            for (task_id, value) in rows {
1711                outputs.insert(task_id_of(task_id)?, from_json("outputs.value", &value)?);
1712            }
1713        }
1714        Ok(outputs)
1715    }
1716
1717    /// `tasks` of a run whose success is stored, in the order they ended (`ended_at`: each row
1718    /// of one write a microsecond apart, in its order; a later cleanup result moves only
1719    /// `updated_at`). Those succeeding now aren't among them yet: they ended last.
1720    ///
1721    /// # Errors
1722    ///
1723    /// [`DbError`] if the query fails or a stored ID doesn't read.
1724    pub async fn ended_in_order(
1725        &self,
1726        run_id: &str,
1727        tasks: &[&TaskId],
1728    ) -> Result<Vec<TaskId>, DbError> {
1729        let mut ended: Vec<TaskId> = Vec::new();
1730        // Small: the tasks one `first_of` chooses from. One query, ordered by the database (a
1731        // time as text would follow Postgres's `DateStyle`).
1732        let wanted: Vec<String> = (2..tasks.len() + 2).map(|n| format!("${n}")).collect();
1733        let text = format!(
1734            "SELECT task_id FROM task_instances \
1735             WHERE run_id = $1{{uuid}} AND map_index = -1 AND state = 'success' \
1736             AND task_id IN ({}) ORDER BY ended_at, task_id",
1737            wanted.join(", ")
1738        );
1739        if tasks.is_empty() {
1740            return Ok(ended);
1741        }
1742        let rows: Vec<(String,)> = on_pool!(self, |pool, backend| {
1743            let mut query = sqlx::query_as(sql_text(backend, &text)).bind(run_id);
1744            for task in tasks {
1745                query = query.bind(task.as_str());
1746            }
1747            query.fetch_all(pool).await?
1748        });
1749        for (task_id,) in rows {
1750            ended.push(task_id_of(task_id)?);
1751        }
1752        Ok(ended)
1753    }
1754
1755    /// A mapped task's instances in a run, in `map_index` order: each one's state, and its
1756    /// outcome and output once it succeeded (what a mapped task's whole output and its lanes
1757    /// are made of, decisions 70 and 77).
1758    ///
1759    /// # Errors
1760    ///
1761    /// [`DbError`] if the query fails or stored data doesn't read.
1762    pub async fn instance_results(
1763        &self,
1764        run_id: &str,
1765        task: &TaskId,
1766    ) -> Result<Vec<InstanceResult>, DbError> {
1767        const RESULTS: &str = "SELECT t.map_index, t.state, t.outcome, o.value{text} \
1768            FROM task_instances t LEFT JOIN outputs o ON o.task_instance_id = t.id \
1769            WHERE t.run_id = $1{uuid} AND t.task_id = $2 AND t.map_index >= 0 \
1770            ORDER BY t.map_index";
1771        let rows: Vec<(i32, String, Option<String>, Option<String>)> =
1772            on_pool!(self, |pool, backend| {
1773                sqlx::query_as(sql(backend, RESULTS))
1774                    .bind(run_id)
1775                    .bind(task.as_str())
1776                    .fetch_all(pool)
1777                    .await?
1778            });
1779        rows.into_iter()
1780            .map(|(map_index, state, outcome, value)| {
1781                Ok(InstanceResult {
1782                    map_index,
1783                    state: from_name("task_instances.state", state)?,
1784                    outcome,
1785                    output: value.map(|v| from_json("outputs.value", &v)).transpose()?,
1786                })
1787            })
1788            .collect()
1789    }
1790
1791    /// One instance of a mapped task in a run: its state, and its outcome and output once it
1792    /// succeeded (what a lane gives its downstream instance).
1793    ///
1794    /// # Errors
1795    ///
1796    /// [`DbError`] if the query fails or stored data doesn't read.
1797    pub async fn instance_result(
1798        &self,
1799        run_id: &str,
1800        task: &TaskId,
1801        map_index: i32,
1802    ) -> Result<Option<InstanceResult>, DbError> {
1803        const RESULT: &str = "SELECT t.state, t.outcome, o.value{text} \
1804            FROM task_instances t LEFT JOIN outputs o ON o.task_instance_id = t.id \
1805            WHERE t.run_id = $1{uuid} AND t.task_id = $2 AND t.map_index = $3";
1806        let row: Option<(String, Option<String>, Option<String>)> =
1807            on_pool!(self, |pool, backend| {
1808                sqlx::query_as(sql(backend, RESULT))
1809                    .bind(run_id)
1810                    .bind(task.as_str())
1811                    .bind(map_index)
1812                    .fetch_optional(pool)
1813                    .await?
1814            });
1815        row.map(|(state, outcome, value)| {
1816            Ok(InstanceResult {
1817                map_index,
1818                state: from_name("task_instances.state", state)?,
1819                outcome,
1820                output: value.map(|v| from_json("outputs.value", &v)).transpose()?,
1821            })
1822        })
1823        .transpose()
1824    }
1825
1826    /// The `unschedulable` task instances of running runs: each one's run, task, `map_index`,
1827    /// DAG version and since when it waits (decision 273).
1828    ///
1829    /// # Errors
1830    ///
1831    /// [`DbError`] if the query fails or stored data doesn't read.
1832    pub async fn unschedulable_instances(&self) -> Result<Vec<Unschedulable>, DbError> {
1833        const WAITING: &str = concat!(
1834            "SELECT r.id{text}, t.task_id, t.map_index, \
1835            r.dag_version_id{text}, {ts<}t.updated_at{>ts} ",
1836            unschedulable_from!(),
1837            " ORDER BY t.updated_at"
1838        );
1839        if self.skipped(crate::probe::Check::Unschedulable).await? {
1840            return Ok(Vec::new());
1841        }
1842        let rows: Vec<(String, String, i32, String, String)> = on_pool!(self, |pool, backend| {
1843            sqlx::query_as(sql(backend, WAITING))
1844                .fetch_all(pool)
1845                .await?
1846        });
1847        let mut waiting = Vec::with_capacity(rows.len());
1848        for (run_id, task_id, map_index, version_id, since) in rows {
1849            waiting.push(Unschedulable {
1850                run_id,
1851                task_id: task_id_of(task_id)?,
1852                map_index,
1853                dag: self.dag_version(&version_id).await?,
1854                since: parse_time("task_instances.updated_at", &since)?,
1855            });
1856        }
1857        Ok(waiting)
1858    }
1859
1860    /// Queues every `unschedulable` task instance again (the set of workers changed).
1861    /// Returns how many.
1862    ///
1863    /// # Errors
1864    ///
1865    /// [`DbError::Sqlx`] if the statement fails.
1866    pub async fn requeue_unschedulable(&self, now: Timestamp) -> Result<u64, DbError> {
1867        const REQUEUE: &str = "UPDATE task_instances SET state = 'queued', ready_at = $1{ts}, \
1868            queued_reason = NULL, updated_at = $1{ts} WHERE state = 'unschedulable'";
1869        let updated = in_tx!(self, |tx, backend| {
1870            sqlx::query(sql(backend, REQUEUE))
1871                .bind(db_time(now))
1872                .execute(&mut *tx)
1873                .await?
1874                .rows_affected()
1875        });
1876        Ok(updated)
1877    }
1878}
1879
1880fn task_id_of(text: String) -> Result<TaskId, DbError> {
1881    TaskId::new(text).map_err(|e| DbError::InvalidData {
1882        what: "task_instances.task_id",
1883        reason: e.to_string(),
1884    })
1885}
1886
1887fn ready(row: ReadyRow, dag: Arc<Dag>) -> Result<ReadyInstance, DbError> {
1888    let (
1889        instance_id,
1890        run_id,
1891        task_id,
1892        try_number,
1893        kind,
1894        planned_for,
1895        since,
1896        version_id,
1897        content_hash,
1898        queued_reason,
1899        parse_version,
1900        map_index,
1901        _,
1902    ) = row;
1903    Ok(ReadyInstance {
1904        instance_id,
1905        run_id,
1906        task_id: task_id_of(task_id)?,
1907        try_number: u32::try_from(try_number).unwrap_or(0),
1908        run_kind: from_name("runs.kind", kind)?,
1909        planned_for: parse_time("runs.planned_for", &planned_for)?,
1910        since: parse_time("runs.since", &since)?,
1911        dag,
1912        version_id,
1913        content_hash,
1914        queued_reason,
1915        parse_version,
1916        map_index,
1917    })
1918}
1919
1920fn stored_attempt(row: AttemptRow) -> Result<StoredAttempt, DbError> {
1921    let (
1922        id,
1923        instance_id,
1924        run_id,
1925        task_id,
1926        try_number,
1927        worker_id,
1928        status,
1929        started,
1930        map_index,
1931        kept,
1932        moves,
1933        moving,
1934    ) = row;
1935    Ok(StoredAttempt {
1936        id,
1937        instance_id,
1938        run_id,
1939        task_id: task_id_of(task_id)?,
1940        try_number: u32::try_from(try_number).unwrap_or(0),
1941        worker_id: worker_id.unwrap_or_default(),
1942        status: status
1943            .map(|s| from_name("attempts.status", s))
1944            .transpose()?,
1945        started,
1946        map_index,
1947        result_kept: kept,
1948        cleanup_moves: u32::try_from(moves).unwrap_or(0),
1949        moving,
1950    })
1951}