Skip to main content

runnerd_core/
sizing.rs

1//! Right-sizing advice from the job history: the spread of each profile's and each job's sampled peaks, waits and
2//! slot use, and the `memory` and `slots` to set. Pure: the store reads the history, the daemon serves the result
3//! (`api::Sizing`). It never changes the config: a client applies advice through `PUT /v1/config`, which validates
4//! it like any other config, and under `[sizing] auto` the daemon applies what `auto::changes` picks the same way.
5
6use crate::admission::Key;
7use crate::admission::recent::Recent;
8use crate::api::{self, Advice, Peaks, Spread};
9use crate::config::{Admission, Config};
10use crate::observe::metrics::SAMPLE_INTERVAL;
11
12pub(crate) use crate::api::GRANULE;
13
14/// Without its container's `memory.events`, a peak at or above this share of its cap, in percent, likely met it.
15const AT_CAP: u64 = 95;
16
17/// Lowering a cap is advised once it saves at least this share of it, in percent.
18const WORTH_LOWERING: u64 = 10;
19
20/// Jobs that waited this long at p95, in seconds, or slots busy this share of the time, in percent, want more
21/// slots.
22const WAITED: u64 = 60;
23const BUSY: u32 = 50;
24
25/// One finished job of this daemon's runners, as sizing reads it. Times in milliseconds.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct Ran {
28    /// `owner/name`.
29    pub repository: String,
30    /// The workflow's name, when known.
31    pub workflow: Option<String>,
32    /// The job's name.
33    pub name: String,
34    /// The profile its runner ran in.
35    pub profile: String,
36    /// Its container's memory cap, when recorded.
37    pub memory_cap: Option<u64>,
38    /// Its container's CPU cap, millicores, when recorded.
39    pub cpu_cap: Option<u64>,
40    /// Its sampled memory peak, bytes, as `measure` counts memory.
41    pub memory_peak: u64,
42    /// Its sampled CPU peak, millicores.
43    pub cpu_peak: u64,
44    /// Its CPU time over its run time, millicores; `None` when not recorded.
45    pub cpu_average: Option<u64>,
46    /// When it was queued.
47    pub queued_at: u64,
48    /// When it started; `None` for a job lost before.
49    pub started_at: Option<u64>,
50    /// When its runner's container started: before `queued_at`, it was a warm runner.
51    pub runner_started_at: u64,
52    /// When it finished, or was found lost.
53    pub finished_at: Option<u64>,
54    /// Whether the kernel killed a process in its container for memory.
55    pub oom_killed: bool,
56    /// Whether its container's memory, or a descendant's, reached a limit with nothing left to reclaim
57    /// (`memory.events` `oom`); `None` when its events were not recorded.
58    pub hit_cap: Option<bool>,
59    /// Whether its container's own limit failed reclaim (`memory.events.local` `oom`), not a descendant's; `None`
60    /// when not recorded, as before schema 14.
61    pub own_cap: Option<bool>,
62    /// What its sampled memory counts.
63    pub measure: Measure,
64    /// Whether it completed with success: a failed or lost run may have stopped before its heaviest step.
65    pub succeeded: bool,
66    /// Whether it completed with `failure` or `timed_out`: not lost, not cancelled.
67    pub failed: bool,
68    /// Its workflow run on GitHub: a re-run of its failed jobs has the same.
69    pub run_id: u64,
70    /// The branch it ran for, when known.
71    pub branch: Option<String>,
72    /// What measured admission reserved for it; `None` under caps or for an adopted runner.
73    pub reserved: Option<u64>,
74    /// How long of its wait it waited because the host's memory could not take its runner, in ms: no more slots
75    /// would have started it sooner.
76    pub host_waited: u64,
77}
78
79/// What a run's sampled memory counts.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum Measure {
82    /// `memory.current` less `inactive_file`, as runners started before schema version 8 were sampled: page cache
83    /// read twice (`active_file`) counts, so peaks overstate what a job needs.
84    WithActiveFile,
85    /// `memory.current` less the file LRU lists (`active_file`, `inactive_file`): an estimate of what a job holds
86    /// without the page cache the kernel can drop.
87    WithoutPageCache,
88}
89
90/// What a run says about its container's memory cap (ADR 0070).
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum Capped {
93    /// The container's own limit failed reclaim: it needed more than the cap.
94    Met,
95    /// Recorded without the local counter: by the reading before it, a kill or a limit hit in the container, or
96    /// without events a peak within `AT_CAP` percent of the cap. Holds and floors as `Met`, never raises a cap.
97    Assumed,
98    /// A process in it was killed for memory while its own limit held: the slice or the host ran out.
99    Killed,
100    /// None of those. A peak near the cap with no `oom` at it is clear: a JVM fills the room it has.
101    Clear,
102}
103
104impl Capped {
105    /// Whether it says the job needed its cap: `Met` or `Assumed`.
106    pub fn met(self) -> bool {
107        matches!(self, Capped::Met | Capped::Assumed)
108    }
109
110    /// Whether it puts its job on its cap: anything but `Clear`.
111    pub fn holds(self) -> bool {
112        self != Capped::Clear
113    }
114}
115
116impl Ran {
117    /// What it says about its container's `cap`. A kill that only a descendant's own limit explains, the counters
118    /// showing a limit hit below the container and none at it, is a service container the job capped itself: clear.
119    /// A kill no sample saw an `oom` before, its last sample within `AT_CAP` percent of the cap, met it in the last
120    /// interval.
121    pub fn capped(&self, cap: u64) -> Capped {
122        match self.own_cap {
123            Some(true) => Capped::Met,
124            // No sample saw `oom` at any level and its last came near the cap: its own limit killed it before the
125            // next sample could count it.
126            Some(false)
127                if self.oom_killed
128                    && self.hit_cap == Some(false)
129                    && self.memory_peak.saturating_mul(100) >= cap.saturating_mul(AT_CAP) =>
130            {
131                Capped::Met
132            }
133            Some(false) if self.oom_killed && self.hit_cap != Some(true) => Capped::Killed,
134            None if self.oom_killed
135                || self.hit_cap.unwrap_or_else(|| {
136                    self.memory_peak.saturating_mul(100) >= cap.saturating_mul(AT_CAP)
137                }) =>
138            {
139                Capped::Assumed
140            }
141            Some(false) | None => Capped::Clear,
142        }
143    }
144}
145
146/// One runner container's time in a slot for a job. Times in milliseconds.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct Held {
149    /// Its profile.
150    pub profile: String,
151    /// When it started holding the slot for a job: its start, or when its job was queued if that came later, as for
152    /// a warm runner.
153    pub started_at: u64,
154    /// When it was removed; `None` while it runs.
155    pub removed_at: Option<u64>,
156}
157
158/// A profile's `cpus` as the daemon ran it from `at` (ms), by its `profile.changed` event: one when it started with
159/// the profile, and after each reload or restart that changed the profile's image, CPUs, memory or slots.
160#[derive(Debug, Clone, PartialEq, Eq)]
161pub struct CpusSet {
162    /// The profile.
163    pub profile: String,
164    /// Its `cpus` from then.
165    pub cpus: u32,
166    /// When, in milliseconds.
167    pub at: u64,
168}
169
170/// A profile's `memory` as the daemon ran it from `at` (ms), by its `profile.changed` event, as `CpusSet` has its
171/// `cpus`.
172#[derive(Debug, Clone, PartialEq, Eq)]
173pub struct MemorySet {
174    /// The profile.
175    pub profile: String,
176    /// Its `memory` from then, in bytes.
177    pub memory: u64,
178    /// When, in milliseconds.
179    pub at: u64,
180}
181
182/// What the store reads for sizing.
183#[derive(Debug, Clone, Default, PartialEq, Eq)]
184pub struct History {
185    /// Finished jobs with a recorded peak, cancelled ones left out.
186    pub jobs: Vec<Ran>,
187    /// Cancelled jobs, for what admission learns from how they ended: a kill for memory, a peak at the cap or past
188    /// what was reserved. Their peaks (0 when never sampled) are not read as a job's size.
189    pub cancelled: Vec<Ran>,
190    /// Runners that held a slot at some point after the history's start.
191    pub runners: Vec<Held>,
192    /// Auto sizing's changes, oldest first, from `CHANGES_READ` before now: what a revert reads (ADR 0070). Empty
193    /// where nothing reads them, as for admission.
194    pub changes: Vec<api::SizingChange>,
195    /// Each profile's `memory` as the daemon ran it, oldest first: since when a raise reads runs at it.
196    pub memory_set: Vec<MemorySet>,
197    /// From when, in ms, the history holds every job (`history_kept`): a wait before it, as of a job queued before
198    /// runnerd first ran, counts from then.
199    pub kept_since: u64,
200}
201
202/// What `advise` sizes against besides the history.
203#[derive(Debug, Clone, Copy)]
204pub struct Window {
205    /// The start asked for, in milliseconds, at most `now`.
206    pub since: u64,
207    /// Now, in milliseconds.
208    pub now: u64,
209    /// Seconds between two samples of a container.
210    pub sample_interval: u64,
211}
212
213impl Window {
214    /// The window `GET /v1/sizing` reads: from `since` (seconds), default 30 days before `now` (seconds), and
215    /// never after `now`.
216    pub fn new(since: Option<u64>, now: u64) -> Window {
217        Window {
218            since: since
219                .unwrap_or_else(|| now.saturating_sub(30 * 24 * 3600))
220                .min(now)
221                .saturating_mul(1000),
222            now: now.saturating_mul(1000),
223            sample_interval: SAMPLE_INTERVAL.as_secs(),
224        }
225    }
226}
227
228/// The advice for every profile of `config` from `history`, against the slice's `memory_max` as `config`'s
229/// admission policy budgets it. Peaks, and the memory advice, go by each job's sizing window over the history's last
230/// 30 days (`memory`, ADR 0070); `window.since` narrows only the waits, the busy share and the starts.
231pub fn advise(
232    config: &Config,
233    memory_max: Option<u64>,
234    history: &History,
235    window: Window,
236) -> api::Sizing {
237    let since = first_runner(history, window.since);
238    let caps = config.memory_caps().map_or(u64::MAX, |caps| caps.0);
239    let mirror = config.mirror_memory();
240    let rules = &config.sizing;
241    let recent = memory::windows(config, history, window.now);
242    let profiles = config
243        .profiles
244        .iter()
245        .map(|(name, profile)| {
246            let jobs: Vec<&Ran> = history
247                .jobs
248                .iter()
249                .filter(|job| job.profile == *name && job.queued_at >= window.since)
250                .collect();
251            let share = profile.memory.0.saturating_mul(u64::from(profile.slots));
252            let busy = busy(history, name, profile.slots, since, window.now);
253            let wait = waits(&jobs, history.kept_since);
254            let starts = starts(&jobs, history.kept_since);
255            let cap = profile.memory.0;
256            let took = memory::took(&history.memory_set, name, cap, window.now);
257            let sized = Sized {
258                cap,
259                cpus: u64::from(profile.cpus) * 1000,
260                slots: profile.slots,
261                share,
262                admission: config.host.admission,
263                room: memory_max.map(|max| match config.host.admission {
264                    // What the slice leaves this profile once the other profiles and the mirror took theirs.
265                    Admission::Caps => max.saturating_sub(caps.saturating_sub(share)),
266                    // Measured admission reserves predicted peaks, not caps: the config check only holds one
267                    // runner of each profile beside the mirror.
268                    Admission::Measured => max.saturating_sub(mirror),
269                }),
270                wants_slots: wait.p95 >= WAITED || busy >= BUSY,
271                min_jobs: rules.min_jobs,
272            };
273            let raises = Raises {
274                history,
275                recent: &recent,
276                profile: name,
277                cap,
278                took,
279                margin: rules.margin,
280            };
281            let memory = job_memory(&raises, &jobs, &sized, window.now, busy);
282            let peaks = memory::peaks(
283                recent.jobs_of(name).flat_map(|(_, runs)| runs.window()),
284                memory.on_cap,
285                sized.cpus,
286            );
287            let current = api::Resize {
288                memory: cap,
289                slots: profile.slots,
290                cpus: None,
291            };
292            let revert = memory::revert(config, history, name, current);
293            let advice = match &revert {
294                Some((_, to)) => Advice::Raise {
295                    memory: to.memory,
296                    slots: to.slots,
297                },
298                None => sized.advice(
299                    &peaks,
300                    Needs {
301                        raise: raises.need(None),
302                        floor: memory.floor.max(memory::revert_floor(history, name)),
303                    },
304                    sized.wants_slots,
305                ),
306            };
307            api::ProfileSizing {
308                name: name.clone(),
309                memory: cap,
310                cpus: profile.cpus,
311                slots: profile.slots,
312                advice,
313                revert: revert.map(|(revert, _)| revert),
314                peaks,
315                wait,
316                starts,
317                busy,
318                wants_slots: sized.wants_slots,
319                jobs: memory.jobs,
320            }
321        })
322        .collect();
323    api::Sizing {
324        since: since / 1000,
325        until: window.now / 1000,
326        margin: rules.margin,
327        sample_interval: window.sample_interval,
328        min_jobs: rules.min_jobs,
329        memory_max,
330        admission: config.host.admission.policy(),
331        profiles,
332        auto: config.sizing.auto,
333        changes: Vec::new(),
334        auto_plan: None,
335    }
336}
337
338/// What a raise of one profile reads (`memory::raise_need`).
339struct Raises<'history> {
340    history: &'history History,
341    recent: &'history Recent,
342    profile: &'history str,
343    /// Its `memory`.
344    cap: u64,
345    /// Since when it has had it, in ms.
346    took: u64,
347    margin: u32,
348}
349
350impl Raises<'_> {
351    /// What a raise needs from the job `key`, or from every job for `None`.
352    fn need(&self, key: Option<&Key>) -> u64 {
353        memory::raise_need(
354            self.history,
355            self.recent,
356            self.profile,
357            self.cap,
358            self.took,
359            self.margin,
360            key,
361        )
362    }
363}
364
365/// What a profile's jobs say about its `memory`.
366struct JobMemory {
367    /// Each job's sizing.
368    jobs: Vec<api::JobSizing>,
369    /// How many of them are on their cap.
370    on_cap: u64,
371    /// The largest of their floors.
372    floor: u64,
373}
374
375/// Each job of `raises.profile` with runs in its window: its peaks, waits and advice; `jobs` are the profile's runs
376/// since the window's start, for the waits.
377fn job_memory(raises: &Raises<'_>, jobs: &[&Ran], sized: &Sized, now: u64, busy: u32) -> JobMemory {
378    let mut on_cap = 0;
379    let mut floor = 0;
380    let sizings = raises
381        .recent
382        .jobs_of(raises.profile)
383        .filter(|(_, runs)| runs.runs() > 0)
384        .map(|(key, runs)| {
385            let held = memory::on_cap(runs, now);
386            on_cap += u64::from(held);
387            let peaks = memory::peaks(runs.window(), u64::from(held), sized.cpus);
388            let needs = Needs {
389                raise: raises.need(Some(key)),
390                floor: memory::floor(runs, raises.margin),
391            };
392            floor = floor.max(needs.floor);
393            let runs_of: Vec<&Ran> = jobs
394                .iter()
395                .copied()
396                .filter(|job| Key::of(job) == *key)
397                .collect();
398            let wait = waits(&runs_of, raises.history.kept_since);
399            api::JobSizing {
400                repository: key.repository.clone(),
401                workflow: key.workflow.clone(),
402                name: key.name.clone(),
403                advice: sized.advice(&peaks, needs, wait.p95 >= WAITED || busy >= BUSY),
404                peaks,
405                wait,
406            }
407        })
408        .collect();
409    JobMemory {
410        jobs: sizings,
411        on_cap,
412        floor,
413    }
414}
415
416/// Where a history read from `start` (ms) begins: at its first runner when that started later, as a new daemon's
417/// history does.
418fn first_runner(history: &History, start: u64) -> u64 {
419    history
420        .runners
421        .iter()
422        .map(|runner| runner.started_at)
423        .min()
424        .map_or(start, |first| first.max(start))
425}
426
427/// The percent of the time from `since` to `now` (ms) that the profile's runners held its `slots`.
428fn busy(history: &History, profile: &str, slots: u32, since: u64, now: u64) -> u32 {
429    let span = now.saturating_sub(since).max(1);
430    let held: u64 = history
431        .runners
432        .iter()
433        .filter(|runner| runner.profile == profile)
434        .map(|runner| {
435            let end = runner.removed_at.unwrap_or(now).min(now);
436            end.saturating_sub(runner.started_at.max(since))
437        })
438        .sum();
439    u32::try_from(
440        (held.saturating_mul(100) / span.saturating_mul(u64::from(slots).max(1))).min(100),
441    )
442    .unwrap_or(100)
443}
444
445/// A profile's limits and the rules advice follows.
446struct Sized {
447    cap: u64,
448    /// Its `cpus`, in millicores: CPU peaks are read only of runs at them.
449    cpus: u64,
450    slots: u32,
451    /// What its slots take of the budget now: `memory × slots`.
452    share: u64,
453    admission: Admission,
454    /// The memory the slice holds for it, as `admission` budgets it: all its slots at their caps under `caps`, one
455    /// runner under `measured`; `None` for an unlimited slice.
456    room: Option<u64>,
457    /// Whether its jobs waited for a slot at p95, or its slots were busy, enough to want more.
458    wants_slots: bool,
459    min_jobs: u32,
460}
461
462/// What a set of jobs' runs say its `memory` needs (`memory`, ADR 0070).
463#[derive(Debug, Clone, Copy)]
464struct Needs {
465    /// What a raise goes to: from runs that met the current cap since the profile took it; 0 without one.
466    raise: u64,
467    /// What a lowering stays at or above: every windowed run's need, and any revert's floor.
468    floor: u64,
469}
470
471impl Sized {
472    /// A raise toward `needs.raise` when it is above the cap; a lowering toward `needs.floor` when that saves a tenth
473    /// and no job is on its cap; else keep, with `needs.floor` as what the jobs need, above the cap or not.
474    fn advice(&self, peaks: &Peaks, needs: Needs, wants_slots: bool) -> Advice {
475        if peaks.jobs < u64::from(self.min_jobs) {
476            return Advice::TooFew { jobs: peaks.jobs };
477        }
478        if needs.raise > self.cap {
479            let need = needs.raise;
480            let fit = |memory: u64| u32::try_from(memory / need).unwrap_or(u32::MAX);
481            let slots = match (self.admission, self.room) {
482                (Admission::Caps, Some(room)) => fit(room).min(self.slots),
483                (Admission::Measured, Some(room)) if room < need => 0,
484                (_, _) => self.slots,
485            };
486            if slots == 0 {
487                return Advice::SliceTooSmall { memory: need };
488            }
489            return Advice::Raise {
490                memory: need,
491                slots,
492            };
493        }
494        let need = needs.floor.max(GRANULE);
495        // A job on its cap may have been held back or killed by it: no lowering until it ran clear of it again.
496        if peaks.on_cap == 0
497            && need <= self.cap
498            && self.cap - need >= self.cap * WORTH_LOWERING / 100
499        {
500            let fit = |memory: u64| u32::try_from(memory / need).unwrap_or(u32::MAX);
501            // Under measured admission slots are not bought with caps: the advice line says when more may help.
502            return Advice::Lower {
503                memory: need,
504                slots: if wants_slots && self.admission == Admission::Caps {
505                    fit(self.share).max(self.slots)
506                } else {
507                    self.slots
508                },
509            };
510        }
511        Advice::Keep { memory: need }
512    }
513}
514
515/// Seconds from queued, or from `kept_since` (ms) if that came later, to started of the jobs that started, less what
516/// they waited for the host's memory.
517fn waits(jobs: &[&Ran], kept_since: u64) -> Spread {
518    spread(
519        jobs.iter()
520            .filter_map(|job| {
521                job.started_at.map(|at| {
522                    at.saturating_sub(job.queued_at.max(kept_since))
523                        .saturating_sub(job.host_waited)
524                        / 1000
525                })
526            })
527            .collect(),
528    )
529}
530
531/// The jobs that started on a warm runner and the others, and their median waits.
532fn starts(jobs: &[&Ran], kept_since: u64) -> api::Starts {
533    let (warm, cold): (Vec<&Ran>, Vec<&Ran>) = jobs
534        .iter()
535        .filter(|job| job.started_at.is_some())
536        .partition(|job| job.runner_started_at < job.queued_at);
537    let count = |jobs: &[&Ran]| u32::try_from(jobs.len()).unwrap_or(u32::MAX);
538    api::Starts {
539        warm: count(&warm),
540        warm_p50: waits(&warm, kept_since).p50,
541        cold: count(&cold),
542        cold_p50: waits(&cold, kept_since).p50,
543    }
544}
545
546/// Nearest-rank percentiles; all zero for no values.
547pub(crate) fn spread(mut values: Vec<u64>) -> Spread {
548    values.sort_unstable();
549    let rank = |percent: usize| {
550        let index = (values.len() * percent).div_ceil(100).saturating_sub(1);
551        values.get(index).copied().unwrap_or(0)
552    };
553    Spread {
554        p50: rank(50),
555        p95: rank(95),
556        p99: rank(99),
557        max: values.last().copied().unwrap_or(0),
558    }
559}
560
561pub mod auto;
562pub mod memory;
563
564#[cfg(test)]
565mod tests;