Skip to main content

schedr_db/
task_memory.rs

1//! A task's peak memory over its attempts (decision 467): the task panel's chart of its last
2//! attempts and the DAG page's p95 peaks, read from the attempts table.
3
4use jiff::Timestamp;
5
6use crate::database::{Database, DbError};
7use crate::query::{db_time, on_pool, parse_time, sql};
8
9#[cfg(test)]
10mod tests;
11
12/// The runs, and the attempts of one task, its peaks are taken from at most, the newest (the
13/// p95 of each).
14pub const PEAKS_PER_TASK: u32 = 1000;
15
16/// An ended attempt's peak memory.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct AttemptPeak {
19    /// The attempt.
20    pub attempt_id: String,
21    /// Its run.
22    pub run_id: String,
23    /// Its instance of a mapped task; none for a task that isn't mapped.
24    pub map_index: Option<u32>,
25    /// Its try.
26    pub try_number: u32,
27    /// How it ended (`success`, `oom_killed`, ...).
28    pub status: String,
29    /// Its peak memory, in bytes; none when it wasn't read (an attempt lost with its worker).
30    pub peak_memory_bytes: Option<u64>,
31    /// When it ended.
32    pub ended_at: Timestamp,
33}
34
35/// Each task's ended attempts' peaks, for its p95.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct TaskPeaks {
38    /// The task.
39    pub task_id: String,
40    /// The peaks read, at most the runs asked for, in no order.
41    pub peaks: Vec<u64>,
42    /// Of those attempts, how many were killed for their memory.
43    pub oom_killed: u32,
44}
45
46impl Database {
47    /// The last `count` attempts of `task_id` of DAG `dag_id` to end, all its instances, the
48    /// oldest first: of its `runs` ended last (`SCHEDR_HIDDEN__WEBSERVER__MEMORY_PEAKS_RUNS`,
49    /// [`PEAKS_PER_TASK`] by default) and those still going.
50    ///
51    /// # Errors
52    ///
53    /// [`DbError`] if the query fails or a row doesn't read.
54    pub async fn task_attempt_peaks(
55        &self,
56        dag_id: &str,
57        task_id: &str,
58        count: u32,
59        runs: u32,
60    ) -> Result<Vec<AttemptPeak>, DbError> {
61        // Codex's review of M5.1k: the last to end, whatever their runs' order. An attempt ends
62        // before its run, so it is among the runs ended since or still going: the DAG's
63        // newest-ended runs (`runs_ended`) and its unfinished ones (`runs_unfinished`), each
64        // run's instance of the task by its unique key, its attempts by theirs.
65        const LAST: &str = "SELECT a.id{text}, r.id{text}, CAST(i.map_index AS BIGINT), \
66            CAST(a.try_number AS BIGINT), a.status, a.peak_memory_bytes, {ts<}a.ended_at{>ts} \
67            FROM (SELECT id FROM (SELECT id FROM runs WHERE dag_id = $1 AND ended_at IS NOT NULL \
68                  ORDER BY ended_at DESC LIMIT $4) ended \
69                  UNION ALL SELECT id FROM runs WHERE dag_id = $1 \
70                  AND state IN ('queued', 'running')) r \
71            JOIN task_instances i ON i.run_id = r.id AND i.task_id = $2 \
72            JOIN attempts a ON a.task_instance_id = i.id \
73            WHERE a.ended_at IS NOT NULL AND a.status IS NOT NULL \
74            ORDER BY a.ended_at DESC, a.id DESC LIMIT $3";
75        type Row = (String, String, i64, i64, String, Option<i64>, String);
76        let rows: Vec<Row> = on_pool!(self, |pool, backend| {
77            sqlx::query_as(sql(backend, LAST))
78                .bind(dag_id)
79                .bind(task_id)
80                .bind(i64::from(count))
81                .bind(i64::from(runs))
82                .fetch_all(pool)
83                .await?
84        });
85        let mut peaks = rows
86            .into_iter()
87            .map(
88                |(attempt_id, run_id, map_index, try_number, status, peak, ended)| {
89                    Ok(AttemptPeak {
90                        attempt_id,
91                        run_id,
92                        map_index: u32::try_from(map_index).ok(),
93                        try_number: u32::try_from(try_number).unwrap_or(0),
94                        status,
95                        peak_memory_bytes: peak.and_then(|p| u64::try_from(p).ok()),
96                        ended_at: parse_time("attempts.ended_at", &ended)?,
97                    })
98                },
99            )
100            .collect::<Result<Vec<_>, DbError>>()?;
101        peaks.reverse();
102        Ok(peaks)
103    }
104
105    /// Each task of DAG `dag_id` with attempts ended since `since`, of its `runs` runs ended
106    /// last since then and those still going: the peaks of its newest `runs` that have one, by
107    /// task.
108    ///
109    /// # Errors
110    ///
111    /// [`DbError`] if the query fails.
112    pub async fn dag_task_peaks(
113        &self,
114        dag_id: &str,
115        since: Timestamp,
116        runs: u32,
117    ) -> Result<Vec<TaskPeaks>, DbError> {
118        // The runs ended since, newest first (`runs_ended`), and those still going
119        // (`runs_unfinished`): a DAG running every minute reads a thousand runs, not 30 days of
120        // them (216,000 attempts of 5 tasks: 850 ms), and a backfill of old moments ending now
121        // counts (Codex's review of M5.1k).
122        const PEAKS: &str = "SELECT task_id, peak, oom FROM (\
123            SELECT i.task_id AS task_id, a.peak_memory_bytes AS peak, \
124            CASE WHEN a.status = 'oom_killed' THEN 1 ELSE 0 END AS oom, \
125            ROW_NUMBER() OVER (PARTITION BY i.task_id ORDER BY a.ended_at DESC, a.id DESC) AS n \
126            FROM (SELECT id FROM (SELECT id FROM runs WHERE dag_id = $1 AND ended_at >= $2{ts} \
127                  ORDER BY ended_at DESC LIMIT $3) ended \
128                  UNION ALL SELECT id FROM runs WHERE dag_id = $1 \
129                  AND state IN ('queued', 'running')) r \
130            JOIN task_instances i ON i.run_id = r.id \
131            JOIN attempts a ON a.task_instance_id = i.id \
132            WHERE a.ended_at >= $2{ts} AND a.peak_memory_bytes IS NOT NULL\
133            ) newest WHERE n <= $3 ORDER BY task_id";
134        let rows: Vec<(String, i64, i32)> = on_pool!(self, |pool, backend| {
135            sqlx::query_as(sql(backend, PEAKS))
136                .bind(dag_id)
137                .bind(db_time(since))
138                .bind(i64::from(runs))
139                .fetch_all(pool)
140                .await?
141        });
142        let mut tasks: Vec<TaskPeaks> = Vec::new();
143        for (task_id, peak, oom) in rows {
144            if tasks.last().is_none_or(|t| t.task_id != task_id) {
145                tasks.push(TaskPeaks {
146                    task_id,
147                    peaks: Vec::new(),
148                    oom_killed: 0,
149                });
150            }
151            if let Some(task) = tasks.last_mut() {
152                task.peaks.push(u64::try_from(peak).unwrap_or(0));
153                task.oom_killed += u32::from(oom != 0);
154            }
155        }
156        Ok(tasks)
157    }
158}