runnerd-core 0.1.3

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
//! The barrier for a starved job (ADR 0096) as `plan` puts it up: who owns it, who waits behind it and why, what never
//! erects one, and over generated sequences, that it neither stalls the queue nor outlives its job.

use super::*;
use crate::scheduler::{Barrier, Drained, PRIORITY_AFTER, SERVED_PRIORITY_AFTER, StartFor};

const LONG_AGO: Duration = Duration::from_mins(15);

fn waited(job: u64) -> Wait {
    Wait {
        job,
        since: now() - LONG_AGO,
    }
}

/// A pool of `name` in `app` with runners of `memory`, whose next job `waits`.
fn pool(name: &str, memory: u64, waits: Waits, queued: &[u64]) -> Repository {
    Repository {
        runner_memory: Some(memory),
        waits,
        ..repository(
            name,
            "app",
            queued.iter().map(|id| job(*id, &["app"])).collect(),
        )
    }
}

fn starved_of_memory(job: u64) -> Waits {
    Waits::default().with_memory(Some(waited(job)))
}

/// `free` of the memory budget left, an empty slice having room for 16G.
fn memory_left(free: i64) -> Budget {
    Budget {
        memory: Some(free),
        drained: Drained {
            memory: Some(16 * i64::try_from(GIB).unwrap()),
            ..Drained::default()
        },
        ..Budget::default()
    }
}

fn gib(amount: i64) -> i64 {
    amount * i64::try_from(GIB).unwrap()
}

fn a_big_job_and_a_small_one(waits: Waits) -> [Repository; 2] {
    [
        pool("o/big", 8 * GIB, waits, &[1]),
        pool("o/small", GIB, Waits::default(), &[2]),
    ]
}

/// The bug: a memory shortage only `continue`d, so a stream of small runners took all that freed up.
#[test]
fn younger_jobs_wait_behind_one_starved_of_memory_though_they_fit() {
    let plan = plan(
        &a_big_job_and_a_small_one(starved_of_memory(1)),
        &profiles(vec![Slot::Free, Slot::Free]),
        memory_left(gib(4)),
        now(),
    );
    assert_eq!(starts(&plan.decisions), []);
    assert_eq!(
        plan.waiting,
        BTreeMap::from([
            (
                1,
                Waiting::Memory {
                    needs: 8 * GIB,
                    free: 4 * GIB
                }
            ),
            (2, Waiting::BehindMemory { job: 1 }),
        ])
    );
    assert_eq!(
        plan.barrier,
        Some(Barrier {
            job: 1,
            scarce: Scarce::Memory,
            memory: 8 * GIB,
            cpu: 2000,
            since: now() - LONG_AGO + PRIORITY_AFTER,
        })
    );
}

/// A barrier from the first shortage would idle the slice for every job that waits out one short run.
#[test]
fn a_job_short_of_memory_lets_younger_ones_past_until_it_waited_long_enough() {
    let just_now = Waits::default().with_memory(Some(Wait {
        job: 1,
        since: now() - PRIORITY_AFTER + Duration::from_secs(1),
    }));
    let plan = plan(
        &a_big_job_and_a_small_one(just_now),
        &profiles(vec![Slot::Free, Slot::Free]),
        memory_left(gib(4)),
        now(),
    );
    assert_eq!(starts(&plan.decisions), [(0, "o/small")]);
    assert_eq!(plan.barrier, None);
    assert!(
        plan.held.contains(&held("o/big", 1, Scarce::Memory)),
        "the plan names the job whose wait goes on"
    );
}

/// One wait for `job` of `waited` ago.
fn waited_for(job: u64, waited: Duration) -> Waits {
    Waits::default().with_memory(Some(Wait {
        job,
        since: now() - waited,
    }))
}

/// The two limits are the rule of ADR 0098: mixing them up either holds on every short wait or starves a large pool.
#[test]
fn a_job_holds_after_the_limit_of_whether_a_barrier_served_its_pool() {
    let barrier = |waits: Waits| {
        plan(
            &a_big_job_and_a_small_one(waits),
            &profiles(vec![Slot::Free, Slot::Free]),
            memory_left(gib(4)),
            now(),
        )
        .barrier
        .map(|barrier| barrier.job)
    };
    let second = Duration::from_secs(1);
    let served = |waits: Waits| waits.with_served(true);
    assert_eq!(
        barrier(waited_for(1, PRIORITY_AFTER.saturating_sub(second))),
        None
    );
    assert_eq!(barrier(waited_for(1, PRIORITY_AFTER)), Some(1));
    assert_eq!(barrier(waited_for(1, SERVED_PRIORITY_AFTER)), None);
    assert_eq!(
        barrier(served(waited_for(
            1,
            SERVED_PRIORITY_AFTER.saturating_sub(second)
        ))),
        None
    );
    assert_eq!(
        barrier(served(waited_for(1, SERVED_PRIORITY_AFTER))),
        Some(1)
    );
}

/// A served pool's shorter limit puts it first for a while; it must not keep an older job's turn from it.
#[test]
fn an_older_job_of_an_unserved_pool_takes_the_barrier_when_it_matures() {
    let owner = |older_waited| {
        let served = waited_for(2, SERVED_PRIORITY_AFTER).with_served(true);
        plan(
            &[
                pool("o/older", 8 * GIB, waited_for(1, older_waited), &[1]),
                pool("o/served", 8 * GIB, served, &[2]),
                pool("o/small", GIB, Waits::default(), &[3]),
            ],
            &profiles(vec![Slot::Free, Slot::Free]),
            memory_left(gib(4)),
            now(),
        )
        .barrier
        .map(|barrier| barrier.job)
    };
    assert_eq!(
        owner(PRIORITY_AFTER.saturating_sub(Duration::from_secs(1))),
        Some(2)
    );
    assert_eq!(owner(PRIORITY_AFTER), Some(1));
}

/// A wait is its job's: one left over from a job gone must not make the next job of the pool jump the queue.
#[test]
fn a_wait_counts_for_its_own_job_alone() {
    let plan = plan(
        &[
            pool("o/big", 8 * GIB, starved_of_memory(9), &[1]),
            pool("o/small", GIB, Waits::default(), &[2]),
        ],
        &profiles(vec![Slot::Free, Slot::Free]),
        memory_left(gib(4)),
        now(),
    );
    assert_eq!(starts(&plan.decisions), [(0, "o/small")]);
}

/// `Budget::memory` is what is left, not the budget: reading it as the total, or its deficit as 0, would either drop
/// exactly the barriers wanted here or invent room.
#[test]
fn a_budget_overdrawn_now_still_erects_a_barrier_as_draining_repays_it() {
    let plan = plan(
        &a_big_job_and_a_small_one(starved_of_memory(1)),
        &profiles(vec![Slot::Free, Slot::Free]),
        memory_left(gib(-3)),
        now(),
    );
    assert_eq!(plan.barrier.map(|barrier| barrier.job), Some(1));
    assert_eq!(plan.waiting[&2], Waiting::BehindMemory { job: 1 });
}

/// A hold no drain can end would stop every younger job for good.
#[test]
fn a_runner_no_empty_slice_holds_erects_no_barrier() {
    let budget = Budget {
        drained: Drained {
            memory: Some(gib(7)),
            ..Drained::default()
        },
        ..memory_left(gib(4))
    };
    let plan = plan(
        &a_big_job_and_a_small_one(starved_of_memory(1)),
        &profiles(vec![Slot::Free, Slot::Free]),
        budget,
        now(),
    );
    assert_eq!(plan.barrier, None);
    assert_eq!(starts(&plan.decisions), [(0, "o/small")]);
    assert_eq!(
        plan.waiting[&1],
        Waiting::Memory {
            needs: 8 * GIB,
            free: 4 * GIB
        },
        "it says why it waits as before"
    );
}

/// Programs outside the slice hold the host: draining CI gives that room to nobody, so younger jobs go on.
#[test]
fn a_host_short_even_with_an_empty_slice_erects_no_barrier() {
    let budget = Budget {
        memory: Some(gib(12)),
        host: Some(gib(4)),
        drained: Drained {
            memory: Some(gib(16)),
            host: Some(gib(6)),
            ..Drained::default()
        },
        ..Budget::default()
    };
    let plan = plan(
        &a_big_job_and_a_small_one(starved_of_memory(1)),
        &profiles(vec![Slot::Free, Slot::Free]),
        budget,
        now(),
    );
    assert_eq!(plan.barrier, None);
    assert_eq!(starts(&plan.decisions), [(0, "o/small")]);
    assert!(
        matches!(plan.waiting[&1], Waiting::HostMemory { .. }),
        "{:?}",
        plan.waiting
    );
}

/// With no budget and no host figure nothing is short: a stale wait must change nothing.
#[test]
fn without_a_memory_budget_or_a_host_figure_a_wait_changes_nothing() {
    let plan = plan(
        &a_big_job_and_a_small_one(starved_of_memory(1)),
        &profiles(vec![Slot::Free, Slot::Free]),
        Budget::default(),
        now(),
    );
    assert_eq!(starts(&plan.decisions), [(0, "o/big"), (1, "o/small")]);
    assert_eq!(plan.barrier, None);
}

/// Host-only admission has no slice budget, and must still protect a starved job.
#[test]
fn a_host_figure_alone_erects_a_barrier() {
    let budget = Budget {
        host: Some(gib(4)),
        drained: Drained {
            host: Some(gib(16)),
            ..Drained::default()
        },
        ..Budget::default()
    };
    let plan = plan(
        &a_big_job_and_a_small_one(starved_of_memory(1)),
        &profiles(vec![Slot::Free, Slot::Free]),
        budget,
        now(),
    );
    assert_eq!(plan.barrier.map(|barrier| barrier.job), Some(1));
    assert_eq!(plan.waiting[&2], Waiting::BehindMemory { job: 1 });
}

/// The interlocks' zeros say nothing of the room there is: no job's wait starts from them and none holds on them.
#[test]
fn a_safety_interlock_suspends_the_barrier_and_starts_no_wait() {
    let budget = Budget {
        held: true,
        ..memory_left(0)
    };
    let plan = plan(
        &[
            pool("o/big", 8 * GIB, starved_of_memory(1), &[1]),
            pool("o/small", GIB, Waits::default(), &[2]),
        ],
        &profiles(vec![Slot::Free, Slot::Free]),
        budget,
        now(),
    );
    assert_eq!(plan.barrier, None);
    assert_eq!(starts(&plan.decisions), []);
    assert_eq!(
        plan.waiting[&2],
        Waiting::Memory {
            needs: GIB,
            free: 0
        }
    );
    assert_eq!(plan.held, []);
}

/// Two barriers would let two large jobs block each other's room; the second waits, and keeps ageing to go next.
#[test]
fn a_second_starved_pool_waits_behind_the_first_and_keeps_ageing() {
    let plan = plan(
        &[
            pool("o/first", 8 * GIB, starved_of_memory(1), &[1]),
            pool("o/second", 8 * GIB, Waits::default(), &[2]),
            pool("o/small", GIB, Waits::default(), &[3]),
        ],
        &profiles(vec![Slot::Free; 3]),
        memory_left(gib(4)),
        now(),
    );
    assert_eq!(plan.barrier.map(|barrier| barrier.job), Some(1));
    assert_eq!(plan.waiting[&2], Waiting::BehindMemory { job: 1 });
    assert_eq!(plan.waiting[&3], Waiting::BehindMemory { job: 1 });
    // A job that fits lacks nothing but its turn.
    assert_eq!(
        plan.held,
        [
            held("o/first", 1, Scarce::Memory),
            held("o/second", 2, Scarce::Memory)
        ]
    );
}

/// An older job keeps its place: a barrier only binds those behind it.
#[test]
fn an_older_job_that_fits_starts_before_the_barrier_of_a_younger_one() {
    let plan = plan(
        &[
            pool("o/small", GIB, Waits::default(), &[1]),
            pool("o/big", 8 * GIB, starved_of_memory(2), &[2]),
        ],
        &profiles(vec![Slot::Free, Slot::Free]),
        memory_left(gib(4)),
        now(),
    );
    assert_eq!(starts(&plan.decisions), [(0, "o/small")]);
    assert_eq!(plan.barrier.map(|barrier| barrier.job), Some(2));
}

/// The barrier falls the moment its job's runner fits: younger ones that fit beside it start in the same plan.
#[test]
fn the_owner_starting_in_this_plan_erects_no_barrier() {
    let plan = plan(
        &a_big_job_and_a_small_one(starved_of_memory(1)),
        &profiles(vec![Slot::Free, Slot::Free]),
        memory_left(gib(9)),
        now(),
    );
    assert_eq!(starts(&plan.decisions), [(0, "o/big"), (1, "o/small")]);
    assert_eq!(plan.barrier, None);
}

/// A job with no free slot could not use the memory a barrier saves; holding others for it would idle the slice.
#[test]
fn a_starved_pool_without_a_free_slot_erects_no_barrier_and_keeps_its_wait() {
    let repositories = [
        pool("o/big", 8 * GIB, starved_of_memory(1), &[1]),
        Repository {
            runner_memory: Some(GIB),
            ..repository("o/small", "small", vec![job(2, &["small"])])
        },
    ];
    let mut profiles = profiles(vec![Slot::Runner(RunnerSlot {
        repository: "o/other".to_owned(),
        busy: true,
        started_at: now(),
        memory: 4 * GIB,
        cpu: 2000,
        usual: None,
        behind: None,
    })]);
    profiles.insert(
        "small".to_owned(),
        Profile {
            memory: GIB,
            cpus: 1000,
            preparing: None,
            upkeep_due: false,
            count: 1,
            ran: Vec::new(),
            slots: vec![Slot::Free],
        },
    );
    let plan = plan(&repositories, &profiles, memory_left(gib(4)), now());
    assert_eq!(plan.barrier, None);
    assert_eq!(starts(&plan.decisions), [(0, "o/small")]);
    assert_eq!(
        plan.waiting[&1],
        Waiting::NoSlot {
            profile: "app".to_owned()
        }
    );
}

/// A wait for one resource must count when the shortage moves to the other, or the job goes back to the end each time.
#[test]
fn a_job_starved_of_cpu_that_now_lacks_memory_owns_the_barrier_as_memory() {
    let waits = Waits::default().with_cpu(Some(waited(1)));
    let plan = plan(
        &a_big_job_and_a_small_one(waits),
        &profiles(vec![Slot::Free, Slot::Free]),
        memory_left(gib(4)),
        now(),
    );
    assert_eq!(
        plan.barrier,
        Some(Barrier {
            job: 1,
            scarce: Scarce::Memory,
            memory: 8 * GIB,
            cpu: 2000,
            since: now() - LONG_AGO + PRIORITY_AFTER,
        })
    );
    assert_eq!(plan.waiting[&2], Waiting::BehindMemory { job: 1 });
}

#[test]
fn a_job_starved_of_memory_that_now_lacks_cpu_owns_the_barrier_as_cpu() {
    let repositories = [
        Repository {
            runner_cpu: Some(4000),
            ..pool("o/big", 8 * GIB, starved_of_memory(1), &[1])
        },
        Repository {
            runner_cpu: Some(500),
            ..pool("o/small", GIB, Waits::default(), &[2])
        },
    ];
    let budget = Budget {
        cpu: Some(1000),
        ..memory_left(gib(12))
    };
    let plan = plan(
        &repositories,
        &profiles(vec![Slot::Free, Slot::Free]),
        budget,
        now(),
    );
    assert_eq!(
        plan.barrier,
        Some(Barrier {
            job: 1,
            scarce: Scarce::Cpu,
            memory: 8 * GIB,
            cpu: 4000,
            since: now() - LONG_AGO + PRIORITY_AFTER,
        })
    );
    assert_eq!(plan.waiting[&2], Waiting::BehindCpu { job: 1 });
}

/// Each pool protecting the resource the other needs would be a deadlock: the older demand alone owns the plan.
#[test]
fn opposing_demands_share_one_barrier_the_older_ones() {
    let repositories = [
        Repository {
            runner_cpu: Some(500),
            ..pool("o/memory", 8 * GIB, starved_of_memory(1), &[1])
        },
        Repository {
            runner_cpu: Some(4000),
            ..pool(
                "o/cpu",
                GIB,
                Waits::default().with_cpu(Some(waited(2))),
                &[2],
            )
        },
    ];
    let budget = Budget {
        cpu: Some(1000),
        ..memory_left(gib(4))
    };
    let plan = plan(
        &repositories,
        &profiles(vec![Slot::Free, Slot::Free]),
        budget,
        now(),
    );
    assert_eq!(plan.barrier.map(|barrier| barrier.job), Some(1));
    assert_eq!(plan.waiting[&2], Waiting::BehindMemory { job: 1 });
}

/// A paused pool, or one backing off, cannot use what a barrier saves.
#[test]
fn a_starved_pool_that_may_not_start_erects_no_barrier() {
    for (paused, held) in [
        (true, None),
        (
            false,
            Some(Hold {
                until: now() + LONG_AGO,
                cause: HoldCause::Start,
            }),
        ),
    ] {
        let mut repositories = a_big_job_and_a_small_one(starved_of_memory(1));
        repositories[0].paused = paused;
        repositories[0].held = held;
        let plan = plan(
            &repositories,
            &profiles(vec![Slot::Free, Slot::Free]),
            memory_left(gib(4)),
            now(),
        );
        assert_eq!(plan.barrier, None);
        assert_eq!(starts(&plan.decisions), [(0, "o/small")]);
    }
}

/// Behind a barrier a job keeps the reason that is true of it: reseeding, or no slot, is not what memory priority
/// does, and another slot would not start it, so auto sizing must not read it as a wait for a slot.
#[test]
fn a_job_behind_a_barrier_with_no_slot_says_so_and_asks_for_no_slot() {
    let repositories = [
        pool("o/big", 8 * GIB, starved_of_memory(1), &[1]),
        Repository {
            runner_memory: Some(GIB),
            ..repository("o/full", "full", vec![job(2, &["full"])])
        },
        Repository {
            runner_memory: Some(GIB),
            ..repository("o/seeding", "seeding", vec![job(3, &["seeding"])])
        },
    ];
    let mut profiles = profiles(vec![Slot::Free]);
    let other = Profile {
        memory: GIB,
        cpus: 1000,
        preparing: None,
        upkeep_due: false,
        count: 1,
        ran: Vec::new(),
        slots: vec![Slot::Runner(RunnerSlot {
            repository: "o/other".to_owned(),
            busy: true,
            started_at: now(),
            memory: GIB,
            cpu: 1000,
            usual: None,
            behind: None,
        })],
    };
    profiles.insert("full".to_owned(), other.clone());
    profiles.insert(
        "seeding".to_owned(),
        Profile {
            preparing: Some(Preparing::Reseeding),
            ..other
        },
    );
    let plan = plan(&repositories, &profiles, memory_left(gib(4)), now());
    assert_eq!(
        plan.waiting[&2],
        Waiting::NoSlot {
            profile: "full".to_owned()
        }
    );
    assert_eq!(
        plan.waiting[&3],
        Waiting::Reseeding {
            profile: "seeding".to_owned()
        }
    );
    assert_eq!(plan.slot_waiting, BTreeSet::new());
}

/// A job behind a barrier that fits but for it would otherwise read as one more slot wanted.
#[test]
fn a_job_behind_a_barrier_is_no_slot_wait() {
    let plan = plan(
        &a_big_job_and_a_small_one(starved_of_memory(1)),
        &profiles(vec![Slot::Free, Slot::Free]),
        memory_left(gib(4)),
        now(),
    );
    assert_eq!(plan.slot_waiting, BTreeSet::new());
}

/// A warm runner starting into the room would take what the barrier saves.
#[test]
fn no_warm_runner_starts_while_a_barrier_stands() {
    let repositories = [
        pool("o/big", 8 * GIB, starved_of_memory(1), &[1]),
        Repository {
            warm: 1,
            ..pool("o/warm", GIB, Waits::default(), &[])
        },
    ];
    let plan = plan(
        &repositories,
        &profiles(vec![Slot::Free, Slot::Free]),
        memory_left(gib(5)),
        now(),
    );
    assert_eq!(starts(&plan.decisions), []);
}

fn warm_runner(repository: &str, memory: u64) -> Slot {
    Slot::Runner(RunnerSlot {
        repository: repository.to_owned(),
        busy: false,
        started_at: now(),
        memory,
        cpu: 500,
        usual: None,
        behind: None,
    })
}

/// Warm runners stop only for a start they make possible: stopping some for room that still would not do loses them
/// for nothing, and a younger job behind the barrier may not reclaim them at all.
#[test]
fn warm_runners_stop_only_for_the_owners_whole_start() {
    let warm = |waiting: &[u64], free: i64| {
        let repositories = [
            pool("o/big", 8 * GIB, starved_of_memory(1), &[1]),
            Repository {
                warm: 1,
                ..pool("o/warm", GIB, Waits::default(), waiting)
            },
        ];
        plan(
            &repositories,
            &profiles(vec![Slot::Free, warm_runner("o/warm", GIB), Slot::Free]),
            memory_left(free),
            now(),
        )
    };
    let short = warm(&[], gib(4));
    assert_eq!(short.barrier.map(|barrier| barrier.job), Some(1));
    assert!(
        !short
            .decisions
            .iter()
            .any(|decision| matches!(decision, Decision::Stop { .. })),
        "{:?}",
        short.decisions
    );
    let enough = warm(&[], gib(7));
    assert_eq!(enough.barrier, None);
    assert_eq!(starts(&enough.decisions), [(0, "o/big")]);
    assert!(
        enough.decisions.contains(&Decision::Stop {
            slot: SlotRef {
                profile: "app".to_owned(),
                index: 1
            },
            reason: StopReason::Room
        }),
        "{:?}",
        enough.decisions
    );
}

/// Unknown labels and an empty queue have no demand to own anything.
#[test]
fn a_job_no_pool_serves_erects_no_barrier() {
    let plan = plan(
        &[pool("o/big", 8 * GIB, starved_of_memory(1), &[])],
        &profiles(vec![Slot::Free]),
        memory_left(gib(4)),
        now(),
    );
    assert_eq!(plan, Plan::default());
    let unserved = [Repository {
        queued: vec![job(1, &["gpu"])],
        ..pool("o/big", 8 * GIB, starved_of_memory(1), &[])
    }];
    let plan = super::plan(
        &unserved,
        &profiles(vec![Slot::Free]),
        memory_left(gib(4)),
        now(),
    );
    assert_eq!(plan.barrier, None);
    assert!(
        matches!(plan.waiting[&1], Waiting::NoPool { .. }),
        "{:?}",
        plan.waiting
    );
}

/// The planner and a model of the engine over generated sequences: jobs queue, runners finish, listings fail, the
/// daemon restarts, a reload changes what a runner takes or removes the pool. Durations are bounded, as the ADR's
/// guarantee assumes.
mod generated {
    use super::*;

    const TICK: Duration = Duration::from_secs(30);
    /// The longest a job here runs, in ticks.
    const LONGEST: u64 = 12;
    const BUDGET: u64 = 16 * GIB;
    const POOLS: [&str; 3] = ["o/big", "o/mid", "o/small"];

    /// `SplitMix64`: the same seed gives the same sequence on every machine.
    struct Rng(u64);

    impl Rng {
        fn next(&mut self) -> u64 {
            self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
            let mut z = self.0;
            z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
            z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
            z ^ (z >> 31)
        }

        fn below(&mut self, n: u64) -> u64 {
            self.next() % n
        }
    }

    struct Running {
        memory: u64,
        ends: u64,
    }

    struct Model {
        tick: u64,
        next_job: u64,
        queued: [Vec<u64>; 3],
        waits: [Waits; 3],
        memory: [u64; 3],
        removed: [bool; 3],
        running: Vec<Running>,
        /// The warm runners, waiting for no job here, by what each takes.
        warm: Vec<u64>,
        /// How many warm runners `o/warm` wants.
        warm_wanted: usize,
        /// What the host's memory lets the slice hold, by the margin in force.
        host: Option<u64>,
    }

    impl Model {
        fn new() -> Model {
            Model {
                tick: 0,
                next_job: 1,
                queued: [Vec::new(), Vec::new(), Vec::new()],
                waits: [Waits::default(); 3],
                memory: [12 * GIB, 6 * GIB, GIB],
                removed: [false; 3],
                running: Vec::new(),
                warm: Vec::new(),
                warm_wanted: 0,
                host: None,
            }
        }

        fn in_use(&self) -> u64 {
            let running: u64 = self.running.iter().map(|running| running.memory).sum();
            running + self.warm.iter().sum::<u64>()
        }

        fn at(&self) -> SystemTime {
            now() + TICK * u32::try_from(self.tick).unwrap()
        }

        fn queue(&mut self, pool: usize) {
            self.queued[pool].push(self.next_job);
            self.next_job += 1;
        }

        /// One plan from listings that succeeded, or failed for `unlisted`; the model commits it as `note_waits` and
        /// `apply_start` do, every start going through. Returns the plan.
        fn plan(&mut self, unlisted: Option<usize>, rng: &mut Rng) -> Plan {
            let at = self.at();
            let in_use = self.in_use();
            let repositories: Vec<Repository> = (0..POOLS.len())
                .filter(|pool| !self.removed[*pool])
                .map(|pool| {
                    let queued = if unlisted == Some(pool) {
                        &[][..]
                    } else {
                        &self.queued[pool][..]
                    };
                    super::pool(POOLS[pool], self.memory[pool], self.waits[pool], queued)
                })
                .chain((self.warm_wanted > 0).then(|| warm("o/warm", "app", self.warm_wanted)))
                .collect();
            let mut slots: Vec<Slot> = self
                .warm
                .iter()
                .map(|memory| {
                    Slot::Runner(RunnerSlot {
                        repository: "o/warm".to_owned(),
                        busy: false,
                        started_at: at,
                        memory: *memory,
                        cpu: 0,
                        usual: None,
                        behind: None,
                    })
                })
                .collect();
            let all = 8usize.saturating_sub(self.running.len()).max(slots.len());
            slots.resize(all, Slot::Free);
            let budget = Budget {
                memory: Some(crate::scheduler::left(BUDGET, in_use)),
                host: self.host.map(|host| crate::scheduler::left(host, in_use)),
                drained: Drained {
                    memory: Some(crate::scheduler::left(BUDGET, 0)),
                    host: self.host.map(|host| crate::scheduler::left(host, 0)),
                    ..Drained::default()
                },
                ..Budget::default()
            };
            let plan = plan(&repositories, &profiles(slots), budget, at);
            // Warm runners come first in the slots: the last of them goes first, so the others keep their place.
            let mut stopped: Vec<usize> = plan
                .decisions
                .iter()
                .filter_map(|decision| match decision {
                    Decision::Stop { slot, .. } => Some(slot.index),
                    Decision::Start { .. } => None,
                })
                .collect();
            stopped.sort_unstable();
            for index in stopped.into_iter().rev() {
                self.warm.remove(index);
            }
            for decision in &plan.decisions {
                if let Decision::Start {
                    for_: StartFor::Warm,
                    memory,
                    ..
                } = decision
                {
                    self.warm.push(*memory);
                } else if let Decision::Start {
                    repository, memory, ..
                } = decision
                {
                    let pool = POOLS.iter().position(|name| name == repository).unwrap();
                    // GitHub gives the runner any of its pool's jobs.
                    let taken = usize::try_from(rng.below(self.queued[pool].len() as u64));
                    self.queued[pool].remove(taken.unwrap());
                    self.waits[pool].started();
                    let ends = self.tick + 1 + rng.below(LONGEST);
                    self.running.push(Running {
                        memory: *memory,
                        ends,
                    });
                }
            }
            for demand in &plan.held {
                let pool = POOLS
                    .iter()
                    .position(|name| *name == demand.pool.repository)
                    .unwrap();
                self.waits[pool].note(demand.scarce, demand.job, at);
            }
            for pool in 0..POOLS.len() {
                if unlisted != Some(pool) {
                    let queued = &self.queued[pool];
                    self.waits[pool].retain(|job| queued.contains(&job));
                    if queued.is_empty() {
                        self.waits[pool].emptied();
                    }
                }
                if let Some(barrier) = plan.barrier {
                    self.waits[pool].own(barrier.job);
                }
            }
            plan
        }

        /// Time passes, and the running jobs due end.
        fn elapse(&mut self) {
            self.tick += 1;
            let tick = self.tick;
            self.running.retain(|running| running.ends > tick);
        }
    }

    /// What a plan must hold, whatever came before it.
    fn holds(model: &Model, plan: &Plan, in_use_before: u64) {
        let behind: BTreeSet<u64> = plan
            .waiting
            .values()
            .filter_map(|reason| match reason {
                Waiting::BehindMemory { job } | Waiting::BehindCpu { job } => Some(*job),
                _ => None,
            })
            .collect();
        assert!(behind.len() <= 1, "never two barriers: {:?}", plan.waiting);
        assert!(
            behind
                .iter()
                .all(|job| plan.barrier.map(|barrier| barrier.job) == Some(*job)),
            "only the plan's barrier holds a job back: {plan:?}"
        );
        let started: u64 = plan
            .decisions
            .iter()
            .filter_map(|decision| match decision {
                Decision::Start { memory, .. } => Some(*memory),
                Decision::Stop { .. } => None,
            })
            .sum();
        assert!(
            in_use_before + started <= BUDGET,
            "starts fit the budget: {plan:?}"
        );
        if let Some(barrier) = plan.barrier {
            assert!(
                model.memory.iter().any(|memory| *memory <= BUDGET),
                "a barrier stands only for what an empty slice holds"
            );
            assert!(
                !plan.waiting.contains_key(&barrier.job)
                    || !matches!(
                        plan.waiting[&barrier.job],
                        Waiting::BehindMemory { .. } | Waiting::BehindCpu { .. }
                    ),
                "its owner keeps its own reason: {plan:?}"
            );
        }
    }

    /// Nothing starting while a job fits needs a barrier to say why (a stalled queue), and no plan breaks `holds`.
    #[test]
    fn the_barrier_never_stalls_the_queue_over_generated_sequences() {
        for seed in 0..256 {
            let mut rng = Rng(seed);
            let mut model = Model::new();
            for _ in 0..200 {
                match rng.below(10) {
                    0..=3 => model.queue(usize::try_from(rng.below(3)).unwrap()),
                    4 => model.waits = [Waits::default(); 3],
                    5 => {
                        let pool = usize::try_from(rng.below(3)).unwrap();
                        model.memory[pool] = (1 + rng.below(20)) * GIB;
                    }
                    6 => {
                        let pool = usize::try_from(rng.below(3)).unwrap();
                        model.removed[pool] = !model.removed[pool];
                        model.waits[pool] = Waits::default();
                    }
                    _ => {}
                }
                let unlisted = (rng.below(5) == 0).then(|| usize::try_from(rng.below(3)).unwrap());
                let in_use = model.in_use();
                let plan = model.plan(unlisted, &mut rng);
                holds(&model, &plan, in_use);
                let started = !starts(&plan.decisions).is_empty();
                let fits = (0..POOLS.len()).any(|pool| {
                    !model.removed[pool]
                        && unlisted != Some(pool)
                        && !model.queued[pool].is_empty()
                        && in_use + model.memory[pool] <= BUDGET
                });
                assert!(
                    started || !fits || plan.barrier.is_some() || model.running.len() >= 8,
                    "seed {seed}: a job's runner fits, no hold is owed, and nothing started: {plan:?}"
                );
                model.elapse();
            }
        }
    }

    /// A barrier that outlives what it waits for stops every queue for nothing: a warm runner that never gives its room
    /// back, a host that holds the runner in no slice. With bounded run times only what started under it can keep one
    /// standing, so each ends within one longest run of the last start.
    #[test]
    fn a_standing_barrier_ends_within_one_longest_run_of_the_last_start() {
        let (mut stood, mut for_served) = (0, 0);
        for seed in 0..256 {
            let mut rng = Rng(seed);
            let mut model = Model::new();
            model.warm_wanted = usize::try_from(rng.below(3)).unwrap();
            // Two of these hold no 12G runner, whatever drains.
            model.host = [None, Some(9 * GIB), Some(11 * GIB), Some(14 * GIB)]
                [usize::try_from(rng.below(4)).unwrap()];
            let mut standing: Option<(u64, u64)> = None;
            for _ in 0..200 {
                for _ in 0..rng.below(3) {
                    model.queue(usize::try_from(rng.below(3)).unwrap());
                }
                let plan = model.plan(None, &mut rng);
                let limit = model.host.unwrap_or(BUDGET).min(BUDGET);
                assert!(
                    model.in_use() <= limit,
                    "seed {seed}: starts fit the budgets: {plan:?}"
                );
                let started = !starts(&plan.decisions).is_empty();
                standing = plan.barrier.map(|barrier| match standing {
                    Some((job, last)) if job == barrier.job && !started => (job, last),
                    _ => (barrier.job, model.tick),
                });
                if let Some((job, last)) = standing {
                    stood += 1;
                    for_served += u32::from(model.waits.iter().any(Waits::served));
                    assert!(
                        model.tick <= last + LONGEST + 1,
                        "seed {seed}: job {job} still holds at tick {} with no start since {last}: {plan:?}",
                        model.tick
                    );
                }
                model.elapse();
            }
        }
        assert!(stood > 0, "generated runs reach a barrier");
        assert!(for_served > 0, "and one beside a pool a barrier served");
    }

    /// With bounded run times, fresh listings and no reload, an aged demand's pool starts a runner once the room
    /// drains: at most the threshold, then one longest run, after its wait began, whatever younger jobs keep arriving.
    #[test]
    fn a_starved_pool_starts_within_a_bound_under_a_stream_of_younger_jobs() {
        let limit = PRIORITY_AFTER.as_secs() / TICK.as_secs();
        for seed in 0..256 {
            let mut rng = Rng(seed);
            let mut model = Model::new();
            // A slice already full of small runners, ending at different times.
            model.queue(2);
            model.queue(2);
            for _ in 0..6 {
                model.queue(2);
            }
            let plan = model.plan(None, &mut rng);
            assert_eq!(starts(&plan.decisions).len(), 8);
            model.queue(0);
            let big = model.next_job - 1;
            let began = model.tick;
            let started = loop {
                model.queue(2);
                model.queue(2);
                let plan = model.plan(None, &mut rng);
                if !model.queued[0].contains(&big) {
                    break model.tick;
                }
                if plan.barrier.is_some() {
                    assert_eq!(
                        starts(&plan.decisions),
                        [],
                        "seed {seed}: nothing younger starts past the barrier"
                    );
                }
                assert!(
                    model.tick <= began + limit + LONGEST + 2,
                    "seed {seed}: the starved pool has not started by tick {}",
                    model.tick
                );
                model.elapse();
            };
            assert!(started <= began + limit + LONGEST + 2);
        }
    }
}

/// The status reads `cpu_held` between two plans, so a start or a listing in between must not end it (ADR 0115).
#[test]
fn a_start_or_a_listing_between_two_plans_leaves_what_the_last_plan_said_of_cpu() {
    let mut waits = Waits::default();
    waits.note(Scarce::Cpu, 1, now());
    waits.set_cpu_held(true);

    waits.started();
    assert_eq!(waits.cpu(), None, "the start ended its wait");
    assert!(waits.cpu_held(), "a start is not the next plan");

    waits.note(Scarce::Cpu, 2, now());
    waits.retain(|_| false);
    assert_eq!(waits.cpu(), None, "the job left the queue");
    assert!(waits.cpu_held(), "a listing is not the next plan");
    assert!(
        !waits.is_empty(),
        "the pool is kept while the last plan's word stands"
    );

    waits.set_cpu_held(false);
    assert!(waits.is_empty(), "the next plan held nothing for CPU");
}

/// Only the start that came to a job owning a barrier is the one that served the pool, once: its log line says so.
#[test]
fn only_the_first_start_for_a_barriers_owner_serves_the_pool() {
    let mut waits = Waits::default();
    waits.note(Scarce::Memory, 1, now());
    assert!(!waits.started(), "no barrier was its own");

    waits.note(Scarce::Memory, 2, now());
    waits.own(2);
    assert!(waits.started(), "job 2 owned the barrier");
    assert!(waits.served(), "the pool was served");

    waits.note(Scarce::Memory, 3, now());
    waits.own(3);
    assert!(!waits.started(), "it was served already");
}