runnerd-core 0.1.5

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
//! The shared build cache on the fakes (ADR 0052): a push to main's entry is a hit for a pull request's job in
//! another slot, the pull request's uploads stay invisible, each job's record keeps what the cache did for it, a tag
//! named like the default branch only reads, the cache is trimmed only once no runner runs, where a repository
//! lets them (ADR 0053), its own branches' pull requests that people opened write while forks' and bots' read, and
//! GitHub Actions cache saves made while GitHub names no runner for their job land once it does (ADR 0085).

use super::*;
use crate::buildcache::{self, BuildCache, actions};

/// An engine on the fakes with a build cache in `dir`, for `config`.
pub(super) fn engine_with_cache(
    github: &FakeGithub,
    docker: &FakeDocker,
    dir: &TestDir,
    config: &str,
) -> (Engine<FakeGithub, FakeDocker>, Handle, BuildCache) {
    let config = Config::parse(config).unwrap();
    let cache = BuildCache::open(
        &dir.0.join("build-cache"),
        &dir.0.join("sockets"),
        config.caches.build.max_size.0,
    )
    .unwrap();
    let store = Store::open(&dir.0.join("history.db")).unwrap();
    let (engine, handle) = Engine::new(
        config,
        github.clone(),
        docker.clone(),
        Setup {
            names: Names::new("runnerd"),
            identity: identity("ci", ID_A),
            memory_max: None,
            cpus: None,
            announced: store.announced().unwrap(),
            paused: store.paused_repositories().unwrap(),
            store,
            paths: Paths {
                cgroup: dir.0.join("cgroup"),
                proc: dir.0.join("proc"),
                sys: dir.0.join("sys"),
            },
            build_cache: Some(cache.clone()),
            action_archives: None,
            unsynced: dir.0.join("unsynced"),
            durability: Durability::new(|| {}, |_| false),
        },
    );
    (engine, handle, cache)
}

pub(super) fn trigger(event: &str, branch: &str) -> github::RunTrigger {
    github::RunTrigger {
        event: event.to_owned(),
        head_branch: Some(branch.to_owned()),
        head_repository: Some("o/r".to_owned()),
        head_sha: "c0ffee".to_owned(),
        by_user: true,
        pull_requests: Vec::new(),
    }
}

/// The runner started in `slot` of `app`, and the directory its container mounts at `buildcache::MOUNT`.
fn runner_in(docker: &FakeDocker, slot: usize) -> (String, std::path::PathBuf) {
    let state = docker.0.lock().unwrap();
    let (name, mounts) = state
        .mounts
        .iter()
        .find(|(name, _)| name.contains(&format!("-app-{slot}-")))
        .unwrap();
    let mount = mounts
        .iter()
        .find(|mount| mount.target.as_deref() == Some(buildcache::MOUNT))
        .unwrap();
    assert_eq!(
        mount.read_only,
        Some(true),
        "a job cannot change its socket"
    );
    (name.clone(), mount.source.clone().unwrap().into())
}

/// Starts a runner per queued job: job 1, run 1, a push to main, in slot 1; job 2, run 2, a pull request, in slot 2.
/// GitHub places each on its runner.
async fn main_and_pull_request(
    github: &FakeGithub,
    docker: &FakeDocker,
    engine: &mut Engine<FakeGithub, FakeDocker>,
) -> [(String, std::path::PathBuf); 2] {
    two_jobs(
        github,
        docker,
        engine,
        [trigger("push", "main"), trigger("pull_request", "main")],
    )
    .await
}

/// Starts a runner per queued job, job 1 of run 1 in slot 1 and job 2 of run 2 in slot 2, their runs started as
/// `triggers` say. GitHub places each on its runner.
async fn two_jobs(
    github: &FakeGithub,
    docker: &FakeDocker,
    engine: &mut Engine<FakeGithub, FakeDocker>,
    triggers: [github::RunTrigger; 2],
) -> [(String, std::path::PathBuf); 2] {
    engine.recover().await.unwrap();
    two_more_jobs(github, docker, engine, 1, triggers).await
}

/// As `two_jobs` on an engine that runs already, for jobs `first` and `first + 1`, each of its own run.
async fn two_more_jobs(
    github: &FakeGithub,
    docker: &FakeDocker,
    engine: &mut Engine<FakeGithub, FakeDocker>,
    first: u64,
    triggers: [github::RunTrigger; 2],
) -> [(String, std::path::PathBuf); 2] {
    let ids = [first, first + 1];
    {
        let mut state = github.0.lock().unwrap();
        state.queued = ids
            .iter()
            .map(|&id| QueuedJob {
                run_id: id,
                ..job(id)
            })
            .collect();
        for (id, trigger) in ids.into_iter().zip(triggers) {
            state.triggers.insert(id, trigger);
        }
    }
    {
        let mut state = docker.0.lock().unwrap();
        for (slot, id) in [1, 2].into_iter().zip(ids) {
            state
                .slot_captures
                .insert(slot, format!("@@job {id} {id}\n"));
        }
        state.mounts.clear();
    }
    // Once jobs ended, the caches are checked first, and runners wait for it.
    for _ in 0..50 {
        engine.tick(Shutdown::No).await;
        if docker.0.lock().unwrap().mounts.len() == 2 {
            break;
        }
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    let runners = [runner_in(docker, 1), runner_in(docker, 2)];
    let mut state = github.0.lock().unwrap();
    for (id, (name, _)) in ids.into_iter().zip(&runners) {
        state.jobs.insert(
            id,
            JobDetails {
                run_id: id,
                runner_name: Some(name.clone()),
                ..details(id, "in_progress", None)
            },
        );
    }
    state.queued.clear();
    runners
}

/// Ticks until neither runner's writes are undecided.
async fn until_decided(
    engine: &mut Engine<FakeGithub, FakeDocker>,
    cache: &BuildCache,
    runners: &[&str],
) {
    for _ in 0..50 {
        if runners.iter().all(|runner| !cache.undecided(runner)) {
            return;
        }
        engine.age_running_reads(Duration::from_hours(1));
        engine.tick(Shutdown::No).await;
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    panic!("the writes of {runners:?} were never decided");
}

/// Saves `archive` under `key` through `socket` as `actions/cache` does, answered at once whatever GitHub has said of
/// the job: its post-step waits for it.
async fn save_now(socket: &std::path::Path, key: &str, archive: &[u8]) -> bool {
    tokio::time::timeout(Duration::from_secs(5), actions::save(socket, key, archive))
        .await
        .expect("a save is answered at once")
}

/// The socket a runner's build cache listens on, by its container's name, if it has one.
pub(super) fn socket_of(docker: &FakeDocker, name: &str) -> Option<std::path::PathBuf> {
    let state = docker.0.lock().unwrap();
    let mount = state
        .mounts
        .get(name)?
        .iter()
        .find(|mount| mount.target.as_deref() == Some(buildcache::MOUNT))?;
    mount.source.clone().map(Into::into)
}

/// A GitHub Actions cache save a runner makes, as soon as it can be answered.
pub(super) async fn save(socket: &std::path::Path) -> bool {
    tokio::time::timeout(
        Duration::from_secs(5),
        actions::save(socket, "deps", b"deps"),
    )
    .await
    .is_ok_and(|saved| saved)
}

/// How many build cache uploads wait on disk to become entries, for the engine in `dir`.
fn uploads(dir: &TestDir) -> usize {
    std::fs::read_dir(dir.0.join("build-cache").join("uploads"))
        .unwrap()
        .count()
}

/// GitHub's jobs API says `job` is queued on no runner, as it can for minutes after the job started.
fn github_names_no_runner(github: &FakeGithub, job: u64) {
    if let Some(details) = github.0.lock().unwrap().jobs.get_mut(&job) {
        details.status = "queued".to_owned();
        details.runner_name = None;
    }
}

/// GitHub's jobs API catches up: `job` is `status` on `runner`.
fn github_names(github: &FakeGithub, job: u64, runner: &str, status: &str) {
    if let Some(details) = github.0.lock().unwrap().jobs.get_mut(&job) {
        details.status = status.to_owned();
        details.runner_name = Some(runner.to_owned());
    }
}

/// The build cache counts of `job`'s record.
async fn counts_of(handle: &Handle, job: u64) -> api::BuildCacheCounts {
    handle.store.flush().await;
    handle
        .store
        .job(job)
        .await
        .unwrap()
        .unwrap()
        .summary
        .metrics
        .build_cache
}

/// Stops every runner container, as when their jobs end, and lets the engine remove them.
async fn jobs_end(docker: &FakeDocker, engine: &mut Engine<FakeGithub, FakeDocker>) {
    for container in &mut docker.0.lock().unwrap().containers {
        container.running = false;
    }
    engine.tick(Shutdown::No).await;
}

#[tokio::test]
async fn a_main_builds_entry_is_a_hit_for_a_pull_request_in_another_slot() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-build-cache");
    let (mut engine, handle, cache) = engine_with_cache(&github, &docker, &dir, CONFIG);
    let [(main, main_socket), (pull, pull_socket)] =
        main_and_pull_request(&github, &docker, &mut engine).await;
    // Gradle stores its first outputs before GitHub has said anything of the job.
    assert_eq!(
        buildcache::request(&main_socket, "PUT", "/gradle/0a1b", b"classes")
            .await
            .0,
        200
    );
    until_decided(&mut engine, &cache, &[&main, &pull]).await;
    assert_eq!(
        buildcache::request(&pull_socket, "GET", "/gradle/0a1b", b"").await,
        (200, b"classes".to_vec())
    );
    // The pull request's upload is accepted, so Gradle keeps the cache on, and main never sees it.
    assert_eq!(
        buildcache::request(&pull_socket, "PUT", "/gradle/ffff", b"poison")
            .await
            .0,
        200
    );
    assert_eq!(
        buildcache::request(&main_socket, "GET", "/gradle/ffff", b"")
            .await
            .0,
        404
    );
    jobs_end(&docker, &mut engine).await;
    handle.store.flush().await;
    let counts = |job: u64| {
        let store = handle.store.clone();
        async move {
            store
                .job(job)
                .await
                .unwrap()
                .unwrap()
                .summary
                .metrics
                .build_cache
        }
    };
    let main_counts = counts(1).await;
    assert_eq!((main_counts.written_bytes, main_counts.misses), (7, 1));
    assert!(main_counts.writer, "the push to main wrote");
    let pull_counts = counts(2).await;
    assert_eq!(
        (
            pull_counts.hits,
            pull_counts.read_bytes,
            pull_counts.refused
        ),
        (1, 7, 1)
    );
    assert!(!pull_counts.writer, "the pull request only read");
    assert!(!main_socket.exists(), "a removed runner's socket goes");
}

#[tokio::test]
async fn a_runner_whose_log_claims_another_runners_job_only_reads() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-build-cache-claim");
    let (mut engine, _handle, cache) = engine_with_cache(&github, &docker, &dir, CONFIG);
    // The pull request's job writes main's job ID into its runner's log before the capture reads it.
    docker
        .0
        .lock()
        .unwrap()
        .slot_captures
        .insert(2, "@@job 1 1\n".to_owned());
    {
        let mut state = github.0.lock().unwrap();
        state.queued = vec![
            job(1),
            QueuedJob {
                run_id: 2,
                ..job(2)
            },
        ];
        state.triggers.insert(1, trigger("push", "main"));
    }
    docker
        .0
        .lock()
        .unwrap()
        .slot_captures
        .insert(1, "@@job 1 1\n".to_owned());
    engine.recover().await.unwrap();
    engine.tick(Shutdown::No).await;
    let (main, _) = runner_in(&docker, 1);
    let (liar, liar_socket) = runner_in(&docker, 2);
    {
        let mut state = github.0.lock().unwrap();
        state.jobs.insert(
            1,
            JobDetails {
                runner_name: Some(main.clone()),
                ..details(1, "in_progress", None)
            },
        );
        state.queued.clear();
    }
    until_decided(&mut engine, &cache, &[&main, &liar]).await;
    assert_eq!(
        buildcache::request(&liar_socket, "PUT", "/gradle/0a1b", b"poison")
            .await
            .0,
        200
    );
    assert_eq!(cache.size().entries, 0, "{liar} stored nothing");
}

/// Uploads one entry of `bytes` to each of `keys` through `socket`.
async fn upload(socket: &std::path::Path, keys: &[&str], bytes: usize) {
    for key in keys {
        let path = format!("/gradle/{key}");
        assert_eq!(
            buildcache::request(socket, "PUT", &path, &vec![0; bytes])
                .await
                .0,
            200
        );
    }
}

#[tokio::test]
async fn the_build_cache_is_trimmed_only_once_no_runner_runs() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-build-cache-trim");
    let config = CONFIG.replace(
        "maven = { max_size = \"5G\" }\n",
        "maven = { max_size = \"5G\" }\nbuild = { max_size = \"16K\" }\n",
    );
    let (mut engine, _handle, cache) = engine_with_cache(&github, &docker, &dir, &config);
    let [(main, main_socket), (pull, _)] =
        main_and_pull_request(&github, &docker, &mut engine).await;
    until_decided(&mut engine, &cache, &[&main, &pull]).await;
    // Each a quarter of the limit, as an entry may be at most.
    upload(&main_socket, &["aa", "bb", "cc", "dd", "ee"], 4096).await;
    assert_eq!(cache.size().bytes, 20 << 10);
    for _ in 0..3 {
        engine.tick(Shutdown::No).await;
    }
    assert_eq!(cache.size().bytes, 20 << 10, "trimmed while jobs run");

    // The jobs end, and the shared caches' check that starts then takes long to measure Docker's volumes; the reseed
    // slot 1's job makes due finishes.
    {
        let mut state = docker.0.lock().unwrap();
        state.volume_sizes_held.send_replace(true);
        state.seed_exit = Some(0);
    }
    jobs_end(&docker, &mut engine).await;
    assert_eq!(
        cache.size().bytes,
        16 << 10,
        "trimmed at the first idle tick"
    );
    // Jobs start before the check ends, and use the build cache as it is.
    let [(main, main_socket), (pull, _)] = two_more_jobs(
        &github,
        &docker,
        &mut engine,
        3,
        [trigger("push", "main"), trigger("pull_request", "main")],
    )
    .await;
    let started = cache.size();
    docker
        .0
        .lock()
        .unwrap()
        .volume_sizes_held
        .send_replace(false);
    for _ in 0..50 {
        if engine.trim.is_none() {
            break;
        }
        engine.tick(Shutdown::No).await;
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    assert!(engine.trim.is_none(), "the check ended");
    assert_eq!(cache.size(), started, "the check trimmed while jobs run");

    // What they store is trimmed once they end.
    until_decided(&mut engine, &cache, &[&main, &pull]).await;
    upload(&main_socket, &["ff"], 4096).await;
    assert_eq!(cache.size().bytes, 20 << 10);
    jobs_end(&docker, &mut engine).await;
    assert_eq!(
        cache.size().bytes,
        16 << 10,
        "trimmed at the next idle tick"
    );
}

#[tokio::test]
async fn a_repository_that_opts_out_gets_no_build_cache() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-build-cache-off");
    let config = CONFIG.replace("warm = 0\n", "warm = 0\nbuild_cache = false\n");
    let (mut engine, _handle, _cache) = engine_with_cache(&github, &docker, &dir, &config);
    github.0.lock().unwrap().queued = vec![job(1)];
    engine.recover().await.unwrap();
    engine.tick(Shutdown::No).await;
    let state = docker.0.lock().unwrap();
    let mounts = state.mounts.values().next().unwrap();
    assert!(
        mounts
            .iter()
            .all(|mount| mount.target.as_deref() != Some(buildcache::MOUNT)),
        "o/r opted out"
    );
}

#[tokio::test]
async fn branches_the_config_names_write_besides_the_default_branch() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-build-cache-branches");
    let config = CONFIG.replace(
        "maven = { max_size = \"5G\" }\n",
        "maven = { max_size = \"5G\" }\nbuild = { branches = [\"release\"] }\n",
    );
    let (mut engine, _handle, cache) = engine_with_cache(&github, &docker, &dir, &config);
    let [(main, main_socket), (release, release_socket)] = two_jobs(
        &github,
        &docker,
        &mut engine,
        [trigger("push", "main"), trigger("push", "release")],
    )
    .await;
    until_decided(&mut engine, &cache, &[&main, &release]).await;
    for (socket, key) in [(&main_socket, "aa"), (&release_socket, "bb")] {
        let path = format!("/gradle/{key}");
        assert_eq!(
            buildcache::request(socket, "PUT", &path, b"classes")
                .await
                .0,
            200
        );
    }
    assert_eq!(cache.size().entries, 2, "main and release both wrote");
}

#[tokio::test]
async fn a_writing_branch_keeps_its_own_actions_cache_entries_and_reads_mains() {
    use crate::buildcache::actions::{restore, save};

    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-actions-cache");
    let config = CONFIG.replace(
        "maven = { max_size = \"5G\" }\n",
        "maven = { max_size = \"5G\" }\nbuild = { branches = [\"release\"] }\n",
    );
    let (mut engine, _handle, cache) = engine_with_cache(&github, &docker, &dir, &config);
    let [(main, main_socket), (release, release_socket)] = two_jobs(
        &github,
        &docker,
        &mut engine,
        [trigger("push", "main"), trigger("push", "release")],
    )
    .await;
    assert!(
        main_socket.join(buildcache::ACTIONS_MARKER).is_file(),
        "it is on by default"
    );
    until_decided(&mut engine, &cache, &[&main, &release]).await;
    assert!(save(&main_socket, "deps", b"main's").await);
    assert!(save(&release_socket, "deps", b"release's").await);
    assert!(save(&main_socket, "tools", b"main's tools").await);
    assert_eq!(
        restore(&main_socket, "deps", &[]).await,
        Some(("deps".to_owned(), b"main's".to_vec())),
        "release's save is in release's scope"
    );
    assert_eq!(
        restore(&release_socket, "deps", &[]).await,
        Some(("deps".to_owned(), b"release's".to_vec()))
    );
    assert_eq!(
        restore(&release_socket, "tools", &[]).await,
        Some(("tools".to_owned(), b"main's tools".to_vec())),
        "a branch falls back to the default branch's entries"
    );
}

/// `CONFIG` with GitHub Actions' cache turned off.
fn actions_cache_off() -> String {
    CONFIG.replace(
        "maven = { max_size = \"5G\" }\n",
        "maven = { max_size = \"5G\" }\nbuild = { actions_cache = false }\n",
    )
}

#[tokio::test]
async fn with_the_actions_cache_off_jobs_keep_githubs() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-actions-cache-off");
    let (mut engine, _handle, cache) =
        engine_with_cache(&github, &docker, &dir, &actions_cache_off());
    let [(main, main_socket), (pull, _)] =
        main_and_pull_request(&github, &docker, &mut engine).await;
    until_decided(&mut engine, &cache, &[&main, &pull]).await;
    assert!(
        !main_socket.join(buildcache::ACTIONS_MARKER).exists(),
        "without the marker the image starts no forwarder and sets no NODE_OPTIONS"
    );
    assert_eq!(
        buildcache::request(&main_socket, "PUT", "/gradle/0a1b", b"classes")
            .await
            .0,
        200,
        "the build cache is as before"
    );
    assert_eq!(cache.size().entries, 1);
}

#[tokio::test]
async fn a_job_started_with_the_actions_cache_keeps_working_after_a_restart_turns_it_off() {
    use crate::buildcache::actions::{restore, save};

    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-actions-cache-restart-off");
    let (mut engine, _handle, cache) = engine_with_cache(&github, &docker, &dir, CONFIG);
    let [(main, main_socket), (pull, _)] =
        main_and_pull_request(&github, &docker, &mut engine).await;
    until_decided(&mut engine, &cache, &[&main, &pull]).await;
    assert!(save(&main_socket, "deps", b"main's").await);
    drop(engine);

    // The daemon restarts with it off and adopts the running job, whose container keeps the preload.
    let (mut engine, _handle, cache) =
        engine_with_cache(&github, &docker, &dir, &actions_cache_off());
    engine.recover().await.unwrap();
    until_decided(&mut engine, &cache, &[&main]).await;
    assert!(
        !main_socket.join(buildcache::ACTIONS_MARKER).exists(),
        "the slot's next runner uses GitHub's cache"
    );
    assert_eq!(restore(&main_socket, "deps", &[]).await, None);
    assert!(
        save(&main_socket, "deps-1", b"late").await,
        "a save is answered as kept, as BuildKit fails a build on a refused one"
    );
    assert_eq!(cache.size().entries, 1, "and dropped");
}

#[tokio::test]
async fn a_tag_named_like_the_default_branch_only_reads() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-build-cache-tag");
    let (mut engine, _handle, cache) = engine_with_cache(&github, &docker, &dir, CONFIG);
    // A tag called main on a commit main never had: GitHub names the tag as the run's head branch.
    github.0.lock().unwrap().off_branch.push("7a9".to_owned());
    let tag = github::RunTrigger {
        head_sha: "7a9".to_owned(),
        ..trigger("push", "main")
    };
    let [(tagged, tagged_socket), (pull, _)] = two_jobs(
        &github,
        &docker,
        &mut engine,
        [tag, trigger("pull_request", "main")],
    )
    .await;
    until_decided(&mut engine, &cache, &[&tagged, &pull]).await;
    assert!(
        github.calls().contains(&"compare main...7a9".to_owned()),
        "{:?}",
        github.calls()
    );
    assert_eq!(
        buildcache::request(&tagged_socket, "PUT", "/gradle/0a1b", b"poison")
            .await
            .0,
        200
    );
    assert_eq!(cache.size().entries, 0, "the tag's run stored nothing");
}

#[tokio::test]
async fn a_push_whose_commit_github_cannot_compare_never_writes() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-build-cache-compare");
    let (mut engine, _handle, cache) = engine_with_cache(&github, &docker, &dir, CONFIG);
    github.0.lock().unwrap().compare_fails = true;
    let [(main, main_socket), (pull, pull_socket)] =
        main_and_pull_request(&github, &docker, &mut engine).await;
    assert_eq!(
        buildcache::request(&main_socket, "PUT", "/gradle/0a1b", b"classes")
            .await
            .0,
        200
    );
    for _ in 0..5 {
        engine.age_running_reads(Duration::from_hours(1));
        engine.tick(Shutdown::No).await;
    }
    assert!(!cache.undecided(&pull), "the pull request was decided");
    assert!(cache.undecided(&main), "main waits for GitHub to compare");
    assert_eq!(
        buildcache::request(&pull_socket, "GET", "/gradle/0a1b", b"")
            .await
            .0,
        404
    );
}

/// `CONFIG` with o/r letting its own branches' pull requests write.
fn pull_requests_write() -> String {
    CONFIG.replace(
        "warm = 0\n",
        "warm = 0\nbuild_cache_writers = \"pull-requests\"\n",
    )
}

/// A `pull_request` run of o/r's branch `feature`, for pull request 7, that a person started.
fn pull_request_run() -> github::RunTrigger {
    github::RunTrigger {
        pull_requests: vec![7],
        ..trigger("pull_request", "feature")
    }
}

/// Pull request 7 as GitHub describes it: a person opened it from o/r's branch `feature`.
fn persons_pull_request() -> github::PullRequest {
    github::PullRequest {
        by_user: true,
        head_repository: Some("o/r".to_owned()),
        head_branch: "feature".to_owned(),
        base_branch: "main".to_owned(),
    }
}

#[tokio::test]
async fn a_persons_pull_request_writes_where_the_repository_lets_it_and_main_hits() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-build-cache-pull-writes");
    let (mut engine, _handle, cache) =
        engine_with_cache(&github, &docker, &dir, &pull_requests_write());
    github
        .0
        .lock()
        .unwrap()
        .pulls
        .insert(7, persons_pull_request());
    let [(pull, pull_socket), (main, main_socket)] = two_jobs(
        &github,
        &docker,
        &mut engine,
        [pull_request_run(), trigger("push", "main")],
    )
    .await;
    // The pull request's last run stores its outputs before GitHub has said anything of it.
    assert_eq!(
        buildcache::request(&pull_socket, "PUT", "/gradle/0a1b", b"classes")
            .await
            .0,
        200
    );
    until_decided(&mut engine, &cache, &[&pull, &main]).await;
    let calls = github.calls();
    assert!(
        calls.contains(&"pull request 7".to_owned())
            && calls.contains(&"compare feature...c0ffee".to_owned()),
        "{calls:?}"
    );
    assert_eq!(
        buildcache::request(&main_socket, "GET", "/gradle/0a1b", b"").await,
        (200, b"classes".to_vec())
    );
}

#[tokio::test]
async fn a_pull_request_from_main_saves_into_its_own_actions_cache_scope_not_mains() {
    use crate::buildcache::actions::{restore, save};

    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-actions-cache-pull-from-main");
    let (mut engine, _handle, cache) =
        engine_with_cache(&github, &docker, &dir, &pull_requests_write());
    // A person who may push only to `evil` opens a pull request from `main` into it: its run is main's commit
    // merged with evil's, running evil's workflow.
    github.0.lock().unwrap().pulls.insert(
        7,
        github::PullRequest {
            head_branch: "main".to_owned(),
            base_branch: "evil".to_owned(),
            ..persons_pull_request()
        },
    );
    let from_main = github::RunTrigger {
        pull_requests: vec![7],
        ..trigger("pull_request", "main")
    };
    let [(pull, pull_socket), (main, main_socket)] = two_jobs(
        &github,
        &docker,
        &mut engine,
        [from_main, trigger("push", "main")],
    )
    .await;
    until_decided(&mut engine, &cache, &[&pull, &main]).await;
    assert!(save(&main_socket, "tools", b"main's tools").await);
    assert!(save(&pull_socket, "deps", b"poison").await);
    assert_eq!(
        restore(&main_socket, "deps", &[]).await,
        None,
        "the pull request's save is in its own scope"
    );
    assert_eq!(
        restore(&pull_socket, "deps", &[]).await,
        Some(("deps".to_owned(), b"poison".to_vec()))
    );
    assert_eq!(
        restore(&pull_socket, "tools", &[]).await,
        Some(("tools".to_owned(), b"main's tools".to_vec())),
        "it reads the default branch's last"
    );
}

#[tokio::test]
async fn forks_bots_and_repositories_that_did_not_opt_in_only_read() {
    let bots_pull_request = github::PullRequest {
        by_user: false,
        ..persons_pull_request()
    };
    let cases = [
        (
            "a fork's pull request, which GitHub ties to no pull request of o/r",
            pull_requests_write(),
            github::RunTrigger {
                head_repository: Some("fork/r".to_owned()),
                pull_requests: Vec::new(),
                ..pull_request_run()
            },
            persons_pull_request(),
        ),
        (
            "Renovate's pull request",
            pull_requests_write(),
            pull_request_run(),
            bots_pull_request,
        ),
        (
            "a run a bot pushed to a person's pull request",
            pull_requests_write(),
            github::RunTrigger {
                by_user: false,
                ..pull_request_run()
            },
            persons_pull_request(),
        ),
        (
            "a person's pull request where o/r did not opt in",
            CONFIG.to_owned(),
            pull_request_run(),
            persons_pull_request(),
        ),
        (
            "a commit the pull request's branch does not have",
            pull_requests_write(),
            github::RunTrigger {
                head_sha: "7a9".to_owned(),
                ..pull_request_run()
            },
            persons_pull_request(),
        ),
    ];
    for (case, config, run, pull_request) in cases {
        let github = FakeGithub::default();
        let docker = FakeDocker::default();
        let dir = TestDir::new("engine-build-cache-pull-reads");
        let (mut engine, _handle, cache) = engine_with_cache(&github, &docker, &dir, &config);
        {
            let mut state = github.0.lock().unwrap();
            state.pulls.insert(7, pull_request);
            state.off_branch.push("7a9".to_owned());
        }
        let [(pull, pull_socket), (main, main_socket)] = two_jobs(
            &github,
            &docker,
            &mut engine,
            [run, trigger("push", "main")],
        )
        .await;
        assert_eq!(
            buildcache::request(&pull_socket, "PUT", "/gradle/ffff", b"poison")
                .await
                .0,
            200,
            "{case}"
        );
        assert!(save_now(&pull_socket, "deps", b"poison").await, "{case}");
        until_decided(&mut engine, &cache, &[&pull, &main]).await;
        assert_eq!(
            buildcache::request(&main_socket, "GET", "/gradle/ffff", b"")
                .await
                .0,
            404,
            "{case} stored nothing"
        );
        assert_eq!(
            actions::restore(&main_socket, "deps", &[]).await,
            None,
            "{case} saved nothing"
        );
        assert_eq!(uploads(&dir), 0, "{case} left nothing on disk");
    }
}

#[tokio::test]
async fn a_pull_request_github_cannot_describe_never_writes() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-build-cache-pull-lookup");
    let (mut engine, _handle, cache) =
        engine_with_cache(&github, &docker, &dir, &pull_requests_write());
    // GitHub does not answer for pull request 7.
    let [(pull, pull_socket), (main, main_socket)] = two_jobs(
        &github,
        &docker,
        &mut engine,
        [pull_request_run(), trigger("push", "main")],
    )
    .await;
    assert_eq!(
        buildcache::request(&pull_socket, "PUT", "/gradle/ffff", b"poison")
            .await
            .0,
        200
    );
    for _ in 0..5 {
        engine.age_running_reads(Duration::from_hours(1));
        engine.tick(Shutdown::No).await;
    }
    assert!(!cache.undecided(&main), "main was decided");
    assert!(
        cache.undecided(&pull),
        "the pull request waits for GitHub to describe it"
    );
    assert_eq!(
        buildcache::request(&main_socket, "GET", "/gradle/ffff", b"")
            .await
            .0,
        404
    );
}

#[tokio::test]
async fn a_main_job_that_ends_before_its_writes_were_decided_keeps_what_it_stored() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-build-cache");
    let (mut engine, handle, cache) = engine_with_cache(&github, &docker, &dir, CONFIG);
    let [(main, main_socket), _] = main_and_pull_request(&github, &docker, &mut engine).await;
    assert!(cache.undecided(&main), "GitHub has not been asked yet");
    // A quick job: it stores its outputs and ends before the next poll asks GitHub about it.
    assert_eq!(
        buildcache::request(&main_socket, "PUT", "/gradle/0a1b", b"classes")
            .await
            .0,
        200
    );
    jobs_end(&docker, &mut engine).await;
    handle.store.flush().await;
    let counts = handle
        .store
        .job(1)
        .await
        .unwrap()
        .unwrap()
        .summary
        .metrics
        .build_cache;
    assert!(counts.writer, "the push to main wrote");
    assert_eq!((counts.written_bytes, counts.refused), (7, 0));
}

#[tokio::test]
async fn jobs_that_end_having_stored_nothing_are_not_asked_about_on_github() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-build-cache-nothing");
    let (mut engine, _handle, cache) = engine_with_cache(&github, &docker, &dir, CONFIG);
    let [(main, _), (pull, _)] = main_and_pull_request(&github, &docker, &mut engine).await;
    assert!(
        cache.undecided(&main) && cache.undecided(&pull),
        "GitHub has not been asked yet"
    );
    // The first tick's visibility ask runs in a task of its own; let it finish so its call is not counted below.
    if let Some(asking) = engine.visibility_asking.take() {
        asking.await.unwrap();
    }
    let before = github.calls().len();
    jobs_end(&docker, &mut engine).await;
    let asked: Vec<String> = github.calls()[before..]
        .iter()
        // Only the polls and the registrations' removal.
        .filter(|call| {
            !["delete ", "runners ", "queued "]
                .iter()
                .any(|polls| call.starts_with(polls))
        })
        .cloned()
        .collect();
    assert_eq!(
        asked,
        Vec::<String>::new(),
        "nothing to keep, nothing to ask"
    );
}

#[tokio::test]
async fn a_stalled_github_does_not_hold_commands_while_an_ended_jobs_uploads_wait() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-build-cache-stalled");
    let (mut engine, handle, _cache) = engine_with_cache(&github, &docker, &dir, CONFIG);
    let [(_, main_socket), _] = main_and_pull_request(&github, &docker, &mut engine).await;
    assert_eq!(
        buildcache::request(&main_socket, "PUT", "/gradle/0a1b", b"classes")
            .await
            .0,
        200
    );
    github.hold_jobs();
    let control = handle.control.clone();
    tokio::join!(jobs_end(&docker, &mut engine), async {
        github.until_waiting(1).await;
        let answered =
            tokio::time::timeout(Duration::from_secs(5), control.resume(one("o/r"))).await;
        github.release_jobs();
        answered.expect("the resume answers").unwrap();
    });
    handle.store.flush().await;
    let counts = handle
        .store
        .job(1)
        .await
        .unwrap()
        .unwrap()
        .summary
        .metrics
        .build_cache;
    assert!(counts.writer, "the push to main wrote once GitHub answered");
    assert_eq!((counts.written_bytes, counts.refused), (7, 0));
}

#[tokio::test]
async fn a_default_branch_renamed_while_runnerd_runs_writes_within_the_hour() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-build-cache-renamed");
    let (mut engine, _handle, cache) = engine_with_cache(&github, &docker, &dir, CONFIG);
    github.0.lock().unwrap().default_branch = Some("master".to_owned());
    let pushes = || [trigger("push", "master"), trigger("push", "main")];
    let [(master, _), (main, _)] = two_jobs(&github, &docker, &mut engine, pushes()).await;
    until_decided(&mut engine, &cache, &[&master, &main]).await;
    // The reseed slot 1's job makes due finishes.
    docker.0.lock().unwrap().seed_exit = Some(0);
    jobs_end(&docker, &mut engine).await;

    // The repository renames master to main; an hour on, runnerd asks GitHub again.
    github.0.lock().unwrap().default_branch = Some("main".to_owned());
    for known in engine.default_branches.values_mut() {
        known.read_at -= Duration::from_secs(3600);
    }
    let [(master, master_socket), (main, main_socket)] =
        two_more_jobs(&github, &docker, &mut engine, 3, pushes()).await;
    until_decided(&mut engine, &cache, &[&master, &main]).await;
    for (socket, key) in [(&master_socket, "aa"), (&main_socket, "bb")] {
        let path = format!("/gradle/{key}");
        assert_eq!(
            buildcache::request(socket, "PUT", &path, b"classes")
                .await
                .0,
            200
        );
    }
    let found = async |key: &str| {
        buildcache::request(&main_socket, "GET", &format!("/gradle/{key}"), b"")
            .await
            .0
    };
    assert_eq!(
        (found("bb").await, found("aa").await),
        (200, 404),
        "main writes, master no longer does"
    );
}

#[tokio::test]
async fn an_actions_cache_save_made_while_github_names_no_runner_lands_once_it_does() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-actions-cache-lag");
    let (mut engine, handle, cache) = engine_with_cache(&github, &docker, &dir, CONFIG);
    let pushes = [trigger("push", "main"), trigger("push", "main")];
    let [(first, first_socket), (second, second_socket)] =
        two_jobs(&github, &docker, &mut engine, pushes).await;
    github_names_no_runner(&github, 1);
    github_names_no_runner(&github, 2);
    // Each job's post-step saves while GitHub still names no runner for it.
    engine.tick(Shutdown::No).await;
    assert!(save_now(&first_socket, "deps", b"deps").await);
    assert!(save_now(&second_socket, "tools", b"tools").await);
    // A reload that lowers the limit and turns the actions cache off leaves the running jobs as they started.
    let reloaded = CONFIG.replace(
        "maven = { max_size = \"5G\" }\n",
        "maven = { max_size = \"5G\" }\nbuild = { actions_cache = false, max_size = \"1M\" }\n",
    );
    engine.reload(Config::parse(&reloaded).unwrap(), None, None);
    for _ in 0..3 {
        engine.tick(Shutdown::No).await;
    }
    assert!(
        cache.undecided(&first) && cache.undecided(&second),
        "both wait for GitHub"
    );
    assert_eq!(cache.size().entries, 0, "nothing is an entry before then");

    // GitHub names the first job's runner while it runs.
    github_names(&github, 1, &first, "in_progress");
    until_decided(&mut engine, &cache, &[&first]).await;
    assert_eq!(
        actions::restore(&second_socket, "deps", &[]).await,
        Some(("deps".to_owned(), b"deps".to_vec()))
    );
    // The second job ends before GitHub names its runner: its save waits without the runner.
    for container in &mut docker.0.lock().unwrap().containers {
        container.running = container.name != second;
    }
    for _ in 0..3 {
        engine.tick(Shutdown::No).await;
    }
    assert!(cache.undecided(&second), "it still waits for GitHub");
    assert!(!second_socket.exists(), "its socket went with its runner");
    github_names(&github, 2, &second, "completed");
    engine.tick(Shutdown::No).await;
    assert_eq!(
        actions::restore(&first_socket, "tools", &[]).await,
        Some(("tools".to_owned(), b"tools".to_vec()))
    );
    let counts = counts_of(&handle, 2).await;
    assert!(
        counts.writer,
        "the second job wrote once GitHub named its runner"
    );
    assert_eq!((counts.written_bytes, counts.refused), (5, 0));
    assert_eq!(uploads(&dir), 0);
}

#[tokio::test]
async fn an_ended_jobs_save_outlives_github_failing_its_run_as_the_job_completes() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-actions-cache-run-fails");
    let (mut engine, handle, cache) = engine_with_cache(&github, &docker, &dir, CONFIG);
    let pushes = [trigger("push", "main"), trigger("push", "main")];
    let [(first, first_socket), (_, second_socket)] =
        two_jobs(&github, &docker, &mut engine, pushes).await;
    github_names_no_runner(&github, 1);
    github_names_no_runner(&github, 2);
    engine.tick(Shutdown::No).await;
    assert!(save_now(&first_socket, "deps", b"deps").await);
    assert!(save_now(&second_socket, "tools", b"tools").await);
    jobs_end(&docker, &mut engine).await;
    assert!(cache.undecided(&first), "GitHub has named no runner yet");

    // GitHub says the job completed on this runner, on the tick it cannot say what started the run.
    let failing = github.0.lock().unwrap().triggers.remove(&1).unwrap();
    github_names(&github, 1, &first, "completed");
    engine.tick(Shutdown::No).await;
    assert!(cache.undecided(&first), "nothing decided its writes");
    assert!(!engine.no_ended_uploads(), "its save still waits");
    assert_eq!(uploads(&dir), 2, "and is still on disk");

    github.0.lock().unwrap().triggers.insert(1, failing);
    engine.tick(Shutdown::No).await;
    let counts = counts_of(&handle, 1).await;
    assert!(counts.writer, "job 1 wrote once GitHub answered");
    assert_eq!(counts.written_bytes, 4);
}

#[tokio::test]
async fn an_ended_jobs_actions_cache_saves_go_when_github_never_names_its_runner() {
    let github = FakeGithub::default();
    let docker = FakeDocker::default();
    let dir = TestDir::new("engine-actions-cache-never");
    let (mut engine, handle, cache) = engine_with_cache(&github, &docker, &dir, CONFIG);
    let pushes = [trigger("push", "main"), trigger("push", "main")];
    let [(first, first_socket), (second, second_socket)] =
        two_jobs(&github, &docker, &mut engine, pushes).await;
    // GitHub names no runner for the first job, and fails every read of the second.
    github_names_no_runner(&github, 1);
    github.0.lock().unwrap().jobs.remove(&2);
    engine.tick(Shutdown::No).await;
    assert!(save_now(&first_socket, "deps", b"deps").await);
    assert!(save_now(&second_socket, "tools", b"tools").await);
    jobs_end(&docker, &mut engine).await;
    for _ in 0..3 {
        engine.tick(Shutdown::No).await;
    }
    assert_eq!(uploads(&dir), 2, "the saves wait for GitHub");

    engine.age_ended_uploads(super::super::build_cache::ENDED_WAIT);
    engine.tick(Shutdown::No).await;
    assert!(engine.no_ended_uploads(), "no runner waits any longer");
    assert!(
        !cache.undecided(&first) && !cache.undecided(&second),
        "both runners' caches closed"
    );
    assert_eq!(cache.size().entries, 0);
    assert_eq!(uploads(&dir), 0, "their saves left nothing on disk");
    for job in [1, 2] {
        let counts = counts_of(&handle, job).await;
        assert!(!counts.writer, "job {job} never wrote");
        assert_eq!((counts.written_bytes, counts.refused), (0, 1), "job {job}");
    }
}