Skip to main content

schedr_master/
samples.rs

1//! A sample of each schedr process a minute (decision 464): the leading master writes its
2//! masters' and workers' (one row per process, however many roles it runs: a standalone is one),
3//! rolls each closed 15-minute window up into averages and peaks, and deletes minute rows past
4//! a day and rollups past 30 days. A webserver in a process of its own writes its own.
5
6use std::collections::{BTreeMap, HashMap};
7use std::time::Duration;
8
9use jiff::{SignedDuration, Timestamp};
10use schedr_db::database::{Database, DbError};
11use schedr_db::samples::{MINUTE, ROLLUP, Sample, Source};
12use schedr_model::usage::{NodeUsage, WorkerParts};
13
14#[cfg(test)]
15mod tests;
16
17/// How long after its end a window waits to be rolled up: a sample stored late (a webserver's
18/// timer, a slow insert) is in it by then.
19pub const ROLL_GRACE: SignedDuration = SignedDuration::from_mins(2);
20/// How the samples are taken and kept (hidden timings, decision 464).
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub struct SampleSettings {
23    /// How often a sample is taken (`MASTER__SAMPLE_INTERVAL`, a minute).
24    pub interval: Duration,
25    /// How long minute samples are kept (`MASTER__SAMPLES_KEPT`, a day).
26    pub minutes_kept: Duration,
27    /// How long rollups are kept (`MASTER__ROLLUPS_KEPT`, 30 days).
28    pub rollups_kept: Duration,
29    /// How long after its end a window waits to be rolled up (`MASTER__SAMPLE_ROLLUP_GRACE`,
30    /// 2 minutes): a sample stored late is in it by then.
31    pub rollup_grace: Duration,
32    /// How often a master writes its row (`MASTER__NODE_HEARTBEAT`, 10 s): one heard from
33    /// within three of them is sampled.
34    pub node_heartbeat: Duration,
35}
36
37impl Default for SampleSettings {
38    fn default() -> Self {
39        Self {
40            interval: Duration::from_mins(1),
41            minutes_kept: Duration::from_hours(24),
42            rollups_kept: Duration::from_hours(24 * 30),
43            rollup_grace: ROLL_GRACE.unsigned_abs(),
44            node_heartbeat: Duration::from_secs(10),
45        }
46    }
47}
48
49/// A master heard from within this many of its heartbeats is sampled.
50pub const MASTERS_HEARD_BEATS: u32 = 3;
51
52/// A worker heard from within this long is sampled (its usage is written once a minute).
53const WORKERS_HEARD: SignedDuration = SignedDuration::from_secs(120);
54
55/// `at` down to a whole multiple of `step` seconds.
56fn floor(at: Timestamp, step: u32) -> Timestamp {
57    let step = i64::from(step);
58    let seconds = at.as_second().div_euclid(step) * step;
59    Timestamp::from_second(seconds).unwrap_or(at)
60}
61
62/// What a pass did, for the statement bound (decision 464): 3 a minute, 7 when a window
63/// closes (its read and insert, then the two deletes), more at a new sampler's first pass,
64/// which rolls every window not rolled yet.
65#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
66pub struct Pass {
67    /// Samples written.
68    pub written: usize,
69    /// Rollups written.
70    pub rolled: u64,
71    /// The statements it made.
72    pub statements: u32,
73}
74
75/// The sampler's memory between passes: each process's last CPU time with when it was measured
76/// and the cores it gave, the last window rolled.
77#[derive(Debug, Default)]
78pub struct Sampler {
79    cpu: HashMap<String, (Timestamp, f64, Option<f64>)>,
80    rolled: Option<Timestamp>,
81    /// A window was rolled since the deletes last succeeded (Grok's review of M5.1i: a failed
82    /// delete waited for the next window).
83    prune: bool,
84}
85
86impl Sampler {
87    /// The cores `process` used between its last measure and this one (`cpu_seconds` measured
88    /// `measured`), remembering it; none for its first, or when its CPU time went back (it
89    /// restarted under the same ID). The same measure again (nothing stored since, Grok's
90    /// review of M5.1i) gives the cores it gave before and keeps it as the baseline.
91    fn cores(&mut self, process: &str, measured: Timestamp, cpu_seconds: f64) -> Option<f64> {
92        if let Some((then, _, cores)) = self.cpu.get(process)
93            && *then == measured
94        {
95            return *cores;
96        }
97        let before = self.cpu.get(process).copied();
98        let cores = before.and_then(|(then, was, _)| {
99            let elapsed = measured.duration_since(then).as_secs_f64();
100            let used = cpu_seconds - was;
101            (elapsed > 0.0 && used >= 0.0 && used.is_finite()).then(|| used / elapsed)
102        });
103        self.cpu
104            .insert(process.to_owned(), (measured, cpu_seconds, cores));
105        cores
106    }
107
108    /// One sample per process at minute `at` from `sources`: a process's roles together
109    /// (with `own`'s roles added to the process `own` names: a standalone's webserver), its
110    /// figures its worker's where it runs one (those have its parts).
111    pub fn samples(
112        &mut self,
113        sources: Vec<Source>,
114        at: Timestamp,
115        own: Option<(&str, &BTreeMap<String, String>)>,
116    ) -> Vec<Sample> {
117        let mut by_process: BTreeMap<String, (BTreeMap<String, String>, Option<Source>)> =
118            BTreeMap::new();
119        for source in sources {
120            let entry = by_process.entry(source.process_id.clone()).or_default();
121            entry
122                .0
123                .insert(source.role.to_owned(), source.node_id.clone());
124            let keep = match &entry.1 {
125                None => true,
126                Some(kept) => kept.parts.is_none() && source.parts.is_some(),
127            };
128            if keep {
129                entry.1 = Some(source);
130            }
131        }
132        if let Some((process, roles)) = own
133            && let Some(entry) = by_process.get_mut(process)
134        {
135            entry
136                .0
137                .extend(roles.iter().map(|(k, v)| (k.clone(), v.clone())));
138        }
139        by_process
140            .into_iter()
141            .filter_map(|(process, (roles, source))| {
142                let source = source?;
143                Some(self.sample(
144                    (process, roles),
145                    &source.usage,
146                    source.parts,
147                    (at, source.at),
148                ))
149            })
150            .collect()
151    }
152
153    /// `usage` of `process` (running `roles`), measured `measured`, as its minute sample at
154    /// minute `at`.
155    pub fn sample(
156        &mut self,
157        (process, roles): (String, BTreeMap<String, String>),
158        usage: &NodeUsage,
159        parts: Option<WorkerParts>,
160        (at, measured): (Timestamp, Timestamp),
161    ) -> Sample {
162        let cpu = self.cores(&process, measured, usage.cpu_seconds);
163        // Its whole memory: a worker's parts are processes of their own.
164        let memory = usage
165            .resident_bytes
166            .saturating_add(parts.as_ref().map_or(0, |p| {
167                p.fork_servers_bytes
168                    .saturating_add(p.watcher_hosts_bytes)
169                    .saturating_add(p.tasks_bytes)
170            }));
171        Sample {
172            process_id: process,
173            step_s: MINUTE,
174            at,
175            roles,
176            resident_avg: usage.resident_bytes,
177            resident_peak: usage.resident_bytes,
178            memory_avg: memory,
179            memory_peak: memory,
180            minutes: 1,
181            cpu_minutes: u32::from(cpu.is_some()),
182            container_minutes: u32::from(usage.container_bytes.is_some()),
183            covered: 1,
184            cpu_seconds: Some(usage.cpu_seconds),
185            cpu_avg: cpu,
186            cpu_peak: cpu,
187            container_avg: usage.container_bytes,
188            container_peak: usage.container_bytes,
189            container_limit: usage.container_limit_bytes,
190            parts,
191        }
192    }
193
194    /// The leader's pass at `now`: this minute's samples of the masters and workers, then,
195    /// once a window has closed since the last one rolled, its rollup and the deletes.
196    ///
197    /// # Errors
198    ///
199    /// [`DbError`] if a statement fails: the next pass goes on (a window not rolled is rolled
200    /// then).
201    pub async fn pass(
202        &mut self,
203        db: &Database,
204        settings: &SampleSettings,
205        now: Timestamp,
206        own: Option<(&str, &BTreeMap<String, String>)>,
207    ) -> Result<Pass, DbError> {
208        let minute = floor(now, MINUTE);
209        let sources = db
210            .sample_sources(
211                now.checked_sub(within(
212                    settings.node_heartbeat.saturating_mul(MASTERS_HEARD_BEATS),
213                ))
214                .unwrap_or(now),
215                now.checked_sub(WORKERS_HEARD).unwrap_or(now),
216            )
217            .await?;
218        let mut pass = Pass {
219            statements: 2,
220            ..Pass::default()
221        };
222        let samples = self.samples(sources, minute, own);
223        if !samples.is_empty() {
224            db.insert_samples(&samples).await?;
225            pass.statements += 1;
226        }
227        pass.written = samples.len();
228        // Every window closed since the last one rolled (a new sampler: since the oldest
229        // minute kept), each once (again after a restart: kept), before any minute is deleted
230        // (Grok's review of M5.1i: a leader down across a boundary lost the windows it missed).
231        // A window closes for rolling up a grace after its end, so that a webserver's sample
232        // stored late is in it: a rollup isn't written again (Codex's review of M5.1j).
233        let grace = within(settings.rollup_grace);
234        let closed = floor(minute.checked_sub(grace).unwrap_or(minute), ROLLUP)
235            .checked_sub(SignedDuration::from_secs(i64::from(ROLLUP)))
236            .unwrap_or(minute);
237        let window = SignedDuration::from_secs(i64::from(ROLLUP));
238        let mut next = if let Some(rolled) = self.rolled {
239            rolled.checked_add(window).unwrap_or(rolled)
240        } else {
241            pass.statements += 1;
242            db.oldest_minute_sample()
243                .await?
244                .map_or(closed, |oldest| floor(oldest, ROLLUP))
245        };
246        // Nothing closed before the oldest minute: none to look for again.
247        if next > closed && self.rolled.is_none() {
248            self.rolled = Some(closed);
249        }
250        while next <= closed {
251            let (rolled, statements) = roll_up(db, next).await?;
252            pass.rolled += rolled;
253            pass.statements += statements;
254            self.rolled = Some(next);
255            self.prune = true;
256            match next.checked_add(window) {
257                Ok(later) => next = later,
258                Err(_) => break,
259            }
260        }
261        if self.prune {
262            let keep = |kept: Duration| {
263                SignedDuration::try_from(kept)
264                    .ok()
265                    .and_then(|kept| now.checked_sub(kept).ok())
266                    .unwrap_or(Timestamp::UNIX_EPOCH)
267            };
268            db.delete_old_samples(MINUTE, keep(settings.minutes_kept))
269                .await?;
270            db.delete_old_samples(ROLLUP, keep(settings.rollups_kept))
271                .await?;
272            pass.statements += 2;
273            self.prune = false;
274        }
275        Ok(pass)
276    }
277}
278
279/// Rolls up the window starting `from`: its minute samples read, one row per process written
280/// (averages rounded, peaks, its roles together); returns the rows written and the statements.
281async fn roll_up(db: &Database, from: Timestamp) -> Result<(u64, u32), DbError> {
282    let to = from
283        .checked_add(SignedDuration::from_secs(i64::from(ROLLUP)))
284        .unwrap_or(from);
285    let minutes = db.samples(MINUTE, from, to).await?;
286    let rolled = rolled_up(&minutes, from);
287    if rolled.is_empty() {
288        return Ok((0, 1));
289    }
290    db.insert_samples(&rolled).await?;
291    Ok((u64::try_from(rolled.len()).unwrap_or(u64::MAX), 2))
292}
293
294/// `minutes` (by process, then time) as one rollup per process at `at`: memory's averages
295/// rounded and peaks, CPU's average and peak over the minutes that have one, the container's
296/// latest limit, every role the window saw, the minutes it covers, and a worker's parts on
297/// average over every minute (its largest tasks left out), so the 7 and 30 days show memory by
298/// kind too.
299#[must_use]
300pub fn rolled_up(minutes: &[Sample], at: Timestamp) -> Vec<Sample> {
301    // The window's minutes in which any process was sampled: a total's denominator.
302    let covered = u32::try_from(
303        minutes
304            .iter()
305            .map(|s| s.at)
306            .collect::<std::collections::BTreeSet<_>>()
307            .len(),
308    )
309    .unwrap_or(u32::MAX);
310    let mut by_process: BTreeMap<&str, Vec<&Sample>> = BTreeMap::new();
311    for sample in minutes {
312        by_process
313            .entry(&sample.process_id)
314            .or_default()
315            .push(sample);
316    }
317    by_process
318        .into_iter()
319        .map(|(process, samples)| {
320            #[expect(clippy::cast_precision_loss, reason = "an average of byte counts")]
321            let average = |values: &[u64]| {
322                (!values.is_empty()).then(|| {
323                    let sum: f64 = values.iter().map(|v| *v as f64).sum();
324                    #[expect(
325                        clippy::cast_possible_truncation,
326                        clippy::cast_sign_loss,
327                        reason = "a rounded average of byte counts: non-negative, in range"
328                    )]
329                    let rounded = (sum / values.len() as f64).round() as u64;
330                    rounded
331                })
332            };
333            let resident: Vec<u64> = samples.iter().map(|s| s.resident_avg).collect();
334            let memory: Vec<u64> = samples.iter().map(|s| s.memory_avg).collect();
335            let container: Vec<u64> = samples.iter().filter_map(|s| s.container_avg).collect();
336            let cpu: Vec<f64> = samples.iter().filter_map(|s| s.cpu_avg).collect();
337            #[expect(clippy::cast_precision_loss, reason = "a count of minutes")]
338            let cpu_avg = (!cpu.is_empty()).then(|| cpu.iter().sum::<f64>() / cpu.len() as f64);
339            Sample {
340                process_id: process.to_owned(),
341                step_s: ROLLUP,
342                at,
343                roles: samples
344                    .iter()
345                    .flat_map(|s| s.roles.iter().map(|(k, v)| (k.clone(), v.clone())))
346                    .collect(),
347                resident_avg: average(&resident).unwrap_or(0),
348                resident_peak: samples.iter().map(|s| s.resident_peak).max().unwrap_or(0),
349                memory_avg: average(&memory).unwrap_or(0),
350                memory_peak: samples.iter().map(|s| s.memory_peak).max().unwrap_or(0),
351                minutes: samples.iter().map(|s| s.minutes).sum(),
352                cpu_minutes: samples.iter().map(|s| s.cpu_minutes).sum(),
353                container_minutes: samples.iter().map(|s| s.container_minutes).sum(),
354                covered,
355                cpu_seconds: None,
356                cpu_avg,
357                cpu_peak: samples.iter().filter_map(|s| s.cpu_peak).reduce(f64::max),
358                container_avg: average(&container),
359                container_peak: samples.iter().filter_map(|s| s.container_peak).max(),
360                // The latest minute's: none there is unlimited (Codex's review of M5.1j).
361                container_limit: samples.last().and_then(|s| s.container_limit),
362                // Each part over every minute, 0 where it ran no worker, so the parts and the
363                // process itself add up to its whole memory (Codex's review of M5.1j).
364                parts: {
365                    let ran = samples.iter().any(|s| s.parts.is_some());
366                    let part = |of: fn(&WorkerParts) -> u64| {
367                        average(
368                            &samples
369                                .iter()
370                                .map(|s| s.parts.as_ref().map_or(0, of))
371                                .collect::<Vec<_>>(),
372                        )
373                        .unwrap_or(0)
374                    };
375                    ran.then(|| WorkerParts {
376                        fork_servers_bytes: part(|p| p.fork_servers_bytes),
377                        watcher_hosts_bytes: part(|p| p.watcher_hosts_bytes),
378                        tasks_bytes: part(|p| p.tasks_bytes),
379                        largest_tasks: Vec::new(),
380                    })
381                },
382            }
383        })
384        .collect()
385}
386
387/// A webserver in a process of its own samples itself every `interval` (decision 464) on `db`
388/// as `process_id`, its figures from `usage`, until `stop` completes; a failure is logged.
389pub async fn sample_webserver(
390    db: Database,
391    interval: Duration,
392    process_id: String,
393    usage: fn() -> Option<NodeUsage>,
394    stop: impl Future<Output = ()>,
395) {
396    tokio::pin!(stop);
397    let mut sampler = Sampler::default();
398    let roles: BTreeMap<String, String> =
399        BTreeMap::from([("webserver".to_owned(), process_id.clone())]);
400    loop {
401        if let Some(usage) = usage() {
402            let measured = Timestamp::now();
403            let sample = sampler.sample(
404                (process_id.clone(), roles.clone()),
405                &usage,
406                None,
407                (floor(measured, MINUTE), measured),
408            );
409            if let Err(error) = db.insert_samples(&[sample]).await {
410                tracing::warn!(%error, "this webserver's sample not stored; trying again in a minute");
411            }
412        }
413        tokio::select! {
414            () = &mut stop => return,
415            () = tokio::time::sleep(interval) => {}
416        }
417    }
418}
419
420/// `duration` as a signed one, the longest when it doesn't fit.
421fn within(duration: Duration) -> SignedDuration {
422    SignedDuration::try_from(duration).unwrap_or(SignedDuration::MAX)
423}