Skip to main content

schedr_db/
samples.rs

1//! Samples of each schedr process (decision 464): one a minute (step 60), and 15-minute
2//! averages and peaks of them (step 900), for the Metrics page's charts.
3
4use std::collections::BTreeMap;
5
6use jiff::Timestamp;
7use schedr_model::usage::{NodeUsage, WorkerParts, WorkerUsage};
8
9use crate::backend::Backend;
10use crate::database::{Database, DbError};
11use crate::query::{db_time, from_json, in_tx, on_pool, parse_time, sql, sql_text, to_json};
12
13#[cfg(test)]
14mod tests;
15
16/// A minute sample's step, in seconds.
17pub const MINUTE: u32 = 60;
18
19/// A rollup's step, in seconds (15 minutes).
20pub const ROLLUP: u32 = 900;
21
22/// The rows one insert writes at most: 22 parameters each, under both databases' limits.
23const ROWS_PER_INSERT: usize = 500;
24
25/// A process's sample, as stored.
26#[derive(Debug, Clone, PartialEq)]
27pub struct Sample {
28    /// The process.
29    pub process_id: String,
30    /// [`MINUTE`] or [`ROLLUP`].
31    pub step_s: u32,
32    /// Its minute, or its window's start.
33    pub at: Timestamp,
34    /// What it runs (`master`, `worker`, `webserver`), each with its node's ID.
35    pub roles: BTreeMap<String, String>,
36    /// Resident memory, in bytes: the minute's, or the window's average.
37    pub resident_avg: u64,
38    /// The highest (a minute's: the same).
39    pub resident_peak: u64,
40    /// Its whole memory, in bytes: itself and, for a worker, its fork servers, wait step hosts
41    /// and running tasks; the minute's, or the window's average.
42    pub memory_avg: u64,
43    /// The highest.
44    pub memory_peak: u64,
45    /// The minutes it covers: 1, or a rollup's minute samples (its averages' weight).
46    pub minutes: u32,
47    /// Of those, the ones with a CPU figure (the CPU average's weight).
48    pub cpu_minutes: u32,
49    /// Of those, the ones with a container figure (the container average's weight).
50    pub container_minutes: u32,
51    /// The minutes of its window in which any process was sampled: 1 for a minute.
52    pub covered: u32,
53    /// CPU time since the process started, in seconds (minute samples).
54    pub cpu_seconds: Option<f64>,
55    /// Cores used since the sample before, or the window's average; none for its first.
56    pub cpu_avg: Option<f64>,
57    /// The highest minute's.
58    pub cpu_peak: Option<f64>,
59    /// Its container's memory, average; none outside a cgroup v2.
60    pub container_avg: Option<u64>,
61    /// The highest.
62    pub container_peak: Option<u64>,
63    /// Its container's limit; none when unlimited.
64    pub container_limit: Option<u64>,
65    /// A worker's memory by part and its largest tasks (a rollup: the parts' averages only).
66    pub parts: Option<WorkerParts>,
67}
68
69/// What the leader samples a process from: a master's or a worker's stored usage.
70#[derive(Debug, Clone, PartialEq)]
71pub struct Source {
72    /// Its process.
73    pub process_id: String,
74    /// `master` or `worker`.
75    pub role: &'static str,
76    /// The master's or the worker's ID.
77    pub node_id: String,
78    /// Its process's figures.
79    pub usage: NodeUsage,
80    /// A worker's parts.
81    pub parts: Option<WorkerParts>,
82    /// When the figures were stored: a master's row heard, a worker's usage written.
83    pub at: Timestamp,
84}
85
86/// The largest byte count stored (4 PiB): a report beyond it is capped, so that the weighted
87/// sums in SQL stay in range (Codex's review of M5.1j).
88const MOST_BYTES: u64 = 1 << 52;
89
90fn int(value: u64) -> i64 {
91    i64::try_from(value.min(MOST_BYTES)).unwrap_or(i64::MAX)
92}
93
94fn unsigned(value: i64) -> u64 {
95    u64::try_from(value).unwrap_or(0)
96}
97
98#[derive(sqlx::FromRow)]
99struct Row {
100    process_id: String,
101    step_s: i64,
102    at: String,
103    roles: String,
104    resident_avg: i64,
105    resident_peak: i64,
106    memory_avg: i64,
107    memory_peak: i64,
108    minutes: i64,
109    cpu_minutes: i64,
110    container_minutes: i64,
111    covered: i64,
112    cpu_seconds: Option<f64>,
113    cpu_avg: Option<f64>,
114    cpu_peak: Option<f64>,
115    container_avg: Option<i64>,
116    container_peak: Option<i64>,
117    container_limit: Option<i64>,
118    parts: Option<String>,
119}
120
121fn sample(row: Row) -> Result<Sample, DbError> {
122    let count = |n: i64| u32::try_from(n).unwrap_or(0);
123    Ok(Sample {
124        process_id: row.process_id,
125        step_s: count(row.step_s),
126        at: parse_time("samples.at", &row.at)?,
127        roles: from_json("samples.roles", &row.roles)?,
128        resident_avg: unsigned(row.resident_avg),
129        resident_peak: unsigned(row.resident_peak),
130        memory_avg: unsigned(row.memory_avg),
131        memory_peak: unsigned(row.memory_peak),
132        minutes: count(row.minutes),
133        cpu_minutes: count(row.cpu_minutes),
134        container_minutes: count(row.container_minutes),
135        covered: count(row.covered),
136        cpu_seconds: row.cpu_seconds,
137        cpu_avg: row.cpu_avg,
138        cpu_peak: row.cpu_peak,
139        container_avg: row.container_avg.map(unsigned),
140        container_peak: row.container_peak.map(unsigned),
141        container_limit: row.container_limit.map(unsigned),
142        parts: row
143            .parts
144            .map(|parts| from_json("samples.parts", &parts))
145            .transpose()?,
146    })
147}
148
149impl Database {
150    /// What the leader samples (decision 464): the masters heard from since `masters_since`
151    /// and the active or draining workers heard from since `workers_since`, each with the
152    /// usage it last stored; none without one.
153    ///
154    /// # Errors
155    ///
156    /// [`DbError`] if a query fails or stored data doesn't read.
157    pub async fn sample_sources(
158        &self,
159        masters_since: Timestamp,
160        workers_since: Timestamp,
161    ) -> Result<Vec<Source>, DbError> {
162        const MASTERS: &str = "SELECT process_id, master_id, usage{text}, \
163            {ts<}heard_at{>ts} FROM masters \
164            WHERE heard_at >= $1{ts} AND usage IS NOT NULL ORDER BY master_id";
165        const WORKERS: &str = "SELECT process_id, worker_id, usage{text}, \
166            {ts<}usage_at{>ts} FROM workers \
167            WHERE state IN ('active', 'draining') AND last_heartbeat_at >= $1{ts} \
168            AND usage IS NOT NULL AND usage_at IS NOT NULL AND process_id IS NOT NULL \
169            ORDER BY worker_id";
170        type Row = (String, String, String, String);
171        let masters: Vec<Row> = on_pool!(self, |pool, backend| {
172            sqlx::query_as(sql(backend, MASTERS))
173                .bind(db_time(masters_since))
174                .fetch_all(pool)
175                .await?
176        });
177        let workers: Vec<Row> = on_pool!(self, |pool, backend| {
178            sqlx::query_as(sql(backend, WORKERS))
179                .bind(db_time(workers_since))
180                .fetch_all(pool)
181                .await?
182        });
183        let mut sources = Vec::with_capacity(masters.len() + workers.len());
184        for (process_id, node_id, usage, at) in masters {
185            sources.push(Source {
186                process_id,
187                role: "master",
188                node_id,
189                usage: from_json("masters.usage", &usage)?,
190                parts: None,
191                at: parse_time("masters.heard_at", &at)?,
192            });
193        }
194        for (process_id, node_id, usage, at) in workers {
195            let usage: WorkerUsage = from_json("workers.usage", &usage)?;
196            sources.push(Source {
197                process_id,
198                role: "worker",
199                node_id,
200                parts: Some(usage.parts()),
201                usage: usage.process,
202                at: parse_time("workers.usage_at", &at)?,
203            });
204        }
205        Ok(sources)
206    }
207
208    /// Stores `samples`; one already stored for its process, step and time is kept.
209    ///
210    /// # Errors
211    ///
212    /// [`DbError::Sqlx`] if a statement fails.
213    pub async fn insert_samples(&self, samples: &[Sample]) -> Result<(), DbError> {
214        if samples.is_empty() {
215            return Ok(());
216        }
217        // Every chunk in one transaction: a rollup is written whole or not at all (Codex's
218        // review of M5.1j: a chunk failing after another committed moved the rollups' end past
219        // the processes it left out).
220        let queries: Vec<(String, &[Sample])> = samples
221            .chunks(ROWS_PER_INSERT)
222            .map(|chunk| (insert_query(chunk.len()), chunk))
223            .collect();
224        in_tx!(self, |tx, backend| {
225            for (query, chunk) in &queries {
226                let text = sql_text(backend, query);
227                let mut insert = sqlx::query(text);
228                for sample in *chunk {
229                    insert = insert
230                        .bind(sample.process_id.clone())
231                        .bind(i64::from(sample.step_s))
232                        .bind(db_time(sample.at))
233                        .bind(to_json(&sample.roles))
234                        .bind(int(sample.resident_avg))
235                        .bind(int(sample.resident_peak))
236                        .bind(int(sample.memory_avg))
237                        .bind(int(sample.memory_peak))
238                        .bind(i64::from(sample.minutes))
239                        .bind(i64::from(sample.cpu_minutes))
240                        .bind(i64::from(sample.container_minutes))
241                        .bind(i64::from(sample.covered))
242                        .bind(sample.cpu_seconds)
243                        .bind(sample.cpu_avg)
244                        .bind(sample.cpu_peak)
245                        .bind(sample.container_avg.map(int))
246                        .bind(sample.container_peak.map(int))
247                        .bind(sample.container_limit.map(int))
248                        .bind(sample.parts.as_ref().map(to_json))
249                        .bind(sample.parts.as_ref().map(|p| int(p.fork_servers_bytes)))
250                        .bind(sample.parts.as_ref().map(|p| int(p.watcher_hosts_bytes)))
251                        .bind(sample.parts.as_ref().map(|p| int(p.tasks_bytes)));
252                }
253                insert.execute(&mut *tx).await?;
254            }
255        });
256        Ok(())
257    }
258
259    /// The oldest minute sample's time; none without one.
260    ///
261    /// # Errors
262    ///
263    /// [`DbError`] if the query fails or the time doesn't read.
264    pub async fn oldest_minute_sample(&self) -> Result<Option<Timestamp>, DbError> {
265        const OLDEST: &str = "SELECT {ts<}MIN(at){>ts} FROM samples WHERE step_s = $1";
266        let oldest: Option<String> = on_pool!(self, |pool, backend| {
267            sqlx::query_scalar(sql(backend, OLDEST))
268                .bind(i64::from(MINUTE))
269                .fetch_one(pool)
270                .await?
271        });
272        oldest.map(|at| parse_time("samples.at", &at)).transpose()
273    }
274
275    /// Deletes the samples of step `step_s` older than `before`; how many.
276    ///
277    /// # Errors
278    ///
279    /// [`DbError::Sqlx`] if the statement fails.
280    pub async fn delete_old_samples(&self, step_s: u32, before: Timestamp) -> Result<u64, DbError> {
281        const DELETE: &str = "DELETE FROM samples WHERE step_s = $1 AND at < $2{ts}";
282        let deleted = in_tx!(self, |tx, backend| {
283            sqlx::query(sql(backend, DELETE))
284                .bind(i64::from(step_s))
285                .bind(db_time(before))
286                .execute(&mut *tx)
287                .await?
288                .rows_affected()
289        });
290        Ok(deleted)
291    }
292
293    /// The samples of step `step_s` in `[from, to)`, by process, then time.
294    ///
295    /// # Errors
296    ///
297    /// [`DbError`] if the query fails or a row doesn't read.
298    pub async fn samples(
299        &self,
300        step_s: u32,
301        from: Timestamp,
302        to: Timestamp,
303    ) -> Result<Vec<Sample>, DbError> {
304        self.samples_of(step_s, from, to, None).await
305    }
306
307    /// As [`Self::samples`], of one process only when `process` names it.
308    ///
309    /// # Errors
310    ///
311    /// [`DbError`] if the query fails or a row doesn't read.
312    pub async fn samples_of(
313        &self,
314        step_s: u32,
315        from: Timestamp,
316        to: Timestamp,
317        process: Option<&str>,
318    ) -> Result<Vec<Sample>, DbError> {
319        const SAMPLES: &str = "SELECT process_id, CAST(step_s AS BIGINT) AS step_s, \
320            {ts<}at{>ts} AS at, roles, resident_avg, resident_peak, memory_avg, memory_peak, \
321            CAST(minutes AS BIGINT) AS minutes, CAST(cpu_minutes AS BIGINT) AS cpu_minutes, \
322            CAST(container_minutes AS BIGINT) AS container_minutes, \
323            CAST(covered AS BIGINT) AS covered, cpu_seconds, cpu_avg, cpu_peak, container_avg, \
324            container_peak, container_limit, parts{text} AS parts FROM samples \
325            WHERE step_s = $1 AND at >= $2{ts} AND at < $3{ts} \
326            AND ($4{text} IS NULL OR process_id = $4{text}) ORDER BY process_id, at";
327        let rows: Vec<Row> = on_pool!(self, |pool, backend| {
328            sqlx::query_as(sql(backend, SAMPLES))
329                .bind(i64::from(step_s))
330                .bind(db_time(from))
331                .bind(db_time(to))
332                .bind(process)
333                .fetch_all(pool)
334                .await?
335        });
336        rows.into_iter().map(sample).collect()
337    }
338
339    /// Each process's samples in `[from, to)` in buckets of `bucket_s` seconds (M5.1j): the
340    /// rollups before `cut`, the minutes from it (those not rolled up yet; `cut` = `from` for
341    /// minutes only), of one process when `process` names it. Averages are weighted by the
342    /// minutes each row covers; peaks are the highest; the limit the highest in the bucket.
343    ///
344    /// # Errors
345    ///
346    /// [`DbError`] if the query fails or a row doesn't read.
347    pub async fn sample_buckets(
348        &self,
349        (from, cut, to): (Timestamp, Timestamp, Timestamp),
350        bucket_s: u32,
351        process: Option<&str>,
352    ) -> Result<Vec<Bucket>, DbError> {
353        type BucketRow = (
354            String,
355            i64,
356            i64,
357            i64,
358            i64,
359            i64,
360            i64,
361            Option<f64>,
362            Option<f64>,
363            Option<i64>,
364            Option<i64>,
365            Option<i64>,
366            Option<i64>,
367            Option<i64>,
368            Option<i64>,
369            i64,
370        );
371        let rows: Vec<BucketRow> = on_pool!(self, |pool, backend| {
372            sqlx::query_as(sql_text(backend, &bucket_query(backend)))
373                .bind(db_time(from))
374                .bind(db_time(within(from, cut, to)))
375                .bind(db_time(to))
376                .bind(i64::from(bucket_s.max(1)))
377                .bind(process)
378                .fetch_all(pool)
379                .await?
380        });
381        rows.into_iter()
382            .map(|row| {
383                Ok(Bucket {
384                    process_id: row.0,
385                    at: from_epoch(row.1)?,
386                    minutes: u32::try_from(row.2).unwrap_or(0),
387                    resident_avg: unsigned(row.3),
388                    resident_peak: unsigned(row.4),
389                    memory_avg: unsigned(row.5),
390                    memory_peak: unsigned(row.6),
391                    cpu_avg: row.7,
392                    cpu_peak: row.8,
393                    container_avg: row.9.map(unsigned),
394                    container_peak: row.10.map(unsigned),
395                    container_limit: row.11.map(unsigned),
396                    parts: row
397                        .12
398                        .zip(row.13)
399                        .zip(row.14)
400                        .map(|((forks, hosts), tasks)| {
401                            (unsigned(forks), unsigned(hosts), unsigned(tasks))
402                        }),
403                    covered: u32::try_from(row.15).unwrap_or(0),
404                })
405            })
406            .collect()
407    }
408
409    /// Each process sampled in `[from, to)` as its latest sample there says: its roles and its
410    /// container's limit (none: unlimited).
411    ///
412    /// # Errors
413    ///
414    /// [`DbError`] if the query fails or a row doesn't read.
415    pub async fn latest_of(
416        &self,
417        from: Timestamp,
418        to: Timestamp,
419        process: Option<&str>,
420    ) -> Result<BTreeMap<String, Latest>, DbError> {
421        // The steps named, so that each side reads an index: the range by `samples_by_time`,
422        // each latest row by the primary key; `CROSS JOIN` keeps that order on SQLite (its
423        // planner otherwise read every row of each process: 150 ms for a few minutes of 100).
424        const LATEST: &str = "SELECT s.process_id, s.roles, s.container_limit, \
425            CAST(s.step_s AS BIGINT), {ts<}s.at{>ts} FROM \
426            (SELECT process_id, MAX(at) AS last FROM samples \
427             WHERE step_s IN (60, 900) AND at >= $1{ts} AND at < $2{ts} \
428             AND ($3{text} IS NULL OR process_id = $3{text}) GROUP BY process_id) l \
429            CROSS JOIN samples s \
430            WHERE s.process_id = l.process_id AND s.step_s IN (60, 900) AND s.at = l.last";
431        let rows: Vec<(String, String, Option<i64>, i64, String)> =
432            on_pool!(self, |pool, backend| {
433                sqlx::query_as(sql(backend, LATEST))
434                    .bind(db_time(from))
435                    .bind(db_time(to))
436                    .bind(process)
437                    .fetch_all(pool)
438                    .await?
439            });
440        let mut latest = BTreeMap::new();
441        // A minute and a rollup at the same time: the minute is the later.
442        for (process_id, roles, limit, step, at) in rows {
443            if step == i64::from(ROLLUP) && latest.contains_key(&process_id) {
444                continue;
445            }
446            latest.insert(
447                process_id,
448                Latest {
449                    at: parse_time("samples.at", &at)?,
450                    roles: from_json("samples.roles", &roles)?,
451                    container_limit: limit.map(unsigned),
452                },
453            );
454        }
455        Ok(latest)
456    }
457
458    /// The end of the newest rollup's window; none without one.
459    ///
460    /// # Errors
461    ///
462    /// [`DbError`] if the query fails or the time doesn't read.
463    pub async fn rolled_up_to(&self) -> Result<Option<Timestamp>, DbError> {
464        const NEWEST: &str = "SELECT {ts<}MAX(at){>ts} FROM samples WHERE step_s = $1";
465        let newest: Option<String> = on_pool!(self, |pool, backend| {
466            sqlx::query_scalar(sql(backend, NEWEST))
467                .bind(i64::from(ROLLUP))
468                .fetch_one(pool)
469                .await?
470        });
471        newest
472            .map(|at| {
473                let at = parse_time("samples.at", &at)?;
474                Ok(at
475                    .checked_add(jiff::SignedDuration::from_secs(i64::from(ROLLUP)))
476                    .unwrap_or(at))
477            })
478            .transpose()
479    }
480
481    /// Every process's whole memory together in buckets of `bucket_s` seconds over `[from,
482    /// to)`, rollups before `cut` and minutes from it (the Deployments page's sparkline,
483    /// M5.1j), oldest first: each process's memory weighted by the minutes it was sampled, over
484    /// the minutes the deployment was sampled in the bucket, so a process replaced within a
485    /// bucket isn't counted twice.
486    ///
487    /// # Errors
488    ///
489    /// [`DbError`] if the query fails or a time doesn't read.
490    pub async fn memory_totals(
491        &self,
492        (from, cut, to): (Timestamp, Timestamp, Timestamp),
493        bucket_s: u32,
494    ) -> Result<Vec<(Timestamp, u64)>, DbError> {
495        let rows: Vec<(i64, i64)> = on_pool!(self, |pool, backend| {
496            sqlx::query_as(sql_text(backend, &totals_query(backend)))
497                .bind(db_time(from))
498                .bind(db_time(within(from, cut, to)))
499                .bind(db_time(to))
500                .bind(i64::from(bucket_s.max(1)))
501                .fetch_all(pool)
502                .await?
503        });
504        rows.into_iter()
505            .map(|(at, total)| Ok((from_epoch(at)?, unsigned(total))))
506            .collect()
507    }
508}
509
510/// A process's samples in a bucket (see [`Database::sample_buckets`]).
511#[derive(Debug, Clone, PartialEq)]
512pub struct Bucket {
513    /// The process.
514    pub process_id: String,
515    /// The bucket's start.
516    pub at: Timestamp,
517    /// The minutes sampled in it.
518    pub minutes: u32,
519    /// Resident memory, the minutes' average.
520    pub resident_avg: u64,
521    /// The highest.
522    pub resident_peak: u64,
523    /// Whole memory, the minutes' average.
524    pub memory_avg: u64,
525    /// The highest.
526    pub memory_peak: u64,
527    /// Cores, the average over the minutes that have one.
528    pub cpu_avg: Option<f64>,
529    /// The highest.
530    pub cpu_peak: Option<f64>,
531    /// Its container's memory, the average over the minutes that have one.
532    pub container_avg: Option<u64>,
533    /// The highest.
534    pub container_peak: Option<u64>,
535    /// Its container's highest limit in the bucket.
536    pub container_limit: Option<u64>,
537    /// A worker's fork servers', wait step hosts' and tasks' averages over all the bucket's
538    /// minutes (0 where it ran no worker); none when it ran none in the bucket.
539    pub parts: Option<(u64, u64, u64)>,
540    /// The minutes the deployment (any process) was sampled in the bucket, read with it: a
541    /// total's denominator.
542    pub covered: u32,
543}
544
545/// An insert of `rows` samples, the ones already stored kept.
546fn insert_query(rows: usize) -> String {
547    let mut query = String::from(
548        "INSERT INTO samples (process_id, step_s, at, roles, resident_avg, resident_peak, \
549         memory_avg, memory_peak, minutes, cpu_minutes, container_minutes, covered, cpu_seconds, \
550         cpu_avg, cpu_peak, container_avg, container_peak, container_limit, parts, forks_avg, \
551         hosts_avg, tasks_avg) VALUES ",
552    );
553    for row in 0..rows {
554        let n = row * 22;
555        if row > 0 {
556            query.push_str(", ");
557        }
558        // Each row's 22 parameters, the time and the parts cast for Postgres.
559        let cell = |k: usize| match k {
560            3 => format!("${}{{ts}}", n + k),
561            19 => format!("${}{{json}}", n + k),
562            _ => format!("${}", n + k),
563        };
564        query.push('(');
565        query.push_str(&(1..=22).map(cell).collect::<Vec<_>>().join(", "));
566        query.push(')');
567    }
568    query.push_str(" ON CONFLICT (process_id, step_s, at) DO NOTHING");
569    query
570}
571
572/// A process as its latest sample says (see [`Database::latest_of`]).
573#[derive(Debug, Clone, PartialEq, Eq)]
574pub struct Latest {
575    /// The sample's time.
576    pub at: Timestamp,
577    /// What it runs, each role with its node's ID.
578    pub roles: BTreeMap<String, String>,
579    /// Its container's limit; none when unlimited.
580    pub container_limit: Option<u64>,
581}
582
583/// A bucket's time read back.
584fn from_epoch(seconds: i64) -> Result<Timestamp, DbError> {
585    Timestamp::from_second(seconds).map_err(|e| DbError::InvalidData {
586        what: "samples.at",
587        reason: e.to_string(),
588    })
589}
590
591/// A row's time in seconds since the epoch, on `backend`.
592const fn epoch(backend: Backend) -> &'static str {
593    match backend {
594        Backend::Sqlite => "CAST(strftime('%s', at) AS INTEGER)",
595        Backend::Postgres => "CAST(EXTRACT(EPOCH FROM at) AS BIGINT)",
596    }
597}
598
599/// The rows of `[from, to)` (`$1`, `$3`): rollups before `$2`, minutes from it; `$2` within
600/// them ([`within`]), so that each side reads only its own rows of `samples_by_time` (a cut a
601/// day before the start had SQLite read a day of minutes for a few).
602const RANGE: &str = "((step_s = 900 AND at >= $1{ts} AND at < $2{ts}) \
603    OR (step_s = 60 AND at >= $2{ts} AND at < $3{ts}))";
604
605/// `cut` within `[from, to]`.
606fn within(from: Timestamp, cut: Timestamp, to: Timestamp) -> Timestamp {
607    cut.max(from).min(to.max(from))
608}
609
610/// `expr` rounded half away from zero on both backends (Postgres rounds a `double precision`
611/// half to even; through `NUMERIC` it doesn't).
612fn round(backend: Backend, expr: &str) -> String {
613    match backend {
614        Backend::Sqlite => format!("ROUND({expr})"),
615        Backend::Postgres => format!("ROUND(CAST({expr} AS NUMERIC))"),
616    }
617}
618
619/// `x` weighted by `weight`, summed in floating point (no overflow).
620fn weighted(x: &str, weight: &str) -> String {
621    format!("SUM(CAST({x} AS DOUBLE PRECISION) * {weight})")
622}
623
624/// [`Database::sample_buckets`]'s query on `backend`.
625fn bucket_query(backend: Backend) -> String {
626    // An average of `x` weighted by `weight`, rounded; none without a weight.
627    let avg = |x: &str, weight: &str| {
628        format!(
629            "CAST({} AS BIGINT)",
630            round(
631                backend,
632                &format!("{} / NULLIF(SUM({weight}), 0)", weighted(x, weight))
633            )
634        )
635    };
636    // A part's average over all the minutes, 0 where the process ran no worker.
637    let part = |x: &str| {
638        format!(
639            "CASE WHEN COUNT({x}) = 0 THEN NULL ELSE CAST({} AS BIGINT) END",
640            round(
641                backend,
642                &format!(
643                    "{} / SUM(minutes)",
644                    weighted(&format!("COALESCE({x}, 0)"), "minutes")
645                )
646            )
647        )
648    };
649    // With the deployment's coverage of each bucket, in the same statement: one snapshot, so
650    // that a sample stored meanwhile doesn't count in one and not the other (Codex's review of
651    // M5.1j).
652    format!(
653        "SELECT p.*, CAST(c.sampled AS BIGINT) FROM \
654         (SELECT process_id, ({e} / $4) * $4 AS bucket, CAST(SUM(minutes) AS BIGINT) AS m, \
655          {res} AS r, MAX(resident_peak) AS rp, {mem} AS mm, MAX(memory_peak) AS mp, \
656          {cpu} / NULLIF(SUM(cpu_minutes), 0) AS ca, MAX(cpu_peak) AS cp, {cont} AS ka, \
657          MAX(container_peak) AS kp, MAX(container_limit) AS kl, {forks} AS fa, {hosts} AS ha, \
658          {tasks} AS ta FROM samples WHERE {RANGE} \
659          AND ($5{{text}} IS NULL OR process_id = $5{{text}}) GROUP BY process_id, bucket) p \
660         JOIN ({c}) c ON c.bucket = p.bucket ORDER BY p.process_id, p.bucket",
661        c = coverage_rows(backend),
662        e = epoch(backend),
663        res = avg("resident_avg", "minutes"),
664        mem = avg("memory_avg", "minutes"),
665        cpu = weighted("cpu_avg", "cpu_minutes"),
666        cont = avg("container_avg", "container_minutes"),
667        forks = part("forks_avg"),
668        hosts = part("hosts_avg"),
669        tasks = part("tasks_avg"),
670    )
671}
672
673/// The minutes sampled in each bucket: each window's (or minute's) coverage once, summed.
674fn coverage_rows(backend: Backend) -> String {
675    format!(
676        "SELECT bucket, SUM(covered) AS sampled FROM \
677         (SELECT ({e} / $4) * $4 AS bucket, at, MAX(covered) AS covered FROM samples \
678          WHERE {RANGE} GROUP BY bucket, at) w GROUP BY bucket",
679        e = epoch(backend),
680    )
681}
682
683/// [`Database::memory_totals`]'s query on `backend`.
684fn totals_query(backend: Backend) -> String {
685    format!(
686        "SELECT m.bucket, CAST({r} AS BIGINT) FROM \
687         (SELECT ({e} / $4) * $4 AS bucket, {w} AS weighted FROM samples WHERE {RANGE} \
688          GROUP BY bucket) m JOIN ({c}) c ON c.bucket = m.bucket ORDER BY m.bucket",
689        e = epoch(backend),
690        w = weighted("memory_avg", "minutes"),
691        c = coverage_rows(backend),
692        r = round(backend, "m.weighted / NULLIF(c.sampled, 0)"),
693    )
694}