runnerd-core 0.1.2

Config, domain logic and API types shared by runnerd and its clients
Documentation
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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
//! One replay of the job history through admission: `simulate` builds a `Replayer`, which goes through the moments jobs
//! arrive and end and answers with a `Replay`. Its state is one value that exists for that one call; only its methods
//! here write it (ADR 0115). It does no I/O and reads no clock.

use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet};
use std::time::{Duration, SystemTime};

use crate::api::{Basis, HostMemory};
use crate::config::Config;
use crate::scheduler::priority::{Around, Backfill, Candidate, Caps, Held, Older, Runner, Short};
use crate::scheduler::{Barrier, Drained, Left, Pool, Scarce, Waits};
use crate::sizing::{Measure, Ran};
use crate::time;

use super::{
    Arrivals, Backfilled, Band, Barriers, Brake, Copies, CreditRoom, GrowthCount, GuardHold,
    HIGH_WATER, Hazard, HostReserve, Key, OOMD_UNDER, Policy, PoolReplay, Predictor, Reading,
    Recorded, Replay, Replaying, RunId, RunKey, RunReplay, RunTrace, STEP, THROTTLES_UNDER, Trace,
    growth, host, pooled, spread,
};

/// A job the replay started.
struct Running<'run> {
    run: &'run Ran,
    /// Its place in the jobs replayed.
    job: u64,
    profile: &'run str,
    /// When it started, in ms.
    started: u64,
    ends: u64,
    /// When it usually ends by, in ms, if it started behind a barrier.
    backfilled: Option<u64>,
    reserved: u64,
    peak: u64,
    /// The CPU it reserves, in millicores, once its job is known.
    cpu: u64,
    /// The CPU it reserves until then, with a trace: what it started with.
    starting_cpu: u64,
    /// Its job.
    key: Key,
    /// What its reservation goes by.
    basis: Basis,
    /// What it reserves until its job is known: its pool's largest prediction when it started.
    starting: u64,
    /// How it ran; `None` without a trace or a run the trace has no samples of.
    trace: Option<&'run RunTrace>,
    /// How long its runner took to start its job, in ms, as it did: its job's samples and name count from then.
    boot: u64,
}

impl Running<'_> {
    /// How long its job has run at `moment`, in ms; `None` while its runner starts.
    fn job_ran(&self, moment: u64) -> Option<u64> {
        moment.checked_sub(self.started + self.boot)
    }

    /// What its samples say at `moment`: nothing yet while its runner starts; `None` without a trace of it.
    fn reading(&self, moment: u64) -> Option<Reading> {
        let trace = self.trace?;
        Some(
            self.job_ran(moment)
                .map_or(Reading::NotYet, |ran| trace.at(ran)),
        )
    }

    /// The CPU it reserves at `moment`, in millicores: as the daemon's runner, what it started with until its job is
    /// known.
    fn cpu_at(&self, moment: u64) -> u64 {
        if self.named(moment) {
            self.cpu
        } else {
            self.starting_cpu.max(self.cpu)
        }
    }

    /// Whether the daemon could name its job at `moment`.
    fn named(&self, moment: u64) -> bool {
        self.trace.is_none_or(|trace| {
            self.job_ran(moment)
                .is_some_and(|ran| ran >= trace.named_after)
        })
    }
}

/// Replays `jobs` through `policy`: each arrives as `how` says and holds its runner as long as it did (`Ran::occupied`:
/// from the runner's start, so a runner's start and GitHub's handing it the job count), in a profile with
/// `slots` (by name; the config's where absent) under the slice's `memory_max`. Jobs start as soon as the policy
/// admits them, in `jobs`' order, which is the job IDs' as the history reads them and `scheduler::plan` serves them: a
/// job that does not fit lets a later one past, until it waited long enough under `how`'s barriers and no later one
/// starts before its pool does, but those `priority::Backfill` lets by. The replay looks again at each such limit, so a
/// quiet queue reaches it too. Usual run times come from `how`'s known runs and those finished before each moment, as
/// predictions do.
/// Measured admission predicts from the runs finished before it decides, as the daemon would, and holds each
/// running job at its peak for its whole run, which the daemon does not see. A job with copies waiting or running
/// beside it is predicted as one with `Copies::Several`. Each moment, the running jobs are predicted again, the
/// first running copy of a job going by its own runs, as the daemon does each tick. Unlike the daemon, the replay
/// knows a job from its start: it never sees a runner whose job is not known yet, and the order jobs started
/// stands for the daemon's slot order.
///
/// With a `cpu_budget` in millicores, a job also starts only when the CPU the running jobs reserve and its own fit
/// it: by caps, each its profile's `cpus`; measured, each its predicted average (`Predictor::predict_cpu`), at most
/// the budget. The replay holds each job's run time whatever the CPU it shares: it shows what admission holds back,
/// not how much a busy CPU slows the jobs.
///
/// With a `Replaying::trace`, the replay runs as the daemon counts: each job uses what its own samples say, shifted to
/// its replayed start, and takes the larger of that and what it reserves; it reserves its pool's largest prediction
/// until the daemon could name its job; a stale sample counts at its cap; the budget goes by `pooled::count`; the host's
/// recorded programs bound what starts, with the margin of `host`; and the mark reads the runners' use with the trace's
/// overhead. It looks every `trace::STEP` and plans every `[host] poll_interval` and at each arrival and end. With
/// `Replaying::growth`, both budgets read the growth count instead (`pooled::Snapshot::growth`), each start judged by
/// the count with it added, and its brake, if on, looks at every plan.
pub fn simulate<'known>(
    config: &Config,
    memory_max: Option<u64>,
    cpu_budget: Option<u64>,
    jobs: &[Ran],
    policy: Policy,
    slots: &BTreeMap<String, u32>,
    how: impl Into<Replaying<'known>>,
) -> Replay {
    let Replaying {
        barriers,
        arrivals,
        known,
        trace,
        most_credit,
        host_reserve,
        credit_room,
        band,
        growth,
    } = how.into();
    let mirror = config.mirror_memory();
    let budget = memory_max.map(|max| max.saturating_sub(mirror));
    let queue = replayable(config, jobs);
    let followers = match arrivals {
        Arrivals::AsQueued => BTreeMap::new(),
        Arrivals::AfterNeeds => followers(&queue),
    };
    let following: BTreeSet<u64> = followers
        .values()
        .flatten()
        .map(|follower| queue[follower.at].job)
        .collect();
    let arriving = (0_usize..)
        .zip(&queue)
        .filter(|(_, queued)| !following.contains(&queued.job))
        .map(|(at, queued)| (queued.run.queued_at, at))
        .collect();
    let mut predictor = Predictor::new(&config.sizing);
    if let (Some(known), Some(first)) = (known, queue.first()) {
        predictor.read_until(known, first.run.queued_at, |profile| {
            config.profiles.get(profile).map(|limits| limits.memory.0)
        });
    }
    let replayer = Replayer {
        config,
        budget,
        cpu_budget,
        policy,
        slots,
        predictor,
        running: Vec::new(),
        waits: Vec::new(),
        most_running: 0,
        worst_overlap: 0,
        last_end: 0,
        under_predicted: 0,
        held_back: 0,
        cpu_held: 0,
        worst_cpu: 0,
        barriers,
        pool_waits: BTreeMap::new(),
        pools: BTreeMap::new(),
        barrier: None,
        backfill: None,
        usual: BTreeMap::new(),
        arriving,
        followers,
        started: Vec::new(),
        runs: BTreeMap::new(),
        backfilled: Backfilled::default(),
        moment: queue.first().map_or(0, |queued| queued.run.queued_at),
        charged: 0,
        capacity: 0,
        barrier_for: 0,
        withheld: 0,
        memory_max,
        mirror,
        trace,
        most_credit,
        host_reserve,
        expects_credit: credit_room,
        host_band: host::HostBand::Plain,
        next_plan: 0,
        needs: RefCell::new(BTreeMap::new()),
        held_for_slice: 0,
        held_for_host: 0,
        host_needs: Vec::new(),
        band,
        slice_waited: 0,
        host_waited: 0,
        hazard: Hazard::default(),
        last: pooled::Count::default(),
        cohorts: Vec::new(),
        growth: growth.filter(|_| trace.is_some() && policy == Policy::Measured),
        brake: growth::Growth::default(),
    };
    replayer.play(&queue)
}

/// What the jobs of `jobs` a replay with `config` runs did as they really ran: each pool's waits, each run attempt's
/// time and the time they waited for the host alone, to read a replay of them against.
pub fn recorded(config: &Config, jobs: &[Ran]) -> Recorded {
    let mut by_pool: BTreeMap<Pool, Vec<u64>> = BTreeMap::new();
    let mut host_waited = 0;
    let mut spans: BTreeMap<RunKey, RunSpan> = BTreeMap::new();
    for Queued { run, .. } in replayable(config, jobs) {
        let waited = run
            .runner_started_at
            .saturating_sub(run.queued_at)
            .saturating_sub(run.unseen);
        by_pool.entry(pool_of(run)).or_default().push(waited / 1000);
        host_waited += run.host_waited;
        let span = spans.entry(run_key(run)).or_insert(RunSpan {
            first_arrival: run.queued_at,
            last_end: 0,
            profiles: BTreeSet::new(),
        });
        span.first_arrival = span.first_arrival.min(run.queued_at);
        span.last_end = span.last_end.max(run.finished_at.unwrap_or(0));
        span.profiles.insert(run.profile.clone());
    }
    Recorded {
        pools: by_pool
            .into_iter()
            .map(|(pool, waits)| {
                let replay = PoolReplay {
                    waits,
                    never_started: 0,
                };
                (pool, replay)
            })
            .collect(),
        runs: spans.into_values().map(RunSpan::replay).collect(),
        host_waited,
    }
}

/// `jobs` a replay can run, in the order they queued: those of a known profile with a run time.
fn replayable<'run>(config: &Config, jobs: &'run [Ran]) -> Vec<Queued<'run>> {
    let mut queue: Vec<Queued<'_>> = (0_u64..)
        .zip(jobs)
        .filter(|(_, run)| config.profiles.contains_key(&run.profile))
        .filter(|(_, run)| matches!((run.started_at, run.finished_at), (Some(start), Some(end)) if end >= start))
        .map(|(job, run)| Queued {
            job,
            run,
            arrived: run.queued_at,
        })
        .collect();
    queue.sort_by_key(|queued| queued.run.queued_at);
    queue
}

/// A job waiting in a replay.
#[derive(Clone, Copy)]
struct Queued<'run> {
    /// Its place in the jobs replayed, which stands for its ID: the order `scheduler::plan` serves jobs in.
    job: u64,
    run: &'run Ran,
    /// When it arrived in the replay, in ms.
    arrived: u64,
}

/// A job that follows another in its run attempt.
#[derive(Clone, Copy)]
struct Follower {
    /// Its place in the replay's queue.
    at: usize,
    /// How long after the job it follows it queued, in ms.
    gap: u64,
}

/// By the job each follows, the jobs of `queue` that queued after another job of their run attempt ended: a job
/// follows the last that ended before it queued, as GitHub queues a job once the last of its `needs` ends. Only a job
/// queued earlier can be followed, so nothing follows itself through a job that took no time.
fn followers(queue: &[Queued<'_>]) -> BTreeMap<u64, Vec<Follower>> {
    let mut attempts: BTreeMap<RunKey, Vec<usize>> = BTreeMap::new();
    for (at, queued) in queue.iter().enumerate() {
        attempts.entry(run_key(queued.run)).or_default().push(at);
    }
    let mut followers: BTreeMap<u64, Vec<Follower>> = BTreeMap::new();
    for attempt in attempts.values() {
        for &at in attempt {
            let queued_at = queue[at].run.queued_at;
            let followed = attempt
                .iter()
                .map(|other| &queue[*other])
                .filter(|other| other.run.queued_at < queued_at)
                .filter_map(|other| Some((other.run.finished_at?, other.job)))
                .filter(|(ended, _)| *ended <= queued_at)
                .max();
            if let Some((ended, job)) = followed {
                let gap = queued_at - ended;
                followers.entry(job).or_default().push(Follower { at, gap });
            }
        }
    }
    followers
}

/// The run attempt `run` belongs to.
fn run_key(run: &Ran) -> RunKey {
    (run.repository.clone(), run.run_id, run.run_attempt)
}

/// What a replay saw of a run attempt so far.
struct RunSpan {
    first_arrival: u64,
    last_end: u64,
    profiles: BTreeSet<String>,
}

impl RunSpan {
    fn replay(self) -> RunReplay {
        RunReplay {
            took: self.last_end.saturating_sub(self.first_arrival) / 1000,
            profiles: self.profiles,
        }
    }
}

/// The pool a job ran in.
fn pool_of(run: &Ran) -> Pool {
    Pool {
        repository: run.repository.clone(),
        profile: run.profile.clone(),
    }
}

/// What a job started at a moment of a replay reserves.
struct Admitted {
    reserved: u64,
    /// What it takes of the budget before its job is known.
    starting: u64,
    /// What `reserved` goes by.
    basis: Basis,
    peak: u64,
    /// Millicores.
    cpu: u64,
    /// What it reserves of the CPU until its job is known, in millicores.
    starting_cpu: u64,
}

/// Whether `one` and `other` are the same job, as `Key` tells them apart. A long queue asks this of every pair of its
/// jobs in every pass, too often for keys to be built.
fn same_job(one: &Ran, other: &Ran) -> bool {
    one.name == other.name && one.repository == other.repository && one.workflow == other.workflow
}

/// What a job's runner starts with at a moment of a replay.
struct Starting {
    /// What it takes of the budget before its job is known.
    memory: u64,
    /// What it reserves once it is.
    reserved: u64,
    /// What that goes by.
    basis: Basis,
    /// What it takes of the CPU budget, in millicores.
    cpu: u64,
}

/// Why a job did not start at a moment of a replay.
enum Refused {
    /// Every slot of its profile is taken.
    Slot,
    /// It does not fit the budget named.
    Budget(Short),
    /// It fits the slice's budget but not what the host's memory leaves it.
    Host(Short),
    /// The slice is at the high-water mark, though the job fits the budget.
    HighWater(Short),
}

/// A replay's state between two moments.
struct Replayer<'run> {
    config: &'run Config,
    budget: Option<u64>,
    cpu_budget: Option<u64>,
    policy: Policy,
    slots: &'run BTreeMap<String, u32>,
    predictor: Predictor,
    running: Vec<Running<'run>>,
    waits: Vec<u64>,
    most_running: u64,
    worst_overlap: u64,
    last_end: u64,
    under_predicted: u64,
    held_back: u64,
    cpu_held: u64,
    worst_cpu: u64,
    barriers: Barriers,
    /// What each pool's next job waited for, as the engine keeps it.
    pool_waits: BTreeMap<Pool, Waits>,
    pools: BTreeMap<Pool, PoolReplay>,
    /// The barrier the last pass ended with.
    barrier: Option<Barrier>,
    /// The room behind it, under `Barriers::On`.
    backfill: Option<Backfill<'run>>,
    /// Each pool's `Predictor::longest_usual` as this pass found it, read once as a plan reads it.
    usual: BTreeMap<Pool, Option<Duration>>,
    /// The jobs not arrived yet whose arrival is known, by when, as places in the queue.
    arriving: BTreeSet<(u64, usize)>,
    /// What arrives once a job ends, by the job.
    followers: BTreeMap<u64, Vec<Follower>>,
    /// The jobs started.
    started: Vec<u64>,
    runs: BTreeMap<RunKey, RunSpan>,
    backfilled: Backfilled,
    /// The moment replayed last, in ms.
    moment: u64,
    charged: u128,
    capacity: u128,
    barrier_for: u64,
    withheld: u128,
    memory_max: Option<u64>,
    mirror: u64,
    trace: Option<&'run Trace>,
    most_credit: u64,
    host_reserve: HostReserve,
    expects_credit: CreditRoom,
    /// The band that stands for the next plan (`next_band`).
    host_band: host::HostBand,
    /// When the next plan with no arrival or end is, in ms.
    next_plan: u64,
    /// What each pool's next runner starts with this pass, with a trace: a long queue asks it of every job, every plan.
    needs: RefCell<BTreeMap<Pool, Need>>,
    /// How many jobs the last pass left waiting for the slice's budget.
    held_for_slice: u64,
    /// How many it left waiting for the host's memory alone.
    held_for_host: u64,
    /// What each of those needs of the host.
    host_needs: Vec<u64>,
    band: Band,
    slice_waited: u64,
    host_waited: u64,
    hazard: Hazard,
    /// The count at the last look, both credits in it; the default with nothing running.
    last: pooled::Count,
    /// The sets of runners that ran when a job started, and the count that let it, while one of them runs.
    cohorts: Vec<Cohort>,
    /// The growth count, with a trace under measured admission.
    growth: Option<GrowthCount>,
    /// Its brake, by the jobs replayed; never engaged without `Brake::On`.
    brake: growth::Growth<u64>,
}

/// What a pool's next runner takes of the budgets before its job is known.
#[derive(Clone, Copy)]
struct Need {
    memory: u64,
    /// Millicores.
    cpu: u64,
}

/// The runners a start left running, and the count it went by.
struct Cohort {
    /// Their places in the jobs replayed.
    jobs: Vec<u64>,
    /// What they counted, in bytes.
    count: u64,
}

impl<'run> Replayer<'run> {
    /// Runs the replay to its end: each moment jobs arrive or end, a limit passes or the samples are read.
    fn play(mut self, queue: &[Queued<'run>]) -> Replay {
        let mut waiting: Vec<Queued<'_>> = Vec::new();
        loop {
            let arrival = self.arriving.first().map(|(arrives, _)| *arrives);
            let end = self.running.iter().map(|running| running.ends).min();
            let event = [arrival, end, self.next_limit()]
                .into_iter()
                .flatten()
                .min();
            let Some(now) = [event, self.next_look(&waiting)]
                .into_iter()
                .flatten()
                .min()
            else {
                break;
            };
            self.account(now);
            self.finish(now);
            if event != Some(now) && !self.plans_at(now) {
                continue;
            }
            self.rereserve(now);
            while let Some(&(arrived, at)) =
                self.arriving.first().filter(|(arrives, _)| *arrives <= now)
            {
                self.arriving.remove(&(arrived, at));
                waiting.push(Queued {
                    arrived,
                    ..queue[at]
                });
            }
            // By arrival, as IDs follow queue time in the daemon: a job that follows a delayed one queues after what arrived
            // meanwhile, though its ID in the history is older.
            waiting.sort_by_key(|queued| (queued.arrived, queued.job));
            self.pass(&mut waiting, now);
            self.note_worst(self.mirror);
        }
        self.replay(queue)
    }

    /// The next moment to read the samples, in ms, with a trace and something to read: a job that ran, or one waiting
    /// while the host's readings go on.
    fn next_look(&self, waiting: &[Queued<'run>]) -> Option<u64> {
        let trace = self.trace?;
        let waits = !waiting.is_empty() && self.moment < trace.ends();
        (!self.running.is_empty() || waits).then_some(self.moment + STEP)
    }

    /// Whether a plan with no arrival or end runs at `now`; if so, the next is a poll later.
    fn plans_at(&mut self, now: u64) -> bool {
        if now < self.next_plan {
            return false;
        }
        let poll = u64::try_from(self.config.host.poll_interval.as_millis()).unwrap_or(u64::MAX);
        self.next_plan = now.saturating_add(poll);
        true
    }

    /// The next moment a pool's wait reaches its limit, in ms.
    fn next_limit(&self) -> Option<u64> {
        self.pool_waits
            .values()
            .flat_map(Waits::deadlines)
            .map(time::ms)
            .filter(|limit| *limit > self.moment)
            .min()
    }

    /// Adds what ran from the last moment to `now`, which is what the last pass left.
    fn account(&mut self, now: u64) {
        let span = now.saturating_sub(self.moment);
        self.look(span);
        let taken = self.taken();
        self.charged += u128::from(taken) * u128::from(span);
        if let Some(budget) = self.budget {
            self.capacity += u128::from(budget) * u128::from(span);
            if self.barrier.is_some() {
                self.withheld += u128::from(budget.saturating_sub(taken)) * u128::from(span);
            }
        }
        if self.barrier.is_some() {
            self.barrier_for += span;
        }
        self.moment = now;
    }

    /// With a trace, notes what the last `span` ms held: the waits, the slice and the host against their lines, what
    /// started runners came to use, and what became of the credit.
    fn look(&mut self, span: u64) {
        let Some(trace) = self.trace else {
            return;
        };
        self.slice_waited += self.held_for_slice * span;
        self.host_waited += self.held_for_host * span;
        if self.running.is_empty() {
            self.last = pooled::Count::default();
            return;
        }
        let slice = self.slice();
        let host_slice = self.used_now() + trace.host_overhead;
        let hazard = &mut self.hazard;
        hazard.slice_peak = hazard.slice_peak.max(slice);
        hazard.active += span;
        if let Some(max) = self.memory_max {
            let mark = max / 100 * HIGH_WATER;
            hazard.over_mark.note(slice.checked_sub(mark), span);
            hazard.over_max.note(slice.checked_sub(max), span);
        }
        if let Some(outside) = trace.outside_at(self.moment) {
            // Signed: past what the host has, by how much.
            let available = signed(trace.total)
                .saturating_sub(signed(outside))
                .saturating_sub(signed(host_slice));
            hazard.under_throttling += span * u64::from(available < signed(THROTTLES_UNDER));
            hazard.under_oomd += span * u64::from(available < signed(OOMD_UNDER));
            hazard.in_band += span * u64::from(self.host_band.is_short());
            hazard.lowest_available = Some(
                hazard
                    .lowest_available
                    .map_or(available, |lowest| lowest.min(available)),
            );
        }
        let count = self.count();
        let braked = self.braked();
        let hazard = &mut self.hazard;
        if self.growth.is_some() {
            if braked {
                hazard.braked += span;
            } else if count.kept.is_none() {
                hazard.guarded += span;
            }
        }
        hazard.credit += u128::from(count.credit) * u128::from(span);
        hazard.most_credit = hazard.most_credit.max(count.credit);
        hazard.host_credit += u128::from(count.host_credit) * u128::from(span);
        let fell = count.credit < self.last.credit;
        hazard.credit_falls += u64::from(fell);
        if fell || count.host_credit < self.last.host_credit {
            self.hazard.overdrawn += u64::from(self.overdrawn(self.last, count));
        }
        self.last = count;
        self.note_unfunded(span);
    }

    /// Whether a credit's fall since the last look, whose count was `last`, left the count past a budget: `MemoryMax`
    /// or the host's limit, each read as it reads the count. The fall alone must cross it, with what runs as it is
    /// `now`, and the last look's count must have been within it: a count already past is no new overdraft, and one
    /// that growth took past is not the credit's.
    fn overdrawn(&self, last: pooled::Count, now: pooled::Count) -> bool {
        let max = self.memory_max.unwrap_or(u64::MAX);
        let host = self.host_memory().map_or(u64::MAX, |memory| {
            host::limit(&memory, self.host_band.is_short())
        });
        let before = pooled::Count {
            credit: last.credit,
            host_credit: last.host_credit,
            ..now
        };
        let crossed = |read: fn(pooled::Count) -> u64, budget: u64| {
            read(now) > budget && read(before) <= budget && read(last) <= budget
        };
        crossed(pooled::Count::pooled, max) || crossed(pooled::Count::hosted, host)
    }

    /// Notes how far what any start left running uses now stands past the count that let it start.
    fn note_unfunded(&mut self, span: u64) {
        let used: BTreeMap<u64, u64> = self
            .running
            .iter()
            .map(|running| (running.job, self.used(running).unwrap_or(0)))
            .collect();
        self.cohorts
            .retain(|cohort| cohort.jobs.iter().any(|job| used.contains_key(job)));
        let all: u64 = used.values().sum();
        let lowest = self.cohorts.iter().map(|cohort| cohort.count).min();
        let mut worst = None;
        // What they all use bounds what any set of them does.
        if lowest.is_some_and(|lowest| all > lowest) {
            for cohort in &self.cohorts {
                let of_cohort: u64 = cohort.jobs.iter().filter_map(|job| used.get(job)).sum();
                worst = worst.max(of_cohort.checked_sub(cohort.count).filter(|past| *past > 0));
            }
        }
        self.hazard.unfunded.note(worst, span);
    }

    /// What `running` uses now, as its samples say; without a trace of it, or a sample of the moment, `None`.
    fn used(&self, running: &Running<'_>) -> Option<u64> {
        match running.reading(self.moment)? {
            Reading::Used(memory) => Some(memory),
            Reading::NotYet | Reading::Stale => None,
        }
    }

    /// What the slice holds now as the mark reads it: its runners' use with the trace's overhead.
    fn slice(&self) -> u64 {
        self.used_now() + self.trace.map_or(0, |trace| trace.overhead)
    }

    /// What the guards read of the slice now, as a sample would show it at a decision.
    fn slice_read(&self) -> u64 {
        self.used_now() + self.trace.map_or(0, |trace| trace.guard_overhead)
    }

    /// What the running jobs use now, as their samples say.
    fn used_now(&self) -> u64 {
        self.running
            .iter()
            .map(|running| self.used(running).unwrap_or(0))
            .sum()
    }

    /// The host as a reading would have it now: its other programs as recorded, the slice as replayed. `None` without
    /// a trace of it.
    fn host_memory(&self) -> Option<HostMemory> {
        let trace = self.trace.filter(|trace| trace.total > 0)?;
        let outside = trace.outside_at(self.moment)?;
        let slice = self.used_now() + trace.host_overhead;
        Some(HostMemory {
            at: self.moment / 1000,
            total: trace.total,
            available: trace.total.saturating_sub(outside).saturating_sub(slice),
            slice,
            some: None,
            full: None,
            holders: Vec::new(),
            ceiling: None,
            swap: None,
        })
    }

    /// The aggregate count of what runs, the mirror's memory with it.
    fn count(&self) -> pooled::Count {
        self.count_with(None)
    }

    /// The count with a runner `starting` that much added, as the next plan would read it: under the credits, the
    /// count with that much more; under the growth count, as much more as it makes the room kept for growth.
    fn count_with(&self, starting: Option<u64>) -> pooled::Count {
        let mut runners = self.held();
        runners.extend(starting.map(|takes| pooled::Runner {
            key: None,
            takes,
            used: Reading::NotYet,
            ran: Some(Duration::ZERO),
            basis: None,
        }));
        // Braked, the growth count rests: its `below` counts.
        let hold = if self.braked() {
            pooled::Hold::Held
        } else {
            pooled::Hold::Free
        };
        self.count_of(&runners, hold)
    }

    /// The count of `runners`, the growth count's brake holding it as `hold` says.
    fn count_of(&self, runners: &[pooled::Runner<'_>], hold: pooled::Hold) -> pooled::Count {
        let host = self.host_memory();
        let measured = self.trace.is_some() && self.policy == Policy::Measured;
        pooled::count(&pooled::Snapshot {
            runners,
            committed: self.mirror,
            slice: Some(pooled::Slice {
                memory: self.slice_read(),
                memory_max: self.memory_max,
            }),
            host: host.map(|memory| {
                host::pooling(
                    &memory,
                    host::Remembered::new(self.host_band, host::Occupancy::Occupied),
                )
            }),
            most: if measured { self.most_credit } else { 0 },
            host_reserve: measured && self.host_reserve == HostReserve::Top2,
            growth: self.growth.map(|growth| pooled::Growth {
                hold,
                ..growth.growth
            }),
        })
    }

    /// What the runners count, as `pooled::count` reads them: what each takes and what its samples say it uses.
    fn held(&self) -> Vec<pooled::Runner<'_>> {
        self.running
            .iter()
            .map(|running| {
                let used = running
                    .reading(self.moment)
                    .filter(|_| running.run.measure == Measure::WithoutPageCache)
                    .unwrap_or(Reading::Stale);
                pooled::Runner {
                    key: running.named(self.moment).then_some(&running.key),
                    takes: self.charge(running),
                    used,
                    ran: Some(Duration::from_millis(
                        running.job_ran(self.moment).unwrap_or(0),
                    )),
                    basis: Some(running.basis),
                }
            })
            .collect()
    }

    /// Whether the growth brake holds the count plain now.
    fn braked(&self) -> bool {
        self.growth.is_some() && self.brake.braked(instant(self.moment)).is_some()
    }

    /// With the growth count's brake on, takes a plan's look at what each runner uses, the room the count keeps and,
    /// with its guard's hold, whether the count is below its guard's line.
    fn look_at_growth(&mut self) {
        let Some(GrowthCount {
            growth,
            brake: Brake::On,
            guard,
        }) = self.growth
        else {
            return;
        };
        let held = self.held();
        let room = pooled::growth_room(&held, growth);
        let guard = match guard {
            GuardHold::On if self.count_of(&held, pooled::Hold::Free).kept.is_none() => {
                growth::Guard::Crossed
            }
            GuardHold::On | GuardHold::Off => growth::Guard::Clear,
        };
        let used: Vec<growth::Use<u64>> = self
            .running
            .iter()
            .zip(&held)
            .filter_map(|(running, runner)| {
                let memory = match runner.used {
                    Reading::Used(memory) => memory,
                    Reading::NotYet => 0,
                    Reading::Stale => return None,
                };
                Some(growth::Use {
                    runner: running.job,
                    memory,
                })
            })
            .collect();
        self.brake.look(instant(self.moment), used, room, guard);
    }

    /// What the host leaves beside what runs, the mirror's memory counted; `None` without a trace of it.
    fn host_left(&self) -> Option<i64> {
        self.host_left_with(self.count())
    }

    /// What the host leaves beside `count`; `None` without a trace of it.
    fn host_left_with(&self, count: pooled::Count) -> Option<i64> {
        let memory = self.host_memory()?;
        let limit = host::limit(
            &memory,
            self.host_band
                .short(host::Occupancy::of(!self.running.is_empty())),
        );
        Some(host::left(limit, count.hosted(), false))
    }

    /// Serves `waiting` at `now`, as one `scheduler::plan` does: each job in turn starts if it fits, until a job that
    /// waited long enough puts up the barrier; the jobs behind it start if `Backfill` lets them, and still age by what
    /// they lack themselves.
    fn pass(&mut self, waiting: &mut Vec<Queued<'run>>, now: u64) {
        let at = instant(now);
        self.look_at_growth();
        self.barrier = None;
        self.backfill = None;
        self.usual.clear();
        self.needs.borrow_mut().clear();
        self.held_for_slice = 0;
        self.held_for_host = 0;
        self.host_needs.clear();
        let listed = waiting.clone();
        let mut index = 0;
        while let Some(queued) = waiting.get(index).copied() {
            match self.admits(queued, waiting, now) {
                Ok(admitted) if self.barrier.is_none() => {
                    waiting.remove(index);
                    self.start(queued, &admitted, None, now);
                }
                Ok(admitted) => match self.passes(queued, &listed) {
                    Some(usual) => {
                        waiting.remove(index);
                        self.start(queued, &admitted, Some(usual), now);
                    }
                    None => index += 1,
                },
                Err(Refused::Slot) => index += 1,
                Err(Refused::Budget(short)) => {
                    if self.barrier.is_none() && short.scarce == Scarce::Cpu {
                        self.cpu_held += 1;
                    }
                    self.held_for_slice += u64::from(short.scarce == Scarce::Memory);
                    let first = self.barrier.is_none();
                    self.hold(queued.run, short, at);
                    if first && self.barrier.is_some() {
                        self.backfill_behind(queued.run, &waiting[..index], &listed, now);
                    }
                    index += 1;
                }
                Err(Refused::Host(short)) => {
                    self.held_for_host += 1;
                    // A job behind a barrier does not wait for the host, as the daemon's `Turn::behind`: the owner does.
                    if self.barrier.is_none() {
                        self.host_needs.push(short.memory);
                    }
                    let first = self.barrier.is_none();
                    self.hold(queued.run, short, at);
                    if first && self.barrier.is_some() {
                        self.backfill_behind(queued.run, &waiting[..index], &listed, now);
                    }
                    index += 1;
                }
                Err(Refused::HighWater(short)) => {
                    if self.barrier.is_none() {
                        self.held_back += 1;
                    }
                    self.hold(queued.run, short, at);
                    index += 1;
                }
            }
        }
        self.host_band = self.next_band();
        self.settle_waits(waiting);
    }

    /// The band that stands for the next pass; a replay does not model stalls.
    fn next_band(&self) -> host::HostBand {
        match self.band {
            Band::AnyWaiter if self.held_for_host > 0 => host::HostBand::Larger,
            Band::AnyWaiter => host::HostBand::Plain,
            Band::NoWaiterFits => self.host_memory().map_or(host::HostBand::Plain, |memory| {
                let reserved = self.count().hosted();
                let needs = self.host_needs.iter().copied();
                host::HostBand::after_plan(&memory, reserved, false, needs)
            }),
        }
    }

    /// What the engine does after a plan: a pool with nothing `waiting` loses its served mark, and one with nothing left
    /// to keep goes.
    fn settle_waits(&mut self, waiting: &[Queued<'run>]) {
        let queued: BTreeSet<Pool> = waiting.iter().map(|queued| pool_of(queued.run)).collect();
        self.pool_waits.retain(|pool, waits| {
            if !queued.contains(pool) {
                waits.emptied();
            }
            !waits.is_empty()
        });
    }

    /// Unless `Barriers::Off`, ages the pool of `run`, which lacks what `short` says, and lets it put up the barrier, as
    /// `scheduler::plan` and the engine do. None ages at the high-water mark, read job by job as `admits` reads it:
    /// its zeros say nothing.
    fn hold(&mut self, run: &'run Ran, short: Short, at: SystemTime) {
        if self.barriers == Barriers::Off {
            return;
        }
        let drained = (!self.at_high_water()).then_some(self.drained());
        let waits = self.pool_waits.entry(pool_of(run)).or_default();
        if drained.is_some() {
            waits.note(short.scarce, short.job, at);
        }
        if self.barrier.is_none() {
            self.barrier = Barrier::of(short, waits, drained, at);
            if self.barrier.is_some() {
                waits.own(short.job);
            }
        }
    }

    /// Under `Barriers::On`, finds the room behind the barrier `run` just put up, `older` being the jobs left waiting
    /// before it and `listed` what the pass began with. A pool's jobs start alike, so its first speaks for it.
    fn backfill_behind(
        &mut self,
        run: &'run Ran,
        older: &[Queued<'run>],
        listed: &[Queued<'run>],
        now: u64,
    ) {
        let Some(barrier) = self.barrier.filter(|_| self.barriers == Barriers::On) else {
            return;
        };
        let mut pools = BTreeSet::new();
        let older: Vec<Older<'_>> = older
            .iter()
            .filter(|queued| self.config.profiles.contains_key(&queued.run.profile))
            .filter(|queued| pools.insert(pool_of(queued.run)))
            .map(|queued| {
                let starting = self.starting(*queued, listed, now);
                Older {
                    profile: &queued.run.profile,
                    free_slot: self.free_slots(&queued.run.profile) > 0,
                    memory: starting.memory,
                    cpu: starting.cpu,
                }
            })
            .collect();
        let runners = self.runners();
        let around = Around {
            left: self.left(),
            credit_room: self.credit_room(),
            host_credit_room: self.host_credit_room(),
            drained: self.drained(),
            runners: &runners,
            older: &older,
        };
        self.backfill = Backfill::behind(barrier, &run.profile, around, instant(now));
    }

    /// How much more the credit could take off what runs, as `Budget::credit_room`.
    fn credit_room(&self) -> u64 {
        if self.trace.is_none()
            || self.policy != Policy::Measured
            || self.expects_credit == CreditRoom::LeftOut
        {
            return 0;
        }
        self.count().credit_room
    }

    /// How much more the host's credit could take off what runs, as `Budget::host_credit_room`.
    fn host_credit_room(&self) -> u64 {
        if self.expects_credit == CreditRoom::LeftOut {
            return 0;
        }
        self.count().host_credit_room
    }

    /// What a drain leaves.
    fn drained(&self) -> Drained {
        Drained {
            memory: self.budget.map(signed),
            cpu: self.cpu_budget.map(signed),
            host: self.host_memory().map(|memory| {
                let limit = host::limit(&memory, !self.running.is_empty());
                signed(limit).saturating_sub(signed(self.mirror))
            }),
            host_plain: self.host_memory().map(|memory| {
                signed(host::limit(&memory, false)).saturating_sub(signed(self.mirror))
            }),
        }
    }

    /// How many of `profile`'s slots are free.
    fn free_slots(&self, profile: &str) -> usize {
        let limits = &self.config.profiles[profile];
        let slots = self.slots.get(profile).copied().unwrap_or(limits.slots);
        let in_profile = self
            .running
            .iter()
            .filter(|running| running.profile == profile)
            .count();
        (slots as usize).saturating_sub(in_profile)
    }

    /// Whether `queued`, which fits, may start behind the barrier, `listed` being what the pass began with: the usual
    /// run time it passes by, if so.
    fn passes(&mut self, queued: Queued<'run>, listed: &[Queued<'run>]) -> Option<Duration> {
        let run = queued.run;
        self.backfill.as_ref()?;
        let predictor = &self.predictor;
        let usual = *self.usual.entry(pool_of(run)).or_insert_with(|| {
            let keys = listed
                .iter()
                .filter(|other| other.run.repository == run.repository)
                .filter(|other| other.run.profile == run.profile)
                .map(|other| Key::of(other.run));
            predictor.longest_usual(keys, &run.profile)
        });
        let candidate = Candidate {
            profile: &run.profile,
            free_slots: self.free_slots(&run.profile),
            usual,
            caps: self.caps(&run.profile),
        };
        let backfill = self.backfill.as_mut()?;
        backfill.admits(candidate).then_some(usual).flatten()
    }

    /// The budgets left beside what runs.
    fn left(&self) -> Left {
        let cpu = self.cpu_taken();
        let left = |budget: u64, taken: u64| signed(budget).saturating_sub(signed(taken));
        Left {
            memory: self.budget.map(|budget| left(budget, self.taken())),
            cpu: self.cpu_budget.map(|budget| left(budget, cpu)),
            host: self.host_left(),
        }
    }

    /// The CPU the running jobs reserve, in millicores.
    fn cpu_taken(&self) -> u64 {
        self.running
            .iter()
            .map(|running| running.cpu_at(self.moment))
            .sum()
    }

    /// `profile`'s caps, its CPU at most the budget, as `scheduler::Profile` has them.
    fn caps(&self, profile: &str) -> Caps {
        let limits = &self.config.profiles[profile];
        let cpu = u64::from(limits.cpus).saturating_mul(1000);
        Caps {
            memory: limits.memory.0,
            cpu: self.cpu_budget.map_or(cpu, |budget| cpu.min(budget)),
        }
    }

    /// Notes the worst moments so far, with the `mirror`'s memory.
    fn note_worst(&mut self, mirror: u64) {
        self.most_running = self.most_running.max(self.running.len() as u64);
        let peaks: u64 = self.running.iter().map(|running| running.peak).sum();
        self.worst_overlap = self.worst_overlap.max(peaks + mirror);
        let cpu: u64 = self
            .running
            .iter()
            .map(|running| running.run.cpu_average.unwrap_or(0))
            .sum();
        self.worst_cpu = self.worst_cpu.max(cpu);
    }

    /// What the replay of `queue` came to.
    fn replay(mut self, queue: &[Queued<'run>]) -> Replay {
        let started: BTreeSet<u64> = self.started.iter().copied().collect();
        let never_started: Vec<&Queued<'_>> = queue
            .iter()
            .filter(|queued| !started.contains(&queued.job))
            .collect();
        for queued in &never_started {
            self.pools
                .entry(pool_of(queued.run))
                .or_default()
                .never_started += 1;
        }
        let waits = self.waits;
        let first = queue.first().map_or(0, |queued| queued.run.queued_at);
        Replay {
            jobs: queue.len() as u64,
            never_started: never_started.len() as u64,
            mean_wait: waits.iter().sum::<u64>() / (waits.len() as u64).max(1),
            wait: spread(waits),
            most_running: self.most_running,
            worst_overlap: self.worst_overlap,
            makespan: self.last_end.saturating_sub(first) / 1000,
            under_predicted: self.under_predicted,
            held_back: self.held_back,
            cpu_held: self.cpu_held,
            worst_cpu: self.worst_cpu,
            pools: self.pools,
            charged: self.charged,
            capacity: self.capacity,
            barrier_for: self.barrier_for,
            withheld: self.withheld,
            runs: self.runs.into_values().map(RunSpan::replay).collect(),
            backfilled: self.backfilled,
            slice_waited: self.slice_waited,
            host_waited: self.host_waited,
            hazard: self.hazard,
        }
    }

    /// What runs, as a backfill reads it: each job's usual run time as the runs finished so far say.
    fn runners(&self) -> Vec<Runner<'_>> {
        self.running
            .iter()
            .map(|running| Runner {
                profile: running.profile,
                started_at: instant(running.started),
                usual: self.predictor.usual(&Key::of(running.run), running.profile),
                memory: self.charge(running),
                cpu: running.cpu_at(self.moment),
                caps: self.caps(running.profile),
                passed: running.backfilled.is_some(),
            })
            .collect()
    }

    /// Whether measured admission starts nothing now: with a trace, what the slice holds is at the high-water mark, and
    /// without one the running jobs' peaks are.
    fn at_high_water(&self) -> bool {
        if self.trace.is_some() {
            return self.policy == Policy::Measured
                && self.memory_max.is_some_and(|max| {
                    self.slice_read().saturating_mul(100) >= max.saturating_mul(HIGH_WATER)
                });
        }
        let peaks: u64 = self.running.iter().map(|running| running.peak).sum();
        self.policy == Policy::Measured
            && self.budget.is_some_and(|budget| {
                peaks.saturating_mul(100) >= budget.saturating_mul(HIGH_WATER)
            })
    }

    /// Ends the jobs that end by `now`, in the order they end; measured admission learns them as the daemon reads
    /// their rows.
    fn finish(&mut self, now: u64) {
        let (ended, running): (Vec<_>, Vec<_>) = std::mem::take(&mut self.running)
            .into_iter()
            .partition(|running| running.ends <= now);
        self.running = running;
        let mut ended = ended;
        ended.sort_by_key(|ended| ended.ends);
        for ended in ended {
            // As the daemon reads the row: under the cap its container had.
            let cap = ended
                .run
                .memory_cap
                .unwrap_or(self.config.profiles[ended.profile].memory.0);
            self.under_predicted += u64::from(ended.peak > ended.reserved);
            let reserved = (self.policy == Policy::Measured).then_some(ended.reserved);
            let run = Ran {
                reserved,
                ..ended.run.clone()
            };
            self.predictor.learn(&run, ended.profile, cap, ended.ends);
            self.last_end = self.last_end.max(ended.ends);
            if let Some(by) = ended.backfilled {
                let overrun = ended.ends.saturating_sub(by);
                self.backfilled.overran += u64::from(overrun > 0);
                self.backfilled.most_overrun = self.backfilled.most_overrun.max(overrun / 1000);
            }
            let span = self.runs.get_mut(&run_key(ended.run));
            if let Some(span) = span {
                span.last_end = span.last_end.max(ended.ends);
            }
            for follower in self.followers.remove(&ended.job).unwrap_or_default() {
                self.arriving
                    .insert((ended.ends + follower.gap, follower.at));
            }
        }
    }

    /// Under measured admission, predicts each running job again, as the daemon's runners follow their job's
    /// prediction every tick: the first running copy of a job, in the order they started, goes by its own runs, and
    /// the others have it beside them.
    fn rereserve(&mut self, now: u64) {
        if self.policy != Policy::Measured {
            return;
        }
        let cpus: Vec<u64> = self
            .running
            .iter()
            .map(|running| self.cpu(&Key::of(running.run), running.profile))
            .collect();
        let mut seen = BTreeSet::new();
        for (running, cpu) in self.running.iter_mut().zip(cpus) {
            let key = Key::of(running.run);
            let copies = if seen.insert(key.clone()) {
                Copies::Alone
            } else {
                Copies::Several
            };
            let limits = &self.config.profiles[running.profile];
            let prediction =
                self.predictor
                    .predict(&key, running.profile, limits.memory.0, now, copies);
            running.reserved = prediction.memory;
            running.basis = prediction.basis;
            running.cpu = cpu;
        }
    }

    /// The CPU a run of `key` in `profile` reserves, in millicores: its profile's `cpus` by caps, its predicted
    /// average measured, at most the CPU budget.
    fn cpu(&self, key: &Key, profile: &str) -> u64 {
        let cap = u64::from(self.config.profiles[profile].cpus).saturating_mul(1000);
        let cpu = match self.policy {
            Policy::Caps => cap,
            Policy::Measured => self.predictor.predict_cpu(key, profile, cap).cpu,
        };
        self.cpu_budget.map_or(cpu, |budget| cpu.min(budget))
    }

    /// What the running jobs take of the budget, as `pooled::count` adds them up, the mirror left out: the budget is
    /// what it leaves.
    fn taken(&self) -> u64 {
        self.count().pooled().saturating_sub(self.mirror)
    }

    /// What `running` takes of the budget: under measured admission, as the daemon counts it, the larger of what it
    /// reserved and what it uses, without a trace its peak for the whole run; with one, until its job is known what it
    /// started reserving, and at its cap while its samples say nothing.
    fn charge(&self, running: &Running<'_>) -> u64 {
        if running.trace.is_none() || self.policy != Policy::Measured {
            return match self.policy {
                Policy::Caps => running.reserved,
                Policy::Measured => running.reserved.max(running.peak),
            };
        }
        let reserved = if running.named(self.moment) {
            running.reserved
        } else {
            running.starting.max(running.reserved)
        };
        match running.reading(self.moment).unwrap_or(Reading::NotYet) {
            Reading::NotYet => reserved,
            Reading::Used(memory) => reserved.max(memory),
            Reading::Stale => self.config.profiles[running.profile].memory.0,
        }
    }

    /// What `queued` reserves if it starts at `now`, or why the policy does not admit it, `waiting` being every job
    /// not started yet.
    fn admits(
        &self,
        queued: Queued<'run>,
        waiting: &[Queued<'run>],
        now: u64,
    ) -> Result<Admitted, Refused> {
        let run = queued.run;
        let Some(limits) = self.config.profiles.get(&run.profile) else {
            return Err(Refused::Slot);
        };
        if self.free_slots(&run.profile) == 0 {
            return Err(Refused::Slot);
        }
        let starting = self.starting(queued, waiting, now);
        let short = |scarce, held| Short {
            job: queued.job,
            scarce,
            held,
            memory: starting.memory,
            cpu: starting.cpu,
        };
        let with = self.count_with(Some(starting.memory));
        if let Some(budget) = self.budget {
            if with.pooled().saturating_sub(self.mirror) > budget {
                return Err(Refused::Budget(short(Scarce::Memory, Held::ByBudget)));
            }
            if self.at_high_water() {
                return Err(Refused::HighWater(short(Scarce::Memory, Held::ByBudget)));
            }
        }
        if self.host_left_with(with).is_some_and(|left| left < 0) {
            return Err(Refused::Host(short(Scarce::Memory, Held::ByHost)));
        }
        if let Some(cpu_budget) = self.cpu_budget {
            let taken = self.cpu_taken();
            if taken + starting.cpu > cpu_budget {
                return Err(Refused::Budget(short(Scarce::Cpu, Held::ByBudget)));
            }
        }
        Ok(Admitted {
            reserved: starting.reserved,
            starting: starting.memory,
            basis: starting.basis,
            // A job over its cap is killed at it.
            peak: run.memory_peak.min(limits.memory.0),
            cpu: self.cpu(&Key::of(run), &run.profile),
            starting_cpu: starting.cpu,
        })
    }

    /// What the runner of `queued` starts with. As in the daemon, it starts reserving the largest prediction among the
    /// waiting jobs of its repository's pool (those that ran in its profile), then its job's own.
    fn starting(&self, queued: Queued<'run>, waiting: &[Queued<'run>], now: u64) -> Starting {
        let run = queued.run;
        let profile = run.profile.as_str();
        let cap = self.config.profiles[profile].memory.0;
        let running = |job: &Ran| {
            self.running
                .iter()
                .any(|running| same_job(running.run, job))
        };
        // A waiting job with a copy waiting or running beside it, as the daemon sees its queue.
        let predicted = |job: &Ran| {
            let key = Key::of(job);
            let waiting = waiting
                .iter()
                .filter(|other| same_job(other.run, job))
                .count();
            let copies = if waiting > 1 || running(job) {
                Copies::Several
            } else {
                Copies::Alone
            };
            self.predictor
                .predict(&key, profile, cap, now, copies)
                .memory
        };
        // The started job, once known: the first of its copies to run goes by its own runs.
        let started = || {
            let key = Key::of(run);
            let copies = if running(run) {
                Copies::Several
            } else {
                Copies::Alone
            };
            self.predictor.predict(&key, profile, cap, now, copies)
        };
        let pool = || {
            waiting
                .iter()
                .map(|other| other.run)
                .filter(|job| job.repository == run.repository && job.profile == run.profile)
        };
        let own = started();
        let need = || Need {
            memory: pool().map(predicted).max().unwrap_or(0),
            // As the daemon starts a runner: at the most CPU any waiting job of its repository's pool reserves.
            cpu: pool()
                .map(|job| self.cpu(&Key::of(job), profile))
                .max()
                .unwrap_or(0),
        };
        let need = if self.trace.is_some() {
            *self
                .needs
                .borrow_mut()
                .entry(pool_of(run))
                .or_insert_with(need)
        } else {
            need()
        };
        let (memory, reserved, basis) = match self.policy {
            Policy::Caps => (cap, cap, Basis::Cap),
            Policy::Measured => (need.memory.max(own.memory), own.memory, own.basis),
        };
        Starting {
            memory,
            reserved,
            basis,
            cpu: need.cpu.max(self.cpu(&Key::of(run), profile)),
        }
    }

    /// Starts `queued` at `now`, which ends its pool's wait; `usual`, the usual run time it started behind a barrier by.
    fn start(
        &mut self,
        queued: Queued<'run>,
        admitted: &Admitted,
        usual: Option<Duration>,
        now: u64,
    ) {
        let run = queued.run;
        let Some((profile, _)) = self.config.profiles.get_key_value(&run.profile) else {
            return;
        };
        let ran_for = run.occupied().unwrap_or_default();
        // A warm runner's start does not count: it came before the job queued.
        let boot = run
            .started_at
            .unwrap_or_default()
            .saturating_sub(run.runner_started_at.max(run.queued_at));
        let waited = now.saturating_sub(queued.arrived) / 1000;
        let span = self.runs.entry(run_key(run)).or_insert(RunSpan {
            first_arrival: queued.arrived,
            last_end: now,
            profiles: BTreeSet::new(),
        });
        span.first_arrival = span.first_arrival.min(queued.arrived);
        span.profiles.insert(run.profile.clone());
        self.started.push(queued.job);
        self.backfilled.jobs += u64::from(usual.is_some());
        let pool = pool_of(run);
        if let Some(waits) = self.pool_waits.get_mut(&pool) {
            waits.started();
        }
        self.pools.entry(pool).or_default().waits.push(waited);
        self.waits.push(waited);
        self.running.push(Running {
            run,
            job: queued.job,
            profile,
            started: now,
            ends: now + ran_for,
            backfilled: usual.map(|usual| {
                now.saturating_add(u64::try_from(usual.as_millis()).unwrap_or(u64::MAX))
            }),
            reserved: admitted.reserved,
            peak: admitted.peak,
            cpu: admitted.cpu,
            starting_cpu: admitted.starting_cpu,
            key: Key::of(run),
            basis: admitted.basis,
            starting: admitted.starting,
            trace: self.trace.and_then(|trace| trace.runs.get(&RunId::of(run))),
            boot,
        });
        self.needs.borrow_mut().clear();
        if self.trace.is_some() {
            self.cohorts.push(Cohort {
                jobs: self.running.iter().map(|running| running.job).collect(),
                count: self.taken(),
            });
        }
    }
}

/// `ms` since the epoch, as `scheduler::plan` reads the clock.
fn instant(ms: u64) -> SystemTime {
    SystemTime::UNIX_EPOCH + Duration::from_millis(ms)
}

/// A budget's bytes or millicores as `Drained` counts them.
fn signed(amount: u64) -> i64 {
    i64::try_from(amount).unwrap_or(i64::MAX)
}