runnerd-core 0.1.1

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
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
//! How soon the engine starts runners for queued jobs on the fakes: idle runners it removes in the same tick do not
//! hold the starts back, and a slot whose job ended takes the next listed job within seconds, through the engine's
//! own loop (ADR 0095).

use tokio::time::Instant;

use super::*;
use crate::scheduler::IDLE_TIMEOUT;
use crate::scheduler::engine::STOP_DEADLINE;

/// `o/r` with an idle runner in slot 1 that waited past `IDLE_TIMEOUT`, whose log capture ends only with its
/// container, and a job of `o/s` queued for slot 2.
async fn idle_runner_beside_a_queued_job(
    github: &FakeGithub,
    docker: &FakeDocker,
    dir: &TestDir,
) -> (Engine<FakeGithub, FakeDocker>, Handle) {
    idle_runner(github, docker);
    {
        let mut state = docker.0.lock().unwrap();
        state.captures_wait = Some(github.clone());
        state.capture_end = CaptureEnd::Container;
    }
    {
        let mut state = github.0.lock().unwrap();
        state.queued = vec![job(5)];
        state.queued_on.insert(5, "o/s".to_owned());
    }
    let (mut engine, handle) = engine_with(github, docker, dir, &two_repositories());
    engine.recover().await.unwrap();
    for occupant in engine.occupants_mut() {
        occupant.started_at -= IDLE_TIMEOUT;
    }
    (engine, handle)
}

#[tokio::test(start_paused = true)]
async fn removing_an_idle_runner_does_not_hold_back_a_start_for_another_repository() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("pacing");
    let (mut engine, handle) = idle_runner_beside_a_queued_job(&github, &docker, &dir).await;

    let began = Instant::now();
    engine.tick(Shutdown::No).await;
    let took = began.elapsed();

    assert_eq!(removed(&docker.calls()), ["remove container-1"]);
    assert_eq!(registered(&github.calls()).len(), 1, "o/s got its runner");
    // The capture of a runner that is still up ends only once its container goes: waiting for it before the
    // removal held every later start of the tick back by the whole drain.
    assert!(
        took < super::super::history::CAPTURE_DRAIN,
        "the tick took {took:?}"
    );
    // The history says why the idle runner went, and why the new one started.
    handle.store.flush().await;
    let history = rusqlite::Connection::open(dir.0.join("history.db")).unwrap();
    let runners: Vec<(String, Option<String>, Option<String>)> = history
        .prepare("SELECT repository, purpose, stopped_for FROM runners ORDER BY started_at")
        .unwrap()
        .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
        .unwrap()
        .collect::<Result<_, _>>()
        .unwrap();
    assert_eq!(
        runners,
        [
            ("o/r".to_owned(), None, Some("expired".to_owned())),
            ("o/s".to_owned(), Some("job".to_owned()), None)
        ]
    );
}

/// What a burst's world saw.
#[derive(Debug, Default)]
struct Seen {
    /// Each job's wait from its queueing to its runner's container start.
    waits: Vec<Duration>,
    /// Each runner start that took the room of one whose job ended while a listed job waited: when that one's
    /// container stopped, and how long until this one's container started.
    turnovers: Vec<(Instant, Duration)>,
    /// Runner containers started.
    starts: usize,
    /// Jobs runners took.
    taken: usize,
    /// Runner starts past the slice's memory, what ran then.
    over_budget: Vec<u64>,
}

/// A runner of the burst with a job.
struct Running {
    container: String,
    name: String,
    job: u64,
    /// When its capture names its job.
    named_at: Instant,
    ends_at: Instant,
}

/// The world around an engine that runs its own loop: `o/r`'s jobs, each taken by an idle runner of this machine
/// `boot` after its container started, named by its log capture `named_after` later, and ending `run` to twice that
/// after it was taken, when its container stops and Docker's events say so, twice, beside one for a container runnerd never ran.
/// GitHub drops an ended runner's registration, as an ephemeral runner's goes with its job.
struct Burst {
    github: FakeGithub,
    docker: FakeDocker,
    boot: Duration,
    run: Duration,
    named_after: Duration,
    /// The slice's `MemoryMax`.
    budget: u64,
    /// Whether removing a runner's container takes 5 to 25 s, different for each, so the slots' generations drift
    /// apart rather than end together.
    slow_removals: bool,
    queued_at: HashMap<u64, Instant>,
    /// The jobs a listing of queued jobs showed.
    listed: BTreeSet<u64>,
    /// Listings of queued jobs so far, and when the world first saw each.
    listings: usize,
    listed_at: Vec<Instant>,
    /// GitHub's calls seen so far, and when the world first saw each repository's queued jobs listings.
    calls_seen: usize,
    listed_at_of: BTreeMap<String, Vec<Instant>>,
    running: Vec<Running>,
    /// The runner containers seen so far, and those that took a job.
    started: BTreeSet<String>,
    assigned: BTreeSet<String>,
    /// When runners stopped while a listed job waited, oldest first: the next starts take their room.
    freed: VecDeque<Instant>,
    seen: Seen,
}

impl Burst {
    fn new(github: &FakeGithub, docker: &FakeDocker, budget: u64) -> Burst {
        Burst {
            github: github.clone(),
            docker: docker.clone(),
            boot: Duration::from_secs(6),
            run: Duration::from_secs(10),
            named_after: Duration::from_secs(1),
            budget,
            slow_removals: false,
            queued_at: HashMap::new(),
            listed: BTreeSet::new(),
            listings: 0,
            listed_at: Vec::new(),
            calls_seen: 0,
            listed_at_of: BTreeMap::new(),
            running: Vec::new(),
            started: BTreeSet::new(),
            assigned: BTreeSet::new(),
            freed: VecDeque::new(),
            seen: Seen::default(),
        }
    }

    /// GitHub queues `count` jobs of `o/r`.
    fn queue(&mut self, count: u64) {
        let mut github = self.github.0.lock().unwrap();
        let first = github
            .queued
            .iter()
            .map(|job| job.id)
            .max()
            .unwrap_or(0)
            .max(self.queued_at.keys().copied().max().unwrap_or(0))
            + 1;
        for id in first..first + count {
            github.queued.push(job(id));
            github.queued_on.insert(id, "o/r".to_owned());
            self.queued_at.insert(id, Instant::now());
        }
    }

    /// When the world first saw each listing of `repository`'s queued jobs since `from`.
    fn listed_since(&self, repository: &str, from: Instant) -> Vec<Instant> {
        self.listed_at_of
            .get(repository)
            .into_iter()
            .flatten()
            .copied()
            .filter(|at| *at >= from)
            .collect()
    }

    /// Whether every job queued so far ran.
    fn done(&self) -> bool {
        self.seen.taken == self.queued_at.len() && self.running.is_empty()
    }

    /// One step of the world, at `now`.
    fn step(&mut self, now: Instant) {
        let (github, docker) = (self.github.clone(), self.docker.clone());
        let mut github = github.0.lock().unwrap();
        let mut docker = docker.0.lock().unwrap();
        let listings = github
            .calls
            .iter()
            .filter(|call| call.starts_with("queued "))
            .count();
        if listings > self.listings {
            self.listings = listings;
            self.listed_at.push(now);
            self.listed.extend(github.queued.iter().map(|job| job.id));
        }
        for call in &github.calls[self.calls_seen..] {
            if let Some(repository) = call.strip_prefix("queued ") {
                let times = self.listed_at_of.entry(repository.to_owned()).or_default();
                if times.last() != Some(&now) {
                    times.push(now);
                }
            }
        }
        self.calls_seen = github.calls.len();
        self.see_starts(&mut docker, now);
        self.take_jobs(&mut github, &mut docker, now);
        self.end_jobs(&mut github, &mut docker, now);
    }

    /// Each runner container started since: what runs then fits the slice, and it takes a stopped one's room.
    fn see_starts(&mut self, docker: &mut DockerState, now: Instant) {
        // Each runner container started since: what runs then fits the slice, and it takes a stopped one's room.
        let new: Vec<String> = docker
            .containers
            .iter()
            .filter(|container| {
                container.labels.contains_key("runnerd.job")
                    && !self.started.contains(&container.id)
            })
            .map(|container| container.id.clone())
            .collect();
        for id in new {
            self.started.insert(id.clone());
            self.seen.starts += 1;
            if self.slow_removals {
                let step = u64::try_from(self.seen.starts * 7 % 5).unwrap();
                docker
                    .slow_removes
                    .insert(id.clone(), Duration::from_secs(5 + step * 5));
            }
            let using: u64 = docker
                .containers
                .iter()
                .filter(|container| {
                    container.running && container.labels.contains_key("runnerd.job")
                })
                .filter_map(|container| docker.memory.get(&container.id))
                .sum();
            if using > self.budget {
                self.seen.over_budget.push(using);
            }
            let name = docker
                .containers
                .iter()
                .find(|container| container.id == id)
                .map(|container| container.name.clone())
                .unwrap_or_default();
            let at = docker.started_on_clock.get(&name).copied().unwrap_or(now);
            if let Some(stopped) = self.freed.pop_front() {
                self.seen
                    .turnovers
                    .push((stopped, at.saturating_duration_since(stopped)));
            }
        }
    }

    /// Each runner up `boot` and idle takes the oldest job queued.
    fn take_jobs(&mut self, github: &mut GithubState, docker: &mut DockerState, now: Instant) {
        let idle: Vec<(String, String)> = docker
            .containers
            .iter()
            .filter(|container| {
                container.running
                    && container.labels.contains_key("runnerd.job")
                    && !self.assigned.contains(&container.id)
                    && docker
                        .started_on_clock
                        .get(&container.name)
                        .is_some_and(|at| now.saturating_duration_since(*at) >= self.boot)
            })
            .map(|container| (container.id.clone(), container.name.clone()))
            .collect();
        for (container, name) in idle {
            let Some(job) = github.queued.iter().map(|job| job.id).min() else {
                break;
            };
            github.queued.retain(|queued| queued.id != job);
            for runner in &mut github.runners {
                if runner.name == name {
                    runner.busy = true;
                }
            }
            let mut details = details(job, "in_progress", None);
            details.runner_name = Some(name.clone());
            github.jobs.insert(job, details);
            let started = docker.started_on_clock.get(&name).copied().unwrap_or(now);
            self.seen
                .waits
                .push(started.saturating_duration_since(self.queued_at[&job]));
            self.seen.taken += 1;
            self.assigned.insert(container.clone());
            self.running.push(Running {
                container,
                name,
                job,
                named_at: now + self.named_after,
                // From `run` to twice it, so jobs end apart, as a burst's do.
                ends_at: now + self.run + self.run * u32::try_from(job * 7 % 11).unwrap() / 10,
            });
        }
    }

    /// Names the jobs of runners up `named_after`, and ends those whose time came.
    fn end_jobs(&mut self, github: &mut GithubState, docker: &mut DockerState, now: Instant) {
        for running in &self.running {
            if running.named_at <= now {
                docker
                    .container_captures
                    .entry(running.container.clone())
                    .or_insert_with(|| format!("@@job {0} {0}\n", running.job));
            }
        }
        let (ended, left): (Vec<Running>, Vec<Running>) = std::mem::take(&mut self.running)
            .into_iter()
            .partition(|running| running.ends_at <= now);
        self.running = left;
        // Listed jobs no runner up waits for, past the one the world may be giving a runner: the room of a runner
        // that stops now is theirs.
        let idle = docker
            .containers
            .iter()
            .filter(|container| {
                container.running
                    && container.labels.contains_key("runnerd.job")
                    && !self.assigned.contains(&container.id)
            })
            .count();
        let listed = github
            .queued
            .iter()
            .filter(|job| self.listed.contains(&job.id))
            .count();
        let waiting = listed > idle + 1;
        for running in ended {
            github.runners.retain(|runner| runner.name != running.name);
            let mut details = details(running.job, "completed", Some("success"));
            details.runner_name = Some(running.name.clone());
            github.jobs.insert(running.job, details);
            if let Some(container) = docker
                .containers
                .iter_mut()
                .find(|container| container.id == running.container)
            {
                container.running = false;
            }
            for id in [
                running.container.as_str(),
                running.container.as_str(),
                "not-a-runner",
            ] {
                docker
                    .events
                    .retain(|events| events.send(Ok(id.to_owned())).is_ok());
            }
            if waiting {
                self.freed.push_back(now);
            }
        }
    }
}

/// The fakes for a burst, with the latencies the owner's host shows (ADR 0092), GitHub's listings taking
/// `listing_lag` more.
fn burst_fakes(listing_lag: Duration) -> (FakeGithub, FakeDocker) {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    {
        let mut state = github.0.lock().unwrap();
        state.strict = true;
        // A request to the API, from the journal's gaps: a listing, a registration, a delete.
        state.latency = Duration::from_millis(300);
        state.listing_latency = listing_lag;
    }
    {
        let mut state = docker.0.lock().unwrap();
        state.captures_wait = Some(github.clone());
        state.capture_end = CaptureEnd::Container;
        // Slot 1's jobs change little: no reseed holds the profile back.
        state.measured = Some(format!("slot 1 changed {} bytes\n", 1 << 20));
        state.latency = DockerLatency {
            start: Duration::from_millis(1000),
            // Not measured yet: `workload_figures` prints a burst under `CONTENTION_PLACEHOLDER` on its own line.
            contention: Duration::ZERO,
            remove_running: Duration::from_millis(1000),
            remove_stopped: Duration::from_millis(300),
            prepare: Duration::ZERO,
        };
    }
    (github, docker)
}

/// Steps `burst` every 100ms until `until` says it is over, or 30 minutes passed.
async fn play(burst: &mut Burst, mut until: impl FnMut(&Burst, Instant) -> bool) {
    let began = Instant::now();
    loop {
        let now = Instant::now();
        burst.step(now);
        if until(burst, now) || now - began > Duration::from_mins(30) {
            return;
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
}

/// Docker's events follow runner containers as they stop, through a stream that breaks off and two that fail to
/// connect, as when Docker restarts. A slot whose job ended while listed jobs waited takes the next one within
/// seconds, not at the next poll, whatever the listings, a removal or a capture take; no job gets two runners and
/// no start passes the slice's memory. The bug it catches: an exit noticed only by the next poll's inspect, a pass
/// that plans from a listing still showing a job a runner took, and one started while the slice was full.
#[tokio::test(start_paused = true)]
async fn a_slot_whose_job_ended_takes_the_next_listed_job_within_seconds() {
    const JOBS: u64 = 16;
    const G: u64 = 1 << 30;
    let (github, docker) = burst_fakes(Duration::from_secs(3));
    let dir = TestDir::new("turnover");
    let config = CONFIG.replace("slots = 2", "slots = 4");
    let (mut engine, handle) = engine_with(&github, &docker, &dir, &config);
    // Three 4G runners fit, not four: memory binds before slots.
    engine.memory_max = Some(12 * G + G / 2);
    let mut burst = Burst::new(&github, &docker, 12 * G + G / 2);
    burst.queue(JOBS);
    let run = tokio::spawn(engine.run());
    let broke = Instant::now() + Duration::from_secs(40);
    play(&mut burst, |burst, now| {
        now >= broke && !burst.running.is_empty()
    })
    .await;
    {
        docker.0.lock().unwrap().fail_events = 2;
        docker.break_events();
    }
    play(&mut burst, Burst::done_at).await;
    handle.shutdown(Shutdown::Force);
    run.await.unwrap();

    let seen = &burst.seen;
    assert_eq!(
        seen.taken,
        usize::try_from(JOBS).unwrap(),
        "every job ran: {seen:?}"
    );
    assert_eq!(
        seen.starts,
        usize::try_from(JOBS).unwrap(),
        "no job got a second runner: {seen:?}"
    );
    assert!(
        seen.over_budget.is_empty(),
        "starts passed the slice: {seen:?}"
    );
    // Every slot freed while the events were followed; the others by the next poll or the reconnect's pass.
    let followed: Vec<Duration> = seen
        .turnovers
        .iter()
        .filter(|(stopped, _)| *stopped < broke || *stopped > broke + Duration::from_secs(10))
        .map(|(_, took)| *took)
        .collect();
    assert!(followed.len() >= 8, "too few slots turned over: {seen:?}");
    assert!(
        followed.iter().all(|took| *took <= Duration::from_secs(4)),
        "a slot waited for its next runner: {followed:?}"
    );
    assert!(
        seen.turnovers
            .iter()
            .all(|(_, took)| *took <= Duration::from_secs(20)),
        "a slot freed while Docker's events were down waited past a poll: {:?}",
        seen.turnovers
    );
    assert!(
        docker
            .0
            .lock()
            .unwrap()
            .events
            .iter()
            .all(tokio::sync::mpsc::UnboundedSender::is_closed),
        "the engine stopped following Docker's events as it stopped"
    );
}

/// Waits until the history stored what the engine sent it, with the clock held: its writer is a thread of its own,
/// which a paused clock does not wait for, so under load a tick could read the history before a write it follows.
async fn stored(store: &Store) {
    let store = store.clone();
    let runtime = tokio::runtime::Handle::current();
    // A blocking task holds a paused clock while it runs.
    tokio::task::spawn_blocking(move || runtime.block_on(store.flush()))
        .await
        .unwrap();
}

/// Six of eight slots run long jobs while GitHub takes 1.8 s a request, as on the owner's host, and a job queues.
/// Its runner's container starts within a start's time of the listing that showed it. Then that job's capture names
/// it, and another job queues: it starts as fast, though the tick that lists it is the first to see the job taken.
/// The bugs it catches: the tick reading every running job's details from GitHub, a few requests at a time, before it
/// planned, which held each start back by about half a second per running job; and reading those of a job a runner
/// took since the last tick, though the history's record of the listing that showed it names it.
#[tokio::test(start_paused = true)]
async fn a_job_listed_beside_running_jobs_starts_without_waiting_for_their_reads() {
    /// How long after the first listing that showed it the `nth` job's runner started.
    fn took(burst: &Burst, queued: Instant, nth: usize) -> Duration {
        let started = queued + burst.seen.waits[nth];
        let listed = burst
            .listed_at
            .iter()
            .copied()
            .find(|at| *at >= queued)
            .unwrap();
        started.saturating_duration_since(listed)
    }
    let (github, docker) = burst_fakes(Duration::ZERO);
    github.0.lock().unwrap().latency = Duration::from_millis(1800);
    let dir = TestDir::new("listed-start");
    let config = CONFIG.replace("slots = 2", "slots = 8");
    let (engine, handle) = engine_with(&github, &docker, &dir, &config);
    let mut burst = Burst::new(&github, &docker, u64::MAX);
    burst.run = Duration::from_hours(1);
    burst.queue(6);
    let run = tokio::spawn(engine.run());
    // The six run and their captures named their jobs, a few ticks ago.
    let settled = Instant::now() + Duration::from_mins(2);
    play(&mut burst, |_, now| now >= settled).await;
    assert_eq!(burst.running.len(), 6, "six jobs run: {:?}", burst.seen);

    burst.queue(1);
    let seventh = Instant::now();
    play(&mut burst, |burst, _| burst.seen.taken == 7).await;
    // Its capture names it; the next tick is the first to take it.
    let named = Instant::now() + burst.named_after;
    play(&mut burst, |_, now| now >= named).await;
    stored(&handle.store).await;
    burst.queue(1);
    let eighth = Instant::now();
    play(&mut burst, |burst, _| burst.seen.taken == 8).await;
    handle.shutdown(Shutdown::Force);
    run.await.unwrap();

    // A start is its registration, 1.8 s, and its container's start, 1 s; the world sees a listing within 0.1 s of
    // its answer. Reading the six jobs before the plan took two rounds of requests more, and the seventh one more.
    for (nth, queued) in [(6, seventh), (7, eighth)] {
        let took = took(&burst, queued, nth);
        assert!(
            took <= Duration::from_secs(3),
            "job {}'s runner started {took:?} after the listing that showed it",
            nth + 1
        );
    }
}

/// Four jobs of `o/r` run while GitHub takes 9 s, then 20 s, to read each, and `o/s` waits for jobs beside it. `o/s`'s
/// listings keep `poll_interval`'s pace, counted from their starts, and once the reads outlast it, a tick rests
/// `TICK_REST` before the next; `o/r`'s, at a third of the interval while its jobs run, are never closer than that. The
/// bug it catches: the next listing counted from a tick's end, so slow reads pushed every listing out by their own
/// length (ADR 0111), or an idle repository listed at an active one's pace (ADR 0128). `o/r`, active, is listed
/// as often as these slow ticks let it, which is the idle pace here.
#[tokio::test(start_paused = true)]
async fn slow_job_reads_do_not_push_the_next_listing_out() {
    /// The gaps between `repository`'s listings the world saw over `span` from now.
    async fn gaps(burst: &mut Burst, repository: &str, span: Duration) -> Vec<Duration> {
        let from = Instant::now();
        play(burst, |_, now| now >= from + span).await;
        gaps_of(&burst.listed_since(repository, from))
    }
    let (github, docker) = burst_fakes(Duration::ZERO);
    github.0.lock().unwrap().job_latency = Duration::from_secs(9);
    let dir = TestDir::new("fixed-rate");
    let config = two_repositories().replace("slots = 2", "slots = 4");
    let (engine, handle) = engine_with(&github, &docker, &dir, &config);
    let mut burst = Burst::new(&github, &docker, u64::MAX);
    burst.run = Duration::from_hours(1);
    burst.queue(4);
    let run = tokio::spawn(engine.run());
    let settled = Instant::now() + Duration::from_mins(2);
    play(&mut burst, |_, now| now >= settled).await;
    assert_eq!(burst.running.len(), 4, "four jobs run: {:?}", burst.seen);

    let read = github.0.lock().unwrap().job_reads;
    let from = Instant::now();
    let paced = gaps(&mut burst, "o/s", Duration::from_mins(3)).await;
    let active = gaps_of(&burst.listed_since("o/r", from));
    assert!(
        github.0.lock().unwrap().job_reads > read,
        "the ticks read the running jobs"
    );
    // The world steps every 100 ms, and sees a listing of queued jobs 0.3 s later when its tick lists runners first.
    assert!(paced.len() >= 10, "too few listings: {paced:?}");
    assert!(
        paced
            .iter()
            .all(|gap| gap.abs_diff(Duration::from_secs(15)) <= Duration::from_millis(400)),
        "o/s's listings left `poll_interval`'s pace: {paced:?}"
    );
    // A tick whose reads take 9 s holds o/r's next listing too: it comes `TICK_REST` after that tick.
    assert!(
        active
            .iter()
            .all(|gap| *gap >= Duration::from_millis(4_900)),
        "o/r's listings came closer than a third of `poll_interval`: {active:?}"
    );

    github.0.lock().unwrap().job_latency = Duration::from_secs(20);
    let slow = gaps(&mut burst, "o/s", Duration::from_mins(3)).await;
    handle.shutdown(Shutdown::Force);
    run.await.unwrap();
    // A tick reads the jobs for 20.3 s, then rests 2 s; one tick at the switch still read at 9 s.
    assert!(slow.len() >= 5, "too few listings: {slow:?}");
    assert!(
        slow.iter()
            .skip(1)
            .all(|gap| *gap >= Duration::from_millis(22_300)),
        "ticks ran back to back: {slow:?}"
    );
}

/// Four jobs run for an hour while something wakes the engine every 5 s, a third of `poll_interval`. Each running job
/// is read once every `poll_interval`, not at every tick. The bug it catches: reads tied to the tick, so a faster
/// tick triples what running jobs cost GitHub for the same steps.
#[tokio::test(start_paused = true)]
async fn running_jobs_are_read_every_poll_interval_whatever_the_ticks() {
    let (github, docker) = burst_fakes(Duration::ZERO);
    let dir = TestDir::new("running-reads");
    let config = CONFIG.replace("slots = 2", "slots = 4");
    let (engine, handle) = engine_with(&github, &docker, &dir, &config);
    let mut burst = Burst::new(&github, &docker, u64::MAX);
    burst.run = Duration::from_hours(1);
    burst.queue(4);
    let run = tokio::spawn(engine.run());
    let settled = Instant::now() + Duration::from_mins(2);
    play(&mut burst, |_, now| now >= settled).await;
    assert_eq!(burst.running.len(), 4, "four jobs run: {:?}", burst.seen);

    let polled = polls(&github.calls());
    let span = Duration::from_mins(3);
    let until = Instant::now() + span;
    let mut last = github.0.lock().unwrap().job_reads;
    let (mut wake, mut reads) = (Instant::now(), vec![]);
    while Instant::now() < until {
        burst.step(Instant::now());
        if Instant::now() >= wake {
            handle.control.wake.notify_one();
            wake += Duration::from_secs(5);
        }
        let now = github.0.lock().unwrap().job_reads;
        if now > last {
            // A round of reads takes about a second: its first is the round's time.
            if reads.last().is_none_or(|&(at, _): &(Instant, usize)| {
                Instant::now() - at > Duration::from_secs(5)
            }) {
                reads.push((Instant::now(), 0));
            }
            if let Some((_, count)) = reads.last_mut() {
                *count += now - last;
            }
            last = now;
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
    let ticks = polls(&github.calls()) - polled;
    handle.shutdown(Shutdown::Force);
    run.await.unwrap();

    assert!(ticks >= 30, "the ticks came every 5 s: {ticks} in {span:?}");
    let gaps: Vec<Duration> = reads.windows(2).map(|pair| pair[1].0 - pair[0].0).collect();
    assert!(
        reads.len() >= 10 && reads.iter().all(|&(_, count)| count == 4),
        "each round reads the four jobs once: {reads:?}"
    );
    // A round's reads begin after its tick's listings, and a tick that lists the runners too reads 0.3 s later.
    assert!(
        gaps.iter()
            .all(|gap| *gap >= Duration::from_millis(14_500) && *gap <= Duration::from_secs(16)),
        "rounds of reads left `poll_interval`'s pace: {gaps:?}"
    );
}

/// A job a runner took that no listing or capture named is read before every plan, not at the poll's pace: admission
/// needs its details, and a tick inside the interval of the last read of the running jobs still reads it. The bug it
/// catches: the pace holding back the read admission waits for, so a start counted a runner's job as nothing.
#[tokio::test]
async fn a_job_no_listing_named_is_read_before_each_plan_inside_the_interval() {
    let (github, docker) = (FakeGithub::default(), FakeDocker::default());
    running_job(&github, &docker, "o/r", 1, 1);
    github.0.lock().unwrap().failed_jobs.insert(1);
    let dir = TestDir::new("unnamed-read");
    let (mut engine, _handle) = engine_in(&github, &docker, &dir);
    engine.recover().await.unwrap();
    engine.tick(Shutdown::No).await;
    let first = github.0.lock().unwrap().job_reads;
    assert!(first > 0, "the first tick reads the job, which fails");

    github.0.lock().unwrap().failed_jobs.clear();
    engine.tick(Shutdown::No).await;
    let second = github.0.lock().unwrap().job_reads;
    assert_eq!(second, first + 1, "the next tick reads it before its plan");
    engine.tick(Shutdown::No).await;
    assert_eq!(
        github.0.lock().unwrap().job_reads,
        second,
        "named now, it is read again only at the poll's pace"
    );
}

/// A running job's run is cancelled and its runner does not exit, so the tick `CANCEL_GRACE` later removes it before
/// it lists, and Docker takes 8 s to. The next listing of the paused repository, idle, still comes `poll_interval`
/// after that tick's. The bug it
/// catches: the next tick counted from the last one's start, so a slow collect before the listing and a quick one
/// after brought two listings 7 s apart, closer than the interval.
#[tokio::test(start_paused = true)]
async fn a_slow_collect_does_not_bring_the_next_listing_sooner() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    running_job(&github, &docker, "o/r", 1, 1);
    docker
        .0
        .lock()
        .unwrap()
        .slow_removes
        .insert("container-1".to_owned(), Duration::from_secs(8));
    let dir = TestDir::new("slow-collect");
    let (engine, handle) = engine_with(&github, &docker, &dir, CONFIG);
    let run = tokio::spawn(engine.run());
    until_state(&handle, 1, JobState::Running).await;
    handle
        .control
        .pause(one("o/r"), RunningJobs::Kill)
        .await
        .unwrap();
    // The pause starts a tick at once, as every command does: pacing is measured from the listings after it.
    tokio::time::sleep(Duration::from_secs(1)).await;
    let mut listed_at = Vec::new();
    let mut listings = github
        .calls()
        .iter()
        .filter(|call| call.starts_with("queued "))
        .count();
    let until =
        Instant::now() + crate::scheduler::engine::control::CANCEL_GRACE + Duration::from_mins(1);
    while Instant::now() < until {
        let now = github
            .calls()
            .iter()
            .filter(|call| call.starts_with("queued "))
            .count();
        if now > listings {
            listings = now;
            listed_at.push(Instant::now());
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
    handle.shutdown(Shutdown::Force);
    run.await.unwrap();

    assert_eq!(removed(&docker.calls()), ["remove container-1"]);
    let gaps: Vec<Duration> = listed_at.windows(2).map(|pair| pair[1] - pair[0]).collect();
    assert!(gaps.len() >= 8, "too few listings: {gaps:?}");
    // The world looks every 100 ms.
    assert!(
        gaps.iter().all(|gap| *gap >= Duration::from_millis(14_900)),
        "two listings came closer than `poll_interval`: {gaps:?}"
    );
}

/// Four slots work through a long backlog while each removal takes 5 to 25 s, so a slot's next runner ends while
/// another's release still waits, generation after generation. Polls keep their pace and a command is answered
/// within a pass's bound. The bug it catches: a pass taking every later exit for as long as some release waited,
/// which, with a backlog, held the engine until it drained: no poll, no command.
#[tokio::test(start_paused = true)]
async fn overlapping_slow_releases_leave_the_polls_and_commands_their_turn() {
    const JOBS: u64 = 48;
    let (github, docker) = burst_fakes(Duration::ZERO);
    let dir = TestDir::new("overlapping-releases");
    let config = CONFIG.replace("slots = 2", "slots = 4");
    let (engine, handle) = engine_with(&github, &docker, &dir, &config);
    let mut burst = Burst::new(&github, &docker, u64::MAX);
    burst.boot = Duration::from_secs(1);
    burst.run = Duration::from_secs(3);
    burst.slow_removals = true;
    burst.queue(JOBS);
    let run = tokio::spawn(engine.run());
    let command = async {
        tokio::time::sleep(Duration::from_mins(1)).await;
        let sent = Instant::now();
        handle
            .control
            .replace_config(
                Config::parse(&config).unwrap(),
                None,
                None,
                Commit::new(|| Ok(None)),
                RunningSlots::Keep,
                Author::Owner,
            )
            .await
            .unwrap();
        sent.elapsed()
    };
    let ((), answered) = tokio::join!(play(&mut burst, Burst::done_at), command);
    let drained = Instant::now();
    handle.shutdown(Shutdown::Force);
    run.await.unwrap();

    assert_eq!(
        burst.seen.taken,
        usize::try_from(JOBS).unwrap(),
        "every job ran: {:?}",
        burst.seen
    );
    assert!(
        answered < Duration::from_secs(90),
        "the command waited {answered:?}"
    );
    let gaps: Vec<Duration> = burst
        .listed_at
        .windows(2)
        .map(|pair| pair[1] - pair[0])
        .chain(burst.listed_at.last().map(|last| drained - *last))
        .collect();
    // A poll interval, the pass before the tick and the one the tick holds, each its join window and its slowest
    // removal.
    assert!(
        gaps.iter().all(|gap| *gap < Duration::from_secs(90)),
        "a poll waited for the backlog: {gaps:?}"
    );
}

/// The containers of `o/r`'s runners in the first profile's slots, as the status says.
fn runner_containers(handle: &Handle) -> Vec<String> {
    handle.status.borrow().profiles[0]
        .slots
        .iter()
        .filter_map(|slot| slot.runner.as_ref().map(|runner| runner.container.clone()))
        .collect()
}

/// A runner that stops before its start returned, and one someone else removed, free their slots on Docker's word
/// within seconds, with the next poll an hour away. The bugs it catches: the hint for a container the engine did not
/// track yet dropped, so its slot waits for the poll; a container gone by the pass's inspect kept as if it still ran.
#[tokio::test(start_paused = true)]
async fn runners_that_stop_at_once_or_are_removed_free_their_slots_before_the_next_poll() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    github.0.lock().unwrap().queued = vec![job(1), job(2)];
    docker.0.lock().unwrap().exit_at_start = 1;
    let dir = TestDir::new("early-exits");
    let config = CONFIG.replace("[host]\n", "[host]\npoll_interval = \"1h\"\n");
    let (engine, handle) = engine_with(&github, &docker, &dir, &config);
    let run = tokio::spawn(engine.run());

    tokio::time::sleep(Duration::from_secs(5)).await;
    let left = runner_containers(&handle);
    assert_eq!(
        left.len(),
        1,
        "the runner that stopped as it started left its slot: {:?}",
        docker.calls()
    );
    {
        let mut state = docker.0.lock().unwrap();
        state.containers.retain(|container| container.id != left[0]);
        state
            .events
            .retain(|events| events.send(Ok(left[0].clone())).is_ok());
    }
    tokio::time::sleep(Duration::from_secs(2)).await;
    let now = runner_containers(&handle);
    assert!(
        !now.contains(&left[0]),
        "the removed runner left its slot: {now:?}"
    );

    handle.shutdown(Shutdown::Force);
    run.await.unwrap();
}

impl Burst {
    fn done_at(&self, _: Instant) -> bool {
        self.done()
    }
}

/// `p50 6.9s, p90 13.4s, max 14.9s over 100`.
fn figures(mut durations: Vec<Duration>) -> String {
    durations.sort();
    let at = |percent: usize| {
        durations[(durations.len() * percent / 100).min(durations.len() - 1)].as_secs_f64()
    };
    format!(
        "p50 {:.1}s, p90 {:.1}s, max {:.1}s over {}",
        at(50),
        at(90),
        at(100),
        durations.len()
    )
}

/// How much longer a runner container's start takes for each other one in flight, as `workload_figures` prints it:
/// a guess until the e2e measures sysbox's starts side by side (ADR 0126).
const CONTENTION_PLACEHOLDER: Duration = Duration::from_millis(250);

/// What a burst into free slots came to.
struct Staircase {
    /// How long after the first listing that showed them each job got its container, shortest first.
    places: Vec<Duration>,
    /// The most registrations GitHub was asked for at once.
    most_registering: usize,
    /// The most runner container starts Docker was asked for at once.
    most_starts: usize,
}

/// A burst of `jobs` jobs, queued together, into 16 free slots, with Docker's starts slowed by `contention` for each
/// other in flight and `slow_first` more for the first: the staircase a start's own time makes of a queue.
async fn burst_into_free_slots(
    jobs: u64,
    contention: Duration,
    slow_first: Option<Duration>,
) -> Staircase {
    let (github, docker) = burst_fakes(Duration::ZERO);
    {
        let mut state = docker.0.lock().unwrap();
        state.latency.contention = contention;
        state.slow_start = slow_first;
    }
    let dir = TestDir::new("staircase");
    let config = CONFIG.replace("slots = 2", "slots = 16");
    let (engine, handle) = engine_with(&github, &docker, &dir, &config);
    let mut burst = Burst::new(&github, &docker, u64::MAX);
    burst.run = Duration::from_hours(1);
    burst.queue(jobs);
    let queued = Instant::now();
    let run = tokio::spawn(engine.run());
    let all = usize::try_from(jobs).unwrap();
    play(&mut burst, |burst, _| burst.seen.taken == all).await;
    handle.shutdown(Shutdown::Force);
    run.await.unwrap();
    let listed = burst.listed_at[0];
    let mut places: Vec<Duration> = burst
        .seen
        .waits
        .iter()
        .map(|wait| (queued + *wait).saturating_duration_since(listed))
        .collect();
    places.sort();
    let most_registering = github.0.lock().unwrap().most_registering;
    let most_starts = docker.0.lock().unwrap().most_runner_starts;
    Staircase {
        places,
        most_registering,
        most_starts,
    }
}

/// How long after the first listing that showed them each of a burst of `jobs` jobs got its container, shortest
/// first, with 16 free slots.
async fn staircase(jobs: u64) -> Vec<Duration> {
    burst_into_free_slots(jobs, Duration::ZERO, None)
        .await
        .places
}

/// Places in tenths of a second, as `workload_figures` prints them.
fn tenths(places: &[Duration]) -> String {
    places
        .iter()
        .map(|place| format!("{:.1}", place.as_secs_f64()))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Twelve jobs queued together into 16 free slots: their runners register one after another, 0.3 s each, while up to
/// four containers start at once, 1 s each, so the queue's places come 0.3 s apart and a fifth start waits for the
/// first container. The bugs it catches: starts one at a time (1.3 s a place), registrations sent side by side, which
/// GitHub asks clients not to do, and more or fewer than four starts in flight.
#[tokio::test(start_paused = true)]
async fn a_burst_into_free_slots_starts_one_registration_at_a_time() {
    let burst = burst_into_free_slots(12, Duration::ZERO, None).await;
    assert_eq!(
        tenths(&burst.places),
        "1.2, 1.5, 1.8, 2.1, 2.5, 2.8, 3.1, 3.4, 3.8, 4.1, 4.4, 4.7"
    );
    assert_eq!(burst.most_registering, 1, "one registration at a time");
    assert_eq!(burst.most_starts, 4, "four containers start at once");
}

/// Eight jobs into free slots while the first container's start takes 20 s, as when sysbox hangs on one: the other
/// seven get their containers as if three slots started them, long before the slow one. The engine still waits for
/// it before its batch ends. The bug it catches: starts that wait for the one before them.
#[tokio::test(start_paused = true)]
async fn a_slow_container_start_holds_back_no_other_start_of_its_batch() {
    let burst = burst_into_free_slots(8, Duration::ZERO, Some(Duration::from_secs(20))).await;
    let (others, slow) = burst.places.split_at(7);
    assert!(
        others.iter().all(|place| *place < Duration::from_secs(5)),
        "the others start beside the slow one: {}",
        tenths(&burst.places)
    );
    assert!(
        slow[0] >= Duration::from_secs(21),
        "the slow one takes its 20 s: {}",
        tenths(&burst.places)
    );
}

/// What a quiet three-repository host asks of GitHub and how soon it sees a job: `o/r` has four long jobs running,
/// `o/s` and `o/t` nothing, and 100 short jobs of `o/r` queue 31.7 s apart, so their moments fall evenly across the
/// 15 s poll. Prints from the job's queueing to the `o/r` listing that showed it, and to its container's start, and
/// what the engine asked per hour.
#[allow(clippy::print_stdout, reason = "the figures are its output")]
#[allow(
    clippy::cast_precision_loss,
    reason = "counts per hour, far below 2^52"
)]
async fn three_repositories() {
    const JOBS: u64 = 100;
    const SPACING: Duration = Duration::from_millis(31_700);
    let (github, docker) = burst_fakes(Duration::ZERO);
    let dir = TestDir::new("three-repositories");
    let config = format!(
        "{}\n[[repositories]]\nname = \"o/t\"\nprofile = \"app\"\nlabels = [\"self-hosted\", \"app\"]\nwarm = 0\n",
        two_repositories().replace("slots = 2", "slots = 8")
    );
    let (engine, handle) = engine_with(&github, &docker, &dir, &config);
    let mut burst = Burst::new(&github, &docker, u64::MAX);
    burst.run = Duration::from_hours(1);
    burst.queue(4);
    let run = tokio::spawn(engine.run());
    let settled = Instant::now() + Duration::from_mins(2);
    play(&mut burst, |_, now| now >= settled).await;
    assert_eq!(burst.running.len(), 4, "four jobs run: {:?}", burst.seen);

    burst.run = Duration::from_secs(10);
    let listings = |github: &FakeGithub| {
        github
            .calls()
            .iter()
            .filter(|call| call.starts_with("queued o/r"))
            .count()
    };
    let before = github.calls();
    let reads = github.0.lock().unwrap().job_reads;
    let began = Instant::now();
    let mut queued = Vec::new();
    // The times of the `o/r` listings, as the world sees them.
    let answered = std::cell::RefCell::new((listings(&github), Vec::new()));
    for _ in 0..JOBS {
        burst.queue(1);
        queued.push(Instant::now());
        let next = Instant::now() + SPACING;
        play(&mut burst, |_, now| {
            let mut answered = answered.borrow_mut();
            let seen = listings(&github);
            if seen > answered.0 {
                answered.0 = seen;
                answered.1.push(now);
            }
            now >= next
        })
        .await;
    }
    let hours = began.elapsed().as_secs_f64() / 3600.0;
    let played = github.calls();
    let reads = github.0.lock().unwrap().job_reads - reads;
    handle.shutdown(Shutdown::Force);
    run.await.unwrap();

    let answered = answered.into_inner().1;
    let to_listing: Vec<Duration> = queued
        .iter()
        .filter_map(|queued| {
            answered
                .iter()
                .find(|at| **at >= *queued)
                .map(|at| *at - *queued)
        })
        .collect();
    let to_container: Vec<Duration> = burst.seen.waits[4..].to_vec();
    let per_hour = |prefix: &str| {
        let count = |calls: &[String]| calls.iter().filter(|call| call.starts_with(prefix)).count();
        (count(&played) - count(&before)) as f64 / hours
    };
    println!(
        "three repositories, o/r with 4 running jobs and o/s, o/t idle, {JOBS} jobs 31.7 s apart, poll_interval 15s:"
    );
    println!(
        "  queued to the listing that showed it: {}",
        figures(to_listing)
    );
    println!("  queued to container start: {}", figures(to_container));
    println!(
        "  GitHub per hour: {:.0} o/r, {:.0} o/s and {:.0} o/t queued listings, {:.0} runner listings, {:.0} job \
         reads, {:.0} registrations, {:.0} deletes",
        per_hour("queued o/r"),
        per_hour("queued o/s"),
        per_hour("queued o/t"),
        per_hour("runners "),
        reads as f64 / hours,
        per_hour("register "),
        per_hour("delete ")
    );
}

/// How soon an idle repository's first job is seen, its first in the history: `o/r` has a job running, `o/s` none until
/// one queues at a moment that falls evenly across the 15 s poll, in a fresh engine each time, as ADR 0107's rule on
/// the wall clock keeps a repository active once a job of it was listed. Prints from its queueing to the listing that
/// showed it.
#[allow(clippy::print_stdout, reason = "the figures are its output")]
async fn the_first_job_of_an_idle_repository() {
    const RUNS: u32 = 20;
    let mut waits = Vec::new();
    for run in 0..RUNS {
        let (github, docker) = burst_fakes(Duration::ZERO);
        running_job(&github, &docker, "o/r", 1, 1);
        let dir = TestDir::new("idle-first-job");
        let (engine, handle) = engine_with(&github, &docker, &dir, &two_repositories());
        let task = tokio::spawn(engine.run());
        tokio::time::sleep(Duration::from_mins(1) + Duration::from_secs(15) * run / RUNS).await;
        let before = github.calls().len();
        {
            let mut state = github.0.lock().unwrap();
            state.queued.push(job(100));
            state.queued_on.insert(100, "o/s".to_owned());
        }
        let queued = Instant::now();
        while !github.calls()[before..]
            .iter()
            .any(|call| call == "queued o/s")
        {
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
        waits.push(queued.elapsed());
        handle.shutdown(Shutdown::Force);
        task.await.unwrap();
    }
    println!(
        "an idle repository's first job, queued to the listing that showed it: {}",
        figures(waits)
    );
}

/// A burst for the figures ADR 0092 and 0095 give, with the latencies the owner's host shows: `BURSTS` bursts of
/// `JOBS` short jobs of `o/r` every `PERIOD`, more than its 8 slots take, through the engine's own loop. Prints how
/// long jobs waited from their queueing to their runner's container start, how long a slot whose job ended waited
/// for its next runner while listed jobs waited, and what the engine asked GitHub per hour; first with Docker's
/// events not followed, as before them, then followed, then followed with something waking the engine every 5 s, as
/// a tick a third of `poll_interval` would (ADR 0124). Then, for the cadence work, the staircase of a burst's starts
/// by place in the queue, and a quiet three-repository host's cadence.
#[tokio::test(start_paused = true)]
#[ignore = "prints a workload's figures; run with --ignored --nocapture"]
#[allow(clippy::print_stdout, reason = "the figures are its output")]
#[allow(
    clippy::cast_precision_loss,
    reason = "counts per hour, far below 2^52"
)]
async fn workload_figures() {
    const BURSTS: u64 = 6;
    const JOBS: u64 = 40;
    const PERIOD: Duration = Duration::from_mins(5);
    for (followed, tick) in [
        (false, None),
        (true, None),
        (true, Some(Duration::from_secs(5))),
    ] {
        let (github, docker) = burst_fakes(Duration::ZERO);
        if !followed {
            docker.0.lock().unwrap().fail_events = u32::MAX;
        }
        let dir = TestDir::new("workload");
        let config = CONFIG.replace("slots = 2", "slots = 8");
        let (engine, handle) = engine_with(&github, &docker, &dir, &config);
        let mut burst = Burst::new(&github, &docker, u64::MAX);
        let run = tokio::spawn(engine.run());
        let began = Instant::now();
        let mut wake = Instant::now();
        for _ in 0..BURSTS {
            burst.queue(JOBS);
            let next = Instant::now() + PERIOD;
            play(&mut burst, |_, now| {
                if let Some(tick) = tick
                    && now >= wake
                {
                    handle.control.wake.notify_one();
                    wake = now + tick;
                }
                now >= next
            })
            .await;
        }
        let hours = began.elapsed().as_secs_f64() / 3600.0;
        handle.shutdown(Shutdown::Force);
        run.await.unwrap();

        let seen = &burst.seen;
        println!(
            "Docker's events {}{}:",
            if followed { "followed" } else { "not followed" },
            if tick.is_some() {
                ", a tick every 5 s"
            } else {
                ""
            }
        );
        println!(
            "  queued to container start: {}",
            figures(seen.waits.clone())
        );
        println!(
            "  a slot's job ended to its next container start: {}",
            figures(seen.turnovers.iter().map(|(_, took)| *took).collect())
        );
        let calls = github.calls();
        let per_hour = |prefix: &str| {
            calls.iter().filter(|call| call.starts_with(prefix)).count() as f64 / hours
        };
        println!(
            "  GitHub per hour: {:.0} queued listings, {:.0} runner listings, {:.0} job reads, {:.0} registrations, \
             {:.0} deletes",
            per_hour("queued "),
            per_hour("runners "),
            github.0.lock().unwrap().job_reads as f64 / hours,
            per_hour("register "),
            per_hour("delete ")
        );
    }
    for jobs in [4, 8, 12, 16] {
        println!(
            "a burst of {jobs} jobs into 16 free slots, the listing that showed them to each one's container, in seconds: {}",
            tenths(&staircase(jobs).await)
        );
    }
    let contended = burst_into_free_slots(16, CONTENTION_PLACEHOLDER, None).await;
    println!(
        "the same burst of 16, with Docker's starts {:.2} s longer for each other one in flight, a placeholder the \
         e2e replaces: {}",
        CONTENTION_PLACEHOLDER.as_secs_f64(),
        tenths(&contended.places)
    );
    three_repositories().await;
    the_first_job_of_an_idle_repository().await;
}

/// Stops a runner container and says so in Docker's events.
fn stop_container(docker: &FakeDocker, id: &str) {
    let mut state = docker.0.lock().unwrap();
    for container in &mut state.containers {
        if container.id == id {
            container.running = false;
        }
    }
    state
        .events
        .retain(|events| events.send(Ok(id.to_owned())).is_ok());
}

/// GitHub completes `job`, which `runner` ran, and drops the runner's registration.
fn complete(github: &FakeGithub, job: u64, runner: &str) {
    let mut state = github.0.lock().unwrap();
    state.queued.retain(|queued| queued.id != job);
    state.runners.retain(|registered| registered.name != runner);
    let mut completed = details(job, "completed", Some("success"));
    completed.runner_name = Some(runner.to_owned());
    state.jobs.insert(job, completed);
}

/// A runner takes job 1 while GitHub still lists it queued, and its capture names it; the tick's read of that job
/// waits while the job ends and a pass releases the runner, then says it completed. The bug it catches: the end of
/// the job's history dropping the engine's knowledge that a runner of this machine took it, so the tick, still
/// holding a listing that shows it queued, started a second runner for it.
#[tokio::test(start_paused = true)]
async fn a_job_that_ended_while_the_tick_read_it_gets_no_second_runner() {
    let (github, docker) = (FakeGithub::default(), FakeDocker::default());
    {
        let mut state = docker.0.lock().unwrap();
        state.captures_wait = Some(github.clone());
        state.capture_end = CaptureEnd::Container;
    }
    github.0.lock().unwrap().queued = vec![job(1)];
    let dir = TestDir::new("closing");
    let (engine, handle) = engine_in(&github, &docker, &dir);
    let run = tokio::spawn(engine.run());
    tokio::time::sleep(Duration::from_secs(5)).await;
    let name = registered(&github.calls())[0]
        .strip_prefix("register ")
        .unwrap()
        .to_owned();
    {
        let mut state = github.0.lock().unwrap();
        for runner in &mut state.runners {
            if runner.name == name {
                runner.busy = true;
            }
        }
        let mut running = details(1, "in_progress", None);
        running.runner_name = Some(name.clone());
        state.jobs.insert(1, running);
    }
    docker
        .0
        .lock()
        .unwrap()
        .container_captures
        .insert(name.clone(), "@@job 1 1\n".to_owned());
    github.hold_jobs();
    // The next poll lists job 1 queued still, and its read waits.
    tokio::time::sleep(Duration::from_secs(15)).await;
    complete(&github, 1, &name);
    stop_container(&docker, &name);
    tokio::time::sleep(Duration::from_secs(3)).await;
    github.release_jobs();
    tokio::time::sleep(Duration::from_secs(5)).await;

    assert_eq!(
        registered(&github.calls()).len(),
        1,
        "job 1 got one runner: {:?}",
        github.calls()
    );
    handle.shutdown(Shutdown::Force);
    run.await.unwrap();
}

/// With one slot, job 2 waits behind job 1's runner. A poll lists `o/r`'s queue, job 2 in it, while `o/s`'s listing
/// waits; meanwhile job 1 ends, a pass starts a runner that takes job 2, whose capture names nothing, and that runner
/// ends too. The bug it catches: the listing that began before that runner took job 2 clearing the engine's
/// suspicion of it once it answers, so the tick started a second runner for job 2.
#[tokio::test(start_paused = true)]
async fn a_listing_older_than_a_runners_unnamed_job_does_not_bring_the_job_back() {
    let (github, docker) = (FakeGithub::default(), FakeDocker::default());
    running_job(&github, &docker, "o/r", 1, 1);
    {
        let mut state = github.0.lock().unwrap();
        state.queued = vec![job(2)];
        state.queued_on.insert(2, "o/r".to_owned());
        let mut running = details(1, "in_progress", None);
        running.runner_name = Some(state.runners[0].name.clone());
        state.jobs.insert(1, running);
    }
    let dir = TestDir::new("generation");
    let config = two_repositories().replace("slots = 2", "slots = 1");
    let (engine, handle) = engine_with(&github, &docker, &dir, &config);
    let run = tokio::spawn(engine.run());
    tokio::time::sleep(Duration::from_secs(5)).await;
    github.hold_queued("o/s");
    // The next poll: `o/r`'s queue answers with job 2, `o/s`'s waits.
    tokio::time::sleep(Duration::from_secs(12)).await;
    let first = github.0.lock().unwrap().runners[0].name.clone();
    complete(&github, 1, &first);
    stop_container(&docker, "container-1");
    tokio::time::sleep(Duration::from_secs(3)).await;
    let calls = github.calls();
    let started = registered(&calls);
    assert_eq!(
        started.len(),
        1,
        "a pass started a runner for job 2: {calls:?}"
    );
    let second = started[0].strip_prefix("register ").unwrap().to_owned();
    {
        let mut state = github.0.lock().unwrap();
        state.queued.clear();
        let mut ran = details(2, "completed", Some("success"));
        ran.runner_name = Some(second.clone());
        state.jobs.insert(2, ran);
        state.runners.retain(|runner| runner.name != second);
    }
    stop_container(&docker, &second);
    tokio::time::sleep(Duration::from_secs(3)).await;
    github.release_queued();
    tokio::time::sleep(Duration::from_secs(5)).await;

    assert_eq!(
        registered(&github.calls()).len(),
        1,
        "job 2 got one runner: {:?}",
        github.calls()
    );
    handle.shutdown(Shutdown::Force);
    run.await.unwrap();
}

/// How one runner's release is held up.
#[derive(Debug, Clone, Copy)]
enum Slow {
    /// Its log capture never ends: the release waits out `CAPTURE_DRAIN`.
    Capture,
    /// Docker takes a minute to remove its container.
    Removal,
}

/// When two runners end, the second at once or once the first's release began.
#[derive(Debug, Clone, Copy)]
enum Ends {
    Together,
    SlowFirst,
}

/// Two runners end while listed jobs wait; one's release is slow. The other's slot takes the next job within seconds,
/// and the slow one's slot stays held until Docker removed its container. The bugs it catches: a pass releasing the
/// runners one after the other before starting any, so an unrelated slow release held every slot; and a pass
/// waiting out the releases it began before it heeds a runner that ended since.
#[tokio::test(start_paused = true)]
async fn a_slow_release_does_not_hold_back_another_slots_next_runner() {
    for (slow, ends) in [
        (Slow::Capture, Ends::Together),
        (Slow::Removal, Ends::Together),
        (Slow::Capture, Ends::SlowFirst),
        (Slow::Removal, Ends::SlowFirst),
    ] {
        let (github, docker) = (FakeGithub::default(), FakeDocker::default());
        running_job(&github, &docker, "o/r", 1, 1);
        running_job(&github, &docker, "o/r", 2, 2);
        {
            let mut state = github.0.lock().unwrap();
            state.queued = vec![job(3), job(4)];
            for id in [1, 2] {
                let name = state.runners[usize::try_from(id - 1).unwrap()].name.clone();
                let mut running = details(id, "in_progress", None);
                running.runner_name = Some(name);
                state.jobs.insert(id, running);
            }
        }
        {
            let mut state = docker.0.lock().unwrap();
            match slow {
                Slow::Capture => {
                    state.stuck_captures.insert("container-1".to_owned());
                }
                Slow::Removal => {
                    state
                        .slow_removes
                        .insert("container-1".to_owned(), Duration::from_mins(1));
                }
            }
        }
        let dir = TestDir::new("slow-release");
        let (engine, handle) = engine_with(&github, &docker, &dir, CONFIG);
        let run = tokio::spawn(engine.run());
        // Between two of o/r's listings, 5 s apart while its runners are busy: a tick that inspects a container as it
        // stops releases it in its own collect, not in a pass.
        tokio::time::sleep(Duration::from_secs(6)).await;
        assert!(
            registered(&github.calls()).is_empty(),
            "both slots are busy"
        );
        for (id, slot) in [(1, 1), (2, 2)] {
            let name = github.0.lock().unwrap().runners[0].name.clone();
            complete(&github, id, &name);
            stop_container(&docker, &format!("container-{slot}"));
            if let Ends::SlowFirst = ends {
                // Slot 1's release begins and waits.
                tokio::time::sleep(Duration::from_secs(2)).await;
            }
        }
        tokio::time::sleep(Duration::from_secs(4)).await;

        let calls = github.calls();
        let started: Vec<&String> = registered(&calls);
        assert_eq!(
            started.len(),
            1,
            "{slow:?}, {ends:?}: slot 2 took a job, slot 1 waits for its release: {calls:?}"
        );
        assert!(
            started[0].contains("-app-2-"),
            "{slow:?}, {ends:?}: the runner started in slot 2: {started:?}"
        );
        handle.shutdown(Shutdown::Force);
        run.await.unwrap();
    }
}

/// Two runners end while listed jobs wait and GitHub does not answer deletes. Slot 1's runner logged its job's end, so
/// GitHub dropped its registration with the job: nothing deletes it. Slot 2's log stops before its job's end, as when
/// the runner was killed, so its registration is deleted, but its slot takes the next job on Docker's word alone. The
/// bugs it catches: every release waiting for GitHub's answer to a delete before freeing its slot, and a delete sent
/// for each runner whose job ended, which GitHub answers "not found".
#[tokio::test(start_paused = true)]
async fn a_slot_takes_its_next_job_without_waiting_for_the_runners_delete() {
    let (github, docker) = (FakeGithub::default(), FakeDocker::default());
    running_job(&github, &docker, "o/r", 1, 1);
    running_job(&github, &docker, "o/r", 2, 2);
    github.0.lock().unwrap().queued = vec![job(3), job(4)];
    docker.0.lock().unwrap().container_logs.insert(
        "container-1".to_owned(),
        "Running job: build\nJob build completed with result: Succeeded\n".to_owned(),
    );
    let dir = TestDir::new("delete-off-turnover");
    let config = CONFIG.replace("[host]\n", "[host]\npoll_interval = \"1h\"\n");
    let (engine, handle) = engine_with(&github, &docker, &dir, &config);
    let run = tokio::spawn(engine.run());
    tokio::time::sleep(Duration::from_secs(5)).await;
    assert!(
        registered(&github.calls()).is_empty(),
        "both slots are busy"
    );
    github.hold_deletes();
    let ids: Vec<u64> = github
        .0
        .lock()
        .unwrap()
        .runners
        .iter()
        .map(|runner| runner.id)
        .collect();
    for (job, slot) in [(1, 1), (2, 2)] {
        let name = github.0.lock().unwrap().runners[0].name.clone();
        complete(&github, job, &name);
        stop_container(&docker, &format!("container-{slot}"));
    }
    tokio::time::sleep(Duration::from_secs(5)).await;

    let calls = github.calls();
    assert_eq!(
        registered(&calls).len(),
        2,
        "both slots took a listed job: {calls:?}"
    );
    assert!(
        !calls.contains(&format!("delete {}", ids[0])),
        "the runner whose job completed is not deleted: {calls:?}"
    );
    assert!(
        calls.contains(&format!("delete {}", ids[1])),
        "the runner whose log stops before its job's end is deleted: {calls:?}"
    );
    github.release_deletes();
    handle.shutdown(Shutdown::Force);
    run.await.unwrap();
}

/// A runner whose log stops before its job's end is released while GitHub holds deletes, and a graceful stop is asked.
/// Returns the running engine, once the runner's delete was sent.
async fn stop_with_a_pending_delete(
    github: &FakeGithub,
    docker: &FakeDocker,
    dir: &TestDir,
) -> tokio::task::JoinHandle<()> {
    running_job(github, docker, "o/r", 1, 1);
    let config = CONFIG.replace("[host]\n", "[host]\npoll_interval = \"1h\"\n");
    let (engine, handle) = engine_with(github, docker, dir, &config);
    let run = tokio::spawn(engine.run());
    until_state(&handle, 1, JobState::Running).await;
    github.hold_deletes();
    let runner = github.0.lock().unwrap().runners[0].clone();
    complete(github, 1, &runner.name);
    stop_container(docker, "container-1");
    tokio::time::sleep(Duration::from_secs(5)).await;
    assert!(
        github.calls().contains(&format!("delete {}", runner.id)),
        "the released runner's delete is sent: {:?}",
        github.calls()
    );
    handle.shutdown(Shutdown::Graceful);
    run
}

/// The bug it catches: the stop returning while the delete still waits for GitHub, so the daemon's exit drops it and
/// the registration stays on GitHub, offline, until runnerd starts again.
#[tokio::test(start_paused = true)]
async fn a_stop_waits_for_a_released_runners_delete() {
    let (github, docker) = (FakeGithub::default(), FakeDocker::default());
    let dir = TestDir::new("stop-waits-for-delete");
    let run = stop_with_a_pending_delete(&github, &docker, &dir).await;
    tokio::time::sleep(Duration::from_secs(10)).await;
    assert!(!run.is_finished(), "the stop waits for the delete");
    github.release_deletes();
    tokio::time::timeout(Duration::from_secs(5), run)
        .await
        .expect("the stop ends once GitHub answers")
        .unwrap();
}

/// The bug it catches: a stop that never ends while GitHub does not answer a delete.
#[tokio::test(start_paused = true)]
async fn a_stop_waits_for_a_delete_github_does_not_answer_only_until_its_deadline() {
    let (github, docker) = (FakeGithub::default(), FakeDocker::default());
    let dir = TestDir::new("stop-delete-deadline");
    let run = stop_with_a_pending_delete(&github, &docker, &dir).await;
    tokio::time::timeout(STOP_DEADLINE + Duration::from_secs(10), run)
        .await
        .expect("the stop ends by its deadline")
        .unwrap();
}

/// A runner started for job 1 takes it, and its capture names it, with the next poll an hour away. The bug it
/// catches: status showing the runner starting, still waiting for its job, until the next listing said it was busy.
#[tokio::test(start_paused = true)]
async fn a_runner_whose_capture_named_its_job_shows_running_before_the_next_poll() {
    let (github, docker) = (FakeGithub::default(), FakeDocker::default());
    docker.0.lock().unwrap().captures_wait = Some(github.clone());
    github.0.lock().unwrap().queued = vec![job(1)];
    let dir = TestDir::new("named-job-status");
    let config = CONFIG.replace("[host]\n", "[host]\npoll_interval = \"1h\"\n");
    let (engine, handle) = engine_with(&github, &docker, &dir, &config);
    let run = tokio::spawn(engine.run());
    let state = |handle: &Handle| {
        let status = handle.status.borrow();
        api::Status::slot_state(&status.profiles[0], &status.profiles[0].slots[0])
    };
    tokio::time::sleep(Duration::from_secs(5)).await;
    assert_eq!(state(&handle).word(), "starting", "{:?}", docker.calls());

    let name = registered(&github.calls())[0]
        .strip_prefix("register ")
        .unwrap()
        .to_owned();
    docker
        .0
        .lock()
        .unwrap()
        .container_captures
        .insert(name, "@@job 1 1\n".to_owned());
    tokio::time::sleep(Duration::from_secs(1)).await;
    assert_eq!(state(&handle).word(), "running");

    handle.shutdown(Shutdown::Force);
    run.await.unwrap();
}

/// With one slot, job 2 of `o/r` waits behind job 1's runner. A poll lists `o/r`'s queue, job 2 in it, while `o/s`'s
/// listing waits; meanwhile job 1 ends, a pass starts a runner that takes job 2 and names it, that runner ends too,
/// and `o/r` is removed from the config and added back. The bug it catches: the engine forgetting with the
/// repository that this machine ran job 2, so the listing that began before, once it answers, started a second
/// runner for it.
#[tokio::test(start_paused = true)]
async fn a_repository_removed_and_added_back_keeps_what_its_runners_took() {
    let (github, docker) = (FakeGithub::default(), FakeDocker::default());
    docker.0.lock().unwrap().captures_wait = Some(github.clone());
    running_job(&github, &docker, "o/r", 1, 1);
    {
        let mut state = github.0.lock().unwrap();
        state.queued = vec![job(2)];
        state.queued_on.insert(2, "o/r".to_owned());
        let mut running = details(1, "in_progress", None);
        running.runner_name = Some(state.runners[0].name.clone());
        state.jobs.insert(1, running);
    }
    let dir = TestDir::new("readded");
    let config = two_repositories().replace("slots = 2", "slots = 1");
    let (engine, handle) = engine_with(&github, &docker, &dir, &config);
    let run = tokio::spawn(engine.run());
    tokio::time::sleep(Duration::from_secs(5)).await;
    github.hold_queued("o/s");
    // The next poll: `o/r`'s queue answers with job 2, `o/s`'s waits.
    tokio::time::sleep(Duration::from_secs(12)).await;
    let first = github.0.lock().unwrap().runners[0].name.clone();
    complete(&github, 1, &first);
    stop_container(&docker, "container-1");
    tokio::time::sleep(Duration::from_secs(3)).await;
    let calls = github.calls();
    let started = registered(&calls);
    assert_eq!(
        started.len(),
        1,
        "a pass started a runner for job 2: {calls:?}"
    );
    let second = started[0].strip_prefix("register ").unwrap().to_owned();
    docker
        .0
        .lock()
        .unwrap()
        .container_captures
        .insert(second.clone(), "@@job 2 2\n".to_owned());
    tokio::time::sleep(Duration::from_secs(1)).await;
    complete(&github, 2, &second);
    stop_container(&docker, &second);
    tokio::time::sleep(Duration::from_secs(3)).await;
    for config in [
        config.replace("name = \"o/r\"", "name = \"o/t\""),
        config.clone(),
    ] {
        handle
            .control
            .replace_config(
                Config::parse(&config).unwrap(),
                None,
                None,
                Commit::new(|| Ok(None)),
                RunningSlots::Keep,
                Author::Owner,
            )
            .await
            .unwrap();
    }
    // GitHub still lists job 2 queued, as it does for a while after a runner took it.
    github.0.lock().unwrap().queued = vec![job(2)];
    github.release_queued();
    tokio::time::sleep(Duration::from_secs(5)).await;

    assert_eq!(
        registered(&github.calls()).len(),
        1,
        "job 2 got one runner: {:?}",
        github.calls()
    );
    handle.shutdown(Shutdown::Force);
    run.await.unwrap();
}

/// When each round of running-job reads began, from the reads' count: reads of one round come within 5 s.
fn read_rounds(reads: &mut Vec<Instant>, count: usize, seen: &mut usize) {
    if count > *seen {
        if reads
            .last()
            .is_none_or(|&at| Instant::now() - at > Duration::from_secs(5))
        {
            reads.push(Instant::now());
        }
        *seen = count;
    }
}

fn gaps_of(times: &[Instant]) -> Vec<Duration> {
    times.windows(2).map(|pair| pair[1] - pair[0]).collect()
}

/// Four jobs of `o/r` run for an hour beside an idle `o/s` while another client drains the rate limit (ADR 0127). The
/// running jobs' reads slow first, then the active repository's listings to the idle pace, then every listing, one
/// step at a time, and a job queued then still gets its runner at once: its registration goes out in the tick that
/// lists it, not at some later pace. The bugs it catches: listings slowed before the job reads, a governor that holds a
/// registration back, a pace that never reaches the engine's reads or its listings, and an idle repository the
/// slowest step leaves at `poll_interval` (ADR 0128).
#[tokio::test(start_paused = true)]
async fn job_reads_slow_first_then_listings_and_a_start_still_goes_out() {
    let (github, docker) = burst_fakes(Duration::ZERO);
    let dir = TestDir::new("governor-pace");
    let config = two_repositories().replace("slots = 2", "slots = 5");
    let (engine, handle) = engine_with(&github, &docker, &dir, &config);
    let mut burst = Burst::new(&github, &docker, u64::MAX);
    burst.run = Duration::from_hours(1);
    burst.queue(4);
    let run = tokio::spawn(engine.run());
    let settled = Instant::now() + Duration::from_mins(2);
    play(&mut burst, |_, now| now >= settled).await;
    assert_eq!(burst.running.len(), 4, "four jobs run: {:?}", burst.seen);

    // 1000 left, 30 minutes to the reset, another client spending 25 a minute and the engine more again: about 1700
    // projected against 900 of room, and enough left after each step for the next one to be judged.
    github.limit(1000, 25);
    let began = Instant::now();
    let (mut reads, mut seen) = (Vec::new(), github.0.lock().unwrap().job_reads);
    let until = began + Duration::from_mins(14);
    while Instant::now() < until {
        burst.step(Instant::now());
        let count = github.0.lock().unwrap().job_reads;
        read_rounds(&mut reads, count, &mut seen);
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
    let listings = burst.listed_since("o/r", began);
    let idle = gaps_of(&burst.listed_since("o/s", began));
    let (read_gaps, listing_gaps) = (gaps_of(&reads), gaps_of(&listings));

    // Before anything is judged, the pace of before: reads every 15 s, the active repository's listings every 5 s.
    let early = |times: &[Instant], gaps: &[Duration]| {
        times
            .windows(2)
            .zip(gaps)
            .take_while(|(pair, _)| pair[1] - began < Duration::from_mins(2))
            .map(|(_, gap)| *gap)
            .collect::<Vec<_>>()
    };
    for gap in early(&reads, &read_gaps) {
        assert!(gap <= Duration::from_secs(17), "early read gap {gap:?}");
    }
    for gap in early(&listings, &listing_gaps) {
        assert!(gap <= Duration::from_secs(6), "early listing gap {gap:?}");
    }
    // The first slowed gap of each kind: job reads before listings.
    let first_slow = |times: &[Instant], gaps: &[Duration], least: u64| {
        times
            .windows(2)
            .zip(gaps)
            .find(|(_, gap)| **gap >= Duration::from_secs(least))
            .map(|(pair, _)| pair[1])
    };
    let slow_reads = first_slow(&reads, &read_gaps, 28).expect("the reads slowed");
    let held = first_slow(&listings, &listing_gaps, 14).expect("o/r's listings slowed");
    let slow_listings = first_slow(&listings, &listing_gaps, 28).expect("the listings slowed");
    assert!(
        slow_reads + Duration::from_mins(3) < held && held < slow_listings,
        "reads slowed at {:?}, o/r's listings to the idle pace at {:?}, every listing at {:?} after the limit",
        slow_reads - began,
        held - began,
        slow_listings - began
    );
    // At the end, all at 4× `poll_interval`.
    assert!(
        read_gaps.last().unwrap() >= &Duration::from_secs(58)
            && listing_gaps.last().unwrap() >= &Duration::from_secs(58)
            && idle.last().unwrap() >= &Duration::from_secs(58),
        "reads {read_gaps:?}, o/r's listings {listing_gaps:?}, o/s's {idle:?}"
    );

    // A fifth job: the first listing that shows it is followed by its registration within seconds.
    let calls = github.calls().len();
    burst.queue(1);
    let queued = Instant::now();
    let (mut listed, mut registered) = (None, None);
    while registered.is_none() && Instant::now() < queued + Duration::from_mins(3) {
        burst.step(Instant::now());
        for call in &github.calls()[calls..] {
            if call.starts_with("queued o/r") {
                listed.get_or_insert(Instant::now());
            }
            if call.starts_with("register ") {
                registered.get_or_insert(Instant::now());
            }
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
    handle.shutdown(Shutdown::Force);
    run.await.unwrap();
    let (listed, registered) = (listed.unwrap(), registered.expect("the job got a runner"));
    assert!(
        registered - listed <= Duration::from_secs(3),
        "listed {:?} after it was queued, registered {:?} after that",
        listed - queued,
        registered - listed
    );
}

/// With a healthy limit, the calls the engine makes are the ones it made before the governor, in the same order: a
/// governor that acts on a limit that is fine, or whose reading changes a tick, shows in the trace.
#[tokio::test(start_paused = true)]
async fn a_healthy_limit_leaves_the_engines_calls_as_they_were() {
    async fn trace(limit: bool) -> Vec<String> {
        let (github, docker) = burst_fakes(Duration::ZERO);
        let dir = TestDir::new("governor-trace");
        let config = CONFIG.replace("slots = 2", "slots = 4");
        let (engine, handle) = engine_with(&github, &docker, &dir, &config);
        let mut burst = Burst::new(&github, &docker, u64::MAX);
        burst.run = Duration::from_mins(4);
        if limit {
            github.limit(5000, 0);
        }
        burst.queue(4);
        let run = tokio::spawn(engine.run());
        let until = Instant::now() + Duration::from_mins(10);
        play(&mut burst, |burst, now| {
            now >= until || (burst.done() && now + Duration::from_mins(8) >= until)
        })
        .await;
        handle.shutdown(Shutdown::Force);
        run.await.unwrap();
        // A runner's name ends in the wall clock's seconds, which no test's clock holds.
        let trace = github.0.lock().unwrap().trace.clone();
        trace
            .into_iter()
            .map(|call| match call.strip_prefix("register ") {
                Some(name) => format!(
                    "register {}",
                    name.rsplit_once('-').map_or(name, |(kept, _)| kept)
                ),
                None => call,
            })
            .collect()
    }
    let (without, with) = (trace(false).await, trace(true).await);
    assert!(without.len() > 100, "a trace to compare: {}", without.len());
    assert_eq!(without, with);
}