Skip to main content

schedr_db/
task_flow.rs

1//! The Metrics page's throughput and start latency (decision 494), read from the attempts
2//! table: how many attempts ended in each bucket, by how they ended, and how long the ones
3//! started in it took from their assignment to their start (`started_at`, the worker's start
4//! in master time, decision 490), as p50 and p95. Each read is one statement over an index on
5//! the time it buckets by.
6
7use jiff::Timestamp;
8
9use crate::backend::Backend;
10use crate::database::{Database, DbError};
11use crate::query::{db_time, on_pool, sql_text};
12
13#[cfg(test)]
14mod tests;
15
16/// Attempts that ended in a bucket, by their status.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct EndedCount {
19    /// The bucket's start.
20    pub at: Timestamp,
21    /// How the attempts ended (`success`, `failed`, `timed_out`, ...).
22    pub status: String,
23    /// How many.
24    pub count: u64,
25}
26
27/// The start latency of the attempts started in a bucket.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct StartLatency {
30    /// The bucket's start.
31    pub at: Timestamp,
32    /// How many started.
33    pub started: u64,
34    /// The median, in milliseconds.
35    pub p50_ms: u64,
36    /// The 95th percentile, in milliseconds.
37    pub p95_ms: u64,
38}
39
40/// A row's `column` in whole seconds since the epoch, rounded down, on `backend`: a time in a
41/// bucket's last half-second stays in it (Grok's review of M5.1l2: Postgres's cast of the
42/// `numeric` epoch rounded it into the next one, and SQLite's `strftime` rounds at the
43/// millisecond). SQLite reads the stored text's whole seconds, `YYYY-MM-DDTHH:MM:SS`.
44fn epoch(backend: Backend, column: &str) -> String {
45    match backend {
46        Backend::Sqlite => format!("CAST(strftime('%s', substr({column}, 1, 19)) AS INTEGER)"),
47        Backend::Postgres => format!("CAST(FLOOR(EXTRACT(EPOCH FROM {column})) AS BIGINT)"),
48    }
49}
50
51/// How long from `assigned_at` to `started_at`, in whole milliseconds, never below zero (a
52/// worker's master time is read from its clock's samples, decision 447).
53fn latency_ms(backend: Backend) -> &'static str {
54    match backend {
55        Backend::Sqlite => {
56            "MAX(0, CAST(ROUND((julianday(started_at) - julianday(assigned_at)) * 86400000) \
57             AS INTEGER))"
58        }
59        Backend::Postgres => {
60            "GREATEST(0, CAST(ROUND(EXTRACT(EPOCH FROM (started_at - assigned_at)) * 1000) \
61             AS BIGINT))"
62        }
63    }
64}
65
66/// `seconds` since the epoch as a timestamp.
67fn from_epoch(seconds: i64) -> Result<Timestamp, DbError> {
68    Timestamp::from_second(seconds).map_err(|e| DbError::InvalidData {
69        what: "attempts' bucket",
70        reason: e.to_string(),
71    })
72}
73
74/// The attempts ended in `[$1, $2)` by bucket of `$3` seconds and status.
75fn ended_query(backend: Backend) -> String {
76    format!(
77        "SELECT ({e} / $3) * $3 AS bucket, status, COUNT(*) FROM attempts \
78         WHERE ended_at >= $1{{ts}} AND ended_at < $2{{ts}} \
79         GROUP BY bucket, status ORDER BY bucket, status",
80        e = epoch(backend, "ended_at"),
81    )
82}
83
84/// The start latency's p50 and p95 of the attempts started in `[$1, $2)`, by bucket of `$3`
85/// seconds: the nearest rank, the `ceil(n * q)`th of a bucket's `n`, in whole numbers.
86fn latency_query(backend: Backend) -> String {
87    format!(
88        "SELECT bucket, n, \
89         MAX(CASE WHEN k = (n * 50 + 99) / 100 THEN ms END), \
90         MAX(CASE WHEN k = (n * 95 + 99) / 100 THEN ms END) FROM \
91         (SELECT bucket, ms, ROW_NUMBER() OVER (PARTITION BY bucket ORDER BY ms) AS k, \
92          COUNT(*) OVER (PARTITION BY bucket) AS n FROM \
93          (SELECT ({e} / $3) * $3 AS bucket, {ms} AS ms FROM attempts \
94           WHERE started_at >= $1{{ts}} AND started_at < $2{{ts}}) started) ranked \
95         WHERE k = (n * 50 + 99) / 100 OR k = (n * 95 + 99) / 100 \
96         GROUP BY bucket, n ORDER BY bucket",
97        e = epoch(backend, "started_at"),
98        ms = latency_ms(backend),
99    )
100}
101
102impl Database {
103    /// The attempts that ended in `[from, to)`, counted by bucket of `bucket_s` seconds and by
104    /// status, oldest first.
105    ///
106    /// # Errors
107    ///
108    /// [`DbError`] if the query fails.
109    pub async fn attempts_ended(
110        &self,
111        (from, to): (Timestamp, Timestamp),
112        bucket_s: u32,
113    ) -> Result<Vec<EndedCount>, DbError> {
114        let rows: Vec<(i64, String, i64)> = on_pool!(self, |pool, backend| {
115            sqlx::query_as(sql_text(backend, &ended_query(backend)))
116                .bind(db_time(from))
117                .bind(db_time(to))
118                .bind(i64::from(bucket_s.max(1)))
119                .fetch_all(pool)
120                .await?
121        });
122        rows.into_iter()
123            .map(|(bucket, status, count)| {
124                Ok(EndedCount {
125                    at: from_epoch(bucket)?,
126                    status,
127                    count: u64::try_from(count).unwrap_or(0),
128                })
129            })
130            .collect()
131    }
132
133    /// The start latency of the attempts started in `[from, to)`, by bucket of `bucket_s`
134    /// seconds, oldest first: each bucket's p50 and p95 (the nearest rank), exact.
135    ///
136    /// # Errors
137    ///
138    /// [`DbError`] if the query fails.
139    pub async fn start_latency(
140        &self,
141        (from, to): (Timestamp, Timestamp),
142        bucket_s: u32,
143    ) -> Result<Vec<StartLatency>, DbError> {
144        let rows: Vec<(i64, i64, Option<i64>, Option<i64>)> = on_pool!(self, |pool, backend| {
145            sqlx::query_as(sql_text(backend, &latency_query(backend)))
146                .bind(db_time(from))
147                .bind(db_time(to))
148                .bind(i64::from(bucket_s.max(1)))
149                .fetch_all(pool)
150                .await?
151        });
152        let ms = |value: Option<i64>| value.and_then(|v| u64::try_from(v).ok()).unwrap_or(0);
153        rows.into_iter()
154            .map(|(bucket, started, p50, p95)| {
155                Ok(StartLatency {
156                    at: from_epoch(bucket)?,
157                    started: u64::try_from(started).unwrap_or(0),
158                    p50_ms: ms(p50),
159                    p95_ms: ms(p95),
160                })
161            })
162            .collect()
163    }
164}