1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
//! Admission: what a new runner reserves of the slice's budget. By caps, its profile's memory. Measured, the
//! largest predicted peak of its repository's queued jobs (`admission::Predictor`, from the job history, read at
//! most once a minute), since GitHub may give the runner any of them; the cap while the slice's memory has no
//! recent sample; and nothing starts while the slice is at `admission::HIGH_WATER` percent of its `MemoryMax`. A
//! job queued twice, queued or running beside a copy, or in a repository with a busy runner whose job is not known
//! yet, is predicted with `admission::Copies::Several`.
//! Under `[host] cpu_overcommit`, a new runner also reserves CPU: its profile's `cpus`, or measured the largest
//! predicted average CPU of its repository's queued jobs, then its own job's once known.
//! Under either policy a new runner also fits what the host's memory leaves the slice beside its other programs
//! (`admission::host`), and nothing starts while the host stalls for memory; running runners are never stopped for
//! it. The spans in which that held a job back go into the history, so sizing does not read them as waits for a
//! slot.
//! Under either policy the same predictor gives each pool and each running runner its usual run time, which says what
//! may start behind a barrier (ADR 0097).
//! Measured, what runs counts as `admission::pooled` adds it up (ADR 0099).
//! It reads the store and the latest host sample and reading; it never writes the config.
use std::collections::{BTreeMap, BTreeSet};
use std::time::{Duration, SystemTime};
use tracing::{info, warn};
use super::Engine;
use crate::admission::{Copies, HIGH_WATER, Key, Prediction, Predictor, host};
use crate::api::{self, AdmissionPolicy, Basis};
use crate::config::Admission;
use crate::docker::DockerApi;
use crate::github::{GithubApi, QueuedJob};
use crate::observe::metrics::SAMPLE_INTERVAL;
use crate::scheduler::{
Barrier, Decision, Demand, Pool, Repository, Scarce, StopReason, Waits, matches,
};
use crate::time;
/// How often the predictor reads the job history again.
const REREAD: Duration = Duration::from_secs(60);
/// How far back it reads, in milliseconds: 30 days.
const HISTORY: u64 = 30 * 24 * 3600 * 1000;
/// What admission keeps between plans.
#[derive(Debug, Default)]
pub(super) struct Measured {
/// What the last plan saw of the host's memory.
pub host: host::Remembered,
/// The jobs the last plan had waiting for the host's memory, and when (ms): each waited since then.
host_waiting: (BTreeSet<u64>, u64),
/// The jobs the last plan had waiting only for a slot (`Plan::slot_waiting`), and when (ms): each waited since.
slot_waiting: (BTreeSet<u64>, u64),
/// What predicts the jobs' peaks and usual run times, and when it read the history.
pub(super) predictor: Option<(Predictor, SystemTime)>,
/// Whether the slice was at the high-water mark at the last plan, so the change is logged once.
pub high_water: bool,
/// The waiting runners `rereserve` raised for a heavier queued job, until they take a job or go. A raise stays
/// once made, so a pass's raise is still known to the tick after it, which stops those past the budget.
pub(super) raised: Vec<String>,
/// The job the last plan let no younger job start before, so the change is logged once.
barrier: Option<u64>,
/// What the host's limit held at the last plan, so the change is logged once.
host_holds: HostHolds,
}
/// What the host's limit holds back at a plan.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
enum HostHolds {
/// Nothing that keeps the larger margin up.
#[default]
Nothing,
/// What runs reaches the limit, while the host has the room (`HostBudget::short_of`).
Counted,
/// The host stalls, or lacks what a job needs.
Short,
}
/// What one plan admits by.
#[derive(Debug, Clone)]
pub(super) struct Admitting {
pub policy: AdmissionPolicy,
/// What each pool's next runner reserves goes by; absent, its profile's memory and `default`.
pub basis: BTreeMap<Pool, Basis>,
/// What a runner reserving its profile's memory goes by.
pub default: Basis,
/// The budget left; `None` for an unlimited slice.
pub free: Option<u64>,
/// The slice's memory, when sampled recently.
pub slice: Option<u64>,
/// Whether the slice is at the high-water mark, so nothing starts.
pub held: bool,
/// What the host's memory leaves new runners, from a recent reading.
pub host: Option<api::HostBudget>,
/// The margin `host` keeps, as the plan's starts each go by it.
pub remembered: host::Remembered,
/// Under `[host] cpu_overcommit`, what the plan admits by CPU.
pub cpu: Option<CpuAdmitting>,
}
/// What one plan admits by CPU.
#[derive(Debug, Clone)]
pub(super) struct CpuAdmitting {
/// What each pool's next runner reserves goes by; absent, its profile's `cpus`.
pub basis: BTreeMap<Pool, Basis>,
/// The CPU budget left, in millicores.
pub free: u64,
}
impl Admitting {
/// The record of a runner of `pool` started reserving `reserved` and `cpu` millicores, which takes them from
/// the budgets left.
pub(super) fn admit(&mut self, pool: &Pool, reserved: u64, cpu: u64) -> api::Admission {
let admission = api::Admission {
policy: self.policy,
reserved,
basis: self.basis.get(pool).copied().unwrap_or(self.default),
free: self.free,
slice: self.slice,
cpu: self.cpu.as_mut().map(|admitting| {
let admission = api::CpuAdmission {
reserved: cpu,
basis: admitting.basis.get(pool).copied().unwrap_or(Basis::Cap),
free: admitting.free,
waited: None,
};
admitting.free = admitting.free.saturating_sub(cpu);
admission
}),
};
self.free = self.free.map(|free| free.saturating_sub(reserved));
admission
}
}
/// What the runners run, as far as admission can tell copies of a job apart.
struct Running {
/// The jobs runners are known to run.
keys: BTreeSet<Key>,
/// The repositories with a runner that took a job not known yet, which may be a copy of any of theirs.
unknown: BTreeSet<String>,
}
impl Running {
/// Whether a copy of `key` may be running.
fn may_run(&self, key: &Key) -> bool {
self.keys.contains(key) || self.unknown.contains(&key.repository)
}
}
/// The largest prediction among `queued`, jobs of `repository` in `profile` under `cap`. A job queued twice, or
/// that may have a copy `running`, has copies beside it.
fn largest<'job>(
predictor: &Predictor,
repository: &str,
profile: &str,
cap: u64,
queued: impl Iterator<Item = &'job QueuedJob>,
running: &Running,
now: u64,
) -> Option<Prediction> {
let keys: Vec<Key> = queued
.map(|job| Key {
repository: repository.to_owned(),
workflow: job.workflow.clone(),
name: job.name.clone(),
})
.collect();
keys.iter()
.map(|key| {
let queued = keys.iter().filter(|other| *other == key).count();
let copies = if queued > 1 || running.may_run(key) {
Copies::Several
} else {
Copies::Alone
};
predictor.predict(key, profile, cap, now, copies)
})
.max_by_key(|prediction| prediction.memory)
}
/// What a runner admitted by CPU (`reserved`) reserves once its job `key` in `profile`, whose `cpus` are `cap`
/// millicores, is known: that job's predicted average CPU, at most the whole `budget`.
fn job_cpu(
predictor: &Predictor,
key: &Key,
profile: &str,
cap: u64,
budget: Option<u64>,
reserved: api::CpuAdmission,
) -> api::CpuAdmission {
let prediction = predictor.predict_cpu(key, profile, cap);
api::CpuAdmission {
reserved: budget.map_or(prediction.cpu, |budget| prediction.cpu.min(budget)),
basis: prediction.basis,
..reserved
}
}
impl<G: GithubApi + 'static, D: DockerApi + 'static> Engine<G, D> {
/// Reads the job history into a new predictor once the last is a minute old. A read that fails keeps the last one;
/// without any, jobs are admitted at their caps and nothing starts behind a barrier. Under caps only usual run times
/// are read from it (ADR 0097).
pub(super) async fn refresh_predictor(&mut self) {
if self
.measured
.predictor
.as_ref()
.is_some_and(|(_, read_at)| read_at.elapsed().is_ok_and(|age| age < REREAD))
{
return;
}
let history = match self
.store
.sizing(time::now_ms().saturating_sub(HISTORY))
.await
{
Ok(history) => history,
Err(error) => {
warn!("cannot read the job history to predict peaks: {error}");
return;
}
};
let profiles = &self.config.profiles;
let predictor = Predictor::read(&self.config.sizing, &history, |profile| {
profiles.get(profile).map(|limits| limits.memory.0)
});
self.measured.predictor = Some((predictor, SystemTime::now()));
}
/// Sets what each repository's next runner reserves, and says what the plan admits by. `free` is the budget
/// the running containers leave.
pub(super) fn admitting(
&self,
repositories: &mut [Repository],
free: Option<u64>,
) -> Admitting {
let mut admitting = Admitting {
policy: AdmissionPolicy::Caps,
basis: BTreeMap::new(),
default: Basis::Cap,
free,
slice: None,
held: false,
host: self.host_budget(),
remembered: self.host_remembered(),
cpu: self.admitting_cpu(repositories),
};
if self.config.host.admission != Admission::Measured {
return admitting;
}
admitting.policy = AdmissionPolicy::Measured;
let now = time::now_ms();
// A sample from the last few intervals: the sampler may be a little late, never minutes.
let fresh = (3 * SAMPLE_INTERVAL).as_secs();
admitting.slice = self
.store
.latest_host_sample()
.filter(|sample| sample.at + fresh >= self.clock.now_ms() / 1000)
.map(|sample| sample.memory);
let (Some(slice), Some(memory_max)) = (admitting.slice, self.memory_max) else {
admitting.default = Basis::Unmeasured;
return admitting;
};
if slice.saturating_mul(100) >= memory_max.saturating_mul(HIGH_WATER) {
admitting.held = true;
admitting.free = Some(0);
return admitting;
}
let Some((predictor, _)) = &self.measured.predictor else {
return admitting;
};
let running = self.running();
for repository in repositories {
let Some(cap) = self
.config
.profiles
.get(&repository.profile)
.map(|p| p.memory.0)
else {
continue;
};
let queued = repository
.queued
.iter()
.filter(|job| matches(job, &repository.labels));
if let Some(prediction) = largest(
predictor,
&repository.name,
&repository.profile,
cap,
queued,
&running,
now,
) {
repository.runner_memory = Some(prediction.memory);
admitting.basis.insert(repository.pool(), prediction.basis);
}
}
admitting
}
/// Makes the budgets `admitting` leaves those the runners leave now, so a start's record says what was free
/// when it started: a stop since the plan gave its runner's back, and a start that failed took nothing.
pub(super) fn refresh_free(&self, admitting: &mut Admitting) {
if !admitting.held {
admitting.free = self
.memory_max
.map(|max| max.saturating_sub(self.count(admitting.remembered).pooled()));
}
if let (Some(cpu), Some(budget)) = (admitting.cpu.as_mut(), self.cpu_budget()) {
cpu.free = budget.saturating_sub(self.cpu_in_use());
}
}
/// The host's latest memory reading, if it is from the last few sample intervals, with the config's
/// `[host] memory_ceiling` (ADR 0084), so a reload that changes it applies at the next plan.
pub(super) fn host_memory(&self) -> Option<api::HostMemory> {
let fresh = (3 * SAMPLE_INTERVAL).as_secs();
self.store
.latest_host_memory()
.filter(|memory| memory.at + fresh >= self.clock.now_ms() / 1000)
.map(|memory| api::HostMemory {
ceiling: self.config.host.memory_ceiling.map(|ceiling| ceiling.0),
..memory
})
}
/// What the host's memory leaves runners beside what runs now, from a reading of the last few sample intervals.
pub(super) fn host_budget(&self) -> Option<api::HostBudget> {
self.host_budget_by(self.host_remembered())
}
/// What the host's memory leaves runners beside what runs now, from a reading of the last few sample intervals,
/// with the margin `remembered` asks for.
pub(super) fn host_budget_by(&self, remembered: host::Remembered) -> Option<api::HostBudget> {
let memory = self.host_memory()?;
Some(host::budget(
memory,
self.count(remembered).plain,
remembered,
))
}
/// What the last plan saw of the host, as the next one goes by it. The larger margin keeps a start from pushing a
/// busy host back to the edge; with no runner in the slice there is no such start to follow, so the first
/// runners need only the margin.
pub(super) fn host_remembered(&self) -> host::Remembered {
host::Remembered {
short: self.measured.host.short && self.occupied().next().is_some(),
..self.measured.host
}
}
/// Remembers what this plan saw of the host for the next: whether it stalled, whether the larger margin stands
/// (`host::short`), and which jobs `waiting` wait for the host's memory. Adds the time since the last plan to the
/// waits of those that waited then, tells insights which of them the host lacks room for (ADR 0103), and logs what
/// holds them when that changes.
pub(super) fn note_host(
&mut self,
admitting: &Admitting,
waiting: &BTreeMap<u64, api::Waiting>,
) {
let stalled = admitting.host.as_ref().is_some_and(|host| host.stalled);
let needs = waiting.values().filter_map(|reason| match reason {
api::Waiting::HostMemory { needs, .. } => Some(*needs),
_ => None,
});
let reserved = self.count(self.host_remembered()).plain;
let short = admitting
.host
.as_ref()
.is_some_and(|host| host::short(&host.memory, reserved, stalled, needs));
let was_short = self.measured.host.short;
self.measured.host = host::Remembered { short, stalled };
let now = time::now_ms();
let waiting_now: BTreeMap<u64, u64> = waiting
.iter()
.filter_map(|(job, reason)| match reason {
api::Waiting::HostMemory { needs, .. } => Some((*job, *needs)),
_ => None,
})
.collect();
let none_waiting = waiting_now.is_empty();
// Insights tell the owner to close programs, so they hear only of the jobs the host itself lacks room for.
// Every job the limit held still adds to `host_waited`: sizing takes that off the wait it reads as one for
// the budget.
let lacking: BTreeSet<u64> = admitting
.host
.iter()
.flat_map(|host| {
waiting_now
.iter()
.filter(|(_, needs)| host.short_of(**needs))
.map(|(job, _)| *job)
})
.collect();
let holds = match (short, stalled || !lacking.is_empty()) {
(false, _) => HostHolds::Nothing,
(true, false) => HostHolds::Counted,
(true, true) => HostHolds::Short,
};
let held = std::mem::replace(&mut self.measured.host_holds, holds);
self.store.host_waiting(lacking, now);
let (waited, since) = std::mem::replace(
&mut self.measured.host_waiting,
(waiting_now.into_keys().collect(), now),
);
if !waited.is_empty() {
self.store
.host_waited(waited.into_iter().collect(), now.saturating_sub(since));
}
let size = crate::config::ByteSize;
match (holds, admitting.host.as_ref()) {
(HostHolds::Short, Some(host)) if held != HostHolds::Short => {
info!(
"the host is short of memory ({} available{}): no runner starts that does not fit {} beside what \
runs",
size(host.memory.available),
if stalled {
", its tasks stall for it"
} else {
""
},
size(host.limit)
);
}
(HostHolds::Counted, Some(host)) if held != HostHolds::Counted => {
info!(
"what runs reserves {} of the {} the host leaves the slice, with {} available: no runner starts \
that does not fit beside it",
size(reserved),
size(host.limit),
size(host.memory.available)
);
}
(HostHolds::Nothing, _) if was_short && none_waiting => {
info!("no job waits for the host's memory now: runners start as the budget allows");
}
(HostHolds::Nothing, _) if was_short => {
info!(
"a job waiting for the host's memory fits its plain margin: the next plan goes by that margin"
);
}
_ => {}
}
}
/// Remembers which jobs this plan had waiting only for a slot (`Plan::slot_waiting`), and adds the time since the
/// last plan to the slot waits of those that did then: what auto sizing reads to add slots (ADR 0090). A job a
/// restart left waiting counts again from the first plan after it.
pub(super) fn note_slots(&mut self, waiting: BTreeSet<u64>) {
let now = time::now_ms();
let (waited, since) = std::mem::replace(&mut self.measured.slot_waiting, (waiting, now));
if !waited.is_empty() {
self.store
.slot_waited(waited.into_iter().collect(), now.saturating_sub(since));
}
}
/// The CPU budget, in millicores: the slice's CPUs times `[host] cpu_overcommit`; `None` without it.
pub(super) fn cpu_budget(&self) -> Option<u64> {
let overcommit = self.config.host.cpu_overcommit?;
Some(crate::config::cpu_budget(self.cpus?, overcommit))
}
/// What the runners reserve of the CPU budget, in millicores: under caps each its container's CPU limit, whatever
/// it reserved under measured admission before a reload, as memory counts it.
pub(super) fn cpu_in_use(&self) -> u64 {
self.occupied()
.map(|(_, occupant)| self.reserves_cpu(occupant))
.sum()
}
/// What a runner reserves of the CPU budget, in millicores, as `cpu_in_use` counts it.
pub(super) fn reserves_cpu(&self, occupant: &super::Occupant) -> u64 {
match self.config.host.admission {
Admission::Caps => occupant.cpus,
Admission::Measured => occupant.reserved_cpu(),
}
}
/// Under a CPU budget, sets what each repository's next runner reserves of it, at most the whole budget so a
/// runner can always start alone: its profile's `cpus`, or under measured admission the largest predicted
/// average CPU of its queued jobs. Says what the plan admits by CPU.
fn admitting_cpu(&self, repositories: &mut [Repository]) -> Option<CpuAdmitting> {
let budget = self.cpu_budget()?;
let mut admitting = CpuAdmitting {
basis: BTreeMap::new(),
free: budget.saturating_sub(self.cpu_in_use()),
};
for repository in repositories {
let Some(cap) = self
.config
.profiles
.get(&repository.profile)
.map(|p| u64::from(p.cpus) * 1000)
else {
continue;
};
let predictor = self
.measured
.predictor
.as_ref()
.filter(|_| self.config.host.admission == Admission::Measured);
let prediction = predictor.and_then(|(predictor, _)| {
repository
.queued
.iter()
.filter(|job| matches(job, &repository.labels))
.map(|job| {
let key = Key {
repository: repository.name.clone(),
workflow: job.workflow.clone(),
name: job.name.clone(),
};
predictor.predict_cpu(&key, &repository.profile, cap)
})
.max_by_key(|prediction| prediction.cpu)
});
let (cpu, basis) = prediction.map_or((cap, Basis::Cap), |prediction| {
(prediction.cpu, prediction.basis)
});
repository.runner_cpu = Some(cpu.min(budget));
admitting.basis.insert(repository.pool(), basis);
}
Some(admitting)
}
/// Sets how long a new runner of each of `repositories` may run: the longest usual run time of the queued jobs its
/// labels match, `taken` left out (ADR 0097). Not `listed_demand`: a job it hides for a runner no capture named yet
/// may still be queued, and GitHub may give it to the new runner.
pub(super) fn usual_runs(&self, repositories: &mut [Repository], taken: &BTreeSet<u64>) {
let Some((predictor, _)) = &self.measured.predictor else {
return;
};
for repository in repositories {
let listed = self.listed_unnamed(&repository.name, taken);
let queued = listed.iter().filter(|job| matches(job, &repository.labels));
let keys = queued.map(|job| Key {
repository: repository.name.clone(),
workflow: job.workflow.clone(),
name: job.name.clone(),
});
repository.usual = predictor.longest_usual(keys, &repository.profile);
}
}
/// How long `occupant`'s job in `profile` usually keeps it, once that job is known and its runs say.
pub(super) fn usual_run(&self, occupant: &super::Occupant, profile: &str) -> Option<Duration> {
let (predictor, _) = self.measured.predictor.as_ref()?;
predictor.usual(occupant.key.as_ref()?, profile)
}
/// Tells apart the jobs of the runners whose job the history now has a record of, unless that record is the
/// unnamed one a runner's claim makes of a job no listing saw: GitHub's details name it (`follow_jobs`).
async fn find_keys(&mut self) {
let unknown: Vec<(String, u64)> = self
.occupied()
.filter(|(_, occupant)| occupant.key.is_none())
.filter_map(|(_, occupant)| Some((occupant.runner_name.clone(), occupant.job?)))
.collect();
for (runner, job) in unknown {
let Ok(Some(record)) = self.store.job(job).await else {
continue;
};
if record.summary.name.is_empty() {
continue;
}
if let Some(occupant) = self
.slots
.values_mut()
.flatten()
.flatten()
.find(|occupant| occupant.runner_name == runner)
{
occupant.key = Some(Key {
repository: record.summary.repository,
workflow: record.summary.workflow,
name: record.summary.name,
});
}
}
}
/// Under measured admission, sets what each running runner reserves: once its job is known, that job's
/// prediction; until then, the larger of what it reserved and the largest prediction among its repository's
/// queued jobs, since GitHub may still give it any of them. A runner a restart adopted without a record of its
/// admission keeps its cap. Each change goes into the runner's row.
pub(super) async fn rereserve(&mut self) {
self.find_keys().await;
if self.config.host.admission != Admission::Measured {
self.measured.raised.clear();
return;
}
let Some((predictor, _)) = &self.measured.predictor else {
return;
};
let now = time::now_ms();
let taken: BTreeSet<u64> = self
.occupied()
.filter_map(|(_, occupant)| occupant.job)
.collect();
let running = self.running();
let cpu_budget = self.cpu_budget();
// The first runner of each known job, in slot order, goes by its own runs; its copies have it beside them,
// as does every runner of a repository with a busy runner whose job is not known yet.
let mut seen = BTreeSet::new();
let mut changed = Vec::new();
let mut raised = std::mem::take(&mut self.measured.raised);
for (profile, slots) in &mut self.slots {
for occupant in slots.iter_mut().flatten() {
let first = occupant
.key
.as_ref()
.is_some_and(|key| seen.insert(key.clone()));
let Some(admission) = &mut occupant.admission else {
continue;
};
// Its job's average CPU once known; until then what it started with, the largest of its queue's.
let cpu = admission.cpu.zip(occupant.key.as_ref()).map(|(cpu, key)| {
job_cpu(predictor, key, profile, occupant.cpus, cpu_budget, cpu)
});
let mut dirty = cpu.is_some() && cpu != admission.cpu;
admission.cpu = cpu.or(admission.cpu);
let prediction = if let Some(key) = &occupant.key {
let copies = if first && !running.unknown.contains(&key.repository) {
Copies::Alone
} else {
Copies::Several
};
Some(predictor.predict(key, profile, occupant.memory, now, copies))
} else {
let labels = self
.config
.pool_in(&occupant.repository, profile)
.map(|repository| repository.labels.as_slice())
.unwrap_or_default();
let queued = self
.repositories
.get(&occupant.repository)
.map(|state| state.queued.as_slice())
.unwrap_or_default()
.iter()
.filter(|job| !taken.contains(&job.id) && matches(job, labels));
largest(
predictor,
&occupant.repository,
profile,
occupant.memory,
queued,
&running,
now,
)
.filter(|prediction| prediction.memory > admission.reserved)
};
if let Some(prediction) = prediction
&& (prediction.memory, prediction.basis)
!= (admission.reserved, admission.basis)
{
admission.reserved = prediction.memory;
admission.basis = prediction.basis;
dirty = true;
if occupant.key.is_none() && !raised.contains(&occupant.runner_name) {
raised.push(occupant.runner_name.clone());
}
}
if dirty {
changed.push((occupant.runner_name.clone(), *admission));
}
}
}
raised.retain(|name| {
self.occupied()
.any(|(_, occupant)| occupant.key.is_none() && occupant.runner_name == *name)
});
self.measured.raised = raised;
for (runner, admission) in changed {
self.store.runner_admission(&runner, admission);
}
}
/// What the runners run: the jobs they are known to, and the repositories with a busy runner whose job is not
/// known yet, as when its log capture failed.
fn running(&self) -> Running {
Running {
keys: self
.occupied()
.filter_map(|(_, occupant)| occupant.key.clone())
.collect(),
unknown: self
.occupied()
.filter(|(_, occupant)| {
(occupant.busy || occupant.job.is_some()) && occupant.key.is_none()
})
.map(|(_, occupant)| occupant.repository.clone())
.collect(),
}
}
/// The waiting runners to stop, as one that waited `IDLE_TIMEOUT` is: those `rereserve` raised for a heavier
/// queued job while what the running containers take is past `MemoryMax`, until it fits again. GitHub could give
/// them that job, so it waits for a runner that fits. One assigned between two ticks keeps it, and counts at
/// its raised reservation from then.
pub(super) fn over_budget(&self, decisions: &[Decision]) -> Vec<Decision> {
let Some(max) = self.memory_max else {
return Vec::new();
};
let mut in_use = self.count(self.host_remembered()).pooled();
let mut stops = Vec::new();
for (slot, occupant) in self.occupied() {
if in_use <= max {
break;
}
let stopping = decisions.iter().any(
|decision| matches!(decision, Decision::Stop { slot: other, .. } if *other == slot),
);
if occupant.busy
|| occupant.job.is_some()
|| stopping
|| !self.measured.raised.contains(&occupant.runner_name)
{
continue;
}
info!(
"{}: stopping {}: raised to {} for a queued job, it does not fit the budget",
occupant.repository,
occupant.runner_name,
crate::config::ByteSize(occupant.reserved())
);
in_use = in_use.saturating_sub(self.takes(occupant));
stops.push(Decision::Stop {
slot,
reason: StopReason::OverBudget,
});
}
stops
}
/// Whether a failure holds `repository`'s pool in `profile` back at `now`.
pub(super) fn backing_off(&self, repository: &str, profile: &str, now: SystemTime) -> bool {
self.repositories[repository]
.holds
.get(profile)
.and_then(|hold| hold.held)
.is_some_and(|hold| hold.until > now)
}
/// Commits what the last plan of a tick or a pass found (ADR 0096): the pools it `held`, each wait starting with
/// the job the plan names, and its `barrier`, which its pool remembers owning. A pool that may not start a runner,
/// paused, backing off or preparing, loses its wait and its served mark (ADR 0098). So does a job's wait that a
/// listing that succeeded no longer shows or a runner of this machine is known to have taken, and the mark goes once
/// such a listing leaves the pool nothing queued. A listing that failed says nothing of the job or the queue: both
/// stay, and the plan, which has no such job, puts up no barrier for it. A status's plan never comes here, so reading
/// the status changes no wait.
pub(super) fn note_waits(&mut self, held: &[Demand], barrier: Option<Barrier>) {
let budget = self.cpu_budget();
let in_use = self.cpu_in_use();
let taken: BTreeSet<u64> = self
.occupied()
.filter_map(|(_, occupant)| occupant.job)
.collect();
let now = SystemTime::now();
let pools: Vec<(Pool, BTreeSet<u64>, bool)> = self
.config
.repositories
.iter()
.map(|repository| {
// Not `listed_demand`: a runner no capture named yet hides the oldest job from the plan, which says
// nothing of whether it took that one.
let queued = self
.listed_unnamed(&repository.name, &taken)
.iter()
.filter(|job| matches(job, &repository.labels))
.map(|job| job.id)
.collect();
let backing_off = self.backing_off(&repository.name, &repository.profile, now);
let preparing = self
.config
.profiles
.get(&repository.profile)
.is_some_and(|profile| self.preparing(&repository.profile, profile).is_some());
let stopped = self.control.is_paused(&repository.name) || backing_off || preparing;
(Pool::from(repository), queued, stopped)
})
.collect();
for (pool, queued, stopped) in pools {
let Some(state) = self.repositories.get_mut(&pool.repository) else {
continue;
};
let listed = state.listed;
let waits = state.waits.entry(pool.profile.clone()).or_default();
if stopped {
*waits = Waits::default();
} else if listed {
waits.retain(|job| queued.contains(&job));
if queued.is_empty() {
waits.emptied();
}
}
let mut cpu_held = false;
for demand in held.iter().filter(|demand| demand.pool == pool) {
cpu_held |= demand.scarce == Scarce::Cpu;
if !waits.note(demand.scarce, demand.job, now) {
continue;
}
match (demand.scarce, budget) {
(Scarce::Memory, _) => info!(
"{}: its next job in {} waits for memory",
pool.repository, pool.profile
),
(Scarce::Cpu, Some(budget)) => info!(
"{}: its next job in {} waits for CPU: runners reserve {} of the budget's {}",
pool.repository,
pool.profile,
api::cpus(in_use),
api::cpus(budget)
),
(Scarce::Cpu, None) => {}
}
}
if let Some(barrier) = barrier {
waits.own(barrier.job);
}
if waits.is_empty() {
state.waits.remove(&pool.profile);
}
if cpu_held {
state.cpu_held.insert(pool.profile);
} else {
state.cpu_held.remove(&pool.profile);
}
}
let job = barrier.map(|barrier| barrier.job);
if job != self.measured.barrier {
if let Some(job) = job {
info!("job {job} waited long enough: no younger job starts until its runner fits");
} else {
info!("no job holds younger ones back any more");
}
self.measured.barrier = job;
}
}
/// Logs when the slice reaches the high-water mark and when it falls under it.
pub(super) fn note_high_water(&mut self, admitting: &Admitting) {
if admitting.held == self.measured.high_water {
return;
}
self.measured.high_water = admitting.held;
let slice = admitting.slice.map_or_else(String::new, |memory| {
format!(" ({})", crate::config::ByteSize(memory))
});
if admitting.held {
info!(
"the slice{slice} is at {HIGH_WATER}% of its MemoryMax: measured admission starts nothing until it \
falls under"
);
} else {
info!(
"the slice{slice} is under {HIGH_WATER}% of its MemoryMax again: measured admission resumes"
);
}
}
}