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