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
//! Insights from synthetic histories of fictional repositories: one `halyard/api` job run a few times a day.

use super::{HeldJob, History, HostHold, HostReading, Run, digest, insights};
use crate::api::{self, AutoNote, InsightKind, JobState, Severity};
use crate::config::Config;

const G: u64 = 1 << 30;
const MINUTE: u64 = 60 * 1000;
const HOUR: u64 = 60 * MINUTE;
const NOW: u64 = 1_800_000_000_000;

const CONFIG: &str = r#"
[host]
slice = "runnerd.slice"
isolation = "sysbox"
admission = "caps"

[caches]
mirror = { enabled = false, memory = "512M", cpus = 1, ttl = "168h" }
pnpm = { max_size = "5G" }
maven = { max_size = "5G" }

[profiles.app]
image_stage = "node"
cpus = 4
memory = "4G"
slots = 2

[[repositories]]
name = "halyard/api"
profile = "app"
labels = ["app"]
"#;

fn config() -> Config {
    Config::parse(CONFIG).unwrap()
}

/// The `n`-th run of `halyard/api`'s `CI / test` on main, `hours_ago` hours before `NOW`, taking `seconds`, and
/// succeeding.
fn test_run(n: u64, hours_ago: u64, seconds: u64) -> Run {
    let finished = NOW - hours_ago * HOUR;
    Run {
        id: 1000 + n,
        repository: "halyard/api".to_owned(),
        workflow: Some("CI".to_owned()),
        name: "test".to_owned(),
        branch: Some("main".to_owned()),
        url: Some(format!(
            "https://github.com/halyard/api/actions/runs/{n}/job/{}",
            1000 + n
        )),
        run_id: n,
        run_attempt: 1,
        state: JobState::Completed,
        conclusion: Some("success".to_owned()),
        queued_at: finished - seconds * 1000 - 20_000,
        started_at: Some(finished - seconds * 1000),
        finished_at: Some(finished),
        runner_started_at: Some(finished - seconds * 1000 - 15_000),
        profile: Some("app".to_owned()),
        memory_peak: Some(G),
        build_cache: None,
        sock_throttled: Some(0),
        unseen: 0,
        cpu_cap: Some(4000),
        cpu_periods: None,
        cpu_throttled: None,
    }
}

/// `runs` in a history that holds every job however old.
fn whole(runs: &[Run]) -> History {
    History {
        runs: runs.to_vec(),
        kept_since: 0,
        host: None,
        readings: Vec::new(),
    }
}

/// Runs oldest first, one every 6 hours, ending an hour ago, taking the given seconds.
fn history(durations: &[u64]) -> Vec<Run> {
    let count = durations.len() as u64;
    durations
        .iter()
        .zip(0..)
        .map(|(seconds, n)| test_run(n, 1 + (count - 1 - n) * 6, *seconds))
        .collect()
}

#[test]
fn a_job_that_got_slower_and_stayed_slower_is_slower_since_its_first_slow_run() {
    // Eight runs at 4 minutes, then six at 6: the first 6-minute run is the 9th.
    let mut durations = vec![240; 8];
    durations.extend([360; 6]);
    let runs = history(&durations);

    let found = insights(&whole(&runs), &config(), 14, NOW).insights;

    assert_eq!(found.len(), 1, "{found:#?}");
    let slower = &found[0];
    assert_eq!(slower.key, "slower:halyard/api/CI/test");
    assert_eq!(slower.severity, Severity::Warning);
    let InsightKind::Slower {
        branch,
        before,
        now,
        since,
    } = &slower.kind
    else {
        panic!("not slower: {slower:#?}");
    };
    assert_eq!((branch.as_deref(), *before, *now), (Some("main"), 240, 360));
    assert_eq!(since.as_ref().map(|since| since.job), Some(runs[8].id));
    assert_eq!(
        slower.sentence,
        "halyard/api: CI / test on main takes 6m now, up from 4m."
    );
}

#[test]
fn a_one_off_slow_run_is_not_a_regression() {
    let mut durations = vec![240; 13];
    durations[10] = 900;

    assert!(
        insights(&whole(&history(&durations)), &config(), 14, NOW)
            .insights
            .is_empty(),
        "one slow run among fast ones says nothing"
    );
}

#[test]
fn a_job_fast_again_in_its_last_two_runs_is_not_slower() {
    let mut durations = vec![240; 8];
    durations.extend([360, 360, 360, 240, 240]);

    assert!(
        insights(&whole(&history(&durations)), &config(), 14, NOW)
            .insights
            .is_empty(),
        "the slow stretch ended"
    );
}

#[test]
fn a_job_that_flips_between_cache_hits_and_misses_is_not_slower() {
    // A build cache hit takes about 40 s and a miss about 2 minutes; more misses lately move the median, not the job.
    let durations = [
        112, 37, 44, 46, 146, 39, 124, 134, 41, 156, 122, 126, 147, 40,
    ];

    assert!(
        insights(&whole(&history(&durations)), &config(), 14, NOW)
            .insights
            .is_empty(),
        "a recent run as fast as before says the job did not get slower"
    );
}

#[test]
fn a_small_slowdown_is_not_a_regression() {
    // 20% up but only 24 seconds.
    let mut durations = vec![120; 8];
    durations.extend([144; 6]);

    assert!(
        insights(&whole(&history(&durations)), &config(), 14, NOW)
            .insights
            .is_empty(),
        "under 30 seconds is noise"
    );
}

#[test]
fn slower_runs_on_a_branch_with_few_runs_do_not_count() {
    let mut runs = history(&[240; 10]);
    for n in 0..6 {
        let mut feature = test_run(100 + n, 2, 600);
        feature.branch = Some("feature/slow".to_owned());
        runs.push(feature);
    }

    assert!(
        insights(&whole(&runs), &config(), 14, NOW)
            .insights
            .is_empty(),
        "only the busiest branch is compared"
    );
}

#[test]
fn main_is_compared_even_when_pull_requests_run_more() {
    let mut runs = history(&[240; 10]);
    // A pull request that adds tests, pushed often: slower, and busier than main.
    for n in 0..14 {
        let mut feature = test_run(100 + n, 30 - n, if n < 7 { 240 } else { 600 });
        feature.branch = Some("feature/more-tests".to_owned());
        runs.push(feature);
    }

    assert!(
        insights(&whole(&runs), &config(), 14, NOW)
            .insights
            .is_empty(),
        "main runs as fast as it did"
    );
}

/// Attempt `attempt` of run `run_id` of `CI / test`, concluding `conclusion`.
fn attempt(run_id: u64, attempt: u32, conclusion: &str) -> Run {
    let mut run = test_run(run_id * 10 + u64::from(attempt), 3, 240);
    run.run_id = run_id;
    run.run_attempt = attempt;
    run.conclusion = Some(conclusion.to_owned());
    run
}

#[test]
fn a_job_that_failed_and_passed_on_a_re_run_is_flaky() {
    let runs = vec![
        attempt(1, 1, "success"),
        attempt(2, 1, "failure"),
        attempt(2, 2, "success"),
        attempt(3, 1, "success"),
    ];

    let found = insights(&whole(&runs), &config(), 14, NOW).insights;

    assert_eq!(found.len(), 1, "{found:#?}");
    assert_eq!(found[0].key, "flaky:halyard/api/CI/test");
    assert_eq!(found[0].kind, InsightKind::Flaky { flaky: 1, total: 3 });
    assert_eq!(
        found[0].severity,
        Severity::Notice,
        "once may be chance: shown, not sent"
    );
    assert_eq!(found[0].runs[0].job, runs[1].id, "links the failed attempt");
    assert_eq!(
        found[0].sentence,
        "halyard/api: CI / test failed and then passed on a re-run in 1 of its 3 runs."
    );
}

#[test]
fn a_job_flaky_twice_is_a_warning() {
    let runs = vec![
        attempt(1, 1, "failure"),
        attempt(1, 2, "success"),
        attempt(2, 1, "timed_out"),
        attempt(2, 2, "success"),
    ];

    let found = insights(&whole(&runs), &config(), 14, NOW).insights;

    assert_eq!(found[0].kind, InsightKind::Flaky { flaky: 2, total: 2 });
    assert_eq!(found[0].severity, Severity::Warning);
}

#[test]
fn a_job_that_failed_again_on_a_re_run_is_not_flaky() {
    let runs = vec![attempt(2, 1, "failure"), attempt(2, 2, "failure")];

    assert!(
        insights(&whole(&runs), &config(), 14, NOW)
            .insights
            .is_empty(),
        "failing twice is broken, not flaky"
    );
}

#[test]
fn a_lost_job_that_passed_on_a_re_run_is_not_flaky() {
    let mut lost = attempt(2, 1, "failure");
    lost.state = JobState::Lost;
    lost.conclusion = None;
    let runs = vec![lost, attempt(2, 2, "success")];

    assert!(
        insights(&whole(&runs), &config(), 14, NOW)
            .insights
            .is_empty(),
        "a vanished runner is the host's fault"
    );
}

/// Five runs on `branch` whose runners found `hits` of 40 lookups each in the build cache, and could write to it
/// or not.
fn cached(branch: &str, hits: u64, writer: bool) -> Vec<Run> {
    history(&[240; 5])
        .into_iter()
        .map(|run| Run {
            branch: Some(branch.to_owned()),
            build_cache: Some(api::BuildCacheCounts {
                hits,
                misses: 40 - hits,
                writer,
                ..api::BuildCacheCounts::default()
            }),
            ..run
        })
        .collect()
}

#[test]
fn main_runs_that_find_nothing_their_predecessors_stored_have_a_cold_cache() {
    let found = insights(&whole(&cached("main", 1, true)), &config(), 14, NOW).insights;
    assert_eq!(found.len(), 1, "{found:?}");
    assert_eq!(
        found[0].kind,
        InsightKind::ColdCache {
            branch: Some("main".to_owned()),
            hits: 5,
            lookups: 200,
        }
    );
    assert!(
        found[0].sentence.contains("2% of its build cache lookups"),
        "{}",
        found[0].sentence
    );
}

#[test]
fn a_warm_cache_or_runs_that_only_read_are_no_insight() {
    for runs in [cached("main", 30, true), cached("feature", 0, false)] {
        let found = insights(&whole(&runs), &config(), 14, NOW).insights;
        assert!(found.is_empty(), "{found:?}");
    }
}

/// Ten runs, those at `throttled` with their sockets throttled for memory pressure.
fn throttled_at(throttled: &[usize]) -> Vec<Run> {
    let mut runs = history(&[240; 10]);
    for at in throttled {
        runs[*at].sock_throttled = Some(846);
    }
    runs
}

#[test]
fn downloads_memory_pressure_throttled_in_several_runs_are_a_warning() {
    let found = insights(&whole(&throttled_at(&[3, 8])), &config(), 14, NOW).insights;
    assert_eq!(found.len(), 1, "{found:?}");
    assert_eq!(found[0].severity, Severity::Warning);
    assert_eq!(
        found[0].kind,
        InsightKind::Throttled {
            throttled: 2,
            total: 10
        }
    );
    let linked: Vec<u64> = found[0].runs.iter().map(|run| run.job).collect();
    assert_eq!(linked, [1008, 1003], "the throttled runs, newest first");
}

#[test]
fn one_throttled_run_is_no_insight() {
    let found = insights(&whole(&throttled_at(&[5])), &config(), 14, NOW).insights;
    assert!(found.is_empty(), "{found:?}");
}

fn peaking(peaks_in_tenths_of_g: &[u64]) -> Vec<Run> {
    let mut runs = history(&vec![240; peaks_in_tenths_of_g.len()]);
    for (run, peak) in runs.iter_mut().zip(peaks_in_tenths_of_g) {
        run.memory_peak = Some(peak * G / 10);
    }
    runs
}

#[test]
fn memory_near_the_cap_is_flagged_with_what_auto_sizing_does() {
    // 3.6G of a 4G cap: 90%.
    let runs = peaking(&[30, 31, 33, 35, 36, 36]);

    let found = insights(&whole(&runs), &config(), 14, NOW).insights;

    assert_eq!(found.len(), 1, "{found:#?}");
    let InsightKind::NearCap {
        profile, cap, auto, ..
    } = &found[0].kind
    else {
        panic!("not near the cap: {found:#?}");
    };
    assert_eq!(
        (profile.as_str(), *cap, *auto),
        ("app", 4 * G, AutoNote::Off)
    );
    assert_eq!(
        found[0].severity,
        Severity::Warning,
        "three runs near the cap and nothing raises it"
    );
    assert!(
        found[0]
            .sentence
            .ends_with("Auto sizing is off: raise app's memory, or turn it on."),
        "{}",
        found[0].sentence
    );

    let auto = Config::parse(&format!("{CONFIG}\n[sizing]\nauto = true\n")).unwrap();
    let found = insights(&whole(&runs), &auto, 14, NOW).insights;
    assert!(
        matches!(
            found[0].kind,
            InsightKind::NearCap {
                auto: AutoNote::Raises,
                ..
            }
        ),
        "auto sizing raises it: {found:#?}"
    );
    assert_eq!(
        found[0].severity,
        Severity::Notice,
        "auto sizing deals with it: shown, not sent"
    );
}

#[test]
fn one_spike_near_the_cap_is_a_notice() {
    // With six runs the 95th percentile is the highest: 3.6G of 4G once.
    let found = insights(
        &whole(&peaking(&[30, 30, 31, 30, 30, 36])),
        &config(),
        14,
        NOW,
    )
    .insights;

    assert!(
        matches!(found[0].kind, InsightKind::NearCap { .. }),
        "{found:#?}"
    );
    assert_eq!(found[0].severity, Severity::Notice);
}

#[test]
fn memory_well_under_the_cap_says_nothing() {
    assert!(
        insights(
            &whole(&peaking(&[20, 21, 22, 20, 24, 25])),
            &config(),
            14,
            NOW
        )
        .insights
        .is_empty(),
        "62% of the cap is fine"
    );
}

#[test]
fn a_job_served_in_two_profiles_is_near_the_cap_by_its_last_profiles_runs_alone() {
    let config = Config::parse(&format!(
        "{CONFIG}\n[profiles.light]\nimage_stage = \"node\"\ncpus = 1\nmemory = \"1G\"\nslots = 1\n"
    ))
    .unwrap();
    // Nine runs of 3G in app, 75% of its 4G, then one of 200M in light: light has one small run, not 300% of its cap.
    let mut runs = peaking(&[30, 30, 30, 30, 30, 30, 30, 30, 30, 2]);
    runs.last_mut().unwrap().profile = Some("light".to_owned());

    assert!(
        insights(&whole(&runs), &config, 14, NOW)
            .insights
            .is_empty(),
        "nothing is near a cap"
    );
}

/// Runs of 240 s, one every 6 hours, each its quota throttled in the given share of its run, per mille, or without
/// a throttling figure (`None`), at app's 4 CPUs.
fn throttled_runs(shares: &[Option<u64>]) -> Vec<Run> {
    let mut runs = history(&vec![240; shares.len()]);
    for (run, share) in runs.iter_mut().zip(shares) {
        // 240 s is 2400 periods of 100 ms, all of them busy.
        run.cpu_periods = share.map(|_| 2400);
        run.cpu_throttled = share.map(|share| share * 2400 / 1000);
    }
    runs
}

fn measured(auto: bool) -> Config {
    Config::parse(&format!(
        "{}\n[sizing]\nauto = {auto}\n",
        CONFIG.replace("admission = \"caps\"", "admission = \"measured\"")
    ))
    .unwrap()
}

fn cpu_held(history: &History, config: &Config) -> Vec<api::Insight> {
    insights(history, config, 14, NOW)
        .insights
        .into_iter()
        .filter(|insight| matches!(insight.kind, InsightKind::CpuHeld { .. }))
        .collect()
}

#[test]
fn a_job_its_cpu_cap_held_back_three_times_says_the_cpus_to_set_under_caps() {
    // Throttled in exactly 15% of their run twice and in 30% once: held, as sizing reads them. 14.9% is not.
    let runs = throttled_runs(&[
        Some(0),
        Some(150),
        Some(149),
        Some(40),
        Some(300),
        Some(150),
        Some(0),
    ]);

    let found = cpu_held(&whole(&runs), &config());

    assert_eq!(found.len(), 1, "{found:#?}");
    assert_eq!(found[0].key, "cpu-held:halyard/api/CI/test");
    assert_eq!(found[0].severity, Severity::Warning, "the owner acts");
    assert_eq!(
        found[0].kind,
        InsightKind::CpuHeld {
            profile: "app".to_owned(),
            cpus: 4,
            held: 3,
            total: 7,
            raised_from: None,
            set: Some(6),
        }
    );
    assert_eq!(
        found[0].sentence,
        "halyard/api: CI / test was held back by app's 4 CPUs in 3 of its last 7 runs, its quota throttling it in 15% \
         of its run or more. Under caps admission each CPU takes budget, so auto sizing does not raise cpus for this: \
         set app's cpus to 6 if runnerctl sizing shows the budget has room."
    );
    let linked: Vec<u64> = found[0].runs.iter().map(|run| run.job).collect();
    assert_eq!(linked, [1005, 1004, 1001], "the held runs, newest first");

    // The profile has other cpus now: these runs say nothing of them.
    let raised = Config::parse(&CONFIG.replace("cpus = 4", "cpus = 6")).unwrap();
    assert!(
        cpu_held(&whole(&runs), &raised).is_empty(),
        "runs at 4 CPUs say nothing of 6"
    );
}

#[test]
fn runs_without_a_throttling_figure_are_neither_held_nor_free() {
    let unknown = [None; 8];
    assert!(
        cpu_held(&whole(&[]), &config()).is_empty(),
        "no runs say nothing"
    );
    assert!(
        cpu_held(&whole(&throttled_runs(&unknown)), &config()).is_empty(),
        "runs from before schema 17 say nothing"
    );
    // Two held runs are under the three sizing raises on, however few runs were measured.
    let mut shares = unknown.to_vec();
    shares.extend([Some(200), Some(200)]);
    assert!(
        cpu_held(&whole(&throttled_runs(&shares)), &config()).is_empty(),
        "two held runs are no insight"
    );
    // A third, among runs without the figure: 3 of the 3 measured, the rest not counted either way.
    shares.insert(3, Some(200));
    let found = cpu_held(&whole(&throttled_runs(&shares)), &config());
    assert!(
        matches!(
            found[0].kind,
            InsightKind::CpuHeld {
                held: 3,
                total: 3,
                ..
            }
        ),
        "{found:#?}"
    );
}

#[test]
fn under_measured_admission_auto_sizing_raises_cpus_until_a_raise_does_not_help() {
    let held = throttled_runs(&[Some(300); 4]);

    let found = cpu_held(&whole(&held), &measured(true));
    assert_eq!(
        found[0].severity,
        Severity::Notice,
        "auto sizing deals with it"
    );
    assert!(
        found[0].sentence.ends_with(
            "Auto sizing raises app's cpus while each raise makes it faster or less throttled and the slice \
             has room; runnerctl sizing says when it cannot."
        ),
        "{}",
        found[0].sentence
    );

    let off = cpu_held(&whole(&held), &measured(false));
    assert_eq!(off[0].severity, Severity::Warning);
    assert!(
        off[0]
            .sentence
            .ends_with("Auto sizing is off: set app's cpus to 6, or turn it on."),
        "{}",
        off[0].sentence
    );

    // Three runs at 3 CPUs before a raise to 4, which took as long and were throttled as much.
    let mut runs = throttled_runs(&[Some(300); 7]);
    for run in &mut runs[..3] {
        run.cpu_cap = Some(3000);
    }
    let unhelped = cpu_held(&whole(&runs), &measured(true));
    assert_eq!(
        unhelped[0].severity,
        Severity::Warning,
        "its runs ask for no further raise"
    );
    assert!(
        matches!(
            unhelped[0].kind,
            InsightKind::CpuHeld {
                raised_from: Some(3),
                set: None,
                held: 4,
                ..
            }
        ),
        "{unhelped:#?}"
    );
    assert!(
        unhelped[0].sentence.ends_with(UNHELPED),
        "{}",
        unhelped[0].sentence
    );

    // Less throttled at 4 than at 3: the raise helped, and auto sizing goes on.
    for run in &mut runs[..3] {
        run.cpu_throttled = Some(960);
    }
    let helped = cpu_held(&whole(&runs), &measured(true));
    assert_eq!(helped[0].severity, Severity::Notice, "{helped:#?}");
}

const UNHELPED: &str = "The raise of app from 3 to 4 CPUs did not make it faster or less throttled, as when its tools \
                        start a worker per CPU, so its runs ask for no further raise; runnerctl sizing says what auto \
                        sizing does next.";

/// `runs` as auto sizing reads them, each averaging `average` millicores of CPU.
fn as_sized(runs: &[Run], average: u64) -> Vec<crate::sizing::Ran> {
    runs.iter()
        .map(|run| crate::sizing::Ran {
            repository: run.repository.clone(),
            workflow: run.workflow.clone(),
            name: run.name.clone(),
            profile: run.profile.clone().unwrap(),
            memory_cap: Some(4 * G),
            cpu_cap: run.cpu_cap,
            memory_peak: G,
            cpu_peak: run.cpu_cap.unwrap(),
            cpu_average: Some(average),
            queued_at: run.queued_at,
            started_at: run.started_at,
            runner_started_at: run.runner_started_at.unwrap(),
            finished_at: run.finished_at,
            oom_killed: false,
            hit_cap: None,
            own_cap: None,
            measure: crate::sizing::Measure::WithoutPageCache,
            succeeded: true,
            failed: false,
            run_id: run.run_id,
            run_attempt: 1,
            branch: run.branch.clone(),
            reserved: None,
            host_waited: 0,
            slot_waited: 0,
            unseen: 0,
            cpu_periods: run.cpu_periods,
            cpu_throttled: run.cpu_throttled,
        })
        .collect()
}

/// The `cpus` auto sizing's look at `NOW` raises app to, in a slice of 32 CPUs and 33G, on `jobs`.
fn sizing_raises_app_to(config: &Config, jobs: Vec<crate::sizing::Ran>) -> Option<u32> {
    let history = crate::sizing::History {
        jobs,
        ..crate::sizing::History::default()
    };
    let (last, running) = (
        std::collections::BTreeMap::new(),
        std::collections::BTreeMap::new(),
    );
    let changes = crate::sizing::auto::changes(
        config,
        &history,
        crate::sizing::auto::Context {
            memory_max: Some(33 * G),
            cpus: Some(32_000),
            window: crate::sizing::Window {
                since: NOW - 30 * 24 * HOUR,
                now: NOW,
                sample_interval: 2,
            },
            last: &last,
            cpus_set: &[],
            running: &running,
            disk: None,
        },
    );
    changes
        .iter()
        .filter(|change| change.profile == "app")
        .find_map(|change| change.to.cpus.filter(|to| *to > 4))
}

/// Seven runs of `name` throttled in `before` per mille of their run at 3 CPUs, the first three, and in `now` at 4.
fn raised(name: &str, ids: u64, before: u64, now: u64) -> Vec<Run> {
    let mut runs = throttled_runs(&[
        Some(before),
        Some(before),
        Some(before),
        Some(now),
        Some(now),
        Some(now),
        Some(now),
    ]);
    for run in &mut runs {
        run.name = name.to_owned();
        run.id += ids;
        run.run_id += ids;
    }
    for run in &mut runs[..3] {
        run.cpu_cap = Some(3000);
    }
    runs
}

#[test]
fn a_raise_that_did_not_help_a_job_whose_runs_average_near_the_cap_never_says_auto_sizing_stopped()
{
    // As long and as throttled at 4 CPUs as at 3, but averaging 3 of the 4: auto sizing raises app on the averages.
    let runs = raised("test", 0, 300, 300);
    let config = measured(true);

    assert_eq!(
        sizing_raises_app_to(&config, as_sized(&runs, 3000)),
        Some(6),
        "auto sizing raises app on the runs' averages"
    );
    let found = cpu_held(&whole(&runs), &config);
    assert!(
        found[0].sentence.ends_with(UNHELPED),
        "{}",
        found[0].sentence
    );
    assert!(
        !found[0].sentence.contains("stopped"),
        "it says what this job's runs ask for, not what auto sizing does: {}",
        found[0].sentence
    );
}

#[test]
fn a_raise_that_did_not_help_one_job_but_helped_another_never_says_auto_sizing_stopped() {
    // test is as throttled at 4 CPUs as at 3; lint is still held back at 4, but less than at 3: its raise helped, so
    // auto sizing raises app for lint, light as both jobs' averages are.
    let mut runs = raised("test", 0, 300, 300);
    runs.extend(raised("lint", 100, 400, 200));
    let config = measured(true);

    assert_eq!(
        sizing_raises_app_to(&config, as_sized(&runs, 1000)),
        Some(6),
        "auto sizing raises app for lint"
    );
    let found = cpu_held(&whole(&runs), &config);
    let sentence = |job: &str| {
        found
            .iter()
            .find(|insight| insight.job.as_deref() == Some(job))
            .map(|insight| (insight.severity, insight.sentence.as_str()))
            .unwrap()
    };
    let (_, test) = sentence("test");
    assert!(test.ends_with(UNHELPED), "{test}");
    assert!(!test.contains("stopped"), "{test}");
    let (severity, lint) = sentence("lint");
    assert_eq!(severity, Severity::Notice, "{lint}");
    assert!(lint.contains("Auto sizing raises app's cpus"), "{lint}");
}

/// A job of `halyard/api` that started `hours_ago` hours before `NOW` after waiting `waited` seconds, on a runner
/// started before it was queued when `warm`.
fn waited(n: u64, hours_ago: u64, waited: u64, warm: bool) -> Run {
    let mut run = test_run(n, hours_ago, 60);
    let started = run.started_at.unwrap();
    run.queued_at = started - waited * 1000;
    run.runner_started_at = Some(if warm {
        run.queued_at - 60_000
    } else {
        started - 5_000
    });
    run
}

#[test]
fn waits_are_split_warm_and_cold_and_longer_ones_are_a_notice() {
    let mut runs: Vec<Run> = (0..6).map(|n| waited(n, 200, 20, false)).collect();
    runs.extend((10..16).map(|n| waited(n, 10, 300, false)));
    runs.extend((20..24).map(|n| waited(n, 10, 2, true)));

    let found = insights(&whole(&runs), &config(), 14, NOW);

    let api = &found.waits[0];
    assert_eq!(api.repository, "halyard/api");
    assert_eq!((api.now.warm.jobs, api.now.cold.jobs), (4, 6));
    assert_eq!((api.now.warm.p50, api.now.cold.p50), (Some(2), Some(300)));
    assert_eq!(api.before.all.p95, Some(20));
    let notice = found
        .insights
        .iter()
        .find(|insight| insight.key == "waits:halyard/api")
        .expect("waits went up");
    assert_eq!(notice.severity, Severity::Notice);
    assert_eq!(
        notice.kind,
        InsightKind::Waits {
            before: 20,
            now: 300
        }
    );
}

#[test]
fn a_week_of_fewer_than_20_jobs_tells_its_longest_wait_and_one_of_more_its_1_in_20() {
    let sentence = |now: u64| {
        let mut runs: Vec<Run> = (0..6).map(|n| waited(n, 200, 20, false)).collect();
        runs.extend((10..10 + now).map(|n| waited(n, 10, 300, false)));
        insights(&whole(&runs), &config(), 14, NOW)
            .insights
            .into_iter()
            .find(|insight| insight.key == "waits:halyard/api")
            .expect("waits went up")
            .sentence
    };
    assert_eq!(
        sentence(19),
        "halyard/api: the longest wait for a runner this week is 5m, up from 20s the week before."
    );
    assert_eq!(
        sentence(20),
        "halyard/api: 1 job in 20 waits 5m or more for a runner this week, up from 20s the week before."
    );
}

#[test]
fn a_week_before_the_history_holds_every_job_is_not_compared() {
    // The history starts 8 days ago: the week before holds only the daemon's first hour, six jobs that waited 20
    // seconds. Against that sliver, this week's 5-minute waits would read "up from 20s the week before".
    let mut runs: Vec<Run> = (0..6).map(|n| waited(n, 8 * 24 - 1, 20, false)).collect();
    runs.extend((10..16).map(|n| waited(n, 10, 300, false)));
    let young = History {
        runs,
        kept_since: NOW - 8 * 24 * HOUR,
        ..History::default()
    };
    let found = insights(&young, &config(), 14, NOW);
    let api = &found.waits[0];
    assert_eq!((api.before.all.jobs, api.before.all.p95), (0, None));
    assert_eq!(
        api.now.all.p95,
        Some(300),
        "this week is what the history has"
    );
    assert!(
        found
            .insights
            .iter()
            .all(|insight| !insight.key.starts_with("waits:")),
        "no waits insight: {:?}",
        found.insights
    );
    assert!(
        digest(&young, &config(), NOW)
            .new
            .iter()
            .all(|insight| !insight.key.starts_with("waits:")),
        "nor in the digest"
    );
    let kept = History {
        kept_since: NOW - 14 * 24 * HOUR,
        host: None,
        ..young
    };
    assert!(
        insights(&kept, &config(), 14, NOW)
            .insights
            .iter()
            .any(|insight| insight.key == "waits:halyard/api"),
        "a history that holds the whole week before compares it"
    );
}

#[test]
fn a_job_queued_before_runnerd_first_ran_waits_from_when_it_did() {
    // runnerd first ran 10 hours ago; six jobs had queued three hours before, and its first runners took them a
    // minute after it started. They waited a minute for runnerd, not four hours.
    let first = NOW - 10 * HOUR;
    let runs: Vec<Run> = (0..6)
        .map(|n| {
            let mut run = waited(n, 9, 60, false);
            run.started_at = Some(first + 60_000);
            run.finished_at = Some(first + 120_000);
            run.queued_at = first - 3 * HOUR;
            run
        })
        .collect();
    let history = History {
        runs,
        kept_since: first,
        ..History::default()
    };
    let found = insights(&history, &config(), 14, NOW);
    assert_eq!(found.waits[0].now.all.p95, Some(60));
    let day = digest(&history, &config(), NOW);
    assert_eq!(day.waits[0].waited, 60, "the digest's longest wait too");
}

#[test]
fn the_digest_counts_the_day_and_lists_only_new_insights() {
    // Flaky two days ago, and again today: not new. Slower since today: new.
    let mut runs = vec![attempt(900, 1, "failure"), attempt(900, 2, "success")];
    for run in &mut runs {
        run.finished_at = Some(NOW - 48 * HOUR);
    }
    let mut durations = vec![240; 9];
    durations.extend([400; 5]);
    let mut slow = history(&durations);
    // The last five runs, and so the slow ones, within the day.
    for (run, hours) in slow.iter_mut().rev().zip([1, 3, 5, 7, 9]) {
        run.finished_at = Some(NOW - hours * HOUR);
        run.started_at = Some(NOW - hours * HOUR - 400_000);
    }
    let mut failed = test_run(500, 2, 60);
    failed.run_id = 500;
    failed.conclusion = Some("failure".to_owned());
    slow.push(failed);
    runs.extend(slow);

    let day = digest(&whole(&runs), &config(), NOW);

    assert_eq!((day.finished, day.failed), (6, 1));
    let new: Vec<&str> = day.new.iter().map(|insight| insight.key.as_str()).collect();
    assert_eq!(new, ["slower:halyard/api/CI/test"]);
    assert_eq!(day.waits.len(), 3);
}

#[test]
fn every_kind_of_insight_reads_back_as_the_daemon_sends_it() {
    let mut runs = history(&[
        240, 240, 240, 240, 240, 240, 240, 240, 360, 360, 360, 360, 360, 360,
    ]);
    for run in &mut runs {
        run.memory_peak = Some(37 * G / 10);
    }
    for run in &mut runs[12..] {
        run.sock_throttled = Some(12);
    }
    for run in &mut runs[11..] {
        run.cpu_periods = Some(3600);
        run.cpu_throttled = Some(1800);
    }
    let mut others = vec![attempt(900, 1, "failure"), attempt(900, 2, "success")];
    others.extend((0..6).map(|n| waited(n + 2000, 200, 20, false)));
    others.extend((10..16).map(|n| waited(n + 2000, 10, 300, false)));
    for run in &mut others {
        run.name = "lint".to_owned();
        run.memory_peak = Some(G);
    }
    runs.extend(others);

    let found = insights(&whole(&runs), &config(), 14, NOW);
    let kinds: Vec<&str> = found
        .insights
        .iter()
        .map(|insight| insight.key.split(':').next().unwrap())
        .collect();
    assert_eq!(
        kinds,
        [
            "throttled",
            "cpu-held",
            "near-cap",
            "slower",
            "waits",
            "flaky"
        ],
        "warnings first: {found:#?}"
    );

    let sent = serde_json::to_string(&found).unwrap();
    let read: api::Insights = serde_json::from_str(&sent).unwrap();
    assert_eq!(read, found);
}

#[test]
fn an_insight_of_a_kind_from_a_later_release_still_reads_by_its_sentence() {
    let sent = r#"{"since": 0, "until": 86400, "waits": [], "insights": [{"key": "later:halyard/api",
        "severity": "warning", "repository": "halyard/api", "workflow": null, "job": null,
        "sentence": "halyard/api: something a later release finds.", "kind": "later", "figure": 3, "runs": []}]}"#;

    let read: api::Insights = serde_json::from_str(sent).unwrap();

    assert_eq!(read.insights[0].kind, InsightKind::Unknown);
    assert_eq!(
        read.insights[0].sentence,
        "halyard/api: something a later release finds."
    );
}

/// Two jobs waiting for the host's memory at `NOW`, the longer for `waited` ms, beside a reading that names java and
/// claude.
fn held(waited: u64) -> HostHold {
    HostHold {
        memory: api::HostMemory {
            at: NOW / 1000 - 2,
            total: 64 * G,
            available: 8 * G,
            slice: 18 * G,
            some: None,
            full: None,
            holders: vec![
                api::Holder {
                    name: "java".to_owned(),
                    memory: 9 * G,
                },
                api::Holder {
                    name: "claude".to_owned(),
                    memory: 5 * G,
                },
            ],
            ceiling: None,
            swap: None,
        },
        seen: NOW - 3_000,
        jobs: vec![
            HeldJob {
                repository: "halyard/web".to_owned(),
                workflow: Some("CI".to_owned()),
                name: "lint".to_owned(),
                waited: 5 * MINUTE,
            },
            HeldJob {
                repository: "halyard/api".to_owned(),
                workflow: Some("CI".to_owned()),
                name: "test".to_owned(),
                waited,
            },
        ],
    }
}

/// The insights at `at` of a history with no finished job and `hold` waiting.
fn holding(hold: Option<HostHold>, at: u64) -> Vec<api::Insight> {
    holding_by(hold, &config(), at)
}

/// The same under `config`.
fn holding_by(hold: Option<HostHold>, config: &Config, at: u64) -> Vec<api::Insight> {
    let history = History {
        host: hold,
        ..History::default()
    };
    insights(&history, config, 14, at).insights
}

#[test]
fn a_job_held_half_an_hour_for_the_hosts_memory_is_a_warning_naming_who_holds_it() {
    // Catches a message that blames the wrong repository, drops the holders, or says closing them frees the whole
    // figure the host holds outside CI.
    let found = holding(Some(held(42 * MINUTE)), NOW);
    let [insight] = found.as_slice() else {
        panic!("one insight: {found:#?}");
    };
    assert_eq!(insight.severity, Severity::Warning);
    assert_eq!(insight.repository, "halyard/api", "the longest waiter's");
    assert_eq!(
        insight.kind,
        InsightKind::HostHeld {
            jobs: 2,
            waited: 42 * 60
        }
    );
    assert_eq!(
        insight.sentence,
        "2 jobs wait for the host's memory, the longest for 42m 00s (halyard/api: CI / test); programs outside CI \
         hold 38G, most java 9G and claude 5G. Closing programs frees only part of that."
    );
    // The same for the whole of a 6-hour window and another after it.
    let key = |at: u64| {
        let mut hold = held(42 * MINUTE);
        hold.memory.at = at / 1000;
        hold.seen = at;
        holding(Some(hold), at)[0].key.clone()
    };
    let window = 6 * HOUR;
    let start = NOW / window * window;
    assert_eq!(key(start), key(start + window - 1000));
    assert_ne!(key(start + window - 1000), key(start + window));
}

#[test]
fn nothing_is_said_of_a_host_wait_that_is_short_unseen_stale_or_from_after_the_look() {
    // Catches a message for every short span, one from a daemon that stopped looking, and the digest's look at 24
    // hours ago finding today's wait.
    let said = |hold, at| !holding(hold, at).is_empty();
    assert!(said(Some(held(30 * MINUTE)), NOW), "30 minutes is enough");
    assert!(!said(Some(held(30 * MINUTE - 1)), NOW), "29m 59s is not");
    assert!(!said(None, NOW), "no job waits for it now");
    let mut no_jobs = held(HOUR);
    no_jobs.jobs.clear();
    assert!(!said(Some(no_jobs), NOW));
    let mut old_reading = held(HOUR);
    old_reading.memory.at = NOW / 1000 - 61;
    assert!(!said(Some(old_reading), NOW), "a reading of a minute ago");
    let mut old_look = held(HOUR);
    old_look.seen = NOW - 61_000;
    assert!(!said(Some(old_look), NOW), "the engine's last look");
    // A slow engine plans once a poll: its look is stale only past three of them.
    let slow = Config::parse(&CONFIG.replace(
        "isolation = \"sysbox\"",
        "isolation = \"sysbox\"\npoll_interval = \"1m\"",
    ))
    .unwrap();
    let mut slow_plan = held(HOUR);
    slow_plan.seen = NOW - 170_000;
    assert!(
        holding_by(Some(slow_plan.clone()), &config(), NOW).is_empty(),
        "170 s is over the default's minute"
    );
    assert!(
        !holding_by(Some(slow_plan.clone()), &slow, NOW).is_empty(),
        "170 s is under three 1-minute polls"
    );
    slow_plan.seen = NOW - 190_000;
    assert!(
        holding_by(Some(slow_plan), &slow, NOW).is_empty(),
        "190 s is over"
    );
    let mut this_second = held(HOUR);
    this_second.seen = NOW + 400;
    assert!(
        said(Some(this_second), NOW),
        "a plan in the second of the look is not from after it"
    );
    let mut next_second = held(HOUR);
    next_second.seen = NOW + 1_000;
    assert!(!said(Some(next_second), NOW), "one in the next is");
    assert!(
        !said(Some(held(HOUR)), NOW - 24 * HOUR),
        "a look from before the reading"
    );
}

#[test]
fn a_host_held_insight_without_names_says_how_much_the_host_holds_and_no_more() {
    // Catches a failure to word a host whose cgroups it cannot read (no holders), or a stray separator.
    let mut hold = held(HOUR);
    hold.memory.holders.clear();
    let found = holding(Some(hold), NOW);
    assert_eq!(
        found[0].sentence,
        "2 jobs wait for the host's memory, the longest for 1h 00m (halyard/api: CI / test); programs outside CI \
         hold 38G. Closing programs frees only part of that."
    );
}

/// Midnight UTC of `NOW`'s day, 8 hours before it.
const TODAY: u64 = NOW / (24 * HOUR) * (24 * HOUR);
const SECOND: u64 = 1000;

/// A reading of a 64G host, whose low line is 20G and critical line 6.4G, `at` ms with `available` and `credit`.
fn reading(at: u64, available: u64, credit: u64, running: bool) -> HostReading {
    HostReading {
        at,
        total: 64 * G,
        available,
        swap_free: Some(8 * G),
        credit,
        running,
    }
}

/// Today: 30s with nothing short, a minute under 20G on a credit, a two-hour gap the daemon did not run, an idle
/// reading at 1G, 20s under 6.4G on a credit, then a minute at 40G. Yesterday: a minute under 6.4G with no credit.
fn readings() -> Vec<HostReading> {
    vec![
        reading(TODAY - 2 * HOUR, 2 * G, 0, true),
        reading(TODAY - 2 * HOUR + 60 * SECOND, 30 * G, 0, false),
        reading(TODAY + HOUR, 30 * G, 0, true),
        reading(TODAY + HOUR + 30 * SECOND, 10 * G, 2 * G, true),
        reading(TODAY + 3 * HOUR, G, 0, false),
        reading(TODAY + 3 * HOUR + 20 * SECOND, 5 * G, 2 * G, true),
        reading(TODAY + 3 * HOUR + 40 * SECOND, 40 * G, 0, true),
    ]
}

#[test]
fn the_host_s_day_counts_only_while_runners_ran_each_reading_for_a_minute_at_most_with_its_share_on_a_credit()
 {
    // Catches a reading counted across a gap the daemon did not run, an idle host's low reading counted as CI's,
    // a day's figures leaking into the next, and a credit's share taken from the wrong readings.
    let history = History {
        readings: readings(),
        ..History::default()
    };
    let found = insights(&history, &config(), 14, NOW);
    let [today, yesterday] = found.host.as_slice() else {
        panic!("two days, newest first: {:#?}", found.host);
    };
    assert_eq!(today.since, TODAY / SECOND);
    assert_eq!((today.running, today.credited), (30 + 60 + 20 + 60, 80));
    assert_eq!((today.low_line, today.critical_line), (20 * G, 64 * G / 10));
    assert_eq!(
        (today.low.seconds, today.low.credited),
        (80, 80),
        "under 20G only on the credit"
    );
    assert_eq!((today.critical.seconds, today.critical.credited), (20, 20));
    assert_eq!(
        (today.lowest, today.lowest_credited),
        (5 * G, Some(5 * G)),
        "the idle 1G is not CI's"
    );
    assert_eq!(
        today.dated_line(),
        "Jan 15: CI ran 2m 50s, 1m 20s of it on a host credit; under 20G available for 1m 20s (1m 20s on a \
         credit); under 6.4G available for 20s (20s on a credit); lowest 5G (5G on a credit); swap free at least 8G"
    );
    assert_eq!((yesterday.running, yesterday.credited), (60, 0));
    assert_eq!(yesterday.critical.seconds, 60);
    assert!(
        !yesterday.line().contains("credit"),
        "a day without a credit says nothing of one: {}",
        yesterday.line()
    );
}

#[test]
fn a_day_under_a_tenth_of_the_host_on_a_credit_warns_once_and_a_day_without_one_does_not() {
    // Catches a warning for a low host the credit had no part in, and a key that changes within the day, which
    // would tell the owner again on every look.
    let history = History {
        readings: readings(),
        ..History::default()
    };
    let warning = |at: u64| {
        let found = insights(&history, &config(), 14, at).insights;
        let [insight] = found.as_slice() else {
            panic!("one warning: {found:#?}");
        };
        insight.clone()
    };
    let insight = warning(NOW);
    assert_eq!(insight.severity, Severity::Warning);
    assert_eq!(
        insight.kind,
        InsightKind::HostLow {
            day: TODAY / SECOND,
            seconds: 20,
            lowest: 5 * G
        }
    );
    assert_eq!(insight.key, warning(NOW + 10 * HOUR).key, "the same day's");
    assert!(
        insight.sentence.contains(
            "[host] pooled_count = false makes the budgets count every reservation again"
        ),
        "{}",
        insight.sentence
    );

    let mut uncredited = readings();
    for reading in &mut uncredited {
        reading.credit = 0;
    }
    let history = History {
        readings: uncredited,
        ..History::default()
    };
    let found = insights(&history, &config(), 14, NOW).insights;
    assert!(
        found.is_empty(),
        "a low host with no credit is no warning: {found:#?}"
    );
}

#[test]
fn the_digest_reads_the_host_over_its_own_24_hours() {
    // Catches a digest that reads the calendar day, or the whole insights window, instead of its 24 hours.
    let history = History {
        readings: readings(),
        ..History::default()
    };
    let day = digest(&history, &config(), NOW + 15 * HOUR).host.unwrap();
    assert_eq!(
        (day.running, day.lowest),
        (170, 5 * G),
        "today's runs, not yesterday's"
    );
    let before = digest(&history, &config(), TODAY - HOUR).host.unwrap();
    assert_eq!((before.running, before.lowest), (60, 2 * G));
    assert_eq!(
        digest(&history, &config(), TODAY + 30 * HOUR).host,
        None,
        "no runner ran in its 24 hours"
    );
}