Skip to main content

schedr_db/
retention.rs

1//! Retention (decisions 430-435): what the master's retention job deletes once `[retention]` no
2//! longer keeps it, a batch per transaction (runs and outputs one DAG at a time). Never an
3//! unfinished run, nor one something unfinished reads, nor what a DAG still needs (see
4//! `KEPT`), unless the DAG was removed long enough ago; a removed DAG then goes with its last
5//! run.
6
7use jiff::Timestamp;
8
9use crate::database::{Database, DbError};
10use crate::query::{BATCH_LIMITS, db_time, in_tx, on_pool, sql};
11
12#[cfg(test)]
13mod tests;
14
15/// Of the runs `r` of a DAG `d`, the ones it still needs (decision 430): its newest scheduled
16/// run, its newest run, the last to end `success` or `failed`, and the successful runs of other
17/// kinds planned after its newest scheduled one, or, without one, its successful backfill runs:
18/// catchup counts their fire times as done (decision 440). A removed DAG keeps them until its
19/// removal is as old as `$1`'s cut: a file missing for a while (a bad sync) costs no history.
20/// Never NULL: a NULL would keep every run, `NOT NULL` being NULL.
21const KEPT: &str = "(d.removed_at IS NULL OR d.removed_at >= $1{ts}) AND ( \
22    r.id IN (SELECT s.id FROM runs s WHERE s.dag_id = r.dag_id AND s.kind = 'scheduled' \
23        ORDER BY s.planned_for DESC, s.id DESC LIMIT 1) \
24    OR r.id IN (SELECT s.id FROM runs s WHERE s.dag_id = r.dag_id \
25        ORDER BY s.planned_for DESC, s.id DESC LIMIT 1) \
26    OR r.id IN (SELECT s.id FROM runs s WHERE s.dag_id = r.dag_id \
27        AND s.state IN ('success', 'failed') AND s.ended_at IS NOT NULL \
28        ORDER BY s.ended_at DESC, s.id DESC LIMIT 1) \
29    OR (r.kind <> 'scheduled' AND r.state = 'success' AND (r.planned_for > \
30        COALESCE((SELECT MAX(s.planned_for) FROM runs s WHERE s.dag_id = r.dag_id \
31         AND s.kind = 'scheduled'), r.planned_for) \
32        OR (r.kind = 'backfill' AND NOT EXISTS (SELECT 1 FROM runs s \
33         WHERE s.dag_id = r.dag_id AND s.kind = 'scheduled')))))";
34
35/// Of the runs `r`, those something unfinished still reads, whatever their DAG: a
36/// `TriggerDagOperator`'s open attempt waiting for it (gone, it would be started again), a
37/// waiting step or trigger handed it (a retry gets the same run). Codex's review of M4.14.
38const HELD: &str = "r.id IN (SELECT a.chained_run_id FROM attempts a \
39        WHERE a.status IS NULL AND a.chained_run_id IS NOT NULL) \
40    OR r.id{text} IN (SELECT t.handed_run FROM task_instances t WHERE t.handed_run IS NOT NULL \
41        AND t.state NOT IN ('success', 'failed', 'cancelled', 'skipped', 'upstream_failed')) \
42    OR r.id{text} IN (SELECT g.run_of_handed_run FROM trigger_progress g \
43        WHERE g.run_of_handed_run IS NOT NULL)";
44
45/// The finished runs `r` of DAG `d` that ended before `$1` and nothing keeps.
46const OLD: &str = "r.state IN ('success', 'failed', 'cancelled') AND r.ended_at < $1{ts}";
47
48/// Taken before a DAG's runs or versions are deleted, so a definition of it (which takes the
49/// same lock) waits, or is seen (Codex's review of M4.14). `NO KEY`: a new run of the DAG (its
50/// foreign key takes a key-share lock) doesn't wait for the batch, nor the master's loop with
51/// it. SQLite's writes are one at a time.
52const LOCK_DAG: &str = "SELECT dag_id FROM dags WHERE dag_id = $1 FOR NO KEY UPDATE";
53
54impl Database {
55    /// The DAG of the oldest run `select` (a query over `runs r JOIN dags d` with `$1`, the
56    /// time) gives, if any: retention works through one DAG per transaction, its row locked.
57    async fn oldest_dag(&self, select: &str, before: &str) -> Result<Option<String>, DbError> {
58        let query = format!(
59            "SELECT r.dag_id FROM runs r JOIN dags d ON d.dag_id = r.dag_id \
60            WHERE {select} ORDER BY r.ended_at, r.id LIMIT 1"
61        );
62        let dag: Option<String> = on_pool!(self, |pool, backend| {
63            sqlx::query_scalar(crate::query::sql_text(backend, &query))
64                .bind(before)
65                .fetch_optional(pool)
66                .await?
67        });
68        Ok(dag)
69    }
70
71    /// Deletes at most `batch` finished runs of one DAG that ended before `before` and aren't
72    /// kept, with their tasks, attempts and outputs; a run they started (`TriggerDagOperator`)
73    /// loses its link to them (decision 431). Then the backfills left without runs, made before
74    /// `before`. Gives how many runs: 0 when none is left.
75    ///
76    /// # Errors
77    ///
78    /// [`DbError`] if a statement fails (nothing of the batch is deleted then).
79    pub async fn delete_old_runs(&self, before: Timestamp, batch: u32) -> Result<u64, DbError> {
80        const UNLINK: &str = "UPDATE runs SET parent_run_id = NULL WHERE parent_run_id = $1{uuid}";
81        const PASSED: &str = "DELETE FROM trigger_progress_passed WHERE item = $1";
82        const DELETE: &str = "DELETE FROM runs WHERE id = $1{uuid}";
83        const BACKFILLS: &str = "DELETE FROM backfills WHERE created_at < $1{ts} \
84            AND NOT EXISTS (SELECT 1 FROM runs WHERE runs.backfill_id = backfills.id)";
85        let eligible = format!("{OLD} AND NOT ({KEPT}) AND NOT ({HELD})");
86        let before = db_time(before);
87        let Some(dag_id) = self.oldest_dag(&eligible, &before).await? else {
88            return Ok(0);
89        };
90        // Chosen again under the lock: what the DAG is now.
91        let old = format!(
92            "SELECT r.id{{text}} FROM runs r JOIN dags d ON d.dag_id = r.dag_id \
93             WHERE r.dag_id = $3 AND {eligible} ORDER BY r.ended_at, r.id LIMIT $2"
94        );
95        let deleted = in_tx!(self, BATCH_LIMITS, |tx, backend| {
96            if backend == crate::Backend::Postgres {
97                sqlx::query(sql(backend, LOCK_DAG))
98                    .bind(&dag_id)
99                    .execute(&mut *tx)
100                    .await?;
101            }
102            let ids: Vec<String> = sqlx::query_scalar(crate::query::sql_text(backend, &old))
103                .bind(&before)
104                .bind(i64::from(batch))
105                .bind(&dag_id)
106                .fetch_all(&mut *tx)
107                .await?;
108            let mut deleted = 0;
109            for id in &ids {
110                sqlx::query(sql(backend, UNLINK))
111                    .bind(id)
112                    .execute(&mut *tx)
113                    .await?;
114                sqlx::query(sql(backend, PASSED))
115                    .bind(id)
116                    .execute(&mut *tx)
117                    .await?;
118                deleted += sqlx::query(sql(backend, DELETE))
119                    .bind(id)
120                    .execute(&mut *tx)
121                    .await?
122                    .rows_affected();
123            }
124            sqlx::query(sql(backend, BACKFILLS))
125                .bind(&before)
126                .execute(&mut *tx)
127                .await?;
128            deleted
129        });
130        Ok(deleted)
131    }
132
133    /// Deletes the outputs of at most `batch` finished runs of one DAG that ended before
134    /// `before` and aren't kept, marking each run (`outputs_deleted_at = now`): its tasks and
135    /// outcomes stay, and an output asked for answers "deleted by retention" (decision 435).
136    /// Gives how many runs: 0 when none is left.
137    ///
138    /// # Errors
139    ///
140    /// [`DbError`] if a statement fails.
141    pub async fn delete_old_outputs(
142        &self,
143        before: Timestamp,
144        batch: u32,
145        now: Timestamp,
146    ) -> Result<u64, DbError> {
147        const OUTPUTS: &str = "DELETE FROM outputs WHERE task_instance_id IN \
148            (SELECT id FROM task_instances WHERE run_id = $1{uuid})";
149        const MARK: &str = "UPDATE runs SET outputs_deleted_at = $2{ts} WHERE id = $1{uuid}";
150        let eligible =
151            format!("{OLD} AND r.outputs_deleted_at IS NULL AND NOT ({KEPT}) AND NOT ({HELD})");
152        let (before, now) = (db_time(before), db_time(now));
153        let Some(dag_id) = self.oldest_dag(&eligible, &before).await? else {
154            return Ok(0);
155        };
156        let old = format!(
157            "SELECT r.id{{text}} FROM runs r JOIN dags d ON d.dag_id = r.dag_id \
158             WHERE r.dag_id = $3 AND {eligible} ORDER BY r.ended_at, r.id LIMIT $2"
159        );
160        let marked = in_tx!(self, BATCH_LIMITS, |tx, backend| {
161            if backend == crate::Backend::Postgres {
162                sqlx::query(sql(backend, LOCK_DAG))
163                    .bind(&dag_id)
164                    .execute(&mut *tx)
165                    .await?;
166            }
167            let ids: Vec<String> = sqlx::query_scalar(crate::query::sql_text(backend, &old))
168                .bind(&before)
169                .bind(i64::from(batch))
170                .bind(&dag_id)
171                .fetch_all(&mut *tx)
172                .await?;
173            for id in &ids {
174                sqlx::query(sql(backend, OUTPUTS))
175                    .bind(id)
176                    .execute(&mut *tx)
177                    .await?;
178                sqlx::query(sql(backend, MARK))
179                    .bind(id)
180                    .bind(&now)
181                    .execute(&mut *tx)
182                    .await?;
183            }
184            ids.len() as u64
185        });
186        Ok(marked)
187    }
188
189    /// Deletes the versions of one DAG that it doesn't run now and no run or trigger uses, its
190    /// row locked: a definition of the same code again stores its version anew (archived
191    /// Retention: DAG versions). Gives how many: 0 when no DAG has any left.
192    ///
193    /// # Errors
194    ///
195    /// [`DbError`] if a statement fails.
196    pub async fn delete_unused_versions(&self) -> Result<u64, DbError> {
197        const UNUSED: &str = "NOT EXISTS (SELECT 1 FROM dags c WHERE c.current_version_id = v.id) \
198            AND NOT EXISTS (SELECT 1 FROM runs r WHERE r.dag_version_id = v.id) \
199            AND NOT EXISTS (SELECT 1 FROM trigger_progress t WHERE t.dag_version_id = v.id{text})";
200        let any = format!("SELECT v.dag_id FROM dag_versions v WHERE {UNUSED} LIMIT 1");
201        let delete = format!(
202            "DELETE FROM dag_versions WHERE id IN \
203            (SELECT v.id FROM dag_versions v WHERE v.dag_id = $1 AND {UNUSED})"
204        );
205        let dag: Option<String> = on_pool!(self, |pool, backend| {
206            sqlx::query_scalar(crate::query::sql_text(backend, &any))
207                .fetch_optional(pool)
208                .await?
209        });
210        let Some(dag_id) = dag else {
211            return Ok(0);
212        };
213        let deleted = in_tx!(self, BATCH_LIMITS, |tx, backend| {
214            if backend == crate::Backend::Postgres {
215                sqlx::query(sql(backend, LOCK_DAG))
216                    .bind(&dag_id)
217                    .execute(&mut *tx)
218                    .await?;
219            }
220            sqlx::query(crate::query::sql_text(backend, &delete))
221                .bind(&dag_id)
222                .execute(&mut *tx)
223                .await?
224                .rows_affected()
225        });
226        Ok(deleted)
227    }
228
229    /// Deletes at most `batch` events triggers found and at most `batch` events posted through
230    /// the API before `before` (decision 434), with what triggers passed of the posted ones.
231    /// Gives how many in all.
232    ///
233    /// # Errors
234    ///
235    /// [`DbError`] if a statement fails.
236    pub async fn delete_old_events(&self, before: Timestamp, batch: u32) -> Result<u64, DbError> {
237        const FOUND: &str = "DELETE FROM events WHERE (dag_id, key) IN \
238            (SELECT dag_id, key FROM events WHERE received_at < $1{ts} \
239             ORDER BY received_at LIMIT $2)";
240        // Not one a waiting step was handed: its retry gets the same (Codex's review of M4.14).
241        const POSTED: &str = "SELECT id{text} FROM named_events WHERE posted_at < $1{ts} \
242            AND id{text} NOT IN (SELECT t.handed_run FROM task_instances t \
243                WHERE t.handed_run IS NOT NULL AND t.state NOT IN \
244                ('success', 'failed', 'cancelled', 'skipped', 'upstream_failed')) \
245            ORDER BY posted_at, id LIMIT $2";
246        const PASSED: &str = "DELETE FROM trigger_progress_passed WHERE item = $1";
247        const DELETE: &str = "DELETE FROM named_events WHERE id = $1{uuid}";
248        let before = db_time(before);
249        let deleted = in_tx!(self, BATCH_LIMITS, |tx, backend| {
250            let mut deleted = sqlx::query(sql(backend, FOUND))
251                .bind(&before)
252                .bind(i64::from(batch))
253                .execute(&mut *tx)
254                .await?
255                .rows_affected();
256            let ids: Vec<String> = sqlx::query_scalar(sql(backend, POSTED))
257                .bind(&before)
258                .bind(i64::from(batch))
259                .fetch_all(&mut *tx)
260                .await?;
261            for id in &ids {
262                sqlx::query(sql(backend, PASSED))
263                    .bind(id)
264                    .execute(&mut *tx)
265                    .await?;
266                deleted += sqlx::query(sql(backend, DELETE))
267                    .bind(id)
268                    .execute(&mut *tx)
269                    .await?
270                    .rows_affected();
271            }
272            deleted
273        });
274        Ok(deleted)
275    }
276
277    /// Deletes at most `batch` commands decided (applied or rejected) that were asked for
278    /// before `before`: the audit trail, kept apart from the runs. Gives how many.
279    ///
280    /// # Errors
281    ///
282    /// [`DbError`] if the statement fails.
283    pub async fn delete_old_commands(&self, before: Timestamp, batch: u32) -> Result<u64, DbError> {
284        const DELETE: &str = "DELETE FROM commands WHERE id IN (SELECT id FROM commands \
285            WHERE status <> 'pending' AND requested_at < $1{ts} ORDER BY requested_at LIMIT $2)";
286        let before = db_time(before);
287        let deleted = in_tx!(self, |tx, backend| {
288            sqlx::query(sql(backend, DELETE))
289                .bind(&before)
290                .bind(i64::from(batch))
291                .execute(&mut *tx)
292                .await?
293                .rows_affected()
294        });
295        Ok(deleted)
296    }
297
298    /// Deletes the DAGs removed before `before` that have no run left, with everything kept
299    /// about them (versions, backfills, events, their trigger, wait step strikes): one whose ID
300    /// appears again starts with no history. Gives how many.
301    ///
302    /// # Errors
303    ///
304    /// [`DbError`] if a statement fails.
305    pub async fn delete_removed_dags(&self, before: Timestamp) -> Result<u64, DbError> {
306        const GONE: &str = "SELECT dag_id FROM dags d WHERE removed_at < $1{ts} \
307            AND NOT EXISTS (SELECT 1 FROM runs r WHERE r.dag_id = d.dag_id) \
308            ORDER BY removed_at LIMIT 100";
309        // Taken first, so a DAG defined again meanwhile is left alone: its definition waits
310        // for this transaction, or this one sees it isn't removed any more.
311        const LOCK_POSTGRES: &str = "SELECT dag_id FROM dags WHERE dag_id = $1 \
312            AND removed_at IS NOT NULL FOR UPDATE";
313        const STILL_SQLITE: &str = "SELECT dag_id FROM dags WHERE dag_id = $1 \
314            AND removed_at IS NOT NULL";
315        const RUNS: &str = "SELECT 1 FROM runs WHERE dag_id = $1 LIMIT 1";
316        const DEPENDENTS: [&str; 9] = [
317            "UPDATE dags SET current_version_id = NULL WHERE dag_id = $1",
318            "DELETE FROM backfills WHERE dag_id = $1",
319            "DELETE FROM dag_versions WHERE dag_id = $1",
320            "DELETE FROM events WHERE dag_id = $1",
321            "DELETE FROM trigger_progress WHERE dag_id = $1",
322            "DELETE FROM trigger_progress_passed WHERE dag_id = $1",
323            "DELETE FROM wait_step_strikes WHERE dag_id = $1",
324            "DELETE FROM dag_triggers WHERE dag_id = $1",
325            "DELETE FROM dags WHERE dag_id = $1",
326        ];
327        let before = db_time(before);
328        let gone: Vec<String> = on_pool!(self, |pool, backend| {
329            sqlx::query_scalar(sql(backend, GONE))
330                .bind(&before)
331                .fetch_all(pool)
332                .await?
333        });
334        let mut deleted = 0;
335        for dag_id in &gone {
336            deleted += in_tx!(self, BATCH_LIMITS, |tx, backend| {
337                let lock = match backend {
338                    crate::Backend::Postgres => LOCK_POSTGRES,
339                    crate::Backend::Sqlite => STILL_SQLITE,
340                };
341                let still: Option<String> = sqlx::query_scalar(sql(backend, lock))
342                    .bind(dag_id)
343                    .fetch_optional(&mut *tx)
344                    .await?;
345                let runs: Option<i32> = sqlx::query_scalar(sql(backend, RUNS))
346                    .bind(dag_id)
347                    .fetch_optional(&mut *tx)
348                    .await?;
349                if still.is_none() || runs.is_some() {
350                    0
351                } else {
352                    for statement in DEPENDENTS {
353                        sqlx::query(sql(backend, statement))
354                            .bind(dag_id)
355                            .execute(&mut *tx)
356                            .await?;
357                    }
358                    1
359                }
360            });
361        }
362        Ok(deleted)
363    }
364}