Skip to main content

schedr_db/
dags.rs

1//! The DAG catalog's storage: parse results with their files, DAGs and DAG versions.
2//!
3//! A parse result is stored as the worker reported it (after the master's validation); the master
4//! works out the DAG list from the current parse of each root and stores the changes
5//! ([`DagChange`]). Each DAG version belongs to one parse (see archive/PROJECT.md, DAG code
6//! delivery and DAG ID conflicts).
7
8use std::collections::{BTreeMap, HashMap};
9
10use jiff::Timestamp;
11use schedr_model::connection::Registry;
12use schedr_model::runner::{ErrorSummary, ParsedFile};
13use schedr_model::{Dag, DagId, DagLocation};
14use uuid::Uuid;
15
16use crate::database::{Database, DbError};
17use crate::query::{BATCH_LIMITS, db_time, from_json, in_tx, on_pool, parse_time, sql, to_json};
18
19/// The rows of removed DAGs' unfinished runs with something not started: the read's `FROM ... WHERE` and its probe check's (decision 485).
20macro_rules! removed_dags_runs_from {
21    () => {
22        "FROM runs r JOIN dags d ON d.dag_id = r.dag_id WHERE d.removed_at IS NOT NULL AND r.state IN ('queued', 'running') AND (r.state = 'queued' OR EXISTS (SELECT 1 FROM task_instances t WHERE t.run_id = r.id AND t.state IN ('scheduled', 'queued', 'up_for_retry', 'unschedulable')) OR EXISTS (SELECT 1 FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id WHERE t.run_id = r.id AND t.state = 'running' AND a.status IS NULL AND a.started_at IS NULL AND t.cancel_requested_at IS NULL))"
23    };
24}
25pub(crate) use removed_dags_runs_from;
26
27/// The rows of scheduled DAGs that can run whose next fire time has come at `$1` or isn't
28/// known: the scheduler's read and its probe check's (decision 485).
29macro_rules! scheduled_due_from {
30    () => {
31        "FROM dag_triggers t JOIN dags d ON d.dag_id = t.dag_id \
32         WHERE t.kind = 'schedule' AND NOT t.paused \
33         AND d.current_version_id IS NOT NULL AND d.removed_at IS NULL AND d.conflict IS NULL \
34         AND (t.next_fire_at IS NULL OR t.next_fire_at <= $1{ts})"
35    };
36}
37pub(crate) use scheduled_due_from;
38
39/// A stored next fire time meaning "none ahead" (decision 485): a schedule past its `end`, a
40/// `@once` done.
41pub const NO_FIRE: Timestamp = Timestamp::constant(253_370_764_800, 0);
42
43#[cfg(test)]
44mod tests;
45
46/// A parse result to store.
47#[derive(Debug, Clone)]
48pub struct NewParse<'a> {
49    /// The root's name.
50    pub root: &'a str,
51    /// The content hash parsed.
52    pub content_hash: &'a str,
53    /// The schedr version of the runner that parsed it.
54    pub schedr_version: &'a str,
55    /// The worker that parsed it.
56    pub worker_id: &'a str,
57    /// When the master received it.
58    pub parsed_at: Timestamp,
59    /// Its files.
60    pub files: &'a [ParsedFile],
61}
62
63/// A DAG's current version.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct CurrentVersion {
66    /// The version's ID.
67    pub version_id: String,
68    /// The parse it comes from.
69    pub parse_id: String,
70    /// The DAG JSON.
71    pub dag: Dag,
72}
73
74/// A stored DAG.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct StoredDag {
77    /// The DAG's ID.
78    pub dag_id: DagId,
79    /// Its trigger's switch (decision 459): whether it is paused; `None` without a trigger
80    /// (run only by hand), which has no switch.
81    pub paused: Option<bool>,
82    /// Whether it was removed (hidden, history kept).
83    pub removed: bool,
84    /// The places defining it, while it is in conflict.
85    pub conflict: Option<Vec<DagLocation>>,
86    /// Its current version (none for a DAG only ever seen in conflict).
87    pub current: Option<CurrentVersion>,
88}
89
90/// A change to the DAG list.
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub enum DagChange {
93    /// The DAG is defined in one place by this parse: it becomes the current version (stored
94    /// once per parse), and the DAG is no longer removed or in conflict. A trigger new to it,
95    /// or of another kind, is stored paused, and losing it deletes its switch (decision 459);
96    /// `pause` pauses an existing one too.
97    Define {
98        /// The definition.
99        dag: Box<Dag>,
100        /// The parse it comes from.
101        parse_id: String,
102        /// Pause its trigger (a removed DAG that came back).
103        pause: bool,
104    },
105    /// The DAG ID is defined in more than one place: it can't run.
106    Conflict {
107        /// The DAG's ID.
108        dag_id: DagId,
109        /// Every place defining it.
110        places: Vec<DagLocation>,
111        /// Pause its trigger (a removed DAG that came back).
112        pause: bool,
113    },
114    /// The DAG is no longer defined: hidden, its history kept.
115    Remove {
116        /// The DAG's ID.
117        dag_id: DagId,
118    },
119}
120
121/// The row of a parse file: path, DAGs JSON, error JSON.
122type FileRow = (String, String, Option<String>, String, String);
123
124/// The row of a stored DAG with its current version.
125type DagRow = (
126    String,
127    Option<bool>,
128    bool,
129    Option<String>,
130    Option<String>,
131    Option<String>,
132    Option<String>,
133);
134
135/// A file of a root's current parse that failed to import (decision 66).
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct ImportErrorRecord {
138    /// The DAG root.
139    pub root: String,
140    /// The root's content hash the parse is of.
141    pub content_hash: String,
142    /// The schedr version of the worker that parsed it.
143    pub schedr_version: String,
144    /// The worker that parsed it.
145    pub worker_id: String,
146    /// The master that stored it; `None` if not known.
147    pub master_id: Option<String>,
148    /// When the parse was stored.
149    pub parsed_at: Timestamp,
150    /// The file, relative to the root.
151    pub path: String,
152    /// Why it failed.
153    pub error: ErrorSummary,
154}
155
156/// A row of [`Database::current_import_errors`]'s query.
157type ImportErrorRow = (
158    String,
159    String,
160    String,
161    String,
162    Option<String>,
163    String,
164    String,
165    String,
166);
167
168/// A stored parse of a (root, content hash).
169#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct StoredParse {
171    /// Its ID.
172    pub id: String,
173    /// The schedr version of the workers that parsed it.
174    pub schedr_version: String,
175    /// When it was stored.
176    pub parsed_at: Timestamp,
177}
178
179impl Database {
180    /// Records that a worker reported `root` at `hash`: a **switch** (the worker had another
181    /// hash before) makes it the most recent; a first report only records it if unknown.
182    ///
183    /// # Errors
184    ///
185    /// [`DbError::Sqlx`] if the statement fails.
186    pub async fn record_root_hash(
187        &self,
188        root: &str,
189        content_hash: &str,
190        switched: bool,
191        now: Timestamp,
192    ) -> Result<(), DbError> {
193        const SWITCH: &str = "INSERT INTO root_hashes (root, content_hash, switched_at) \
194            VALUES ($1, $2, $3{ts}) ON CONFLICT (root, content_hash) \
195            DO UPDATE SET switched_at = excluded.switched_at";
196        const SEEN: &str = "INSERT INTO root_hashes (root, content_hash, switched_at) \
197            VALUES ($1, $2, $3{ts}) ON CONFLICT (root, content_hash) DO NOTHING";
198        let query = if switched { SWITCH } else { SEEN };
199        in_tx!(self, |tx, backend| {
200            sqlx::query(sql(backend, query))
201                .bind(root)
202                .bind(content_hash)
203                .bind(db_time(now))
204                .execute(&mut *tx)
205                .await?;
206        });
207        Ok(())
208    }
209
210    /// When workers last switched to each recorded hash of `root`.
211    ///
212    /// # Errors
213    ///
214    /// [`DbError`] if the query fails or a stored time doesn't read.
215    pub async fn root_hash_switches(
216        &self,
217        root: &str,
218    ) -> Result<BTreeMap<String, Timestamp>, DbError> {
219        const SWITCHES: &str = "SELECT content_hash, {ts<}switched_at{>ts} FROM root_hashes \
220            WHERE root = $1";
221        let rows: Vec<(String, String)> = on_pool!(self, |pool, backend| {
222            sqlx::query_as(sql(backend, SWITCHES))
223                .bind(root)
224                .fetch_all(pool)
225                .await?
226        });
227        rows.into_iter()
228            .map(|(hash, at)| Ok((hash, parse_time("root_hashes.switched_at", &at)?)))
229            .collect()
230    }
231
232    /// Every stored parse of (root, hash), one per schedr version, oldest first.
233    ///
234    /// # Errors
235    ///
236    /// [`DbError`] if the query fails or a stored time doesn't read.
237    pub async fn parses_of(
238        &self,
239        root: &str,
240        content_hash: &str,
241    ) -> Result<Vec<StoredParse>, DbError> {
242        const PARSES: &str = "SELECT id{text}, schedr_version, {ts<}parsed_at{>ts} \
243            FROM parse_results WHERE root = $1 AND content_hash = $2 ORDER BY parsed_at, id";
244        let rows: Vec<(String, String, String)> = on_pool!(self, |pool, backend| {
245            sqlx::query_as(sql(backend, PARSES))
246                .bind(root)
247                .bind(content_hash)
248                .fetch_all(pool)
249                .await?
250        });
251        rows.into_iter()
252            .map(|(id, schedr_version, parsed_at)| {
253                Ok(StoredParse {
254                    id,
255                    schedr_version,
256                    parsed_at: parse_time("parse_results.parsed_at", &parsed_at)?,
257                })
258            })
259            .collect()
260    }
261
262    /// The ID of the parse of (root, hash, schedr version), if stored.
263    ///
264    /// # Errors
265    ///
266    /// [`DbError::Sqlx`] if the query fails.
267    pub async fn find_parse(
268        &self,
269        root: &str,
270        content_hash: &str,
271        schedr_version: &str,
272    ) -> Result<Option<String>, DbError> {
273        const FIND: &str = "SELECT id{text} FROM parse_results \
274            WHERE root = $1 AND content_hash = $2 AND schedr_version = $3";
275        let id = on_pool!(self, |pool, backend| {
276            sqlx::query_scalar(sql(backend, FIND))
277                .bind(root)
278                .bind(content_hash)
279                .bind(schedr_version)
280                .fetch_optional(pool)
281                .await?
282        });
283        Ok(id)
284    }
285
286    /// Stores a parse result and its files, and returns its ID. A parse of the same (root,
287    /// hash, schedr version) stored meanwhile wins: its ID is returned and nothing is stored.
288    ///
289    /// # Errors
290    ///
291    /// [`DbError::Sqlx`] if a statement fails (nothing is stored then).
292    pub async fn insert_parse(&self, parse: &NewParse<'_>) -> Result<String, DbError> {
293        const INSERT: &str = "INSERT INTO parse_results \
294            (id, root, content_hash, schedr_version, worker_id, parsed_at) \
295            VALUES ($1{uuid}, $2, $3, $4, $5, $6{ts}) \
296            ON CONFLICT (root, content_hash, schedr_version) DO NOTHING";
297        const FILE: &str = "INSERT INTO parse_files \
298            (parse_result_id, path, dags, error, worker_id, master_id, parsed_at, connections, \
299            script_roots) \
300            VALUES ($1{uuid}, $2, $3{json}, $4{json}, $5, $6, $7{ts}, $8{json}, $9{json})";
301        let id = Uuid::now_v7().to_string();
302        let inserted = in_tx!(self, BATCH_LIMITS, |tx, backend| {
303            let done = sqlx::query(sql(backend, INSERT))
304                .bind(&id)
305                .bind(parse.root)
306                .bind(parse.content_hash)
307                .bind(parse.schedr_version)
308                .bind(parse.worker_id)
309                .bind(db_time(parse.parsed_at))
310                .execute(&mut *tx)
311                .await?;
312            let inserted = done.rows_affected() == 1;
313            if inserted {
314                for file in parse.files {
315                    sqlx::query(sql(backend, FILE))
316                        .bind(&id)
317                        .bind(&file.path)
318                        .bind(to_json(&file.dags))
319                        .bind(file.error.as_ref().map(to_json))
320                        .bind(parse.worker_id)
321                        .bind(self.fenced_as())
322                        .bind(db_time(parse.parsed_at))
323                        .bind(to_json(&file.connections))
324                        .bind(to_json(&file.script_roots))
325                        .execute(&mut *tx)
326                        .await?;
327                }
328            }
329            inserted
330        });
331        if inserted {
332            return Ok(id);
333        }
334        let existing = self
335            .find_parse(parse.root, parse.content_hash, parse.schedr_version)
336            .await?;
337        Ok(existing.unwrap_or(id))
338    }
339
340    /// Replaces files of a stored parse (a re-parse of files that failed transiently,
341    /// decision 72.2): each of `files` takes the place of the stored file at its path, parsed
342    /// by `worker_id` at `parsed_at` (decision 93).
343    ///
344    /// # Errors
345    ///
346    /// [`DbError::Sqlx`] if a statement fails.
347    pub async fn replace_parse_files(
348        &self,
349        parse_id: &str,
350        files: &[ParsedFile],
351        worker_id: &str,
352        parsed_at: Timestamp,
353    ) -> Result<(), DbError> {
354        const DELETE: &str =
355            "DELETE FROM parse_files WHERE parse_result_id = $1{uuid} AND path = $2";
356        const FILE: &str = "INSERT INTO parse_files \
357            (parse_result_id, path, dags, error, worker_id, master_id, parsed_at, connections, \
358            script_roots) \
359            VALUES ($1{uuid}, $2, $3{json}, $4{json}, $5, $6, $7{ts}, $8{json}, $9{json})";
360        in_tx!(self, BATCH_LIMITS, |tx, backend| {
361            for file in files {
362                sqlx::query(sql(backend, DELETE))
363                    .bind(parse_id)
364                    .bind(&file.path)
365                    .execute(&mut *tx)
366                    .await?;
367                sqlx::query(sql(backend, FILE))
368                    .bind(parse_id)
369                    .bind(&file.path)
370                    .bind(to_json(&file.dags))
371                    .bind(file.error.as_ref().map(to_json))
372                    .bind(worker_id)
373                    .bind(self.fenced_as())
374                    .bind(db_time(parsed_at))
375                    .bind(to_json(&file.connections))
376                    .bind(to_json(&file.script_roots))
377                    .execute(&mut *tx)
378                    .await?;
379            }
380        });
381        Ok(())
382    }
383
384    /// The worker that parsed each file of a parse, by path (decision 93): the parse's own,
385    /// or the one that parsed the file again.
386    ///
387    /// # Errors
388    ///
389    /// [`DbError::Sqlx`] if the query fails.
390    pub async fn parse_file_workers(
391        &self,
392        parse_id: &str,
393    ) -> Result<BTreeMap<String, String>, DbError> {
394        const WORKERS: &str = "SELECT path, worker_id FROM parse_files \
395            WHERE parse_result_id = $1{uuid}";
396        let rows: Vec<(String, String)> = on_pool!(self, |pool, backend| {
397            sqlx::query_as(sql(backend, WORKERS))
398                .bind(parse_id)
399                .fetch_all(pool)
400                .await?
401        });
402        Ok(rows.into_iter().collect())
403    }
404
405    /// The files of a stored parse, in path order.
406    ///
407    /// # Errors
408    ///
409    /// [`DbError::Sqlx`] if the query fails, [`DbError::InvalidData`] if a stored file doesn't
410    /// read back.
411    pub async fn parse_files(&self, parse_id: &str) -> Result<Vec<ParsedFile>, DbError> {
412        const FILES: &str = "SELECT path, dags{text}, error{text}, connections{text}, \
413            script_roots{text} FROM parse_files WHERE parse_result_id = $1{uuid} ORDER BY path";
414        let rows: Vec<FileRow> = on_pool!(self, |pool, backend| {
415            sqlx::query_as(sql(backend, FILES))
416                .bind(parse_id)
417                .fetch_all(pool)
418                .await?
419        });
420        rows.into_iter()
421            .map(|(path, dags, error, connections, script_roots)| {
422                Ok(ParsedFile {
423                    dags: from_json("parse_files.dags", &dags)?,
424                    connections: from_json("parse_files.connections", &connections)?,
425                    script_roots: from_json("parse_files.script_roots", &script_roots)?,
426                    error: error
427                        .map(|e| from_json("parse_files.error", &e))
428                        .transpose()?,
429                    path,
430                    warnings: Vec::new(),
431                })
432            })
433            .collect()
434    }
435
436    /// The connections of `root`'s current parse (decision 174), as the master builds its
437    /// registry: empty when it has none.
438    ///
439    /// # Errors
440    ///
441    /// [`DbError::Sqlx`] if the query fails, [`DbError::InvalidData`] if a stored connection
442    /// doesn't read back.
443    pub async fn current_connections(&self, root: &str) -> Result<Registry, DbError> {
444        const CONNECTIONS: &str = "SELECT f.path, f.connections{text} FROM current_parses c \
445            JOIN parse_files f ON f.parse_result_id = c.parse_result_id \
446            WHERE c.root = $1 ORDER BY f.path";
447        let rows: Vec<(String, String)> = on_pool!(self, |pool, backend| {
448            sqlx::query_as(sql(backend, CONNECTIONS))
449                .bind(root)
450                .fetch_all(pool)
451                .await?
452        });
453        let files = rows
454            .into_iter()
455            .map(|(path, connections)| {
456                Ok(ParsedFile {
457                    script_roots: Vec::new(),
458                    connections: from_json("parse_files.connections", &connections)?,
459                    path,
460                    dags: Vec::new(),
461                    error: None,
462                    warnings: Vec::new(),
463                })
464            })
465            .collect::<Result<Vec<_>, DbError>>()?;
466        Ok(Registry::of(&files))
467    }
468
469    /// Records `parse_id` as `root`'s current parse (the master's decision), at `now`.
470    ///
471    /// # Errors
472    ///
473    /// [`DbError::Sqlx`] if the statement fails.
474    pub async fn set_current_parse(
475        &self,
476        root: &str,
477        parse_id: &str,
478        now: Timestamp,
479    ) -> Result<(), DbError> {
480        const SET: &str = "INSERT INTO current_parses (root, parse_result_id, decided_at) \
481            VALUES ($1, $2{uuid}, $3{ts}) ON CONFLICT (root) DO UPDATE SET \
482            parse_result_id = excluded.parse_result_id, decided_at = excluded.decided_at";
483        in_tx!(self, |tx, backend| {
484            sqlx::query(sql(backend, SET))
485                .bind(root)
486                .bind(parse_id)
487                .bind(db_time(now))
488                .execute(&mut *tx)
489                .await?;
490        });
491        Ok(())
492    }
493
494    /// Each root's current parse, as last recorded by [`Self::set_current_parse`]: root to
495    /// parse ID.
496    ///
497    /// # Errors
498    ///
499    /// [`DbError::Sqlx`] if the query fails.
500    pub async fn current_parses(&self) -> Result<BTreeMap<String, String>, DbError> {
501        const CURRENT: &str = "SELECT root, parse_result_id{text} FROM current_parses";
502        let rows: Vec<(String, String)> = on_pool!(self, |pool, backend| {
503            sqlx::query_as(sql(backend, CURRENT))
504                .fetch_all(pool)
505                .await?
506        });
507        Ok(rows.into_iter().collect())
508    }
509
510    /// The files of each root's current parse that failed to import, by root and path
511    /// (decision 66).
512    ///
513    /// # Errors
514    ///
515    /// [`DbError::Sqlx`] if the query fails, [`DbError::InvalidData`] if a stored error or time
516    /// doesn't read back.
517    pub async fn current_import_errors(&self) -> Result<Vec<ImportErrorRecord>, DbError> {
518        const ERRORS: &str = "SELECT c.root, r.content_hash, r.schedr_version, f.worker_id, \
519            f.master_id, {ts<}f.parsed_at{>ts}, f.path, f.error{text} \
520            FROM current_parses c \
521            JOIN parse_results r ON r.id = c.parse_result_id \
522            JOIN parse_files f ON f.parse_result_id = c.parse_result_id \
523            WHERE f.error IS NOT NULL ORDER BY c.root, f.path";
524        let rows: Vec<ImportErrorRow> = on_pool!(self, |pool, backend| {
525            sqlx::query_as(sql(backend, ERRORS)).fetch_all(pool).await?
526        });
527        rows.into_iter()
528            .map(
529                |(
530                    root,
531                    content_hash,
532                    schedr_version,
533                    worker_id,
534                    master_id,
535                    parsed_at,
536                    path,
537                    error,
538                )| {
539                    Ok(ImportErrorRecord {
540                        root,
541                        content_hash,
542                        schedr_version,
543                        worker_id,
544                        master_id,
545                        parsed_at: parse_time("parse_files.parsed_at", &parsed_at)?,
546                        path,
547                        error: from_json("parse_files.error", &error)?,
548                    })
549                },
550            )
551            .collect()
552    }
553
554    /// Every stored DAG (removed ones too), with its current version, in DAG ID order.
555    ///
556    /// # Errors
557    ///
558    /// [`DbError::Sqlx`] if the query fails, [`DbError::InvalidData`] if stored JSON doesn't
559    /// read back.
560    pub async fn stored_dags(&self) -> Result<Vec<StoredDag>, DbError> {
561        const DAGS: &str = "SELECT d.dag_id, t.paused, d.removed_at IS NOT NULL, \
562            d.conflict{text}, v.id{text}, v.parse_result_id{text}, v.dag_json{text} \
563            FROM dags d LEFT JOIN dag_triggers t ON t.dag_id = d.dag_id \
564            LEFT JOIN dag_versions v ON v.id = d.current_version_id \
565            ORDER BY d.dag_id";
566        let rows: Vec<DagRow> = on_pool!(self, |pool, backend| {
567            sqlx::query_as(sql(backend, DAGS)).fetch_all(pool).await?
568        });
569        rows.into_iter().map(stored_dag).collect()
570    }
571
572    /// The DAGs whose queued tasks mustn't be assigned, each `true` when removed (their tasks
573    /// not started are cancelled, B192) and `false` when in an ID conflict (they wait until it
574    /// is resolved, B193; decision 107).
575    ///
576    /// # Errors
577    ///
578    /// [`DbError::Sqlx`] if the query fails.
579    pub async fn held_dags(&self) -> Result<BTreeMap<String, bool>, DbError> {
580        const HELD: &str = "SELECT dag_id, removed_at IS NOT NULL FROM dags \
581            WHERE removed_at IS NOT NULL OR conflict IS NOT NULL";
582        let rows: Vec<(String, bool)> = on_pool!(self, |pool, backend| {
583            sqlx::query_as(sql(backend, HELD)).fetch_all(pool).await?
584        });
585        Ok(rows.into_iter().collect())
586    }
587
588    /// The unfinished runs of removed DAGs with something not started yet (B192): queued runs,
589    /// and running ones with a task scheduled, queued, up for retry or unschedulable, or with
590    /// an assignment not started whose cancel isn't asked yet. The master cancels what they
591    /// haven't started; their running attempts finish.
592    ///
593    /// # Errors
594    ///
595    /// [`DbError::Sqlx`] if the query fails.
596    pub async fn removed_dags_runs(&self) -> Result<Vec<String>, DbError> {
597        const RUNS: &str = concat!(
598            "SELECT r.id{text} ",
599            removed_dags_runs_from!(),
600            " ORDER BY r.triggered_at, r.id"
601        );
602        if self.skipped(crate::probe::Check::RemovedDagsRuns).await? {
603            return Ok(Vec::new());
604        }
605        Ok(on_pool!(self, |pool, backend| {
606            sqlx::query_scalar(sql(backend, RUNS))
607                .fetch_all(pool)
608                .await?
609        }))
610    }
611
612    /// The scheduled DAGs that can run whose next fire time has come at `now` or isn't known
613    /// (decision 485), with what is stored (`None`: not known).
614    ///
615    /// # Errors
616    ///
617    /// [`DbError`] if the query fails or a stored time doesn't read.
618    pub async fn scheduled_due(
619        &self,
620        now: Timestamp,
621    ) -> Result<Vec<(DagId, Option<Timestamp>)>, DbError> {
622        const DUE: &str = concat!(
623            "SELECT t.dag_id, {ts<}t.next_fire_at{>ts} ",
624            scheduled_due_from!(),
625            " ORDER BY t.dag_id"
626        );
627        if self.skipped_at(crate::probe::Check::Scheduled, now).await? {
628            return Ok(Vec::new());
629        }
630        let rows: Vec<(String, Option<String>)> = on_pool!(self, |pool, backend| {
631            sqlx::query_as(sql(backend, DUE))
632                .bind(db_time(now))
633                .fetch_all(pool)
634                .await?
635        });
636        rows.into_iter()
637            .map(|(dag, at)| {
638                let at = at
639                    .map(|at| parse_time("dag_triggers.next_fire_at", &at))
640                    .transpose()?;
641                Ok((crate::runs::dag_id_of(dag)?, at))
642            })
643            .collect()
644    }
645
646    /// Every trigger's stored next time (`None`: not known): a scheduled DAG's next fire time,
647    /// for a round visiting every DAG (decision 485), and an event trigger's next moment, for
648    /// the trigger loop (decision 486).
649    ///
650    /// # Errors
651    ///
652    /// [`DbError`] if the query fails or a stored time doesn't read.
653    pub async fn next_fires(&self) -> Result<HashMap<DagId, Option<Timestamp>>, DbError> {
654        const ALL: &str = "SELECT dag_id, {ts<}next_fire_at{>ts} FROM dag_triggers";
655        let rows: Vec<(String, Option<String>)> = on_pool!(self, |pool, backend| {
656            sqlx::query_as(sql(backend, ALL)).fetch_all(pool).await?
657        });
658        rows.into_iter()
659            .map(|(dag, at)| {
660                let at = at
661                    .map(|at| parse_time("dag_triggers.next_fire_at", &at))
662                    .transpose()?;
663                Ok((crate::runs::dag_id_of(dag)?, at))
664            })
665            .collect()
666    }
667
668    /// The trigger loop's looks, taken at the start of its pass (decision 486): each trigger it
669    /// looks after whose look isn't known (`NULL`: a named event posted, a new version, an
670    /// unpause) is set to [`NO_FIRE`] first, then all are read. A post from then on finds a
671    /// look to clear, and is announced; one before it is in the pass's scans (Grok's second
672    /// review of M5.1f2: a post while the look was already `NULL` cleared nothing, and the
673    /// pass's store hid it). The pass looks at every trigger anyway; the look only wakes it.
674    ///
675    /// # Errors
676    ///
677    /// [`DbError`] if a statement fails or a stored time doesn't read.
678    pub async fn claim_looks(&self) -> Result<HashMap<DagId, Option<Timestamp>>, DbError> {
679        const CLAIM: &str = "UPDATE dag_triggers SET next_fire_at = $1{ts} \
680            WHERE kind IN ('run_of', 'event') AND NOT paused AND next_fire_at IS NULL";
681        const ALL: &str = "SELECT dag_id, {ts<}next_fire_at{>ts} FROM dag_triggers";
682        let rows: Vec<(String, Option<String>)> = in_tx!(self, |tx, backend| {
683            sqlx::query(sql(backend, CLAIM))
684                .bind(db_time(NO_FIRE))
685                .execute(&mut *tx)
686                .await?;
687            sqlx::query_as(sql(backend, ALL))
688                .fetch_all(&mut *tx)
689                .await?
690        });
691        rows.into_iter()
692            .map(|(dag, at)| {
693                let at = at
694                    .map(|at| parse_time("dag_triggers.next_fire_at", &at))
695                    .transpose()?;
696                Ok((crate::runs::dag_id_of(dag)?, at))
697            })
698            .collect()
699    }
700
701    /// As [`Self::set_next_fire`], only while the stored time is still `was`: a time cleared
702    /// meanwhile (a named event posted during the trigger pass, Grok's review of M5.1f2) is
703    /// left cleared, for the probe to find. A look not known is never stored over: whatever
704    /// cleared it is looked at by the next pass. Returns whether it was stored.
705    ///
706    /// # Errors
707    ///
708    /// [`DbError::Sqlx`] if the statement fails.
709    pub async fn set_next_fire_if(
710        &self,
711        dag_id: &DagId,
712        was: Timestamp,
713        at: Timestamp,
714    ) -> Result<bool, DbError> {
715        const SET: &str = "UPDATE dag_triggers SET next_fire_at = $1{ts} WHERE dag_id = $2 \
716            AND next_fire_at = $3{ts}";
717        let stored = in_tx!(self, |tx, backend| {
718            sqlx::query(sql(backend, SET))
719                .bind(db_time(at))
720                .bind(dag_id.as_str())
721                .bind(db_time(was))
722                .execute(&mut *tx)
723                .await?
724                .rows_affected()
725        });
726        Ok(stored == 1)
727    }
728
729    /// Stores when the master looks at `dag_id`'s trigger next ([`NO_FIRE`]: nothing ahead): a
730    /// scheduled DAG's next fire time (decision 485), an event trigger's next moment (decision
731    /// 486). A DAG without a trigger's row changes nothing.
732    ///
733    /// # Errors
734    ///
735    /// [`DbError::Sqlx`] if the statement fails.
736    pub async fn set_next_fire(&self, dag_id: &DagId, at: Timestamp) -> Result<(), DbError> {
737        const SET: &str = "UPDATE dag_triggers SET next_fire_at = $1{ts} WHERE dag_id = $2";
738        in_tx!(self, |tx, backend| {
739            sqlx::query(sql(backend, SET))
740                .bind(db_time(at))
741                .bind(dag_id.as_str())
742                .execute(&mut *tx)
743                .await?;
744        });
745        Ok(())
746    }
747
748    /// DAG `dag_id` as [`Self::stored_dags`] lists it, read alone (B136: one DAG's reads
749    /// read every DAG); `None` if it was never stored.
750    ///
751    /// # Errors
752    ///
753    /// [`DbError`] if the query fails or its stored DAG doesn't read.
754    pub async fn stored_dag(&self, dag_id: &DagId) -> Result<Option<StoredDag>, DbError> {
755        const DAG: &str = "SELECT d.dag_id, t.paused, d.removed_at IS NOT NULL, \
756            d.conflict{text}, v.id{text}, v.parse_result_id{text}, v.dag_json{text} \
757            FROM dags d LEFT JOIN dag_triggers t ON t.dag_id = d.dag_id \
758            LEFT JOIN dag_versions v ON v.id = d.current_version_id \
759            WHERE d.dag_id = $1";
760        let row: Option<DagRow> = on_pool!(self, |pool, backend| {
761            sqlx::query_as(sql(backend, DAG))
762                .bind(dag_id.as_str())
763                .fetch_optional(pool)
764                .await?
765        });
766        row.map(stored_dag).transpose()
767    }
768
769    /// Pauses or unpauses a DAG's trigger. Returns whether it has one (decision 459: a DAG run
770    /// only by hand has no switch).
771    ///
772    /// # Errors
773    ///
774    /// [`DbError::Sqlx`] if the statement fails.
775    pub async fn set_paused(&self, dag_id: &DagId, paused: bool) -> Result<bool, DbError> {
776        self.set_paused_at(dag_id, paused, Timestamp::now()).await
777    }
778
779    /// As [`Self::set_paused`], unpausing at `now`: its `live_since` (decision 353) changes in the
780    /// same statement, cleared by a pause, set by an unpause unless it was live already.
781    ///
782    /// # Errors
783    ///
784    /// [`DbError::Sqlx`] if the statement fails.
785    pub async fn set_paused_at(
786        &self,
787        dag_id: &DagId,
788        paused: bool,
789        now: Timestamp,
790    ) -> Result<bool, DbError> {
791        // A switch changed: its next fire time isn't known any more (decision 485).
792        const PAUSE: &str = "UPDATE dag_triggers SET paused = $1, next_fire_at = NULL, \
793            live_since = CASE WHEN $1 THEN NULL WHEN EXISTS (SELECT 1 FROM dags d \
794                WHERE d.dag_id = dag_triggers.dag_id AND d.removed_at IS NULL \
795                AND d.conflict IS NULL) THEN COALESCE(live_since, $3{ts}) END \
796            WHERE dag_id = $2";
797        let changed = in_tx!(self, |tx, backend| {
798            sqlx::query(sql(backend, PAUSE))
799                .bind(paused)
800                .bind(dag_id.as_str())
801                .bind(db_time(now))
802                .execute(&mut *tx)
803                .await?
804                .rows_affected()
805        });
806        Ok(changed == 1)
807    }
808
809    /// Stores changes to the DAG list, all or none.
810    ///
811    /// # Errors
812    ///
813    /// [`DbError::Sqlx`] if a statement fails (nothing is stored then).
814    #[expect(
815        clippy::too_many_lines,
816        reason = "one transaction over each kind of change, its statements read together"
817    )]
818    pub async fn apply_dag_changes(
819        &self,
820        changes: &[DagChange],
821        now: Timestamp,
822    ) -> Result<(), DbError> {
823        const ENSURE: &str = "INSERT INTO dags (dag_id, first_seen_at) \
824            VALUES ($1, $2{ts}) ON CONFLICT (dag_id) DO NOTHING";
825        const VERSION: &str = "INSERT INTO dag_versions \
826            (id, dag_id, parse_result_id, dag_json, created_at) \
827            VALUES ($1{uuid}, $2, $3{uuid}, $4{json}, $5{ts}) \
828            ON CONFLICT (dag_id, parse_result_id) DO NOTHING";
829        const OLD_TRIGGER: &str = "SELECT v.dag_json{text} FROM dags d \
830            JOIN dag_versions v ON v.id = d.current_version_id WHERE d.dag_id = $1";
831        // Its trigger's switch (decision 459), before the DAG's row changes: new, or of another
832        // kind ($2), paused; else kept, paused by $3. `live_since` (decision 353) with it: kept
833        // while it stays live with the same trigger, set when it comes back unpaused or its
834        // trigger changes ($4), cleared while it is paused, in conflict or removed.
835        // `event_name` ($6, decision 486): what an `EventNamed` waits for, so a post clears
836        // only its listeners' stored time.
837        const SWITCH: &str = "INSERT INTO dag_triggers (dag_id, kind, paused, live_since, \
838            event_name) VALUES ($1, $2, TRUE, NULL, $6) ON CONFLICT (dag_id) DO UPDATE SET \
839            paused = CASE WHEN dag_triggers.kind <> excluded.kind THEN TRUE \
840                ELSE (dag_triggers.paused OR $3) END, \
841            live_since = CASE WHEN dag_triggers.kind <> excluded.kind \
842                OR dag_triggers.paused OR $3 THEN NULL \
843                WHEN EXISTS (SELECT 1 FROM dags d WHERE d.dag_id = $1 \
844                    AND d.removed_at IS NULL AND d.conflict IS NULL) AND NOT $4 \
845                THEN COALESCE(dag_triggers.live_since, $5{ts}) ELSE $5{ts} END, \
846            kind = excluded.kind, event_name = excluded.event_name, next_fire_at = NULL";
847        const NO_SWITCH: &str = "DELETE FROM dag_triggers WHERE dag_id = $1";
848        const CURRENT: &str = "UPDATE dags SET current_version_id = (SELECT id FROM dag_versions \
849            WHERE dag_id = $1 AND parse_result_id = $2{uuid}), \
850            removed_at = NULL, conflict = NULL WHERE dag_id = $1";
851        const CONFLICT: &str = "UPDATE dags SET conflict = $1{json}, removed_at = NULL \
852            WHERE dag_id = $2";
853        const CONFLICT_SWITCH: &str = "UPDATE dag_triggers SET live_since = NULL, \
854            paused = (paused OR $1), next_fire_at = NULL WHERE dag_id = $2";
855        const REMOVE: &str = "UPDATE dags SET removed_at = $1{ts}, conflict = NULL \
856            WHERE dag_id = $2";
857        const REMOVE_SWITCH: &str =
858            "UPDATE dag_triggers SET live_since = NULL, next_fire_at = NULL WHERE dag_id = $1";
859        const FORGET_PASSED: &str = "DELETE FROM trigger_progress_passed WHERE dag_id = $1";
860        // As retention's: not one a new run's foreign key waits for.
861        const LOCK: &str = "SELECT dag_id FROM dags WHERE dag_id = $1 FOR NO KEY UPDATE";
862        let now = db_time(now);
863        in_tx!(self, BATCH_LIMITS, |tx, backend| {
864            for change in changes {
865                match change {
866                    DagChange::Define {
867                        dag,
868                        parse_id,
869                        pause,
870                    } => {
871                        sqlx::query(sql(backend, ENSURE))
872                            .bind(dag.id.as_str())
873                            .bind(&now)
874                            .execute(&mut *tx)
875                            .await?;
876                        // As retention does before deleting its versions: one waits for the
877                        // other, so the version made current here isn't deleted meanwhile
878                        // (Codex's review of M4.14). SQLite's writes are one at a time.
879                        if backend == crate::Backend::Postgres {
880                            sqlx::query(sql(backend, LOCK))
881                                .bind(dag.id.as_str())
882                                .execute(&mut *tx)
883                                .await?;
884                        }
885                        sqlx::query(sql(backend, VERSION))
886                            .bind(Uuid::now_v7().to_string())
887                            .bind(dag.id.as_str())
888                            .bind(parse_id)
889                            .bind(to_json(dag))
890                            .bind(&now)
891                            .execute(&mut *tx)
892                            .await?;
893                        let old: Option<(String,)> = sqlx::query_as(sql(backend, OLD_TRIGGER))
894                            .bind(dag.id.as_str())
895                            .fetch_optional(&mut *tx)
896                            .await?;
897                        let new_trigger = old.is_some_and(|(json,)| {
898                            serde_json::from_str::<serde_json::Value>(&json)
899                                .ok()
900                                .and_then(|mut old| {
901                                    old.get_mut("trigger").map(serde_json::Value::take)
902                                })
903                                != serde_json::to_value(&dag.trigger).ok()
904                        });
905                        if let Some(kind) = dag.trigger.kind() {
906                            sqlx::query(sql(backend, SWITCH))
907                                .bind(dag.id.as_str())
908                                .bind(kind)
909                                .bind(*pause)
910                                .bind(new_trigger)
911                                .bind(&now)
912                                .bind(match &dag.trigger {
913                                    schedr_model::Trigger::EventNamed { event } => {
914                                        Some(event.name.as_str())
915                                    }
916                                    _ => None,
917                                })
918                                .execute(&mut *tx)
919                                .await?;
920                        } else {
921                            sqlx::query(sql(backend, NO_SWITCH))
922                                .bind(dag.id.as_str())
923                                .execute(&mut *tx)
924                                .await?;
925                        }
926                        sqlx::query(sql(backend, CURRENT))
927                            .bind(dag.id.as_str())
928                            .bind(parse_id)
929                            .execute(&mut *tx)
930                            .await?;
931                    }
932                    DagChange::Conflict {
933                        dag_id,
934                        places,
935                        pause,
936                    } => {
937                        sqlx::query(sql(backend, ENSURE))
938                            .bind(dag_id.as_str())
939                            .bind(&now)
940                            .execute(&mut *tx)
941                            .await?;
942                        sqlx::query(sql(backend, CONFLICT))
943                            .bind(to_json(places))
944                            .bind(dag_id.as_str())
945                            .execute(&mut *tx)
946                            .await?;
947                        sqlx::query(sql(backend, CONFLICT_SWITCH))
948                            .bind(*pause)
949                            .bind(dag_id.as_str())
950                            .execute(&mut *tx)
951                            .await?;
952                    }
953                    DagChange::Remove { dag_id } => {
954                        sqlx::query(sql(backend, REMOVE))
955                            .bind(&now)
956                            .bind(dag_id.as_str())
957                            .execute(&mut *tx)
958                            .await?;
959                        sqlx::query(sql(backend, REMOVE_SWITCH))
960                            .bind(dag_id.as_str())
961                            .execute(&mut *tx)
962                            .await?;
963                        // What its trigger passed is read only while it is live (B186).
964                        sqlx::query(sql(backend, FORGET_PASSED))
965                            .bind(dag_id.as_str())
966                            .execute(&mut *tx)
967                            .await?;
968                    }
969                }
970            }
971        });
972        Ok(())
973    }
974}
975
976fn stored_dag(row: DagRow) -> Result<StoredDag, DbError> {
977    let (dag_id, paused, removed, conflict, version_id, parse_id, dag_json) = row;
978    let current = match (version_id, parse_id, dag_json) {
979        (Some(version_id), Some(parse_id), Some(json)) => Some(CurrentVersion {
980            version_id,
981            parse_id,
982            dag: from_json("dag_versions.dag_json", &json)?,
983        }),
984        _ => None,
985    };
986    Ok(StoredDag {
987        dag_id: DagId::new(dag_id).map_err(|e| DbError::InvalidData {
988            what: "dags.dag_id",
989            reason: e.to_string(),
990        })?,
991        paused,
992        removed,
993        conflict: conflict
994            .map(|c| from_json("dags.conflict", &c))
995            .transpose()?,
996        current,
997    })
998}