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    pub admission: AdmissionPolicy,
40    /// Every configured profile, by name.
41    pub profiles: Vec<ProfileSizing>,
42    /// Whether the daemon applies advice itself, `[sizing] auto`.
43    pub auto: bool,
44    /// The changes auto sizing made since `since`, oldest first.
45    pub changes: Vec<SizingChange>,
46    /// Under auto sizing, what it does next and when. `None` while it is off.
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub auto_plan: Option<AutoPlan>,
49}
50
51/// What auto sizing will do: its rules, the changes its next look would make as the history and config are now, and
52/// the profiles a recent change holds.
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct AutoPlan {
55    /// Seconds between two looks of the daemon's.
56    pub every: u64,
57    /// `[sizing] interval`: the least time between a change to one profile and one that lowers it, in seconds.
58    pub interval: u64,
59    /// `[sizing] raise_interval`: the least time between a change to one profile and one that only raises it, in
60    /// seconds.
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`.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub blocked: Option<String>,
73    /// The profiles whose jobs the CPU cap holds back and whose `cpus` the next look cannot raise, and why.
74    #[serde(default, skip_serializing_if = "Vec::is_empty")]
75    pub refused: Vec<SizingRefused>,
76}
77
78/// A raise of a profile's `cpus` its jobs ask for that auto sizing cannot make, as when it does not fit the CPU
79/// budget.
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81pub struct SizingRefused {
82    /// The profile.
83    pub profile: String,
84    /// Which job the cap holds back, and what keeps it from a raise.
85    pub reason: String,
86}
87
88/// A profile auto sizing changes nothing in before `until`, and lowers nothing in before `lower_until`.
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90pub struct SizingHold {
91    /// The profile.
92    pub profile: String,
93    /// When its last change was made.
94    pub changed: u64,
95    /// When it may be raised again, in seconds since the Unix epoch.
96    pub until: u64,
97    /// When it may be lowered again.
98    pub lower_until: u64,
99}
100
101impl SizingHold {
102    /// When it may be lowered again.
103    pub fn lowered_after(&self) -> u64 {
104        self.lower_until.max(self.until)
105    }
106}
107
108/// A profile's `memory` and `slots` as auto sizing changed them in the config file.
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110pub struct SizingChange {
111    /// When it was written.
112    pub at: u64,
113    /// The profile.
114    pub profile: String,
115    /// What they were: writing these back undoes it.
116    pub from: Resize,
117    /// What they are now.
118    pub to: Resize,
119    /// Why, as the advice said it then.
120    pub reason: String,
121    /// Whether it may not have been written: recorded before its file was written, and the config no longer said
122    /// whether it was when runnerd looked again. It still holds the interval, and `from` is still what it replaced.
123    pub uncertain: bool,
124}
125
126/// One profile: its limits now, its jobs' peaks and waits, and the advice.
127#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128pub struct ProfileSizing {
129    /// The profile.
130    pub name: String,
131    /// Its `memory` now: each container's hard limit.
132    pub memory: u64,
133    /// Its `cpus` now.
134    pub cpus: u32,
135    /// Its `slots` now.
136    pub slots: u32,
137    /// Its jobs' peaks.
138    pub peaks: Peaks,
139    /// Seconds from queued to started, leaving out the time before the history's start and the time no runnerd
140    /// ran (ADR 0081).
141    pub wait: Spread,
142    /// Its jobs by whether a warm runner took them, and how long each kind waited.
143    pub starts: Starts,
144    /// The percent of the time since `since` its slots held a runner for a job, from when the job was queued, over
145    /// its `slots` now.
146    pub busy: u32,
147    /// Whether its jobs waited a minute or more for a slot at p95, or its slots were busy half the time: more slots
148    /// would help.
149    pub wants_slots: bool,
150    /// What to set `memory` and `slots` to. Sized for its largest peak, so no job gets less than it used.
151    pub advice: Advice,
152    /// When the advice is to take back a lowering auto sizing made that went too far: what showed it.
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub revert: Option<SizingRevert>,
155    /// When a bound of the config holds the advice's `memory` away from what its jobs need: `[host]
156    /// memory_ceiling` or `max_memory` under it, `min_memory` over it (ADR 0086, 0088).
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub hold: Option<MemoryHold>,
159    /// Each job that ran in it, by repository, workflow and name.
160    pub jobs: Vec<JobSizing>,
161}
162
163/// A bound of the config holding a profile's `memory` away from what its jobs need: the config check refuses a
164/// profile past it, so the advice goes no further than `bound`, and auto sizing writes it as is (ADR 0086, 0088). Under
165/// a raise it says only that no raise past `bound` is possible, not that the jobs fit.
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
167pub struct MemoryHold {
168    /// What the jobs need, in bytes: the raise they ask for, the `memory` a revert goes back to, or the lowering's
169    /// floor.
170    pub need: u64,
171    /// The `memory` the advice goes to at most, or for a lowering at least.
172    pub bound: u64,
173    /// Which bound it is.
174    pub by: MemoryBound,
175}
176
177/// Which bound of the config holds a profile's `memory`.
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
179#[serde(rename_all = "kebab-case", tag = "kind")]
180pub enum MemoryBound {
181    /// `[host] memory_ceiling` less the mirror, down to a multiple of 256M so that the config file says it exactly:
182    /// the most one runner may have (ADR 0086).
183    Ceiling {
184        /// `[host] memory_ceiling`, in bytes.
185        ceiling: u64,
186        /// The mirror's memory beside it, 0 while the mirror is off.
187        mirror: u64,
188    },
189    /// The profile's `max_memory`.
190    MaxMemory,
191    /// The profile's `min_memory`.
192    MinMemory,
193}
194
195/// A lowering of a profile's `memory` by auto sizing that went too far, which the advice takes back (ADR 0070).
196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
197pub struct SizingRevert {
198    /// The `memory` it lowered to, in bytes.
199    pub from: u64,
200    /// The `memory` it lowered from, which the advice goes back to.
201    pub to: u64,
202    /// The job that showed it, as `owner/name workflow / job`.
203    pub job: String,
204    /// How.
205    pub cause: RevertCause,
206}
207
208/// What showed a lowering went too far.
209#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
210#[serde(rename_all = "kebab-case", tag = "kind")]
211pub enum RevertCause {
212    /// A run met the lowered cap.
213    Met,
214    /// The job, which succeeded before the lowering, failed this many times in a row at it, in different workflow
215    /// runs and on more than one branch: a heap sized from the cgroup's limit fails without the kernel's limit.
216    Failed {
217        /// How many.
218        runs: u32,
219    },
220}
221
222/// A profile's jobs by whether their runner was already up when GitHub queued them (ADR 0050).
223#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
224pub struct Starts {
225    /// Jobs that started on a warm runner: one that started before the job was queued.
226    pub warm: u32,
227    /// Their median wait from queued to started, in seconds.
228    pub warm_p50: u64,
229    /// Jobs whose runner started after they were queued.
230    pub cold: u32,
231    /// Their median wait, in seconds.
232    pub cold_p50: u64,
233}
234
235/// The jobs of one name in one workflow of one repository.
236#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237pub struct JobSizing {
238    /// `owner/name` on GitHub.
239    pub repository: String,
240    /// The workflow's name, when the history knew it.
241    pub workflow: Option<String>,
242    /// The job's name in the workflow.
243    pub name: String,
244    /// Its runs' peaks.
245    pub peaks: Peaks,
246    /// Seconds from queued to started, leaving out the time before the history's start and the time no runnerd
247    /// ran (ADR 0081).
248    pub wait: Spread,
249    /// What its profile's `memory` would be for this job alone, and the `slots` that would fit in the memory the
250    /// profile's slots take now.
251    pub advice: Advice,
252}
253
254/// The peaks of a set of jobs, each the highest of its samples.
255#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
256pub struct Peaks {
257    /// How many jobs: the number of peaks the percentiles are taken over.
258    pub jobs: u64,
259    /// Of those, how many met their container's memory cap: its own limit failed reclaim (for a run recorded
260    /// before that was told apart, a kill or a limit hit in the container, or without events a peak within 5% of it).
261    /// They may need more than they show.
262    pub at_cap: u64,
263    /// How many of their jobs are on their cap: one of their runs met it or was killed for memory, and fewer than 3
264    /// successful runs since were clear of it. No lowering while any is.
265    #[serde(default, skip_serializing_if = "is_zero")]
266    pub on_cap: u64,
267    /// Memory without page cache, in bytes.
268    pub memory: Spread,
269    /// CPU, in millicores, of the runs at the profile's `cpus` now: a run at a larger cap may have peaked past them.
270    pub cpu: Spread,
271    /// How many runs `cpu` is over: those of `jobs` at the profile's `cpus` now.
272    #[serde(default)]
273    pub cpu_runs: u64,
274}
275
276#[expect(
277    clippy::trivially_copy_pass_by_ref,
278    reason = "serde's skip_serializing_if passes a reference"
279)]
280fn is_zero(count: &u64) -> bool {
281    *count == 0
282}
283
284/// Percentiles of a set of values, by nearest rank: each is one of the values, and with fewer than 100 values
285/// `p99` is the largest.
286#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
287pub struct Spread {
288    /// The median.
289    pub p50: u64,
290    /// The 95th percentile.
291    pub p95: u64,
292    /// The 99th percentile.
293    pub p99: u64,
294    /// The largest.
295    pub max: u64,
296}
297
298/// What a cap keeps at least over the largest peak, for page cache: 1G. Peaks leave page cache out, and a container
299/// whose memory past them leaves the kernel less than about 500M of page cache to reclaim at its cap reclaims badly,
300/// which throttles its sockets and slows its downloads (ADR 0055).
301pub const PAGE_CACHE_ROOM: u64 = 1 << 30;
302
303/// What to set a profile's `memory` and `slots` to. `memory` is the largest sampled peak plus the margin, or plus
304/// `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
305/// the heaviest run, not a percentile.
306#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
307#[serde(rename_all = "kebab-case", tag = "kind")]
308pub enum Advice {
309    /// Fewer than `min_jobs` jobs: too few to advise on.
310    TooFew {
311        /// How many there are.
312        jobs: u64,
313    },
314    /// The cap fits, and lowering it would save less than a tenth or a run met its cap.
315    Keep {
316        /// What the jobs need.
317        memory: u64,
318    },
319    /// The cap is a tenth or more above what the jobs need, and no run met its cap.
320    Lower {
321        /// The new `memory`.
322        memory: u64,
323        /// The new `slots`: under `caps` admission, as many as fit in the memory the slots take now when jobs waited
324        /// for one; else the same.
325        slots: u32,
326    },
327    /// The jobs need more than the cap.
328    Raise {
329        /// The new `memory`.
330        memory: u64,
331        /// The new `slots`: the same, or under `caps` admission as many as the slice's `MemoryMax` still holds.
332        slots: u32,
333    },
334    /// The jobs need more than the cap, and the slice's `MemoryMax` does not hold one slot of what they need (under
335    /// `measured` admission, one runner beside the mirror): the slice has to grow first. Also when the cap is at
336    /// what `[host] memory_ceiling` or `max_memory` holds it to (`ProfileSizing::held`): that has to grow first.
337    SliceTooSmall {
338        /// What the jobs need.
339        memory: u64,
340    },
341}
342
343impl Advice {
344    /// The `memory` and `slots` to write, when they differ from the profile's.
345    pub fn change(&self) -> Option<Resize> {
346        match *self {
347            Advice::Lower { memory, slots } | Advice::Raise { memory, slots } => Some(Resize {
348                memory,
349                slots,
350                cpus: None,
351            }),
352            Advice::TooFew { .. } | Advice::Keep { .. } | Advice::SliceTooSmall { .. } => None,
353        }
354    }
355}
356
357/// A profile's new `memory`, `slots` and, when auto sizing changed them, `cpus`.
358#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
359pub struct Resize {
360    /// Bytes.
361    pub memory: u64,
362    /// Slots.
363    pub slots: u32,
364    /// CPUs per slot; `None` leaves them as they are, as advice does and as auto sizing's changes recorded before it
365    /// changed them.
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    pub cpus: Option<u32>,
368}
369
370impl AutoPlan {
371    /// Its rules in words, as clients say them after `runnerd`: `looks every 5 minutes, raises a profile at most
372    /// once every 1 hour and lowers it at most once every 24 hours, moving its memory and CPUs by at most 25% at a
373    /// time`.
374    pub fn rules(&self) -> String {
375        if self.raise_interval == 0 || self.raise_interval >= self.interval {
376            return format!(
377                "looks every {} and changes a profile at most once every {}, moving its memory by at most {}% at a \
378                 time",
379                period(self.every),
380                period(self.interval),
381                self.max_step
382            );
383        }
384        format!(
385            "looks every {}, raises a profile at most once every {} and lowers it at most once every {}, moving its \
386             memory and CPUs by at most {}% at a time",
387            period(self.every),
388            period(self.raise_interval),
389            period(self.interval),
390            self.max_step
391        )
392    }
393}
394
395/// A setting's length in words, as a config's periods read: `5 minutes`, `24 hours`, `90 s`.
396pub fn period(seconds: u64) -> String {
397    let plural = |count: u64, unit: &str| {
398        if count == 1 {
399            format!("{count} {unit}")
400        } else {
401            format!("{count} {unit}s")
402        }
403    };
404    match seconds {
405        0 => "0 s".to_owned(),
406        _ if seconds.is_multiple_of(3600) => plural(seconds / 3600, "hour"),
407        _ if seconds.is_multiple_of(60) => plural(seconds / 60, "minute"),
408        _ => format!("{seconds} s"),
409    }
410}
411
412impl Resize {
413    /// What going from `from` to these sizes changes, such as `memory 9G → 6.75G, slots 2`, with `cpus 12 → 15` when
414    /// both have CPUs and they differ; without `from`, these alone, such as `memory 6.75G, slots 2`.
415    pub fn line_from(&self, from: Option<&Resize>) -> String {
416        let memory = match from {
417            Some(from) if from.memory != self.memory => format!(
418                "memory {} → {}",
419                ByteSize(from.memory),
420                ByteSize(self.memory)
421            ),
422            _ => format!("memory {}", ByteSize(self.memory)),
423        };
424        let slots = match from {
425            Some(from) if from.slots != self.slots => {
426                format!("slots {} → {}", from.slots, self.slots)
427            }
428            _ => format!("slots {}", self.slots),
429        };
430        let cpus = match (from.and_then(|from| from.cpus), self.cpus) {
431            (Some(from), Some(to)) if from != to => format!(", cpus {from} → {to}"),
432            _ => String::new(),
433        };
434        format!("{memory}, {slots}{cpus}")
435    }
436}
437
438impl SizingChange {
439    /// What it changed, such as `memory 9G → 6.75G, slots 2`, and `cpus 12 → 15` when it changed them.
440    pub fn line(&self) -> String {
441        let line = self.to.line_from(Some(&self.from));
442        if self.uncertain {
443            format!("{line} (may not have been written)")
444        } else {
445            line
446        }
447    }
448}
449
450impl Sizing {
451    /// One line on what to do with a profile and why, as `runnerctl sizing`, the dashboard and `runnerd doctor`
452    /// say it, such as `lower memory to 2.5G from 7G, its largest peak + 15%; 5 slots fit in the same 14G`.
453    /// Under `measured` admission, when jobs wanted more slots, it adds that `slots` is not bought with caps there, or
454    /// with auto sizing on, that it adds them.
455    pub fn advice_line(&self, profile: &ProfileSizing) -> String {
456        let line = self.memory_line(profile);
457        if self.admission == AdmissionPolicy::Measured
458            && profile.wants_slots
459            && !matches!(profile.advice, Advice::TooFew { .. })
460        {
461            let then = if self.auto {
462                "auto sizing adds one at a time while every profile's slots fit the slice at their jobs' peaks"
463            } else {
464                "measured admission reserves predicted peaks, not caps, so more slots may fit: raise slots by hand"
465            };
466            format!(
467                "{line}; jobs waited {}s for a slot (p95) and slots were busy {}%: {then}",
468                profile.wait.p95, profile.busy
469            )
470        } else {
471            line
472        }
473    }
474
475    /// `advice_line` without what it says about slots under measured admission.
476    pub(crate) fn memory_line(&self, profile: &ProfileSizing) -> String {
477        let size = |bytes: u64| ByteSize(bytes).to_string();
478        let peaks = &profile.peaks;
479        let need = self.need_reason(peaks);
480        let at_cap = format!(
481            "{} of {} jobs ran out of memory at their cap",
482            peaks.at_cap, peaks.jobs
483        );
484        match profile.advice {
485            Advice::TooFew { jobs } => format!(
486                "{jobs} jobs, too few to advise on (it takes {}); largest peak {} of a {} cap",
487                self.min_jobs,
488                size(peaks.memory.max),
489                size(profile.memory)
490            ),
491            Advice::Keep { .. } if peaks.on_cap > 0 => format!(
492                "keep {}: {} of its jobs met their cap or were killed for memory, and fewer than 3 runs since ran \
493                 clear of it",
494                size(profile.memory),
495                peaks.on_cap
496            ),
497            Advice::Keep { memory } if memory > profile.memory => format!(
498                "keep {}: its recent runs need {}, but none is known to have run out of memory at {} since it was set",
499                size(profile.memory),
500                size(memory),
501                size(profile.memory)
502            ),
503            Advice::Keep { memory } => match profile.hold {
504                Some(hold) => format!(
505                    "keep {}, {}: {need} is {}",
506                    size(profile.memory),
507                    hold.bound_line(),
508                    size(memory)
509                ),
510                None => format!("keep {}: {need} is {}", size(profile.memory), size(memory)),
511            },
512            Advice::Lower { memory, slots } => {
513                let share = profile.memory * u64::from(profile.slots);
514                // `min_memory` holds it over what the jobs need: `lower memory to 6G from 8G, its min_memory: its
515                // largest peak + 15% is 4G`.
516                let need = match profile.hold {
517                    Some(hold) => format!("{}: {need} is {}", hold.bound_line(), size(hold.need)),
518                    None => need,
519                };
520                if self.admission == AdmissionPolicy::Measured {
521                    return format!(
522                        "lower memory to {} from {}, {need}",
523                        size(memory),
524                        size(profile.memory)
525                    );
526                }
527                let then = if slots > profile.slots {
528                    format!("{slots} slots fit in the same {}", size(share))
529                } else {
530                    format!(
531                        "frees {} of the budget",
532                        size(share - memory * u64::from(slots))
533                    )
534                };
535                format!(
536                    "lower memory to {} from {}, {need}; {then}",
537                    size(memory),
538                    size(profile.memory)
539                )
540            }
541            Advice::Raise { memory, .. } if let Some(revert) = &profile.revert => {
542                let held = match profile.hold {
543                    Some(hold) if memory < revert.to => format!(", {}", hold.bound_line()),
544                    _ => String::new(),
545                };
546                format!(
547                    "raise memory back to {}{held}: {}",
548                    size(memory),
549                    revert.why()
550                )
551            }
552            Advice::Raise { memory, slots } => {
553                let why = if peaks.at_cap > 0 {
554                    at_cap
555                } else {
556                    format!("{need} is above the {} cap", size(profile.memory))
557                };
558                let slots = if slots < profile.slots {
559                    format!("; {slots} of its {} slots fit the slice", profile.slots)
560                } else {
561                    String::new()
562                };
563                match profile.hold {
564                    Some(hold) => format!(
565                        "raise memory to {}, {}, short of the {} its jobs need: {why}{slots}",
566                        size(memory),
567                        hold.bound_line(),
568                        size(hold.need)
569                    ),
570                    None => format!("raise memory to {}: {why}{slots}", size(memory)),
571                }
572            }
573            Advice::SliceTooSmall { memory } => too_small_line(profile, memory, need),
574        }
575    }
576}
577
578/// The advice line of a profile whose jobs need `memory` and get no raise, with `need` how that comes from its
579/// peaks, or the revert that asks for it: a bound of the config holds it where it is (`ProfileSizing::held`), or the
580/// slice is too small.
581fn too_small_line(profile: &ProfileSizing, memory: u64, need: String) -> String {
582    let why = profile.revert.as_ref().map_or(need, SizingRevert::why);
583    if let Some(hold) = profile.held() {
584        let then = match hold.by {
585            MemoryBound::Ceiling { .. } => {
586                "raise [host] memory_ceiling if the host can grow further"
587            }
588            MemoryBound::MaxMemory | MemoryBound::MinMemory => "raise max_memory to give them more",
589        };
590        return format!(
591            "keep {}, {}: its jobs need {} ({why}); {then}",
592            ByteSize(profile.memory),
593            hold.bound_line(),
594            ByteSize(memory)
595        );
596    }
597    let then = profile
598        .hold
599        .map(|hold| {
600            format!(
601                "; {} then holds it at {}",
602                hold.by.name(),
603                ByteSize(hold.bound)
604            )
605        })
606        .unwrap_or_default();
607    format!(
608        "needs {} ({why}), more than the slice holds for one slot: raise the slice's MemoryMax first{then}",
609        ByteSize(memory)
610    )
611}
612
613impl MemoryHold {
614    /// What holds the `memory`, as the advice line says it after the `memory` it goes to: `the most the host's 24G
615    /// memory_ceiling leaves one runner beside the mirror's 1G`, `its max_memory` or `its min_memory`.
616    pub fn bound_line(&self) -> String {
617        match self.by {
618            MemoryBound::Ceiling { ceiling, mirror: 0 } => format!(
619                "the most the host's {} memory_ceiling leaves one runner",
620                ByteSize(ceiling)
621            ),
622            MemoryBound::Ceiling { ceiling, mirror } => format!(
623                "the most the host's {} memory_ceiling leaves one runner beside the mirror's {}",
624                ByteSize(ceiling),
625                ByteSize(mirror)
626            ),
627            MemoryBound::MaxMemory => "its max_memory".to_owned(),
628            MemoryBound::MinMemory => "its min_memory".to_owned(),
629        }
630    }
631}
632
633impl MemoryBound {
634    /// The setting, as the config names it: `[host] memory_ceiling`, `max_memory` or `min_memory`.
635    pub fn name(self) -> &'static str {
636        match self {
637            MemoryBound::Ceiling { .. } => "[host] memory_ceiling",
638            MemoryBound::MaxMemory => "max_memory",
639            MemoryBound::MinMemory => "min_memory",
640        }
641    }
642}
643
644impl SizingRevert {
645    /// What showed the lowering went too far, as the advice line says it: `halyard/ledger CI / test met the 10G cap
646    /// since auto sizing lowered it from 14G`.
647    fn why(&self) -> String {
648        let how = match self.cause {
649            RevertCause::Met => format!("met the {} cap", ByteSize(self.from)),
650            RevertCause::Failed { runs } => {
651                format!("failed {runs} times in a row at {}", ByteSize(self.from))
652            }
653        };
654        format!(
655            "{} {how} since auto sizing lowered it from {}",
656            self.job,
657            ByteSize(self.to)
658        )
659    }
660}