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, ByteSize, 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 /// How much of its wait passed while no runnerd ran, in ms.
78 pub unseen: u64,
79 /// The periods of its CPU quota it had work in (`api::JobMetrics::cpu_periods`); `None` where the kernel kept no
80 /// figure, as in runs from before schema 17.
81 pub cpu_periods: Option<u64>,
82 /// Of those, the periods its quota throttled it in (`api::JobMetrics::cpu_throttled`).
83 pub cpu_throttled: Option<u64>,
84}
85
86/// A job's wait for a runner as sizing, insights and the history's figures count it: from when GitHub queued it, or
87/// from when the history holds every job if that came later (`history_kept`), as for a job queued before runnerd
88/// first ran, to when it started, less what of it passed while no runnerd ran (ADR 0081). A job's own page shows its
89/// whole wait, as GitHub's does; arrivals, as `simulate` and warm runners model them, go by `queued_at`.
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub struct Wait {
92 /// When GitHub queued it, in ms.
93 pub queued_at: u64,
94 /// When it started, in ms.
95 pub started_at: u64,
96 /// How much of it passed while no runnerd ran, in ms.
97 pub unseen: u64,
98}
99
100impl Wait {
101 /// In ms, 0 at least, with the history holding every job since `kept_since` (ms).
102 pub fn counted(self, kept_since: u64) -> u64 {
103 self.started_at
104 .saturating_sub(self.queued_at.max(kept_since))
105 .saturating_sub(self.unseen)
106 }
107}
108
109/// A run its CPU quota throttled in this share of its run or more, in percent, was held back by its cap: it ran as
110/// fast as the cap let it, so its average says what the cap allowed. No lowering reads it, under `measured`
111/// admission it raises the cap, and insights name its job (ADR 0079). The share is of the run's wall time in 100 ms
112/// periods, not of the periods the kernel counted, which leave out the time it was idle: a job that waits on the
113/// network for most of its run and bursts past its cap in a few compiles is throttled in most of its busy periods and
114/// in little of its run. A throttled period loses only part of its 100 ms, so the share is more than the time the cap
115/// cost. The Android quality gate lost about 90 s of its 517 at 9 CPUs, 17% of its run, and was throttled in 28% of
116/// it, 21% at 13 and 16% at 19; an 8-minute job whose three 20-second compiles want 20 CPUs is throttled in 11%, and
117/// lost about 6%.
118pub const HELD: u64 = 15;
119
120/// What a run's CPU quota did to it, as auto sizing and insights read it (ADR 0079). Times in milliseconds.
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub struct Throttling {
123 /// When it started.
124 pub started_at: Option<u64>,
125 /// When it finished.
126 pub finished_at: Option<u64>,
127 /// The periods of its CPU quota it had work in (`api::JobMetrics::cpu_periods`); `None` where the kernel kept no
128 /// figure, as in runs from before schema 17.
129 pub periods: Option<u64>,
130 /// Of those, the periods its quota throttled it in (`api::JobMetrics::cpu_throttled`).
131 pub throttled: Option<u64>,
132}
133
134impl Throttling {
135 /// How long it ran, from its start to its finish; `None` without either.
136 pub fn took(self) -> Option<u64> {
137 Some(self.finished_at?.saturating_sub(self.started_at?))
138 }
139
140 /// The share of its run its quota throttled it in, per mille: its throttled periods over its run's wall time in
141 /// 100 ms periods, or over the periods the kernel counted when those are more, as when its start or finish is
142 /// unknown. `None` without a throttling figure.
143 pub fn share(self) -> Option<u64> {
144 let (periods, throttled) = self.periods.zip(self.throttled)?;
145 let run = self.took().map_or(0, |took| took / 100).max(periods);
146 Some(throttled.saturating_mul(1000) / run.max(1))
147 }
148
149 /// Whether its cap held it back: throttled in `HELD` percent of its run or more. `None` without a throttling
150 /// figure: unknown, never read as free.
151 pub fn held(self) -> Option<bool> {
152 let share = self.share()?;
153 Some(self.throttled.is_some_and(|throttled| throttled > 0) && share >= HELD * 10)
154 }
155}
156
157/// What a run's sampled memory counts.
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159pub enum Measure {
160 /// `memory.current` less `inactive_file`, as runners started before schema version 8 were sampled: page cache
161 /// read twice (`active_file`) counts, so peaks overstate what a job needs.
162 WithActiveFile,
163 /// `memory.current` less the file LRU lists (`active_file`, `inactive_file`): an estimate of what a job holds
164 /// without the page cache the kernel can drop.
165 WithoutPageCache,
166}
167
168/// What a run says about its container's memory cap (ADR 0070).
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub enum Capped {
171 /// The container's own limit failed reclaim: it needed more than the cap.
172 Met,
173 /// Recorded without the local counter: by the reading before it, a kill or a limit hit in the container, or
174 /// without events a peak within `AT_CAP` percent of the cap. Holds and floors as `Met`, never raises a cap.
175 Assumed,
176 /// A process in it was killed for memory while its own limit held: the slice or the host ran out.
177 Killed,
178 /// None of those. A peak near the cap with no `oom` at it is clear: a JVM fills the room it has.
179 Clear,
180}
181
182impl Capped {
183 /// Whether it says the job needed its cap: `Met` or `Assumed`.
184 pub fn met(self) -> bool {
185 matches!(self, Capped::Met | Capped::Assumed)
186 }
187
188 /// Whether it puts its job on its cap: anything but `Clear`.
189 pub fn holds(self) -> bool {
190 self != Capped::Clear
191 }
192}
193
194impl Ran {
195 /// Its wait, once it started.
196 pub fn wait(&self) -> Option<Wait> {
197 Some(Wait {
198 queued_at: self.queued_at,
199 started_at: self.started_at?,
200 unseen: self.unseen,
201 })
202 }
203
204 /// What its CPU quota did to it.
205 pub fn throttling(&self) -> Throttling {
206 Throttling {
207 started_at: self.started_at,
208 finished_at: self.finished_at,
209 periods: self.cpu_periods,
210 throttled: self.cpu_throttled,
211 }
212 }
213
214 /// What it says about its container's `cap`. A kill that only a descendant's own limit explains, the counters
215 /// showing a limit hit below the container and none at it, is a service container the job capped itself: clear.
216 /// A kill no sample saw an `oom` before, its last sample within `AT_CAP` percent of the cap, met it in the last
217 /// interval.
218 pub fn capped(&self, cap: u64) -> Capped {
219 match self.own_cap {
220 Some(true) => Capped::Met,
221 // No sample saw `oom` at any level and its last came near the cap: its own limit killed it before the
222 // next sample could count it.
223 Some(false)
224 if self.oom_killed
225 && self.hit_cap == Some(false)
226 && self.memory_peak.saturating_mul(100) >= cap.saturating_mul(AT_CAP) =>
227 {
228 Capped::Met
229 }
230 Some(false) if self.oom_killed && self.hit_cap != Some(true) => Capped::Killed,
231 None if self.oom_killed
232 || self.hit_cap.unwrap_or_else(|| {
233 self.memory_peak.saturating_mul(100) >= cap.saturating_mul(AT_CAP)
234 }) =>
235 {
236 Capped::Assumed
237 }
238 Some(false) | None => Capped::Clear,
239 }
240 }
241}
242
243/// One runner container's time in a slot for a job. Times in milliseconds.
244#[derive(Debug, Clone, PartialEq, Eq)]
245pub struct Held {
246 /// Its profile.
247 pub profile: String,
248 /// When it started holding the slot for a job: its start, or when its job was queued if that came later, as for
249 /// a warm runner.
250 pub started_at: u64,
251 /// When it was removed; `None` while it runs.
252 pub removed_at: Option<u64>,
253}
254
255/// A profile's `cpus` as the daemon ran it from `at` (ms), by its `profile.changed` event: one when it started with
256/// the profile, and after each reload or restart that changed the profile's image, CPUs, memory or slots.
257#[derive(Debug, Clone, PartialEq, Eq)]
258pub struct CpusSet {
259 /// The profile.
260 pub profile: String,
261 /// Its `cpus` from then.
262 pub cpus: u32,
263 /// When, in milliseconds.
264 pub at: u64,
265}
266
267/// A profile's `memory` as the daemon ran it from `at` (ms), by its `profile.changed` event, as `CpusSet` has its
268/// `cpus`.
269#[derive(Debug, Clone, PartialEq, Eq)]
270pub struct MemorySet {
271 /// The profile.
272 pub profile: String,
273 /// Its `memory` from then, in bytes.
274 pub memory: u64,
275 /// When, in milliseconds.
276 pub at: u64,
277}
278
279/// What the store reads for sizing.
280#[derive(Debug, Clone, Default, PartialEq, Eq)]
281pub struct History {
282 /// Finished jobs with a recorded peak, cancelled ones left out.
283 pub jobs: Vec<Ran>,
284 /// Cancelled jobs, for what admission learns from how they ended: a kill for memory, a peak at the cap or past
285 /// what was reserved. Their peaks (0 when never sampled) are not read as a job's size.
286 pub cancelled: Vec<Ran>,
287 /// Runners that held a slot at some point after the history's start.
288 pub runners: Vec<Held>,
289 /// Auto sizing's changes, oldest first, from `CHANGES_READ` before now: what a revert reads (ADR 0070). Empty
290 /// where nothing reads them, as for admission.
291 pub changes: Vec<api::SizingChange>,
292 /// Each profile's `memory` as the daemon ran it, oldest first: since when a raise reads runs at it.
293 pub memory_set: Vec<MemorySet>,
294 /// From when, in ms, the history holds every job (`history_kept`): a wait before it, as of a job queued before
295 /// runnerd first ran, counts from then.
296 pub kept_since: u64,
297}
298
299/// What `advise` sizes against besides the history.
300#[derive(Debug, Clone, Copy)]
301pub struct Window {
302 /// The start asked for, in milliseconds, at most `now`.
303 pub since: u64,
304 /// Now, in milliseconds.
305 pub now: u64,
306 /// Seconds between two samples of a container.
307 pub sample_interval: u64,
308}
309
310impl Window {
311 /// The window `GET /v1/sizing` reads: from `since` (seconds), default 30 days before `now` (seconds), and
312 /// never after `now`.
313 pub fn new(since: Option<u64>, now: u64) -> Window {
314 Window {
315 since: since
316 .unwrap_or_else(|| now.saturating_sub(30 * 24 * 3600))
317 .min(now)
318 .saturating_mul(1000),
319 now: now.saturating_mul(1000),
320 sample_interval: SAMPLE_INTERVAL.as_secs(),
321 }
322 }
323}
324
325/// The advice for every profile of `config` from `history`, against the slice's `memory_max` as `config`'s
326/// admission policy budgets it. Peaks, and the memory advice, go by each job's sizing window over the history's last
327/// 30 days (`memory`, ADR 0070); `window.since` narrows only the waits, the busy share and the starts.
328pub fn advise(
329 config: &Config,
330 memory_max: Option<u64>,
331 history: &History,
332 window: Window,
333) -> api::Sizing {
334 let since = first_runner(history, window.since);
335 let caps = config.memory_caps().map_or(u64::MAX, |caps| caps.0);
336 let mirror = config.mirror_memory();
337 let rules = &config.sizing;
338 let recent = memory::windows(config, history, window.now);
339 let ceiling = Bound::ceiling(config);
340 let profiles = config
341 .profiles
342 .iter()
343 .map(|(name, profile)| {
344 let jobs: Vec<&Ran> = history
345 .jobs
346 .iter()
347 .filter(|job| job.profile == *name && job.queued_at >= window.since)
348 .collect();
349 let share = profile.memory.0.saturating_mul(u64::from(profile.slots));
350 let busy = busy(history, name, profile.slots, since, window.now);
351 let wait = waits(&jobs, history.kept_since);
352 let starts = starts(&jobs, history.kept_since);
353 let cap = profile.memory.0;
354 let took = memory::took(&history.memory_set, name, cap, window.now);
355 let sized = Sized {
356 cap,
357 cpus: u64::from(profile.cpus) * 1000,
358 slots: profile.slots,
359 share,
360 admission: config.host.admission,
361 room: memory_max.map(|max| match config.host.admission {
362 // What the slice leaves this profile once the other profiles and the mirror took theirs.
363 Admission::Caps => max.saturating_sub(caps.saturating_sub(share)),
364 // Measured admission reserves predicted peaks, not caps: the config check only holds one
365 // runner of each profile beside the mirror.
366 Admission::Measured => max.saturating_sub(mirror),
367 }),
368 wants_slots: wait.p95 >= WAITED || busy >= BUSY,
369 min_jobs: rules.min_jobs,
370 upper: upper(
371 ceiling,
372 Bound::of(profile.max_memory, api::MemoryBound::MaxMemory),
373 ),
374 lower: Bound::of(profile.min_memory, api::MemoryBound::MinMemory),
375 max_slots: profile.max_slots.unwrap_or(u32::MAX),
376 };
377 let raises = Raises {
378 history,
379 recent: &recent,
380 profile: name,
381 cap,
382 took,
383 margin: rules.margin,
384 };
385 let memory = job_memory(&raises, &jobs, &sized, window.now, busy);
386 let peaks = memory::peaks(
387 recent.jobs_of(name).flat_map(|(_, runs)| runs.window()),
388 memory.on_cap,
389 sized.cpus,
390 );
391 let current = api::Resize {
392 memory: cap,
393 slots: profile.slots,
394 cpus: None,
395 };
396 let revert = memory::revert(config, history, name, current);
397 let advised = if let Some((_, to)) = &revert {
398 sized.reverted(*to)
399 } else {
400 let needs = Needs {
401 raise: raises.need(None),
402 floor: memory.floor.max(memory::revert_floor(history, name)),
403 };
404 sized.advice(&peaks, needs, sized.wants_slots)
405 };
406 api::ProfileSizing {
407 name: name.clone(),
408 memory: cap,
409 cpus: profile.cpus,
410 slots: profile.slots,
411 advice: advised.advice,
412 revert: revert.map(|(revert, _)| revert),
413 hold: advised.hold,
414 peaks,
415 wait,
416 starts,
417 busy,
418 wants_slots: sized.wants_slots,
419 jobs: memory.jobs,
420 }
421 })
422 .collect();
423 api::Sizing {
424 since: since / 1000,
425 until: window.now / 1000,
426 margin: rules.margin,
427 sample_interval: window.sample_interval,
428 min_jobs: rules.min_jobs,
429 memory_max,
430 admission: config.host.admission.policy(),
431 profiles,
432 auto: config.sizing.auto,
433 changes: Vec::new(),
434 auto_plan: None,
435 }
436}
437
438/// The bound of a raise: the lower of `ceiling` and `max_memory`, the ceiling when they are the same, since
439/// raising `max_memory` alone would not let a raise past it.
440fn upper(ceiling: Option<Bound>, max_memory: Option<Bound>) -> Option<Bound> {
441 match (ceiling, max_memory) {
442 (Some(ceiling), Some(max)) if max.memory < ceiling.memory => Some(max),
443 (ceiling, max) => ceiling.or(max),
444 }
445}
446
447/// What a raise of one profile reads (`memory::raise_need`).
448struct Raises<'history> {
449 history: &'history History,
450 recent: &'history Recent,
451 profile: &'history str,
452 /// Its `memory`.
453 cap: u64,
454 /// Since when it has had it, in ms.
455 took: u64,
456 margin: u32,
457}
458
459impl Raises<'_> {
460 /// What a raise needs from the job `key`, or from every job for `None`.
461 fn need(&self, key: Option<&Key>) -> u64 {
462 memory::raise_need(
463 self.history,
464 self.recent,
465 self.profile,
466 self.cap,
467 self.took,
468 self.margin,
469 key,
470 )
471 }
472}
473
474/// What a profile's jobs say about its `memory`.
475struct JobMemory {
476 /// Each job's sizing.
477 jobs: Vec<api::JobSizing>,
478 /// How many of them are on their cap.
479 on_cap: u64,
480 /// The largest of their floors.
481 floor: u64,
482}
483
484/// Each job of `raises.profile` with runs in its window: its peaks, waits and advice; `jobs` are the profile's runs
485/// since the window's start, for the waits.
486fn job_memory(raises: &Raises<'_>, jobs: &[&Ran], sized: &Sized, now: u64, busy: u32) -> JobMemory {
487 let mut on_cap = 0;
488 let mut floor = 0;
489 let sizings = raises
490 .recent
491 .jobs_of(raises.profile)
492 .filter(|(_, runs)| runs.runs() > 0)
493 .map(|(key, runs)| {
494 let held = memory::on_cap(runs, now);
495 on_cap += u64::from(held);
496 let peaks = memory::peaks(runs.window(), u64::from(held), sized.cpus);
497 let needs = Needs {
498 raise: raises.need(Some(key)),
499 floor: memory::floor(runs, raises.margin),
500 };
501 floor = floor.max(needs.floor);
502 let runs_of: Vec<&Ran> = jobs
503 .iter()
504 .copied()
505 .filter(|job| Key::of(job) == *key)
506 .collect();
507 let wait = waits(&runs_of, raises.history.kept_since);
508 // A job's advice says what it needs; only its profile's is bounded by what can be written.
509 let unbounded = Sized {
510 upper: None,
511 lower: None,
512 ..*sized
513 };
514 api::JobSizing {
515 repository: key.repository.clone(),
516 workflow: key.workflow.clone(),
517 name: key.name.clone(),
518 advice: unbounded
519 .advice(&peaks, needs, wait.p95 >= WAITED || busy >= BUSY)
520 .advice,
521 peaks,
522 wait,
523 }
524 })
525 .collect();
526 JobMemory {
527 jobs: sizings,
528 on_cap,
529 floor,
530 }
531}
532
533/// Where a history read from `start` (ms) begins: at its first runner when that started later, as a new daemon's
534/// history does.
535fn first_runner(history: &History, start: u64) -> u64 {
536 history
537 .runners
538 .iter()
539 .map(|runner| runner.started_at)
540 .min()
541 .map_or(start, |first| first.max(start))
542}
543
544/// The percent of the time from `since` to `now` (ms) that the profile's runners held its `slots`.
545fn busy(history: &History, profile: &str, slots: u32, since: u64, now: u64) -> u32 {
546 let span = now.saturating_sub(since).max(1);
547 let held: u64 = history
548 .runners
549 .iter()
550 .filter(|runner| runner.profile == profile)
551 .map(|runner| {
552 let end = runner.removed_at.unwrap_or(now).min(now);
553 end.saturating_sub(runner.started_at.max(since))
554 })
555 .sum();
556 u32::try_from(
557 (held.saturating_mul(100) / span.saturating_mul(u64::from(slots).max(1))).min(100),
558 )
559 .unwrap_or(100)
560}
561
562/// A profile's limits and the rules advice follows.
563#[derive(Clone, Copy)]
564struct Sized {
565 cap: u64,
566 /// Its `cpus`, in millicores: CPU peaks are read only of runs at them.
567 cpus: u64,
568 slots: u32,
569 /// What its slots take of the budget now: `memory × slots`.
570 share: u64,
571 admission: Admission,
572 /// The memory the slice holds for it, as `admission` budgets it: all its slots at their caps under `caps`, one
573 /// runner under `measured`; `None` for an unlimited slice.
574 room: Option<u64>,
575 /// Whether its jobs waited for a slot at p95, or its slots were busy, enough to want more.
576 wants_slots: bool,
577 min_jobs: u32,
578 /// The most `memory` a raise goes to: what `[host] memory_ceiling` leaves one runner (`Config::runner_ceiling`)
579 /// down to a granule, or `max_memory` when that is less; `None` without either.
580 upper: Option<Bound>,
581 /// The least `memory` a lowering goes to, `min_memory`.
582 lower: Option<Bound>,
583 /// The most `slots` a lowering or a revert gives it, `max_slots`: the config check refuses more.
584 max_slots: u32,
585}
586
587/// A bound of the config on a profile's `memory`: the config check refuses a profile past it.
588#[derive(Clone, Copy)]
589struct Bound {
590 memory: u64,
591 by: api::MemoryBound,
592}
593
594impl Bound {
595 /// What `[host] memory_ceiling` leaves one runner (`Config::runner_ceiling`), down to a granule so the config
596 /// file says it exactly and the check never reads more back.
597 fn ceiling(config: &Config) -> Option<Bound> {
598 let most = config.runner_ceiling()?;
599 Some(Bound {
600 memory: most / GRANULE * GRANULE,
601 by: api::MemoryBound::Ceiling {
602 ceiling: config.host.memory_ceiling?.0,
603 mirror: config.mirror_memory(),
604 },
605 })
606 }
607
608 /// A profile's `size` as the bound `by`.
609 fn of(size: Option<ByteSize>, by: api::MemoryBound) -> Option<Bound> {
610 size.map(|size| Bound { memory: size.0, by })
611 }
612}
613
614/// A profile's advice, and the bound that holds its `memory` away from what its jobs need.
615struct Advised {
616 advice: Advice,
617 hold: Option<api::MemoryHold>,
618}
619
620impl From<Advice> for Advised {
621 fn from(advice: Advice) -> Advised {
622 Advised { advice, hold: None }
623 }
624}
625
626/// What a set of jobs' runs say its `memory` needs (`memory`, ADR 0070).
627#[derive(Debug, Clone, Copy)]
628struct Needs {
629 /// What a raise goes to: from runs that met the current cap since the profile took it; 0 without one.
630 raise: u64,
631 /// What a lowering stays at or above: every windowed run's need, and any revert's floor.
632 floor: u64,
633}
634
635impl Sized {
636 /// A raise toward `needs.raise` when it is above the cap; a lowering toward `needs.floor`, no further than
637 /// `min_memory`, when that saves a tenth and no job is on its cap; else keep, with `needs.floor` as what the jobs
638 /// need, above the cap or not.
639 fn advice(&self, peaks: &Peaks, needs: Needs, wants_slots: bool) -> Advised {
640 if peaks.jobs < u64::from(self.min_jobs) {
641 return Advice::TooFew { jobs: peaks.jobs }.into();
642 }
643 if needs.raise > self.cap {
644 return self.raise(needs.raise, self.slots);
645 }
646 let need = needs.floor.max(GRANULE);
647 // A job on its cap may have been held back or killed by it: no lowering until it ran clear of it again.
648 if peaks.on_cap == 0
649 && need <= self.cap
650 && self.cap - need >= self.cap * WORTH_LOWERING / 100
651 {
652 let hold = self
653 .lower
654 .filter(|min| min.memory > need)
655 .map(|min| api::MemoryHold {
656 need,
657 bound: min.memory,
658 by: min.by,
659 });
660 let memory = hold.map_or(need, |hold| hold.bound);
661 if memory >= self.cap {
662 return Advised {
663 advice: Advice::Keep { memory: need },
664 hold,
665 };
666 }
667 let fit = |room: u64| u32::try_from(room / memory).unwrap_or(u32::MAX);
668 // Under measured admission slots are not bought with caps: the advice line says when more may help.
669 let advice = Advice::Lower {
670 memory,
671 slots: if wants_slots && self.admission == Admission::Caps {
672 fit(self.share).min(self.max_slots).max(self.slots)
673 } else {
674 self.slots
675 },
676 };
677 return Advised { advice, hold };
678 }
679 Advice::Keep { memory: need }.into()
680 }
681
682 /// The raise that takes back a lowering that went too far, to `to`: as far as `[host] memory_ceiling` and
683 /// `max_memory` allow, which a reload may have lowered since, with as many of `to`'s slots as the slice and
684 /// `max_slots` hold now.
685 fn reverted(&self, to: api::Resize) -> Advised {
686 self.raise(to.memory, to.slots.min(self.max_slots))
687 }
688
689 /// A raise toward `need` with at most `slots`: no further than `[host] memory_ceiling` and `max_memory` allow,
690 /// since a raise the config check refuses would be proposed again at every look, and with the slots the slice
691 /// holds at that memory, as `admission` budgets it. None while the bound allows nothing past the cap or the slice
692 /// holds no slot: the jobs need `need`.
693 fn raise(&self, need: u64, slots: u32) -> Advised {
694 let hold = self
695 .upper
696 .filter(|most| need > most.memory)
697 .map(|most| api::MemoryHold {
698 need,
699 bound: most.memory,
700 by: most.by,
701 });
702 let memory = hold.map_or(need, |hold| hold.bound);
703 let too_small = Advised {
704 advice: Advice::SliceTooSmall { memory: need },
705 hold,
706 };
707 if memory <= self.cap {
708 return too_small;
709 }
710 let fit = |room: u64| u32::try_from(room / memory).unwrap_or(u32::MAX);
711 let slots = match (self.admission, self.room) {
712 (Admission::Caps, Some(room)) => fit(room).min(slots),
713 (Admission::Measured, Some(room)) if room < memory => 0,
714 (_, _) => slots,
715 };
716 if slots == 0 {
717 return too_small;
718 }
719 Advised {
720 advice: Advice::Raise { memory, slots },
721 hold,
722 }
723 }
724}
725
726/// The [waits](Wait) of the jobs that started, in seconds, less what they waited for the host's memory.
727fn waits(jobs: &[&Ran], kept_since: u64) -> Spread {
728 spread(
729 jobs.iter()
730 .filter_map(|job| {
731 job.wait()
732 .map(|wait| wait.counted(kept_since).saturating_sub(job.host_waited) / 1000)
733 })
734 .collect(),
735 )
736}
737
738/// The jobs that started on a warm runner and the others, and their median waits.
739fn starts(jobs: &[&Ran], kept_since: u64) -> api::Starts {
740 let (warm, cold): (Vec<&Ran>, Vec<&Ran>) = jobs
741 .iter()
742 .filter(|job| job.started_at.is_some())
743 .partition(|job| job.runner_started_at < job.queued_at);
744 let count = |jobs: &[&Ran]| u32::try_from(jobs.len()).unwrap_or(u32::MAX);
745 api::Starts {
746 warm: count(&warm),
747 warm_p50: waits(&warm, kept_since).p50,
748 cold: count(&cold),
749 cold_p50: waits(&cold, kept_since).p50,
750 }
751}
752
753/// Nearest-rank percentiles; all zero for no values.
754pub(crate) fn spread(mut values: Vec<u64>) -> Spread {
755 values.sort_unstable();
756 let rank = |percent: usize| {
757 let index = (values.len() * percent).div_ceil(100).saturating_sub(1);
758 values.get(index).copied().unwrap_or(0)
759 };
760 Spread {
761 p50: rank(50),
762 p95: rank(95),
763 p99: rank(99),
764 max: values.last().copied().unwrap_or(0),
765 }
766}
767
768pub mod auto;
769pub mod memory;
770
771#[cfg(test)]
772mod tests;