Skip to main content

schedr_db/
instances.rs

1//! Task instances of runs: created when a run starts, moved forward by the master, and the
2//! run's result when they have all finished.
3
4use std::sync::Arc;
5
6use jiff::Timestamp;
7use schedr_model::{CleanupResult, Dag, RunState, TaskId, TaskInstanceState};
8use uuid::Uuid;
9
10use crate::database::{Database, DbError};
11use crate::query::{
12    db_time, from_json, from_name, in_tx, on_pool, parse_time, sql, sql_text, to_json,
13};
14
15/// The rows of running runs without instances: the read's `FROM ... WHERE` and its probe check's (decision 485).
16macro_rules! newly_running_from {
17    () => {
18        "FROM runs r WHERE r.state = 'running' AND NOT EXISTS (SELECT 1 FROM task_instances t WHERE t.run_id = r.id)"
19    };
20}
21pub(crate) use newly_running_from;
22
23/// The rows up for retry and due at `$1`: the read's `FROM ... WHERE` and its probe check's (decision 485).
24macro_rules! due_retries_from {
25    () => {
26        "FROM task_instances WHERE state = 'up_for_retry' AND ready_at <= $1{ts}"
27    };
28}
29pub(crate) use due_retries_from;
30
31#[cfg(test)]
32mod tests;
33
34/// A running run whose task instances aren't created yet.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct NewlyRunning {
37    /// The run's ID.
38    pub run_id: String,
39    /// The DAG version it runs.
40    pub dag: Arc<Dag>,
41}
42
43/// A stored task instance.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct StoredInstance {
46    /// Its ID.
47    pub id: String,
48    /// The task.
49    pub task_id: TaskId,
50    /// Its place among a mapped task's instances; -1 for an unmapped task, and for a mapped
51    /// task as a whole (decision 74).
52    pub map_index: i32,
53    /// Its state.
54    pub state: TaskInstanceState,
55    /// Attempts made so far.
56    pub try_number: u32,
57    /// Attempts that used a retry.
58    pub retries_used: u32,
59    /// When it became (or becomes) ready to run.
60    pub ready_at: Option<Timestamp>,
61    /// Whether a user asked to cancel it (`schedr tasks cancel`).
62    pub cancel_requested: bool,
63    /// Its outcome, once it succeeded.
64    pub outcome: Option<String>,
65    /// Why it ended without an attempt, when it did (decision 78).
66    pub reason: Option<String>,
67    /// A mapped task as a whole, once expanded: the size of each dimension of its instances.
68    pub map_sizes: Option<Vec<usize>>,
69    /// How its cleanups ended, if it has any: the last, unless one failed.
70    pub cleanup_result: Option<CleanupResult>,
71}
72
73/// A run with its task instances.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct RunTasks {
76    /// The run's state.
77    pub state: RunState,
78    /// Whether a user asked to cancel it.
79    pub cancel_requested: bool,
80    /// The DAG version it runs.
81    pub dag: Arc<Dag>,
82    /// The schedr version of the parse that DAG version came from.
83    pub parse_version: String,
84    /// Its task instances, in task ID order, then `map_index` order.
85    pub instances: Vec<StoredInstance>,
86}
87
88impl RunTasks {
89    /// Whether an attempt of `instance` is being cancelled: it was asked to be, or its run was,
90    /// unless it is a resource's cleanup, which a run's cancel keeps (decision 277).
91    #[must_use]
92    pub fn cancels(&self, instance: &StoredInstance) -> bool {
93        instance.cancel_requested
94            || (self.cancel_requested && self.dag.resource_of_cleanup(&instance.task_id).is_none())
95    }
96
97    /// As [`Self::cancels`], by the instance's ID (`false` for one not in the run).
98    #[must_use]
99    pub fn cancels_instance(&self, instance_id: &str) -> bool {
100        self.instances
101            .iter()
102            .find(|i| i.id == instance_id)
103            .is_some_and(|i| self.cancels(i))
104    }
105}
106
107/// A change to a task instance.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct InstanceUpdate {
110    /// The task.
111    pub task_id: TaskId,
112    /// Which of its instances (-1: an unmapped task, or a mapped one as a whole).
113    pub map_index: i32,
114    /// Its new state.
115    pub state: TaskInstanceState,
116    /// When it is ready to run (`queued`, `up_for_retry`); cleared otherwise.
117    pub ready_at: Option<Timestamp>,
118    /// Its outcome, on success.
119    pub outcome: Option<String>,
120    /// Whether the attempt that led here used a retry.
121    pub used_retry: bool,
122    /// Why it ends without an attempt (decision 78); kept when `None`.
123    pub reason: Option<String>,
124    /// A mapped task that expanded: its dimensions' sizes; kept when `None`.
125    pub map_sizes: Option<Vec<usize>>,
126}
127
128type InstanceRow = (
129    String,
130    String,
131    String,
132    i32,
133    i32,
134    Option<String>,
135    bool,
136    Option<String>,
137    i32,
138    Option<String>,
139    Option<String>,
140    Option<String>,
141);
142/// A run's state, whether it is being cancelled, its DAG version and its parse's version.
143type RunRow = (String, bool, String, String);
144
145/// `updates` with one entry per instance, in the order each first appears: one given
146/// twice ends as its last update says, its used retries added up, as one statement each in
147/// turn did (one statement for many rows would apply one of them, any).
148fn merged(updates: &[InstanceUpdate]) -> Vec<(&InstanceUpdate, i32)> {
149    let mut merged: Vec<(&InstanceUpdate, i32)> = Vec::with_capacity(updates.len());
150    let mut at: std::collections::HashMap<(&TaskId, i32), usize> = std::collections::HashMap::new();
151    for update in updates {
152        let retries = i32::from(update.used_retry);
153        let key = (&update.task_id, update.map_index);
154        if let Some(&i) = at.get(&key) {
155            let used = merged[i].1 + retries;
156            merged[i] = (update, used);
157        } else {
158            at.insert(key, merged.len());
159            merged.push((update, retries));
160        }
161    }
162    merged
163}
164
165/// The most task instances one `UPDATE` changes (eight parameters each).
166const UPDATES_PER_STATEMENT: usize = 500;
167
168/// The most task instances one `INSERT` creates (seven parameters each: well under SQLite's
169/// 32,766 and Postgres's 65,535).
170const INSTANCES_PER_STATEMENT: usize = 500;
171
172impl Database {
173    /// Running runs with no task instances yet, oldest first.
174    ///
175    /// # Errors
176    ///
177    /// [`DbError`] if the query fails or a stored DAG doesn't read.
178    pub async fn newly_running(&self) -> Result<Vec<NewlyRunning>, DbError> {
179        const NEW: &str = concat!(
180            "SELECT r.id{text}, r.dag_version_id{text} ",
181            newly_running_from!(),
182            " ORDER BY r.started_at, r.id"
183        );
184        if self.skipped(crate::probe::Check::NewlyRunning).await? {
185            return Ok(Vec::new());
186        }
187        let rows: Vec<(String, String)> = on_pool!(self, |pool, backend| {
188            sqlx::query_as(sql(backend, NEW)).fetch_all(pool).await?
189        });
190        let mut runs = Vec::with_capacity(rows.len());
191        for (run_id, version_id) in rows {
192            let dag = self.dag_version(&version_id).await?;
193            runs.push(NewlyRunning { run_id, dag });
194        }
195        Ok(runs)
196    }
197
198    /// Creates task instances of a run in their first states: (task, `map_index`, state); a
199    /// run's own when it starts, a mapped task's when it expands.
200    ///
201    /// # Errors
202    ///
203    /// [`DbError::Sqlx`] if a statement fails (nothing is stored then).
204    pub async fn create_instances(
205        &self,
206        run_id: &str,
207        states: &[(TaskId, i32, TaskInstanceState)],
208        now: Timestamp,
209    ) -> Result<(), DbError> {
210        let now_text = db_time(now);
211        // Many rows a statement (a run of a wide DAG was one statement a task, B18), in chunks
212        // that stay under SQLite's and Postgres's limits on parameters.
213        in_tx!(self, |tx, backend| {
214            for chunk in states.chunks(INSTANCES_PER_STATEMENT) {
215                let rows: Vec<String> = (0..chunk.len())
216                    .map(|i| {
217                        let n = i * 7;
218                        format!(
219                            "(${}{{uuid}}, ${}{{uuid}}, ${}, ${}, ${}, ${}{{ts}}, ${}{{ts}})",
220                            n + 1,
221                            n + 2,
222                            n + 3,
223                            n + 4,
224                            n + 5,
225                            n + 6,
226                            n + 7
227                        )
228                    })
229                    .collect();
230                let text = format!(
231                    "INSERT INTO task_instances \
232                     (id, run_id, task_id, map_index, state, ready_at, updated_at) VALUES {}",
233                    rows.join(", ")
234                );
235                let text = sql_text(backend, &text);
236                let mut insert = sqlx::query(text);
237                for (task_id, map_index, state) in chunk {
238                    let ready = (*state == TaskInstanceState::Queued).then(|| now_text.clone());
239                    insert = insert
240                        .bind(Uuid::now_v7().to_string())
241                        .bind(run_id)
242                        .bind(task_id.as_str())
243                        .bind(*map_index)
244                        .bind(state.to_string())
245                        .bind(ready)
246                        .bind(&now_text);
247                }
248                insert.execute(&mut *tx).await?;
249            }
250        });
251        Ok(())
252    }
253
254    /// A run with its DAG version and task instances; `None` for an unknown run.
255    ///
256    /// # Errors
257    ///
258    /// [`DbError`] if a query fails or stored data doesn't read.
259    pub async fn run_tasks(&self, run_id: &str) -> Result<Option<RunTasks>, DbError> {
260        const RUN: &str = "SELECT r.state, r.cancel_requested_at IS NOT NULL, v.id{text}, \
261            p.schedr_version FROM runs r JOIN dag_versions v ON v.id = r.dag_version_id \
262            JOIN parse_results p ON p.id = v.parse_result_id WHERE r.id = $1{uuid}";
263        const INSTANCES: &str = "SELECT id{text}, task_id, state, try_number, retries_used, \
264            {ts<}ready_at{>ts}, cancel_requested_at IS NOT NULL, outcome, map_index, reason, \
265            map_sizes{text}, cleanup_result FROM task_instances WHERE run_id = $1{uuid} \
266            ORDER BY task_id, map_index";
267        let (run, rows): (Option<RunRow>, Vec<InstanceRow>) = on_pool!(self, |pool, backend| {
268            let run = sqlx::query_as(sql(backend, RUN))
269                .bind(run_id)
270                .fetch_optional(&mut *pool)
271                .await?;
272            let rows = sqlx::query_as(sql(backend, INSTANCES))
273                .bind(run_id)
274                .fetch_all(&mut *pool)
275                .await?;
276            (run, rows)
277        });
278        let Some((state, cancel_requested, version_id, parse_version)) = run else {
279            return Ok(None);
280        };
281        let dag = self.dag_version(&version_id).await?;
282        Ok(Some(RunTasks {
283            state: from_name("runs.state", state)?,
284            cancel_requested,
285            dag,
286            parse_version,
287            instances: rows.into_iter().map(instance).collect::<Result<_, _>>()?,
288        }))
289    }
290
291    /// Records how a cleanup of an instance ended. A failure stays: a later attempt's
292    /// cleanup succeeding doesn't undo it (it fails the run, see archive/PROJECT.md, Run result).
293    ///
294    /// # Errors
295    ///
296    /// [`DbError::Sqlx`] if the statement fails.
297    pub async fn set_cleanup_result(
298        &self,
299        instance_id: &str,
300        result: CleanupResult,
301        now: Timestamp,
302    ) -> Result<(), DbError> {
303        const SET: &str = "UPDATE task_instances SET cleanup_result = $1, updated_at = $2{ts} \
304            WHERE id = $3{uuid} AND (cleanup_result IS NULL \
305            OR cleanup_result NOT IN ('failed', 'worker_lost'))";
306        in_tx!(self, |tx, backend| {
307            sqlx::query(sql(backend, SET))
308                .bind(result.to_string())
309                .bind(db_time(now))
310                .bind(instance_id)
311                .execute(&mut *tx)
312                .await?;
313        });
314        Ok(())
315    }
316
317    /// Stores changes to a run's task instances, all or none.
318    ///
319    /// # Errors
320    ///
321    /// [`DbError::Sqlx`] if a statement fails.
322    pub async fn update_instances(
323        &self,
324        run_id: &str,
325        updates: &[InstanceUpdate],
326        now: Timestamp,
327    ) -> Result<(), DbError> {
328        let updates = merged(updates);
329        // Each row a microsecond after the one before, in the order given: what ended in one
330        // write keeps that order (`ended_in_order`, a `first_of` decided later; M4B.4).
331        let times: Vec<String> = (0..updates.len())
332            .map(|k| {
333                let step = jiff::SignedDuration::from_micros(i64::try_from(k).unwrap_or(i64::MAX));
334                db_time(now.checked_add(step).unwrap_or(now))
335            })
336            .collect();
337        // Many rows a statement, joined to a list of values (a finished task in a wide DAG
338        // changes many at once, B18); `columnN` names the list's columns on both backends.
339        in_tx!(self, |tx, backend| {
340            for (chunk, times) in updates
341                .chunks(UPDATES_PER_STATEMENT)
342                .zip(times.chunks(UPDATES_PER_STATEMENT))
343            {
344                let rows: Vec<String> = (0..chunk.len())
345                    .map(|i| {
346                        let n = 1 + i * 9;
347                        format!(
348                            "(${}, ${}, ${}, ${}{{ts}}, ${}, ${}, ${}, ${}{{json}}, ${}{{ts}})",
349                            n + 1,
350                            n + 2,
351                            n + 3,
352                            n + 4,
353                            n + 5,
354                            n + 6,
355                            n + 7,
356                            n + 8,
357                            n + 9
358                        )
359                    })
360                    .collect();
361                let text = format!(
362                    "UPDATE task_instances AS t SET state = v.column3, ready_at = v.column4, \
363                     outcome = v.column5, retries_used = t.retries_used + v.column6, \
364                     reason = COALESCE(v.column7, t.reason), \
365                     map_sizes = COALESCE(v.column8, t.map_sizes), updated_at = v.column9, \
366                     ended_at = CASE WHEN v.column3 IN ('success', 'failed', 'upstream_failed', \
367                         'skipped', 'cancelled') THEN v.column9 END \
368                     FROM (VALUES {}) AS v \
369                     WHERE t.run_id = $1{{uuid}} AND t.task_id = v.column1 \
370                     AND t.map_index = v.column2",
371                    rows.join(", ")
372                );
373                let mut update = sqlx::query(sql_text(backend, &text)).bind(run_id);
374                for ((one, retries), at) in chunk.iter().zip(times) {
375                    update = update
376                        .bind(one.task_id.as_str())
377                        .bind(one.map_index)
378                        .bind(one.state.to_string())
379                        .bind(one.ready_at.map(db_time))
380                        .bind(one.outcome.as_deref())
381                        .bind(*retries)
382                        .bind(one.reason.as_deref())
383                        .bind(one.map_sizes.as_ref().map(to_json))
384                        .bind(at);
385                }
386                update.execute(&mut *tx).await?;
387            }
388        });
389        Ok(())
390    }
391
392    /// Sets the waiting reasons of queued task instances (`(instance ID, reason)`): one
393    /// statement per distinct reason and 500 instances, where it was one
394    /// per instance (B18); most waiting tasks share a few reasons.
395    ///
396    /// # Errors
397    ///
398    /// [`DbError::Sqlx`] if a statement fails.
399    pub async fn set_queued_reasons(
400        &self,
401        reasons: &[(String, String)],
402        now: Timestamp,
403    ) -> Result<(), DbError> {
404        let mut by_reason: std::collections::BTreeMap<&str, Vec<&str>> =
405            std::collections::BTreeMap::new();
406        for (instance_id, reason) in reasons {
407            by_reason.entry(reason).or_default().push(instance_id);
408        }
409        let now = db_time(now);
410        in_tx!(self, |tx, backend| {
411            for (reason, instances) in &by_reason {
412                for chunk in instances.chunks(UPDATES_PER_STATEMENT) {
413                    let ids: Vec<String> = (3..chunk.len() + 3)
414                        .map(|n| format!("${n}{{uuid}}"))
415                        .collect();
416                    let text = format!(
417                        "UPDATE task_instances SET queued_reason = $1, updated_at = $2{{ts}} \
418                         WHERE state IN ('queued', 'cleaning_up') AND id IN ({})",
419                        ids.join(", ")
420                    );
421                    let mut update = sqlx::query(sql_text(backend, &text))
422                        .bind(*reason)
423                        .bind(&now);
424                    for id in chunk {
425                        update = update.bind(*id);
426                    }
427                    update.execute(&mut *tx).await?;
428                }
429            }
430        });
431        Ok(())
432    }
433
434    /// Records a run's result.
435    ///
436    /// # Errors
437    ///
438    /// [`DbError::Sqlx`] if the statement fails.
439    pub async fn finish_run(
440        &self,
441        run_id: &str,
442        state: RunState,
443        now: Timestamp,
444    ) -> Result<(), DbError> {
445        const FINISH: &str = "UPDATE runs SET state = $1, ended_at = $2{ts} WHERE id = $3{uuid}";
446        in_tx!(self, |tx, backend| {
447            sqlx::query(sql(backend, FINISH))
448                .bind(state.to_string())
449                .bind(db_time(now))
450                .bind(run_id)
451                .execute(&mut *tx)
452                .await?;
453        });
454        Ok(())
455    }
456
457    /// Marks a run as being cancelled (the first request counts).
458    ///
459    /// # Errors
460    ///
461    /// [`DbError::Sqlx`] if the statement fails.
462    pub async fn request_cancel(&self, run_id: &str, now: Timestamp) -> Result<(), DbError> {
463        const CANCEL: &str = "UPDATE runs SET cancel_requested_at = $1{ts} \
464            WHERE id = $2{uuid} AND cancel_requested_at IS NULL";
465        in_tx!(self, |tx, backend| {
466            sqlx::query(sql(backend, CANCEL))
467                .bind(db_time(now))
468                .bind(run_id)
469                .execute(&mut *tx)
470                .await?;
471        });
472        Ok(())
473    }
474
475    /// Marks a running task as being cancelled (the first request counts).
476    ///
477    /// # Errors
478    ///
479    /// [`DbError::Sqlx`] if the statement fails.
480    pub async fn request_task_cancel(
481        &self,
482        run_id: &str,
483        task_id: &TaskId,
484        now: Timestamp,
485    ) -> Result<(), DbError> {
486        const CANCEL: &str = "UPDATE task_instances SET cancel_requested_at = $1{ts} \
487            WHERE run_id = $2{uuid} AND task_id = $3 AND cancel_requested_at IS NULL";
488        in_tx!(self, |tx, backend| {
489            sqlx::query(sql(backend, CANCEL))
490                .bind(db_time(now))
491                .bind(run_id)
492                .bind(task_id.as_str())
493                .execute(&mut *tx)
494                .await?;
495        });
496        Ok(())
497    }
498
499    /// A mapped task's dimensions' sizes in a run, once it expanded.
500    ///
501    /// # Errors
502    ///
503    /// [`DbError`] if the query fails or the stored sizes don't read.
504    pub async fn map_sizes(
505        &self,
506        run_id: &str,
507        task_id: &TaskId,
508    ) -> Result<Option<Vec<usize>>, DbError> {
509        const SIZES: &str = "SELECT map_sizes{text} FROM task_instances \
510            WHERE run_id = $1{uuid} AND task_id = $2 AND map_index = -1";
511        let row: Option<(Option<String>,)> = on_pool!(self, |pool, backend| {
512            sqlx::query_as(sql(backend, SIZES))
513                .bind(run_id)
514                .bind(task_id.as_str())
515                .fetch_optional(pool)
516                .await?
517        });
518        row.and_then(|(sizes,)| sizes)
519            .map(|s| from_json("task_instances.map_sizes", &s))
520            .transpose()
521    }
522
523    /// Marks one running task instance as being cancelled (a mapped task's step that failed,
524    /// decision 75a), the first request counting.
525    ///
526    /// # Errors
527    ///
528    /// [`DbError::Sqlx`] if the statement fails.
529    pub async fn request_instance_cancel(
530        &self,
531        run_id: &str,
532        task_id: &TaskId,
533        map_index: i32,
534        now: Timestamp,
535    ) -> Result<(), DbError> {
536        const CANCEL: &str = "UPDATE task_instances SET cancel_requested_at = $1{ts} \
537            WHERE run_id = $2{uuid} AND task_id = $3 AND map_index = $4 \
538            AND cancel_requested_at IS NULL";
539        in_tx!(self, |tx, backend| {
540            sqlx::query(sql(backend, CANCEL))
541                .bind(db_time(now))
542                .bind(run_id)
543                .bind(task_id.as_str())
544                .bind(map_index)
545                .execute(&mut *tx)
546                .await?;
547        });
548        Ok(())
549    }
550
551    /// Queues an `unschedulable` task again (`schedr tasks retry`); whether it was one.
552    ///
553    /// # Errors
554    ///
555    /// [`DbError::Sqlx`] if the statement fails.
556    pub async fn retry_unschedulable(
557        &self,
558        run_id: &str,
559        (task_id, map_index): (&TaskId, Option<i32>),
560        now: Timestamp,
561    ) -> Result<bool, DbError> {
562        const RETRY: &str = "UPDATE task_instances SET state = 'queued', ready_at = $1{ts}, \
563            queued_reason = NULL, updated_at = $1{ts} \
564            WHERE run_id = $2{uuid} AND task_id = $3 AND state = 'unschedulable' \
565            AND ($4 IS NULL OR map_index = $4)";
566        let updated = in_tx!(self, |tx, backend| {
567            sqlx::query(sql(backend, RETRY))
568                .bind(db_time(now))
569                .bind(run_id)
570                .bind(task_id.as_str())
571                .bind(map_index)
572                .execute(&mut *tx)
573                .await?
574                .rows_affected()
575        });
576        Ok(updated > 0)
577    }
578
579    /// The task instances whose retry delay has passed: (run ID, task ID, `map_index`), oldest
580    /// first.
581    ///
582    /// # Errors
583    ///
584    /// [`DbError`] if the query fails or a stored ID doesn't read.
585    pub async fn due_retries(&self, now: Timestamp) -> Result<Vec<(String, TaskId, i32)>, DbError> {
586        const DUE: &str = concat!(
587            "SELECT run_id{text}, task_id, map_index ",
588            due_retries_from!(),
589            " ORDER BY ready_at, id"
590        );
591        if self
592            .skipped_at(crate::probe::Check::DueRetries, now)
593            .await?
594        {
595            return Ok(Vec::new());
596        }
597        let rows: Vec<(String, String, i32)> = on_pool!(self, |pool, backend| {
598            sqlx::query_as(sql(backend, DUE))
599                .bind(db_time(now))
600                .fetch_all(pool)
601                .await?
602        });
603        rows.into_iter()
604            .map(|(run_id, task_id, map_index)| Ok((run_id, task_id_of(task_id)?, map_index)))
605            .collect()
606    }
607
608    /// Stores a task instance's output (stored JSON) with its outcome.
609    ///
610    /// # Errors
611    ///
612    /// [`DbError::Sqlx`] if the statement fails.
613    pub async fn store_output(
614        &self,
615        instance_id: &str,
616        outcome: &str,
617        value: &serde_json::Value,
618    ) -> Result<(), DbError> {
619        const OUTPUT: &str = "INSERT INTO outputs (task_instance_id, outcome, value, size_bytes) \
620            VALUES ($1{uuid}, $2, $3{json}, $4) ON CONFLICT (task_instance_id) DO UPDATE \
621            SET outcome = excluded.outcome, value = excluded.value, size_bytes = excluded.size_bytes";
622        let text = to_json(value);
623        let size = i64::try_from(text.len()).unwrap_or(i64::MAX);
624        in_tx!(self, |tx, backend| {
625            sqlx::query(sql(backend, OUTPUT))
626                .bind(instance_id)
627                .bind(outcome)
628                .bind(&text)
629                .bind(size)
630                .execute(&mut *tx)
631                .await?;
632        });
633        Ok(())
634    }
635
636    /// Stores several instances' outputs, as [`Self::store_output`] does each, in statements of
637    /// up to `UPDATES_PER_STATEMENT` rows (M4B.4, B184). An instance named twice keeps the
638    /// later.
639    ///
640    /// # Errors
641    ///
642    /// [`DbError::Sqlx`] if a statement fails.
643    pub async fn store_outputs(
644        &self,
645        outputs: &[(&str, &str, &serde_json::Value)],
646    ) -> Result<(), DbError> {
647        // One row per instance: a statement may not change a row twice (Postgres refuses).
648        let mut rows: Vec<(&str, &str, String)> = Vec::with_capacity(outputs.len());
649        for (instance_id, outcome, value) in outputs {
650            rows.retain(|(id, _, _)| id != instance_id);
651            rows.push((instance_id, outcome, to_json(value)));
652        }
653        in_tx!(self, |tx, backend| {
654            for chunk in rows.chunks(UPDATES_PER_STATEMENT) {
655                let values: Vec<String> = (0..chunk.len())
656                    .map(|i| {
657                        let n = i * 4;
658                        format!(
659                            "(${}{{uuid}}, ${}, ${}{{json}}, ${})",
660                            n + 1,
661                            n + 2,
662                            n + 3,
663                            n + 4
664                        )
665                    })
666                    .collect();
667                let text = format!(
668                    "INSERT INTO outputs (task_instance_id, outcome, value, size_bytes) VALUES {} \
669                     ON CONFLICT (task_instance_id) DO UPDATE SET outcome = excluded.outcome, \
670                     value = excluded.value, size_bytes = excluded.size_bytes",
671                    values.join(", ")
672                );
673                let mut insert = sqlx::query(sql_text(backend, &text));
674                for (instance_id, outcome, text) in chunk {
675                    insert = insert
676                        .bind(*instance_id)
677                        .bind(*outcome)
678                        .bind(text)
679                        .bind(i64::try_from(text.len()).unwrap_or(i64::MAX));
680                }
681                insert.execute(&mut *tx).await?;
682            }
683        });
684        Ok(())
685    }
686
687    /// Stores the output of a task that isn't mapped, by its ID in the run (a task the master
688    /// ended itself: no attempt knows its instance).
689    ///
690    /// # Errors
691    ///
692    /// [`DbError::Sqlx`] if the statement fails.
693    pub async fn store_task_output(
694        &self,
695        run_id: &str,
696        task_id: &TaskId,
697        outcome: &str,
698        value: &serde_json::Value,
699    ) -> Result<(), DbError> {
700        const OUTPUT: &str = "INSERT INTO outputs (task_instance_id, outcome, value, size_bytes) \
701            SELECT id, $3, $4{json}, $5 FROM task_instances \
702            WHERE run_id = $1{uuid} AND task_id = $2 AND map_index = -1 \
703            ON CONFLICT (task_instance_id) DO UPDATE \
704            SET outcome = excluded.outcome, value = excluded.value, size_bytes = excluded.size_bytes";
705        let text = to_json(value);
706        let size = i64::try_from(text.len()).unwrap_or(i64::MAX);
707        in_tx!(self, |tx, backend| {
708            sqlx::query(sql(backend, OUTPUT))
709                .bind(run_id)
710                .bind(task_id.as_str())
711                .bind(outcome)
712                .bind(&text)
713                .bind(size)
714                .execute(&mut *tx)
715                .await?;
716        });
717        Ok(())
718    }
719
720    /// A task instance's output and outcome, if stored.
721    ///
722    /// # Errors
723    ///
724    /// [`DbError`] if the query fails or the stored value doesn't read.
725    pub async fn output(
726        &self,
727        instance_id: &str,
728    ) -> Result<Option<(String, serde_json::Value)>, DbError> {
729        const OUTPUT: &str =
730            "SELECT outcome, value{text} FROM outputs WHERE task_instance_id = $1{uuid}";
731        let row: Option<(String, String)> = on_pool!(self, |pool, backend| {
732            sqlx::query_as(sql(backend, OUTPUT))
733                .bind(instance_id)
734                .fetch_optional(pool)
735                .await?
736        });
737        row.map(|(outcome, value)| Ok((outcome, from_json("outputs.value", &value)?)))
738            .transpose()
739    }
740}
741
742fn task_id_of(text: String) -> Result<TaskId, DbError> {
743    TaskId::new(text).map_err(|e| DbError::InvalidData {
744        what: "task_instances.task_id",
745        reason: e.to_string(),
746    })
747}
748
749fn instance(row: InstanceRow) -> Result<StoredInstance, DbError> {
750    let (
751        id,
752        task_id,
753        state,
754        try_number,
755        retries_used,
756        ready_at,
757        cancel_requested,
758        outcome,
759        map_index,
760        reason,
761        map_sizes,
762        cleanup_result,
763    ) = row;
764    Ok(StoredInstance {
765        id,
766        task_id: task_id_of(task_id)?,
767        map_index,
768        state: from_name("task_instances.state", state)?,
769        try_number: u32::try_from(try_number).unwrap_or(0),
770        retries_used: u32::try_from(retries_used).unwrap_or(0),
771        ready_at: ready_at
772            .map(|t| parse_time("task_instances.ready_at", &t))
773            .transpose()?,
774        cancel_requested,
775        outcome,
776        reason,
777        map_sizes: map_sizes
778            .map(|s| from_json("task_instances.map_sizes", &s))
779            .transpose()?,
780        cleanup_result: cleanup_result
781            .map(|name| from_name("task_instances.cleanup_result", name))
782            .transpose()?,
783    })
784}