1use 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
12pub const PEAKS_PER_TASK: u32 = 1000;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct AttemptPeak {
19 pub attempt_id: String,
21 pub run_id: String,
23 pub map_index: Option<u32>,
25 pub try_number: u32,
27 pub status: String,
29 pub peak_memory_bytes: Option<u64>,
31 pub ended_at: Timestamp,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct TaskPeaks {
38 pub task_id: String,
40 pub peaks: Vec<u64>,
42 pub oom_killed: u32,
44}
45
46impl Database {
47 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 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 pub async fn dag_task_peaks(
113 &self,
114 dag_id: &str,
115 since: Timestamp,
116 runs: u32,
117 ) -> Result<Vec<TaskPeaks>, DbError> {
118 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}