Skip to main content

runnerd_core/api/
sizing.rs

1//! Right-sizing as clients read it: per profile and per job (repository, workflow and job name), the spread of the
2//! job history's sampled memory and CPU peaks, how long jobs waited for a slot, how busy the slots were, and what
3//! to set each profile's `memory` and `slots` to. Plain data; the daemon computes it from the history. Sizes are
4//! bytes, CPU millicores, times seconds since the Unix epoch.
5
6use serde::{Deserialize, Serialize};
7
8use crate::api::AdmissionPolicy;
9use crate::config::ByteSize;
10
11mod shown;
12
13pub use shown::{GRANULE, Need, ProfilePlan, SAMPLE_INTERVAL, need, sampled_note};
14
15/// `GET /v1/sizing` query parameters.
16#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
17pub struct SizingQuery {
18    /// Only jobs queued at or after this time; default 30 days ago.
19    pub since: Option<u64>,
20}
21
22/// `GET /v1/sizing`: what the job history says each configured profile needs.
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24pub struct Sizing {
25    /// The start of the history read: `since`, or the first runner recorded after it.
26    pub since: u64,
27    /// When it was computed.
28    pub until: u64,
29    /// The percent added to a sampled peak, `[sizing] margin`: peaks are sampled every `sample_interval`
30    /// seconds, so a shorter spike between two samples goes unseen.
31    pub margin: u32,
32    /// Seconds between two samples of a job's container.
33    pub sample_interval: u64,
34    /// The fewest jobs a profile or job needs before its percentiles become advice, `[sizing] min_jobs`.
35    pub min_jobs: u32,
36    /// The slice's `MemoryMax`; `None` when it is unlimited.
37    pub memory_max: Option<u64>,
38    /// `[host] admission`, which the advice budgets `MemoryMax` by.
39    #[serde(default)]
40    pub admission: AdmissionPolicy,
41    /// Every configured profile, by name.
42    pub profiles: Vec<ProfileSizing>,
43    /// Whether the daemon applies advice itself, `[sizing] auto`.
44    #[serde(default)]
45    pub auto: bool,
46    /// The changes auto sizing made since `since`, oldest first.
47    #[serde(default)]
48    pub changes: Vec<SizingChange>,
49    /// Under auto sizing, what it does next and when. `None` while it is off, and from a daemon before it said.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub auto_plan: Option<AutoPlan>,
52}
53
54/// What auto sizing will do: its rules, the changes its next look would make as the history and config are now, and
55/// the profiles a recent change holds.
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct AutoPlan {
58    /// Seconds between two looks of the daemon's.
59    pub every: u64,
60    /// `[sizing] interval`: the least time between a change to one profile and one that lowers it, in seconds.
61    pub interval: u64,
62    /// `[sizing] raise_interval`: the least time between a change to one profile and one that only raises it, in
63    /// seconds. 0 from a daemon before it said: `interval` then holds every change.
64    #[serde(default)]
65    pub raise_interval: u64,
66    /// `[sizing] max_step`: the most one change moves a profile's `memory`, in percent of it.
67    pub max_step: u32,
68    /// The changes the next look would make, in the order it would make them; `at` is when this was worked out.
69    /// None of them is made while `blocked` says why.
70    pub next: Vec<SizingChange>,
71    /// The profiles a change in the last `interval` holds from some change, the hold that ends first first.
72    pub held: Vec<SizingHold>,
73    /// Why no look changes anything until the owner acts, as when the file on disk differs from the config runnerd
74    /// runs with. `None` when the next look may write `next`, and from a daemon before it said.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub blocked: Option<String>,
77}
78
79/// A profile auto sizing changes nothing in before `until`, and lowers nothing in before `lower_until`.
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81pub struct SizingHold {
82    /// The profile.
83    pub profile: String,
84    /// When its last change was made.
85    pub changed: u64,
86    /// When it may be raised again, in seconds since the Unix epoch.
87    pub until: u64,
88    /// When it may be lowered again; 0 from a daemon before it said, which held every change until `until`.
89    #[serde(default)]
90    pub lower_until: u64,
91}
92
93impl SizingHold {
94    /// When it may be lowered again.
95    pub fn lowered_after(&self) -> u64 {
96        self.lower_until.max(self.until)
97    }
98}
99
100/// A profile's `memory` and `slots` as auto sizing changed them in the config file.
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
102pub struct SizingChange {
103    /// When it was written.
104    pub at: u64,
105    /// The profile.
106    pub profile: String,
107    /// What they were: writing these back undoes it.
108    pub from: Resize,
109    /// What they are now.
110    pub to: Resize,
111    /// Why, as the advice said it then.
112    pub reason: String,
113    /// Whether it may not have been written: recorded before its file was written, and the config no longer said
114    /// whether it was when runnerd looked again. It still holds the interval, and `from` is still what it replaced.
115    #[serde(default)]
116    pub uncertain: bool,
117}
118
119/// One profile: its limits now, its jobs' peaks and waits, and the advice.
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121pub struct ProfileSizing {
122    /// The profile.
123    pub name: String,
124    /// Its `memory` now: each container's hard limit.
125    pub memory: u64,
126    /// Its `cpus` now.
127    pub cpus: u32,
128    /// Its `slots` now.
129    pub slots: u32,
130    /// Its jobs' peaks.
131    pub peaks: Peaks,
132    /// Seconds from queued to started.
133    pub wait: Spread,
134    /// Its jobs by whether a warm runner took them, and how long each kind waited. Empty from a daemon before warm
135    /// runners.
136    #[serde(default)]
137    pub starts: Starts,
138    /// The percent of the time since `since` its slots held a runner for a job, from when the job was queued, over
139    /// its `slots` now.
140    pub busy: u32,
141    /// Whether its jobs waited a minute or more for a slot at p95, or its slots were busy half the time: more slots
142    /// would help.
143    #[serde(default)]
144    pub wants_slots: bool,
145    /// What to set `memory` and `slots` to. Sized for its largest peak, so no job gets less than it used.
146    pub advice: Advice,
147    /// Each job that ran in it, by repository, workflow and name.
148    pub jobs: Vec<JobSizing>,
149}
150
151/// A profile's jobs by whether their runner was already up when GitHub queued them (ADR 0050).
152#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
153pub struct Starts {
154    /// Jobs that started on a warm runner: one that started before the job was queued.
155    pub warm: u32,
156    /// Their median wait from queued to started, in seconds.
157    pub warm_p50: u64,
158    /// Jobs whose runner started after they were queued.
159    pub cold: u32,
160    /// Their median wait, in seconds.
161    pub cold_p50: u64,
162}
163
164/// The jobs of one name in one workflow of one repository.
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166pub struct JobSizing {
167    /// `owner/name` on GitHub.
168    pub repository: String,
169    /// The workflow's name, when the history knew it.
170    pub workflow: Option<String>,
171    /// The job's name in the workflow.
172    pub name: String,
173    /// Its runs' peaks.
174    pub peaks: Peaks,
175    /// Seconds from queued to started.
176    pub wait: Spread,
177    /// What its profile's `memory` would be for this job alone, and the `slots` that would fit in the memory the
178    /// profile's slots take now.
179    pub advice: Advice,
180}
181
182/// The peaks of a set of jobs, each the highest of its samples.
183#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
184pub struct Peaks {
185    /// How many jobs: the number of peaks the percentiles are taken over.
186    pub jobs: u64,
187    /// Of those, how many met their container's memory cap: killed for memory, or out of memory at it with
188    /// nothing left to reclaim (for a run whose container's events were not recorded, a peak within 5% of it). They
189    /// may need more than they show.
190    pub at_cap: u64,
191    /// Memory without page cache, in bytes.
192    pub memory: Spread,
193    /// CPU, in millicores.
194    pub cpu: Spread,
195}
196
197/// Percentiles of a set of values, by nearest rank: each is one of the values, and with fewer than 100 values
198/// `p99` is the largest.
199#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
200pub struct Spread {
201    /// The median.
202    pub p50: u64,
203    /// The 95th percentile.
204    pub p95: u64,
205    /// The 99th percentile.
206    pub p99: u64,
207    /// The largest.
208    pub max: u64,
209}
210
211/// What a cap keeps at least over the largest peak, for page cache: 1G. Peaks leave page cache out, and a container
212/// whose memory past them leaves the kernel less than about 500M of page cache to reclaim at its cap reclaims badly,
213/// which throttles its sockets and slows its downloads (ADR 0055).
214pub const PAGE_CACHE_ROOM: u64 = 1 << 30;
215
216/// What to set a profile's `memory` and `slots` to. `memory` is the largest sampled peak plus the margin, or plus
217/// `PAGE_CACHE_ROOM` when that is more, rounded up to 256M: the cap kills a job that goes over it, so it is sized for
218/// the heaviest run, not a percentile.
219#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
220#[serde(rename_all = "kebab-case", tag = "kind")]
221pub enum Advice {
222    /// Fewer than `min_jobs` jobs: too few to advise on.
223    TooFew {
224        /// How many there are.
225        jobs: u64,
226    },
227    /// The cap fits, and lowering it would save less than a tenth or a run met its cap.
228    Keep {
229        /// What the jobs need.
230        memory: u64,
231    },
232    /// The cap is a tenth or more above what the jobs need, and no run met its cap.
233    Lower {
234        /// The new `memory`.
235        memory: u64,
236        /// The new `slots`: under `caps` admission, as many as fit in the memory the slots take now when jobs waited
237        /// for one; else the same.
238        slots: u32,
239    },
240    /// The jobs need more than the cap.
241    Raise {
242        /// The new `memory`.
243        memory: u64,
244        /// The new `slots`: the same, or under `caps` admission as many as the slice's `MemoryMax` still holds.
245        slots: u32,
246    },
247    /// The jobs need more than the cap, and the slice's `MemoryMax` does not hold one slot of what they need (under
248    /// `measured` admission, one runner beside the mirror): the slice has to grow first.
249    SliceTooSmall {
250        /// What the jobs need.
251        memory: u64,
252    },
253}
254
255impl Advice {
256    /// The `memory` and `slots` to write, when they differ from the profile's.
257    pub fn change(&self) -> Option<Resize> {
258        match *self {
259            Advice::Lower { memory, slots } | Advice::Raise { memory, slots } => Some(Resize {
260                memory,
261                slots,
262                cpus: None,
263            }),
264            Advice::TooFew { .. } | Advice::Keep { .. } | Advice::SliceTooSmall { .. } => None,
265        }
266    }
267}
268
269/// A profile's new `memory`, `slots` and, when auto sizing changed them, `cpus`.
270#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
271pub struct Resize {
272    /// Bytes.
273    pub memory: u64,
274    /// Slots.
275    pub slots: u32,
276    /// CPUs per slot; `None` leaves them as they are, as advice does and as auto sizing's changes recorded before it
277    /// changed them.
278    #[serde(default, skip_serializing_if = "Option::is_none")]
279    pub cpus: Option<u32>,
280}
281
282impl AutoPlan {
283    /// Its rules in words, as clients say them after `runnerd`: `looks every 5 minutes, raises a profile at most
284    /// once every 1 hour and lowers it at most once every 24 hours, moving its memory and CPUs by at most 25% at a
285    /// time`.
286    pub fn rules(&self) -> String {
287        if self.raise_interval == 0 || self.raise_interval >= self.interval {
288            return format!(
289                "looks every {} and changes a profile at most once every {}, moving its memory by at most {}% at a \
290                 time",
291                period(self.every),
292                period(self.interval),
293                self.max_step
294            );
295        }
296        format!(
297            "looks every {}, raises a profile at most once every {} and lowers it at most once every {}, moving its \
298             memory and CPUs by at most {}% at a time",
299            period(self.every),
300            period(self.raise_interval),
301            period(self.interval),
302            self.max_step
303        )
304    }
305}
306
307/// A setting's length in words, as a config's periods read: `5 minutes`, `24 hours`, `90 s`.
308pub fn period(seconds: u64) -> String {
309    let plural = |count: u64, unit: &str| {
310        if count == 1 {
311            format!("{count} {unit}")
312        } else {
313            format!("{count} {unit}s")
314        }
315    };
316    match seconds {
317        0 => "0 s".to_owned(),
318        _ if seconds.is_multiple_of(3600) => plural(seconds / 3600, "hour"),
319        _ if seconds.is_multiple_of(60) => plural(seconds / 60, "minute"),
320        _ => format!("{seconds} s"),
321    }
322}
323
324impl SizingChange {
325    /// What it changed, such as `memory 9G → 6.75G, slots 2`, and `cpus 12 → 15` when it changed them.
326    pub fn line(&self) -> String {
327        let memory = if self.from.memory == self.to.memory {
328            format!("memory {}", ByteSize(self.to.memory))
329        } else {
330            format!(
331                "memory {} → {}",
332                ByteSize(self.from.memory),
333                ByteSize(self.to.memory)
334            )
335        };
336        let slots = if self.from.slots == self.to.slots {
337            format!("slots {}", self.to.slots)
338        } else {
339            format!("slots {} → {}", self.from.slots, self.to.slots)
340        };
341        let cpus = match (self.from.cpus, self.to.cpus) {
342            (Some(from), Some(to)) if from != to => format!(", cpus {from} → {to}"),
343            _ => String::new(),
344        };
345        if self.uncertain {
346            format!("{memory}, {slots}{cpus} (may not have been written)")
347        } else {
348            format!("{memory}, {slots}{cpus}")
349        }
350    }
351}
352
353impl Sizing {
354    /// One line on what to do with a profile and why, as `runnerctl sizing`, the dashboard and `runnerd doctor`
355    /// say it, such as `lower memory to 2.5G from 7G, its largest peak + 15%; 5 slots fit in the same 14G`.
356    /// Under `measured` admission, when jobs wanted more slots, it adds that `slots` is not bought with caps there, or
357    /// with auto sizing on, that it adds them.
358    pub fn advice_line(&self, profile: &ProfileSizing) -> String {
359        let line = self.memory_line(profile);
360        if self.admission == AdmissionPolicy::Measured
361            && profile.wants_slots
362            && !matches!(profile.advice, Advice::TooFew { .. })
363        {
364            let then = if self.auto {
365                "auto sizing adds one at a time while every profile's slots fit the slice at their jobs' peaks"
366            } else {
367                "measured admission reserves predicted peaks, not caps, so more slots may fit: raise slots by hand"
368            };
369            format!(
370                "{line}; jobs waited {}s for a slot (p95) and slots were busy {}%: {then}",
371                profile.wait.p95, profile.busy
372            )
373        } else {
374            line
375        }
376    }
377
378    /// `advice_line` without what it says about slots under measured admission.
379    pub(crate) fn memory_line(&self, profile: &ProfileSizing) -> String {
380        let size = |bytes: u64| ByteSize(bytes).to_string();
381        let peaks = &profile.peaks;
382        let need = self.need_reason(peaks);
383        let at_cap = format!(
384            "{} of {} jobs ran out of memory at their cap",
385            peaks.at_cap, peaks.jobs
386        );
387        match profile.advice {
388            Advice::TooFew { jobs } => format!(
389                "{jobs} jobs, too few to advise on (it takes {}); largest peak {} of a {} cap",
390                self.min_jobs,
391                size(peaks.memory.max),
392                size(profile.memory)
393            ),
394            Advice::Keep { .. } if peaks.at_cap > 0 => format!(
395                "keep {}: {at_cap}, so they may need more than they show",
396                size(profile.memory)
397            ),
398            Advice::Keep { memory } => {
399                format!("keep {}: {need} is {}", size(profile.memory), size(memory))
400            }
401            Advice::Lower { memory, slots } => {
402                let share = profile.memory * u64::from(profile.slots);
403                if self.admission == AdmissionPolicy::Measured {
404                    return format!(
405                        "lower memory to {} from {}, {need}",
406                        size(memory),
407                        size(profile.memory)
408                    );
409                }
410                let then = if slots > profile.slots {
411                    format!("{slots} slots fit in the same {}", size(share))
412                } else {
413                    format!(
414                        "frees {} of the budget",
415                        size(share - memory * u64::from(slots))
416                    )
417                };
418                format!(
419                    "lower memory to {} from {}, {need}; {then}",
420                    size(memory),
421                    size(profile.memory)
422                )
423            }
424            Advice::Raise { memory, slots } => {
425                let why = if peaks.at_cap > 0 {
426                    at_cap
427                } else {
428                    format!("{need} is above the {} cap", size(profile.memory))
429                };
430                let slots = if slots < profile.slots {
431                    format!("; {slots} of its {} slots fit the slice", profile.slots)
432                } else {
433                    String::new()
434                };
435                format!("raise memory to {}: {why}{slots}", size(memory))
436            }
437            Advice::SliceTooSmall { memory } => format!(
438                "needs {memory_needed} ({need}), more than the slice holds for one slot: raise the slice's \
439                 MemoryMax first",
440                memory_needed = size(memory)
441            ),
442        }
443    }
444}
445
446// The wire format is JSON, which only the host and client features read.
447#[cfg(all(test, any(feature = "host", feature = "client")))]
448mod tests;