Skip to main content

schedr_api/
attempt_memory.rs

1//! A task's peak memory over its attempts (M5.1k, decision 467): the task panel's chart of its
2//! last attempts, and the DAG page's p95 peak of each task against its limit.
3#![expect(
4    clippy::missing_errors_doc,
5    reason = "handler docs become OpenAPI descriptions; errors are listed as responses"
6)]
7
8use axum::Json;
9use axum::extract::{Path, State};
10use jiff::{SignedDuration, Timestamp};
11use schedr_db::dags::StoredDag;
12use schedr_db::task_memory::{AttemptPeak, TaskPeaks};
13
14use crate::error::ApiError;
15use crate::routes::{ApiResult, known_dag, parse_dag_id};
16use crate::state::ApiState;
17use crate::views::{AttemptMemoryList, AttemptMemoryView, DagMemoryList, TaskPeakView};
18
19#[cfg(test)]
20mod tests;
21
22/// The attempts the task panel charts.
23pub const CHARTED_ATTEMPTS: u32 = 30;
24
25/// How far back the DAG page's peaks reach.
26pub const PEAKS_OVER: SignedDuration = SignedDuration::from_hours(30 * 24);
27
28/// A task's last ended attempts' peak memory, all its runs and instances (decision 467).
29#[utoipa::path(get, path = "/api/v1/dags/{dag_id}/tasks/{task_id}/memory", tag = "dags",
30    params(("dag_id" = String, Path, description = "The DAG's ID"),
31        ("task_id" = String, Path, description = "The task's ID")),
32    responses((status = 200, body = AttemptMemoryList), (status = 404, body = crate::views::ErrorBody)))]
33pub async fn task_memory(
34    State(state): State<ApiState>,
35    Path((dag_id, task_id)): Path<(String, String)>,
36) -> ApiResult<AttemptMemoryList> {
37    let dag_id = parse_dag_id(&dag_id)?;
38    let dag = known_dag(&state, &dag_id).await?;
39    let attempts = state
40        .db
41        .task_attempt_peaks(
42            dag_id.as_str(),
43            &task_id,
44            CHARTED_ATTEMPTS,
45            state.limits.memory_peaks_runs,
46        )
47        .await?;
48    let defined = limits(&dag)
49        .into_iter()
50        .find(|(id, _)| *id == task_id)
51        .map(|(_, limit)| limit);
52    if defined.is_none() && attempts.is_empty() {
53        return Err(ApiError::NotFound(format!(
54            "no task `{task_id}` in DAG `{dag_id}`"
55        )));
56    }
57    Ok(Json(AttemptMemoryList {
58        task_id,
59        limit_bytes: defined.flatten(),
60        attempts: attempts.into_iter().map(view).collect(),
61    }))
62}
63
64/// Each task's p95 peak memory over its attempts of the last 30 days, against its limit:
65/// closest to it first (decision 467).
66#[utoipa::path(get, path = "/api/v1/dags/{dag_id}/memory", tag = "dags",
67    params(("dag_id" = String, Path, description = "The DAG's ID")),
68    responses((status = 200, body = DagMemoryList), (status = 404, body = crate::views::ErrorBody)))]
69pub async fn dag_memory(
70    State(state): State<ApiState>,
71    Path(dag_id): Path<String>,
72) -> ApiResult<DagMemoryList> {
73    let dag_id = parse_dag_id(&dag_id)?;
74    let dag = known_dag(&state, &dag_id).await?;
75    let since = (state.clock)()
76        .checked_sub(state.limits.memory_peaks_window)
77        .unwrap_or(Timestamp::UNIX_EPOCH);
78    let peaks = state
79        .db
80        .dag_task_peaks(dag_id.as_str(), since, state.limits.memory_peaks_runs)
81        .await?;
82    Ok(Json(DagMemoryList {
83        since,
84        tasks: ranked(peaks, &limits(&dag)),
85    }))
86}
87
88/// Each task of the DAG's current version with its memory budget.
89fn limits(dag: &StoredDag) -> Vec<(String, Option<u64>)> {
90    dag.current
91        .iter()
92        .flat_map(|current| &current.dag.tasks)
93        .map(|task| (task.id.to_string(), task.settings.memory_bytes))
94        .collect()
95}
96
97fn view(peak: AttemptPeak) -> AttemptMemoryView {
98    AttemptMemoryView {
99        attempt_id: peak.attempt_id,
100        run_id: peak.run_id,
101        map_index: peak.map_index,
102        try_number: peak.try_number,
103        status: peak.status,
104        peak_memory_bytes: peak.peak_memory_bytes,
105        ended_at: peak.ended_at,
106    }
107}
108
109/// The tasks' peaks, those with a limit closest to it first, then the rest by p95.
110fn ranked(peaks: Vec<TaskPeaks>, limits: &[(String, Option<u64>)]) -> Vec<TaskPeakView> {
111    let mut tasks: Vec<TaskPeakView> = peaks
112        .into_iter()
113        .filter_map(|mut task| {
114            let p95 = p95(&mut task.peaks)?;
115            let limit_bytes = limits
116                .iter()
117                .find(|(id, _)| *id == task.task_id)
118                .and_then(|(_, limit)| *limit);
119            #[expect(
120                clippy::cast_precision_loss,
121                reason = "a share of a limit: two decimals are shown"
122            )]
123            let of_limit = limit_bytes
124                .filter(|limit| *limit > 0)
125                .map(|limit| p95 as f64 / limit as f64);
126            Some(TaskPeakView {
127                attempts: u32::try_from(task.peaks.len()).unwrap_or(u32::MAX),
128                max_bytes: task.peaks.last().copied().unwrap_or(p95),
129                p95_bytes: p95,
130                oom_killed: task.oom_killed,
131                limit_bytes,
132                of_limit,
133                task_id: task.task_id,
134            })
135        })
136        .collect();
137    tasks.sort_by(|a, b| {
138        match (a.of_limit, b.of_limit) {
139            (Some(x), Some(y)) => y.total_cmp(&x),
140            (Some(_), None) => std::cmp::Ordering::Less,
141            (None, Some(_)) => std::cmp::Ordering::Greater,
142            (None, None) => b.p95_bytes.cmp(&a.p95_bytes),
143        }
144        .then_with(|| a.task_id.cmp(&b.task_id))
145    });
146    tasks
147}
148
149/// The 95th percentile by nearest rank (the smallest value at least 95% of them are at or
150/// below), sorting `peaks`; none of none.
151fn p95(peaks: &mut [u64]) -> Option<u64> {
152    peaks.sort_unstable();
153    let rank = (peaks.len() * 95).div_ceil(100);
154    peaks.get(rank.checked_sub(1)?).copied()
155}