Skip to main content

schedr_db/
run_of.rs

1//! What a `wait_for(RunOf(...))` step reads of another DAG's runs (decision 353).
2
3use jiff::Timestamp;
4
5use crate::database::{Database, DbError};
6use crate::query::{db_time, in_tx, on_pool, parse_time, sql};
7
8/// A run of the DAG waited for, as far as the step needs it.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct OtherRun {
11    /// The run's ID.
12    pub run_id: String,
13    /// The run's state, or its task's when the step waits for a task (`queued` for a run whose
14    /// tasks aren't made yet, `missing` for a run that ended without that task).
15    pub state: String,
16    /// When it ended, if it did.
17    pub ended_at: Option<Timestamp>,
18}
19
20/// Which runs of the other DAG count.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum Matching {
23    /// The runs planned for this moment (`lag` given).
24    PlannedFor(Timestamp),
25    /// The first to end at or after this moment (no `lag`).
26    EndedAfter(Timestamp),
27    /// The first to end strictly after this run, which ended at this moment (an `@sensor`'s
28    /// next after the one it returned `NOT_YET` for).
29    EndedAfterRun(Timestamp, String),
30}
31
32/// Where an `@sensor(wait_for=RunOf(...))` stands (decision 353).
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct SensorWait {
35    /// Since when it waits: its `max_wait` runs from here.
36    pub since: Timestamp,
37    /// The run last handed to its function, and when it (or its task) ended.
38    pub handed: Option<(String, Timestamp)>,
39    /// The last run it returned `NOT_YET` for, and when that run (or its task) ended.
40    pub waited: Option<(String, Timestamp)>,
41}
42
43impl Database {
44    /// The run of `dag` that `matching` picks (the newest planned for the moment, or the first to
45    /// end after it), with its state, or `task`'s state in it; none yet: empty.
46    ///
47    /// # Errors
48    ///
49    /// [`DbError`] if the query fails.
50    pub async fn runs_of(
51        &self,
52        dag: &str,
53        task: Option<&str>,
54        matching: Matching,
55    ) -> Result<Vec<OtherRun>, DbError> {
56        // Of the runs planned for the moment only the newest counts (the user's, option C): a
57        // run started again for it replaces the older ones, as Airflow's clear would.
58        const RUNS_FOR: &str = "SELECT id{text}, state, {ts<}ended_at{>ts} FROM runs \
59            WHERE dag_id = $1 AND planned_for = $2{ts} ORDER BY triggered_at DESC, id DESC LIMIT 1";
60        // A run whose tasks aren't made yet (queued) still counts: a rerun on its way.
61        const TASKS_FOR: &str = "SELECT r.id{text}, COALESCE(t.state, CASE WHEN r.state IN \
62            ('queued', 'running') THEN 'queued' ELSE 'missing' END), {ts<}t.ended_at{>ts} \
63            FROM runs r LEFT JOIN task_instances t \
64            ON t.run_id = r.id AND t.task_id = $3 AND t.map_index = -1 \
65            WHERE r.dag_id = $1 AND r.planned_for = $2{ts} \
66            ORDER BY r.triggered_at DESC, r.id DESC LIMIT 1";
67        const RUN_ENDED: &str = "SELECT id{text}, state, {ts<}ended_at{>ts} FROM runs \
68            WHERE dag_id = $1 AND ended_at >= $2{ts} ORDER BY ended_at, id LIMIT 1";
69        const TASK_ENDED: &str = "SELECT r.id{text}, t.state, {ts<}t.ended_at{>ts} \
70            FROM task_instances t JOIN runs r ON r.id = t.run_id \
71            WHERE t.task_id = $3 AND t.map_index = -1 AND t.ended_at >= $2{ts} AND r.dag_id = $1 \
72            ORDER BY t.ended_at, r.id LIMIT 1";
73        const RUN_AFTER: &str = "SELECT id{text}, state, {ts<}ended_at{>ts} FROM runs \
74            WHERE dag_id = $1 AND ended_at >= $2{ts} AND (ended_at > $2{ts} OR id > $4{uuid}) \
75            ORDER BY ended_at, id LIMIT 1";
76        const TASK_AFTER: &str = "SELECT r.id{text}, t.state, {ts<}t.ended_at{>ts} \
77            FROM task_instances t JOIN runs r ON r.id = t.run_id \
78            WHERE t.task_id = $3 AND t.map_index = -1 AND t.ended_at >= $2{ts} AND r.dag_id = $1 \
79            AND (t.ended_at > $2{ts} OR r.id > $4{uuid}) ORDER BY t.ended_at, r.id LIMIT 1";
80        let (query, at, after) = match (matching, task.is_some()) {
81            (Matching::PlannedFor(at), false) => (RUNS_FOR, at, None),
82            (Matching::PlannedFor(at), true) => (TASKS_FOR, at, None),
83            (Matching::EndedAfter(at), false) => (RUN_ENDED, at, None),
84            (Matching::EndedAfter(at), true) => (TASK_ENDED, at, None),
85            (Matching::EndedAfterRun(at, run), false) => (RUN_AFTER, at, Some(run)),
86            (Matching::EndedAfterRun(at, run), true) => (TASK_AFTER, at, Some(run)),
87        };
88        let rows: Vec<(String, String, Option<String>)> = on_pool!(self, |pool, backend| {
89            let mut statement = sqlx::query_as(sql(backend, query))
90                .bind(dag)
91                .bind(db_time(at))
92                .bind(task.unwrap_or_default());
93            if let Some(after) = &after {
94                statement = statement.bind(after);
95            }
96            statement.fetch_all(pool).await?
97        });
98        rows.into_iter()
99            .map(|(run_id, state, ended_at)| {
100                Ok(OtherRun {
101                    run_id,
102                    state,
103                    ended_at: ended_at.map(|at| parse_time("ended_at", &at)).transpose()?,
104                })
105            })
106            .collect()
107    }
108
109    /// Parks a `wait_for` step the master holds before looking at it (decision 487): the round
110    /// skips it until `look_at` (its `max_wait` deadline), or until what it waits for, run or
111    /// task of DAG `waits_dag` ending or event `waits_event` posted, clears it. Stored first, so
112    /// what ends after the look clears it, and what ended before is seen by the look. Only a
113    /// queued instance is parked.
114    ///
115    /// # Errors
116    ///
117    /// [`DbError::Sqlx`] if the statement fails.
118    pub async fn park_wait(
119        &self,
120        instance_id: &str,
121        look_at: Timestamp,
122        (waits_dag, waits_event): (Option<&str>, Option<&str>),
123    ) -> Result<(), DbError> {
124        const PARK: &str = "UPDATE task_instances SET look_at = $1{ts}, waits_dag = $2, \
125            waits_event = $3 WHERE id = $4{uuid} AND state = 'queued'";
126        in_tx!(self, |tx, backend| {
127            sqlx::query(sql(backend, PARK))
128                .bind(db_time(look_at))
129                .bind(waits_dag)
130                .bind(waits_event)
131                .bind(instance_id)
132                .execute(&mut *tx)
133                .await?;
134        });
135        Ok(())
136    }
137
138    /// Since when a queued task instance is ready, if it is.
139    ///
140    /// # Errors
141    ///
142    /// [`DbError`] if the query fails or the stored time doesn't read.
143    pub async fn ready_since(&self, instance_id: &str) -> Result<Option<Timestamp>, DbError> {
144        const SINCE: &str = "SELECT {ts<}ready_at{>ts} FROM task_instances WHERE id = $1{uuid} AND ready_at IS NOT NULL";
145        let row: Option<(String,)> = on_pool!(self, |pool, backend| {
146            sqlx::query_as(sql(backend, SINCE))
147                .bind(instance_id)
148                .fetch_optional(pool)
149                .await?
150        });
151        row.map(|(at,)| parse_time("task_instances.ready_at", &at))
152            .transpose()
153    }
154
155    /// The runs of `dag` (or of its `task`) that succeeded after `after` (or, without it, since
156    /// `since`), oldest first, to `limit`, that haven't started a run of `started` yet
157    /// (decision 353): with each its `planned_for` and when it (or its task) ended. `after` is
158    /// strict, by end and run ID, so a run is never read twice, events kept or not.
159    ///
160    /// # Errors
161    ///
162    /// [`DbError`] if the query fails or a stored time doesn't read.
163    pub async fn succeeded_since(
164        &self,
165        of: (&str, Option<&str>),
166        started: &str,
167        from: RunOfFrom<'_>,
168        limit: u32,
169    ) -> Result<Vec<(String, Timestamp, Timestamp)>, DbError> {
170        self.runs_since(of, started, from, limit, false).await
171    }
172
173    /// As [`Self::succeeded_since`], every run that ended, whatever its state: what an
174    /// `@trigger(wait_for=...)`'s function is called for.
175    ///
176    /// # Errors
177    ///
178    /// [`DbError`] if the query fails or a stored time doesn't read.
179    pub async fn ended_since(
180        &self,
181        of: (&str, Option<&str>),
182        from: RunOfFrom<'_>,
183        limit: u32,
184    ) -> Result<Vec<(String, Timestamp, Timestamp)>, DbError> {
185        self.runs_since(of, "", from, limit, true).await
186    }
187
188    async fn runs_since(
189        &self,
190        (dag, task): (&str, Option<&str>),
191        started: &str,
192        from: RunOfFrom<'_>,
193        limit: u32,
194        any_end: bool,
195    ) -> Result<Vec<(String, Timestamp, Timestamp)>, DbError> {
196        const RUNS_ENDED: &str = "SELECT r.id{text}, {ts<}r.planned_for{>ts}, {ts<}r.ended_at{>ts} FROM runs r \
197            WHERE r.dag_id = $1 AND r.state IN ('success', 'failed', 'cancelled') AND r.ended_at >= $2{ts} \
198            AND (r.ended_at > $2{ts} OR $4 IS NULL OR r.id > $4{uuid}) \
199            ORDER BY r.ended_at, r.id LIMIT $3";
200        const TASKS_ENDED: &str = "SELECT r.id{text}, {ts<}r.planned_for{>ts}, {ts<}t.ended_at{>ts} \
201            FROM task_instances t JOIN runs r ON r.id = t.run_id \
202            WHERE t.task_id = $5 AND t.map_index = -1 \
203            AND t.state IN ('success', 'failed', 'cancelled', 'skipped', 'upstream_failed') \
204            AND t.ended_at >= $2{ts} AND r.dag_id = $1 \
205            AND (t.ended_at > $2{ts} OR $4 IS NULL OR r.id > $4{uuid}) \
206            ORDER BY t.ended_at, r.id LIMIT $3";
207        const RUNS: &str = "SELECT r.id{text}, {ts<}r.planned_for{>ts}, {ts<}r.ended_at{>ts} FROM runs r \
208            WHERE r.dag_id = $1 AND r.state = 'success' AND r.ended_at >= $2{ts} \
209            AND (r.ended_at > $2{ts} OR $5 IS NULL OR r.id > $5{uuid}) \
210            AND NOT EXISTS (SELECT 1 FROM events e WHERE e.dag_id = $3 AND e.key = r.id{text}) \
211            ORDER BY r.ended_at, r.id LIMIT $4";
212        const TASKS: &str = "SELECT r.id{text}, {ts<}r.planned_for{>ts}, {ts<}t.ended_at{>ts} \
213            FROM task_instances t JOIN runs r ON r.id = t.run_id \
214            WHERE t.task_id = $6 AND t.map_index = -1 AND t.state = 'success' \
215            AND t.ended_at >= $2{ts} AND r.dag_id = $1 \
216            AND (t.ended_at > $2{ts} OR $5 IS NULL OR r.id > $5{uuid}) \
217            AND NOT EXISTS (SELECT 1 FROM events e WHERE e.dag_id = $3 AND e.key = r.id{text}) \
218            ORDER BY t.ended_at, r.id LIMIT $4";
219        let (since, after_run) = match from {
220            RunOfFrom::Since(at) => (at, None),
221            RunOfFrom::After(seen) => (seen.at, Some(seen.run.as_str())),
222        };
223        let rows: Vec<(String, String, String)> = on_pool!(self, |pool, backend| {
224            // What ended for a function is never deduplicated by its events: it may start none,
225            // or key them its own way; its cursor alone says what it has had.
226            let query = match (task.is_some(), any_end) {
227                (true, false) => TASKS,
228                (false, false) => RUNS,
229                (true, true) => TASKS_ENDED,
230                (false, true) => RUNS_ENDED,
231            };
232            let mut statement = sqlx::query_as(sql(backend, query))
233                .bind(dag)
234                .bind(db_time(since));
235            if !any_end {
236                statement = statement.bind(started);
237            }
238            statement = statement.bind(i64::from(limit)).bind(after_run);
239            if let Some(task) = task {
240                statement = statement.bind(task);
241            }
242            statement.fetch_all(pool).await?
243        });
244        rows.into_iter()
245            .map(|(id, at, ended)| {
246                Ok::<_, DbError>((
247                    id,
248                    parse_time("runs.planned_for", &at)?,
249                    parse_time("ended_at", &ended)?,
250                ))
251            })
252            .collect()
253    }
254
255    /// Since when a DAG has been live: unpaused and defined without a break (decision 353).
256    ///
257    /// # Errors
258    ///
259    /// [`DbError`] if the query fails or the stored time doesn't read.
260    pub async fn live_since(&self, dag: &str) -> Result<Option<Timestamp>, DbError> {
261        const SINCE: &str = "SELECT {ts<}live_since{>ts} FROM dag_triggers WHERE dag_id = $1 \
262             AND live_since IS NOT NULL";
263        let row: Option<(String,)> = on_pool!(self, |pool, backend| {
264            sqlx::query_as(sql(backend, SINCE))
265                .bind(dag)
266                .fetch_optional(pool)
267                .await?
268        });
269        row.map(|(at,)| parse_time("dag_triggers.live_since", &at))
270            .transpose()
271    }
272
273    /// How far a `trigger=RunOf(...)` reading `source` has looked: the last run it started one
274    /// for. A cursor of another source (the trigger changed) counts as none.
275    ///
276    /// # Errors
277    ///
278    /// [`DbError`] if the query fails or the stored time doesn't read.
279    pub async fn run_of_seen(&self, dag: &str, source: &str) -> Result<Option<RunOfSeen>, DbError> {
280        const SEEN: &str = "SELECT {ts<}run_of_seen_at{>ts}, run_of_seen_run FROM trigger_progress \
281            WHERE dag_id = $1 AND run_of_source = $2 AND run_of_seen_at IS NOT NULL \
282            AND run_of_seen_run IS NOT NULL";
283        let row: Option<(String, String)> = on_pool!(self, |pool, backend| {
284            sqlx::query_as(sql(backend, SEEN))
285                .bind(dag)
286                .bind(source)
287                .fetch_optional(pool)
288                .await?
289        });
290        row.map(|(at, run)| {
291            Ok(RunOfSeen {
292                at: parse_time("trigger_progress.run_of_seen_at", &at)?,
293                run,
294            })
295        })
296        .transpose()
297    }
298
299    /// Records the last run a `trigger=RunOf(...)` reading `source` started one for, on its
300    /// `triggers` row.
301    ///
302    /// # Errors
303    ///
304    /// [`DbError::Sqlx`] if the statement fails.
305    pub async fn set_run_of_seen(
306        &self,
307        dag: &str,
308        source: &str,
309        seen: &RunOfSeen,
310    ) -> Result<(), DbError> {
311        const SET: &str = "INSERT INTO trigger_progress \
312            (dag_id, failures, run_of_source, run_of_seen_at, run_of_seen_run) \
313            VALUES ($1, 0, $2, $3{ts}, $4) ON CONFLICT (dag_id) DO UPDATE SET \
314            run_of_source = excluded.run_of_source, run_of_seen_at = excluded.run_of_seen_at, \
315            run_of_seen_run = excluded.run_of_seen_run";
316        in_tx!(self, |tx, backend| {
317            sqlx::query(sql(backend, SET))
318                .bind(dag)
319                .bind(source)
320                .bind(db_time(seen.at))
321                .bind(&seen.run)
322                .execute(&mut *tx)
323                .await?;
324        });
325        Ok(())
326    }
327}
328
329/// The last run a `trigger=RunOf(...)` started one for: when it (or its task) ended, and its ID.
330#[derive(Debug, Clone, PartialEq, Eq)]
331pub struct RunOfSeen {
332    /// When it (or its task) ended.
333    pub at: Timestamp,
334    /// Its run ID.
335    pub run: String,
336}
337
338/// Where a pass of `trigger=RunOf(...)` reads from.
339#[derive(Debug, Clone, Copy)]
340pub enum RunOfFrom<'a> {
341    /// From this moment on, inclusive: when the DAG became live.
342    Since(Timestamp),
343    /// Strictly after this run.
344    After(&'a RunOfSeen),
345}
346
347impl Database {
348    /// Where an `@sensor(wait_for=RunOf(...))` instance stands, its waiting starting `now` if
349    /// it hadn't (decision 353).
350    ///
351    /// # Errors
352    ///
353    /// [`DbError`] if a statement fails or a stored time doesn't read.
354    pub async fn sensor_wait(
355        &self,
356        instance_id: &str,
357        now: Timestamp,
358    ) -> Result<Option<SensorWait>, DbError> {
359        // From when it was queued, not when a round first looked (a round's write may have
360        // failed); written once, then only read (Grok's review of M4.11d2).
361        const START: &str = "UPDATE task_instances \
362            SET waiting_since = COALESCE(ready_at, $2{ts}) \
363            WHERE id = $1{uuid} AND waiting_since IS NULL";
364        const READ: &str = "SELECT {ts<}waiting_since{>ts}, handed_run, {ts<}handed_at{>ts}, \
365            waited_run, {ts<}waited_at{>ts} FROM task_instances \
366            WHERE id = $1{uuid} AND waiting_since IS NOT NULL";
367        type Row = (
368            String,
369            Option<String>,
370            Option<String>,
371            Option<String>,
372            Option<String>,
373        );
374        let read: Option<Row> = on_pool!(self, |pool, backend| {
375            sqlx::query_as(sql(backend, READ))
376                .bind(instance_id)
377                .fetch_optional(pool)
378                .await?
379        });
380        let row = if let Some(row) = read {
381            Some(row)
382        } else {
383            in_tx!(self, |tx, backend| {
384                sqlx::query(sql(backend, START))
385                    .bind(instance_id)
386                    .bind(db_time(now))
387                    .execute(&mut *tx)
388                    .await?;
389                sqlx::query_as(sql(backend, READ))
390                    .bind(instance_id)
391                    .fetch_optional(&mut *tx)
392                    .await?
393            })
394        };
395        let pair = |run: Option<String>, at: Option<String>, what| match (run, at) {
396            (Some(run), Some(at)) => parse_time(what, &at).map(|at| Some((run, at))),
397            _ => Ok(None),
398        };
399        row.map(|(since, handed, handed_at, waited, waited_at)| {
400            let handed = pair(handed, handed_at, "task_instances.handed_at")?;
401            let waited = pair(waited, waited_at, "task_instances.waited_at")?;
402            Ok(SensorWait {
403                since: parse_time("task_instances.waiting_since", &since)?,
404                handed,
405                waited,
406            })
407        })
408        .transpose()
409    }
410
411    /// Records the run handed to an `@sensor(wait_for=...)`'s function as it is assigned, and
412    /// when it (or its task) ended. It waits no more: its park is dropped (decision 487), so a
413    /// round that couldn't assign it (no free slot, the round's assignments made) leaves it for
414    /// the next (Grok's review of M5.1f2).
415    ///
416    /// # Errors
417    ///
418    /// [`DbError::Sqlx`] if the statement fails.
419    pub async fn hand_run(
420        &self,
421        instance_id: &str,
422        run_id: &str,
423        ended_at: Timestamp,
424    ) -> Result<(), DbError> {
425        const HAND: &str = "UPDATE task_instances SET handed_run = $2, handed_at = $3{ts}, \
426            look_at = NULL WHERE id = $1{uuid}";
427        // Fenced: a master that lost its lease doesn't overwrite what the leader handed.
428        in_tx!(self, |tx, backend| {
429            sqlx::query(sql(backend, HAND))
430                .bind(instance_id)
431                .bind(run_id)
432                .bind(db_time(ended_at))
433                .execute(&mut *tx)
434                .await?;
435        });
436        Ok(())
437    }
438
439    /// Records that the function returned `NOT_YET` for the run it was handed: the next call is
440    /// for a later one.
441    ///
442    /// # Errors
443    ///
444    /// [`DbError::Sqlx`] if the statement fails.
445    pub async fn not_yet(&self, instance_id: &str) -> Result<(), DbError> {
446        const SEEN: &str = "UPDATE task_instances SET waited_run = handed_run, waited_at = handed_at \
447             WHERE id = $1{uuid}";
448        // A named event handed is kept as passed, in the same transaction: read back behind
449        // the cursor, it isn't handed again (B185). Looked up by its ID as a UUID, so the
450        // event's index serves it (Codex's review: a cast column scanned every event).
451        const HANDED: &str = "SELECT handed_run FROM task_instances WHERE id = $1{uuid}";
452        const PASS: &str = "INSERT INTO sensor_passed (instance_id, item) \
453            SELECT $1{uuid}, id FROM named_events WHERE id = $2{uuid} \
454            ON CONFLICT (instance_id, item) DO NOTHING";
455        in_tx!(self, |tx, backend| {
456            let handed: Option<Option<String>> = sqlx::query_scalar(sql(backend, HANDED))
457                .bind(instance_id)
458                .fetch_optional(&mut *tx)
459                .await?;
460            // A run's ID is handed too: only an event's is in `named_events`.
461            if let Some(item) = handed
462                .flatten()
463                .filter(|item| uuid::Uuid::parse_str(item).is_ok())
464            {
465                sqlx::query(sql(backend, PASS))
466                    .bind(instance_id)
467                    .bind(item)
468                    .execute(&mut *tx)
469                    .await?;
470            }
471            sqlx::query(sql(backend, SEEN))
472                .bind(instance_id)
473                .execute(&mut *tx)
474                .await?;
475        });
476        Ok(())
477    }
478
479    /// What an `@sensor(wait_for=...)`'s function is given of `run_id` (its `RunResult`):
480    /// the run's ID, DAG, `planned_for`, state and end, and with `task` that task's state,
481    /// outcome and output (a mapped task's, the list of its elements'). `None` for a run gone.
482    ///
483    /// # Errors
484    ///
485    /// [`DbError`] if a query fails or what is stored doesn't read.
486    pub async fn run_result(
487        &self,
488        run_id: &str,
489        task: Option<&schedr_model::TaskId>,
490    ) -> Result<Option<serde_json::Value>, DbError> {
491        const RUN: &str = "SELECT dag_id, {ts<}planned_for{>ts}, state, {ts<}ended_at{>ts} \
492            FROM runs WHERE id = $1{uuid}";
493        const TASK: &str = "SELECT state, outcome, {ts<}ended_at{>ts} FROM task_instances \
494            WHERE run_id = $1{uuid} AND task_id = $2 AND map_index = -1";
495        let run: Option<(String, String, String, Option<String>)> =
496            on_pool!(self, |pool, backend| {
497                sqlx::query_as(sql(backend, RUN))
498                    .bind(run_id)
499                    .fetch_optional(pool)
500                    .await?
501            });
502        let Some((dag_id, planned_for, state, ended_at)) = run else {
503            return Ok(None);
504        };
505        // Tagged as the Python API stores a `datetime` (`{"$datetime": ...}`), to decode as one.
506        let time = |what, at: &str| {
507            parse_time(what, at).map(|t| serde_json::json!({"$datetime": t.to_string()}))
508        };
509        let mut result = serde_json::json!({
510            "run_id": run_id,
511            "dag_id": dag_id,
512            "planned_for": time("runs.planned_for", &planned_for)?,
513            "state": state,
514            "ended_at": ended_at.as_deref().map(|at| time("runs.ended_at", at)).transpose()?,
515        });
516        let Some(task) = task else {
517            return Ok(Some(result));
518        };
519        let found: Option<(String, Option<String>, Option<String>)> =
520            on_pool!(self, |pool, backend| {
521                sqlx::query_as(sql(backend, TASK))
522                    .bind(run_id)
523                    .bind(task.as_str())
524                    .fetch_optional(pool)
525                    .await?
526            });
527        // A mapped task's values are its elements', in order: the list a downstream reads.
528        let mut output = self.outputs_of(run_id, &[task]).await?.remove(task);
529        if output.is_none() {
530            let elements = self.instance_results(run_id, task).await?;
531            output = (!elements.is_empty()).then(|| {
532                serde_json::Value::Array(
533                    elements
534                        .into_iter()
535                        .map(|e| e.output.unwrap_or(serde_json::Value::Null))
536                        .collect(),
537                )
538            });
539        }
540        result["task_id"] = serde_json::json!(task.as_str());
541        result["task_state"] = serde_json::json!(found.as_ref().map(|(state, ..)| state));
542        result["outcome"] =
543            serde_json::json!(found.as_ref().and_then(|(_, outcome, _)| outcome.as_ref()));
544        result["output"] = output.unwrap_or(serde_json::Value::Null);
545        Ok(Some(result))
546    }
547}
548
549impl Database {
550    /// Records the run an `@trigger(wait_for=...)` of `dag` was given, as it is placed: what its
551    /// clean end moves it past, or a skip passes (decision 353).
552    ///
553    /// # Errors
554    ///
555    /// [`DbError::Sqlx`] if the statement fails.
556    pub async fn hand_trigger_run(&self, dag: &str, seen: &RunOfSeen) -> Result<(), DbError> {
557        // Another run than the one it failed on starts with no failures (Codex's review): those
558        // were the dropped run's.
559        const HAND: &str = "INSERT INTO trigger_progress (dag_id, failures, run_of_handed_run, \
560            run_of_handed_at) VALUES ($1, 0, $2, $3{ts}) ON CONFLICT (dag_id) DO UPDATE SET \
561            failures = CASE WHEN COALESCE(trigger_progress.run_of_handed_run, '') = excluded.run_of_handed_run \
562                THEN trigger_progress.failures ELSE 0 END, \
563            not_before = CASE WHEN COALESCE(trigger_progress.run_of_handed_run, '') = excluded.run_of_handed_run \
564                THEN trigger_progress.not_before ELSE NULL END, \
565            run_of_handed_run = excluded.run_of_handed_run, \
566            run_of_handed_at = excluded.run_of_handed_at";
567        in_tx!(self, |tx, backend| {
568            sqlx::query(sql(backend, HAND))
569                .bind(dag)
570                .bind(&seen.run)
571                .bind(db_time(seen.at))
572                .execute(&mut *tx)
573                .await?;
574        });
575        Ok(())
576    }
577
578    /// The run an `@trigger(wait_for=...)` of `dag` was last given and hasn't passed yet.
579    ///
580    /// # Errors
581    ///
582    /// [`DbError`] if the query fails or the stored time doesn't read.
583    pub async fn trigger_run_handed(&self, dag: &str) -> Result<Option<RunOfSeen>, DbError> {
584        const READ: &str = "SELECT run_of_handed_run, {ts<}run_of_handed_at{>ts} FROM trigger_progress \
585            WHERE dag_id = $1 AND run_of_handed_run IS NOT NULL AND run_of_handed_at IS NOT NULL";
586        let row: Option<(String, String)> = on_pool!(self, |pool, backend| {
587            sqlx::query_as(sql(backend, READ))
588                .bind(dag)
589                .fetch_optional(pool)
590                .await?
591        });
592        row.map(|(run, at)| {
593            Ok(RunOfSeen {
594                at: parse_time("trigger_progress.run_of_handed_at", &at)?,
595                run,
596            })
597        })
598        .transpose()
599    }
600
601    // A named event's cursor never moves back: one handed late, behind it, would reopen a stretch
602    // whose passed rows are forgotten (Codex's review of B186). A run's moves as before.
603    /// Moves an `@trigger(wait_for=...)` of `dag` reading `source` past the run it was given:
604    /// done with it, or passing it (`skipped`: why, kept as its last error). Its failures in a
605    /// row start again. With `call`, ends that call in the same statement, so the call can't
606    /// end without the run passed (Codex's review); without, only while no call runs. Gives
607    /// whether it was passed.
608    ///
609    /// # Errors
610    ///
611    /// [`DbError::Sqlx`] if the statement fails.
612    pub async fn pass_trigger_run(
613        &self,
614        dag: &str,
615        source: &str,
616        skipped: Option<&str>,
617        call: Option<&str>,
618    ) -> Result<bool, DbError> {
619        const PASS: &str = "UPDATE trigger_progress SET run_of_source = $2, \
620            run_of_seen_at = CASE WHEN run_of_seen_at IS NOT NULL AND run_of_seen_at > run_of_handed_at \
621            AND EXISTS (SELECT 1 FROM named_events e WHERE e.id = run_of_handed_run{uuid}) THEN run_of_seen_at ELSE run_of_handed_at END, \
622            run_of_seen_run = CASE WHEN run_of_seen_at IS NOT NULL AND run_of_seen_at > run_of_handed_at \
623            AND EXISTS (SELECT 1 FROM named_events e WHERE e.id = run_of_handed_run{uuid}) THEN run_of_seen_run ELSE run_of_handed_run END, \
624            run_of_handed_run = NULL, run_of_handed_at = NULL, failures = 0, not_before = NULL, \
625            last_error = COALESCE($3, last_error) \
626            WHERE dag_id = $1 AND run_of_handed_run IS NOT NULL AND instance_id IS NULL";
627        const END_AND_PASS: &str = "UPDATE trigger_progress SET run_of_source = $2, \
628            run_of_seen_at = CASE WHEN run_of_seen_at IS NOT NULL AND run_of_seen_at > run_of_handed_at \
629            AND EXISTS (SELECT 1 FROM named_events e WHERE e.id = run_of_handed_run{uuid}) THEN run_of_seen_at ELSE run_of_handed_at END, \
630            run_of_seen_run = CASE WHEN run_of_seen_at IS NOT NULL AND run_of_seen_at > run_of_handed_at \
631            AND EXISTS (SELECT 1 FROM named_events e WHERE e.id = run_of_handed_run{uuid}) THEN run_of_seen_run ELSE run_of_handed_run END, \
632            run_of_handed_run = NULL, run_of_handed_at = NULL, failures = 0, not_before = NULL, \
633            last_error = COALESCE($3, last_error), instance_id = NULL, worker_id = NULL, \
634            dag_version_id = NULL, code_hash = NULL \
635            WHERE dag_id = $1 AND run_of_handed_run IS NOT NULL AND instance_id = $4";
636        // Kept as passed in the same transaction, under the same conditions (decision 354): a
637        // named event only, the one ever read back (B186).
638        const KEEP: &str = "INSERT INTO trigger_progress_passed (dag_id, item) \
639            SELECT dag_id, run_of_handed_run FROM trigger_progress t WHERE dag_id = $1 \
640            AND run_of_handed_run IS NOT NULL AND ($2 IS NULL AND instance_id IS NULL \
641            OR instance_id = $2) AND EXISTS (SELECT 1 FROM named_events e \
642            WHERE e.id = t.run_of_handed_run{uuid}) ON CONFLICT (dag_id, item) DO NOTHING";
643        let passed = in_tx!(self, |tx, backend| {
644            sqlx::query(sql(backend, KEEP))
645                .bind(dag)
646                .bind(call)
647                .execute(&mut *tx)
648                .await?;
649            let statement = match call {
650                Some(call) => sqlx::query(sql(backend, END_AND_PASS))
651                    .bind(dag)
652                    .bind(source)
653                    .bind(skipped)
654                    .bind(call),
655                None => sqlx::query(sql(backend, PASS))
656                    .bind(dag)
657                    .bind(source)
658                    .bind(skipped),
659            };
660            statement.execute(&mut *tx).await?.rows_affected()
661        });
662        Ok(passed == 1)
663    }
664}
665
666impl Database {
667    /// An `@trigger(wait_for=...)` of `dag` whose call `call` returned an event the master has
668    /// stored: its item is passed, the call left running (its end passes nothing more). Gives
669    /// whether it was passed.
670    ///
671    /// # Errors
672    ///
673    /// [`DbError::Sqlx`] if the statement fails.
674    pub async fn pass_trigger_run_stored(
675        &self,
676        dag: &str,
677        source: &str,
678        call: &str,
679    ) -> Result<bool, DbError> {
680        const PASS: &str = "UPDATE trigger_progress SET run_of_source = $2, \
681            run_of_seen_at = CASE WHEN run_of_seen_at IS NOT NULL AND run_of_seen_at > run_of_handed_at \
682            AND EXISTS (SELECT 1 FROM named_events e WHERE e.id = run_of_handed_run{uuid}) THEN run_of_seen_at ELSE run_of_handed_at END, \
683            run_of_seen_run = CASE WHEN run_of_seen_at IS NOT NULL AND run_of_seen_at > run_of_handed_at \
684            AND EXISTS (SELECT 1 FROM named_events e WHERE e.id = run_of_handed_run{uuid}) THEN run_of_seen_run ELSE run_of_handed_run END, \
685            run_of_handed_run = NULL, run_of_handed_at = NULL, failures = 0, not_before = NULL \
686            WHERE dag_id = $1 AND run_of_handed_run IS NOT NULL AND instance_id = $3";
687        const KEEP: &str = "INSERT INTO trigger_progress_passed (dag_id, item) \
688            SELECT dag_id, run_of_handed_run FROM trigger_progress t WHERE dag_id = $1 \
689            AND run_of_handed_run IS NOT NULL AND instance_id = $2 \
690            AND EXISTS (SELECT 1 FROM named_events e WHERE e.id = t.run_of_handed_run{uuid}) \
691            ON CONFLICT (dag_id, item) DO NOTHING";
692        let passed = in_tx!(self, |tx, backend| {
693            sqlx::query(sql(backend, KEEP))
694                .bind(dag)
695                .bind(call)
696                .execute(&mut *tx)
697                .await?;
698            sqlx::query(sql(backend, PASS))
699                .bind(dag)
700                .bind(source)
701                .bind(call)
702                .execute(&mut *tx)
703                .await?
704                .rows_affected()
705        });
706        Ok(passed == 1)
707    }
708
709    /// An `@trigger(wait_for=...)` of `dag` whose call couldn't be made for its run (too big to
710    /// send): a failure with `error`, not started again before `not_before`.
711    ///
712    /// # Errors
713    ///
714    /// [`DbError::Sqlx`] if the statement fails.
715    pub async fn trigger_call_refused(
716        &self,
717        dag: &str,
718        error: &str,
719        not_before: Option<Timestamp>,
720    ) -> Result<(), DbError> {
721        const REFUSED: &str = "UPDATE trigger_progress SET last_error = $2, failures = failures + 1, \
722            not_before = $3{ts} WHERE dag_id = $1 AND instance_id IS NULL";
723        in_tx!(self, |tx, backend| {
724            sqlx::query(sql(backend, REFUSED))
725                .bind(dag)
726                .bind(error)
727                .bind(not_before.map(db_time))
728                .execute(&mut *tx)
729                .await?;
730        });
731        Ok(())
732    }
733}