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
//! Records: no secret of a runner survives into one, the limits they are kept within, and what a shell in one shows.

use std::collections::BTreeSet;
use std::path::Path;
use std::process::Command;
use std::time::Duration;

use super::{
    banner, expired, failed, failure_cause, listed, make_room, runner_fault, secrets_left,
};
use crate::api::{self, RecordRemoval};
use crate::config::{ByteSize, Records};
use crate::testdir::TestDir;

const TOKEN: &str = "ghs_16C7e42F292c6912E7710c838347Ae178B4a";
const JIT_CONFIG: &str = "eyJydW5uZXIiOiJqaXQtY29uZmlnIn0=";

/// Every file a runner container may hold a secret in, with that secret.
const SECRETS: &[(&str, &str)] = &[
    ("run/runnerd/jitconfig", JIT_CONFIG),
    (
        "home/runner/.runner",
        "{\"agentId\": 7, \"gitHubUrl\": \"https://github.com/o/app\"}",
    ),
    (
        "home/runner/.credentials",
        "{\"scheme\": \"OAuth\", \"data\": {\"clientId\": \"1\"}}",
    ),
    (
        "home/runner/.credentials_rsaparams",
        "{\"d\": \"private-key\"}",
    ),
    ("home/runner/_work/_temp/git-credentials-1f2e.config", TOKEN),
    (
        "home/runner/_work/_temp/_runner_file_commands/set_env_1f2e",
        "DEPLOY_KEY=from-a-secret",
    ),
    (
        "home/runner/_work/_temp/.npmrc",
        "//npm.pkg.github.com/:_authToken=from-a-secret",
    ),
    (
        "home/runner/.docker/config.json",
        "{\"auths\": {\"ghcr.io\": {\"auth\": \"from-a-secret\"}}}",
    ),
    ("home/runner/.git-credentials", TOKEN),
    (
        "home/runner/.netrc",
        "machine github.com password from-a-secret",
    ),
    (
        "home/runner/.npmrc",
        "//registry.npmjs.org/:_authToken=from-a-secret",
    ),
    ("home/runner/.pypirc", "password = from-a-secret"),
    (
        "home/runner/.cargo/credentials.toml",
        "token = \"from-a-secret\"",
    ),
    (
        "home/runner/.ssh/id_ed25519",
        "-----BEGIN OPENSSH PRIVATE KEY-----",
    ),
    ("home/runner/.config/gh/hosts.yml", TOKEN),
    ("home/runner/.kube/config", "token: from-a-secret"),
    // What a job's own steps and tools leave, which no list of names covers.
    (
        "home/runner/.gitconfig",
        "[url \"https://x-access-token:github_pat_11ABCDEFG@github.com/\"]\n\tinsteadOf = https://github.com/",
    ),
    (
        "home/runner/.aws/credentials",
        "[default]\naws_secret_access_key = from-a-secret",
    ),
    (
        "home/runner/.gnupg/private-keys-v1.d/0A1B.key",
        "(private-key from-a-secret)",
    ),
    ("home/runner/.config/gcloud/credentials.db", "from-a-secret"),
    ("home/runner/.terraformrc", "token = \"from-a-secret\""),
    (
        "home/runner/.cargo/config.toml",
        "[registries.internal]\ntoken = \"from-a-secret\"",
    ),
    ("tmp/deploy.pem", "-----BEGIN RSA PRIVATE KEY-----"),
    ("var/tmp/kubeconfig", "token: from-a-secret"),
];

/// What the image has before the runner starts, which stays.
const IMAGE: &[(&str, &str)] = &[
    ("home/runner/.bashrc", "# ~/.bashrc"),
    ("tmp/hsperfdata_root/12", "jvm"),
    ("run/docker.pid", "42"),
];

/// What the job made, which a record is for.
const WORKSPACE: &[(&str, &str)] = &[
    ("home/runner/_work/app/app/src/main.rs", "fn main() {}"),
    ("home/runner/_work/app/app/target/debug/app", "binary"),
    (
        "home/runner/_work/_actions/actions/checkout/v7/action.yml",
        "name: checkout",
    ),
    (
        "home/runner/_diag/pages/1_job_1.log",
        "##[group]Run cargo test",
    ),
];

/// The Rust toolchain a job installed, which a shell needs to re-run its steps.
const TOOLCHAIN: &[(&str, &str)] = &[
    (
        "home/runner/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/bin/rustc",
        "rustc",
    ),
    (
        "home/runner/.rustup/settings.toml",
        "default_toolchain = \"stable\"",
    ),
    ("home/runner/.cargo/bin/cargo", "cargo"),
    (
        "home/runner/.cargo/registry/cache/index.crates.io-1949cf8c6b5b557f/serde-1.0.0.crate",
        "crate",
    ),
];

/// A repository's config as `actions/checkout` leaves it when the job ends before its post step: with the token.
const GIT_CONFIG: &str = "[core]\n\trepositoryformatversion = 0\n[remote \"origin\"]\n\turl = https://github.com/o/app\n\
     [http \"https://github.com/\"]\n\textraheader = AUTHORIZATION: basic eC1hY2Nlc3MtdG9rZW46Z2hzXzE2Qzc=\n";

fn write(root: &Path, path: &str, text: &str) {
    let path = root.join(path);
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(path, text).unwrap();
}

/// The paths under `root` changed after `since`, as a container's changes list them: `/home/runner/...`.
fn changed(root: &Path, since: (i64, i64)) -> Vec<String> {
    use std::os::unix::fs::MetadataExt as _;
    let mut found = Vec::new();
    let mut dirs = vec![root.to_owned()];
    while let Some(dir) = dirs.pop() {
        for entry in std::fs::read_dir(&dir).unwrap() {
            let path = entry.unwrap().path();
            let metadata = std::fs::symlink_metadata(&path).unwrap();
            if (metadata.ctime(), metadata.ctime_nsec()) > since {
                found.push(format!("/{}", path.strip_prefix(root).unwrap().display()));
            }
            if metadata.is_dir() {
                dirs.push(path);
            }
        }
    }
    found.sort();
    found
}

/// Touches the marker the entrypoint writes before the runner starts, a moment after what is there already.
fn runner_starts(root: &Path) -> (i64, i64) {
    use std::os::unix::fs::MetadataExt as _;
    std::thread::sleep(Duration::from_millis(20));
    write(root, "run/runnerd-since", "");
    let marker = std::fs::metadata(root.join("run/runnerd-since")).unwrap();
    std::thread::sleep(Duration::from_millis(20));
    (marker.ctime(), marker.ctime_nsec())
}

#[test]
fn a_record_keeps_no_secret_of_the_runner_or_the_job() {
    let dir = TestDir::new("scrub");
    let root = &dir.0;
    for (path, text) in IMAGE {
        write(root, path, text);
    }
    let started = runner_starts(root);
    for (path, text) in SECRETS.iter().chain(WORKSPACE).chain(TOOLCHAIN) {
        write(root, path, text);
    }
    write(root, "home/runner/_work/app/app/.git/config", GIT_CONFIG);
    write(
        root,
        "home/runner/_work/app/app/.git/modules/lib/config",
        GIT_CONFIG,
    );

    let before = changed(root, started);
    let caught = secrets_left(before.iter().map(String::as_str));
    for (secret, _) in SECRETS {
        assert!(
            caught.iter().any(|path| *path == format!("/{secret}")),
            "/{secret} is caught before a commit: {caught:?}"
        );
    }

    let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../image/scrub.sh");
    let status = Command::new("bash").arg(script).arg(root).status().unwrap();
    assert!(status.success(), "scrub.sh exits 0");

    let after = changed(root, started);
    assert_eq!(
        secrets_left(after.iter().map(String::as_str)),
        Vec::<String>::new()
    );
    for path in &after {
        let file = root.join(path.trim_start_matches('/'));
        if file.is_file() {
            let text = std::fs::read_to_string(&file).unwrap();
            for (_, secret) in SECRETS {
                assert!(!text.contains(secret), "{path} keeps a secret: {text}");
            }
            assert!(
                !text.contains("extraheader"),
                "{path} keeps the token: {text}"
            );
        }
    }
    for (path, text) in WORKSPACE.iter().chain(IMAGE).chain(TOOLCHAIN) {
        assert_eq!(std::fs::read_to_string(root.join(path)).unwrap(), *text);
    }
    let config =
        std::fs::read_to_string(root.join("home/runner/_work/app/app/.git/config")).unwrap();
    assert!(
        config.contains("url = https://github.com/o/app"),
        "{config}"
    );
}

#[test]
fn a_refused_record_names_the_first_paths_and_counts_the_rest() {
    let paths: Vec<String> = (1..=7).map(|n| format!("/tmp/{n}")).collect();
    assert_eq!(
        listed(&paths),
        "/tmp/1, /tmp/2, /tmp/3, /tmp/4, /tmp/5 and 2 more"
    );
    assert_eq!(listed(&paths[..2]), "/tmp/1, /tmp/2");
}

#[test]
fn a_file_where_a_kept_toolchain_directory_goes_is_caught() {
    assert_eq!(
        secrets_left(["/home/runner/.cargo", "/home/runner/.rustup"]),
        ["/home/runner/.cargo", "/home/runner/.rustup"]
    );
    assert_eq!(
        secrets_left([
            "/home/runner/.cargo",
            "/home/runner/.cargo/bin",
            "/home/runner/.cargo/bin/cargo",
            "/home/runner/.cargo/credentials.toml",
        ]),
        ["/home/runner/.cargo/credentials.toml"]
    );
}

#[test]
fn only_a_failed_job_is_recorded() {
    let log = "√ Connected to GitHub\n2026-10-23 01:08:55Z: Listening for Jobs\n\
               2026-10-23 01:08:55Z: Running job: build\n";
    assert!(
        failed(&format!(
            "{log}2026-10-23 01:09:27Z: Job build completed with result: Failed\n"
        )),
        "a failed job is recorded"
    );
    for result in ["Succeeded", "Canceled"] {
        let log = format!("{log}2026-10-23 01:09:27Z: Job build completed with result: {result}\n");
        assert!(!failed(&log), "a job that {result} is not recorded");
    }
    assert!(!failed(log), "a job that never completed is not recorded");
}

fn record(job: u64, created_at: u64, gib: u64) -> api::Record {
    api::Record {
        job,
        repository: "o/app".to_owned(),
        profile: "app".to_owned(),
        workflow: None,
        name: None,
        created_at,
        bytes: gib << 30,
        image: super::image(job),
    }
}

fn limits() -> Records {
    Records {
        max_total: ByteSize(10 << 30),
        max_count: 3,
        max_age: Duration::from_hours(24),
        min_free: ByteSize(5 << 30),
    }
}

const NOW: u64 = 100_000;
const PLENTY: Option<u64> = Some(1 << 40);

#[test]
fn a_new_record_past_max_count_removes_the_oldest() {
    let records = [
        record(3, NOW - 10, 1),
        record(1, NOW - 30, 1),
        record(2, NOW - 20, 1),
    ];
    let removed = make_room(&records, &BTreeSet::new(), &limits(), 1 << 30, PLENTY, NOW);
    assert_eq!(removed, Ok(vec![(1, RecordRemoval::Count)]));
}

#[test]
fn a_new_record_past_max_total_removes_the_oldest_until_it_fits() {
    let records = [record(1, NOW - 30, 4), record(2, NOW - 20, 4)];
    let removed = make_room(&records, &BTreeSet::new(), &limits(), 3 << 30, PLENTY, NOW);
    assert_eq!(removed, Ok(vec![(1, RecordRemoval::Size)]));
    assert_eq!(
        make_room(&records, &BTreeSet::new(), &limits(), 11 << 30, PLENTY, NOW).unwrap_err(),
        "it would take 11G, more than records.max_total (10G)"
    );
}

#[test]
fn records_past_max_age_go() {
    let records = [record(1, NOW - 90_000, 1), record(2, NOW - 20, 1)];
    assert_eq!(
        expired(&records, &BTreeSet::new(), &limits(), NOW),
        vec![(1, RecordRemoval::Age)]
    );
    assert_eq!(
        make_room(&records, &BTreeSet::new(), &limits(), 1 << 30, PLENTY, NOW),
        Ok(vec![(1, RecordRemoval::Age)])
    );
}

#[test]
fn no_record_leaves_docker_less_than_min_free() {
    let records = [record(1, NOW - 30, 1)];
    let refused = make_room(
        &records,
        &BTreeSet::new(),
        &limits(),
        2 << 30,
        Some(6 << 30),
        NOW,
    );
    assert_eq!(
        refused.unwrap_err(),
        "Docker has 6G free; a record of 2G would leave less than records.min_free (5G)"
    );
    assert_eq!(
        make_room(
            &records,
            &BTreeSet::new(),
            &limits(),
            1 << 30,
            Some(6 << 30),
            NOW
        ),
        Ok(Vec::new())
    );
}

#[test]
fn a_record_with_a_shell_open_stays() {
    let records = [
        record(1, NOW - 90_000, 1),
        record(2, NOW - 30, 1),
        record(3, NOW - 20, 1),
    ];
    let open = BTreeSet::from([1, 2]);
    assert_eq!(expired(&records, &open, &limits(), NOW), Vec::new());
    let removed = make_room(&records, &open, &limits(), 1 << 30, PLENTY, NOW);
    assert_eq!(removed, Ok(vec![(3, RecordRemoval::Count)]));
    let all_open = BTreeSet::from([1, 2, 3]);
    assert!(
        make_room(&records, &all_open, &limits(), 1 << 30, PLENTY, NOW).is_err(),
        "no record is made when every one in its way has a shell open"
    );
}

fn step(number: u32, name: &str, conclusion: &str) -> api::Step {
    api::Step {
        number,
        name: name.to_owned(),
        status: "completed".to_owned(),
        conclusion: Some(conclusion.to_owned()),
        started_at: None,
        completed_at: None,
    }
}

fn failed_job() -> api::Job {
    let summary: api::JobSummary = serde_json::from_value(serde_json::json!({
        "id": 42, "repository": "o/app", "run_id": 7, "run_attempt": 1, "workflow": "CI", "name": "test",
        "branch": "main", "url": null, "labels": [], "state": "completed", "conclusion": "failure",
        "runner": null, "timeline": {"queued_at": 1}, "metrics": {"mirror_bytes": 0, "build_cache": api::BuildCacheCounts::default()},
        "log": {"lines": 0, "bytes": 0, "truncated": false}
    }))
    .unwrap();
    api::Job {
        admission: None,
        summary,
        steps: vec![
            step(1, "Set up job", "success"),
            step(2, "Set up runner", "success"),
            step(3, "Run actions/checkout@v7", "success"),
            step(4, "Unit tests", "failure"),
            step(5, "Lint", "skipped"),
        ],
        record: None,
    }
}

fn log() -> Vec<String> {
    [
        "2026-10-23T01:08:56.1Z ##[group]GITHUB_TOKEN Permissions",
        "2026-10-23T01:08:56.1Z Contents: read",
        "2026-10-23T01:08:56.1Z ##[endgroup]",
        "2026-10-23T01:08:58.4Z ##[group]Run '/usr/local/bin/runnerd-job-started.sh'",
        "2026-10-23T01:08:58.4Z ##[endgroup]",
        "2026-10-23T01:08:58.5Z ##[group]Run actions/checkout@v7",
        "2026-10-23T01:08:58.5Z with:",
        "2026-10-23T01:08:58.5Z   fetch-depth: 1",
        "2026-10-23T01:08:58.5Z ##[endgroup]",
        "2026-10-23T01:08:59.0Z ##[group]Fetching the repository",
        "2026-10-23T01:08:59.0Z ##[endgroup]",
        "2026-10-23T01:09:25.7Z ##[group]Run cargo test --locked",
        "2026-10-23T01:09:25.7Z \u{1b}[36;1mcargo test --locked\u{1b}[0m",
        "2026-10-23T01:09:25.7Z shell: /usr/bin/bash -e {0}",
        "2026-10-23T01:09:25.7Z env:",
        "2026-10-23T01:09:25.7Z   RUSTFLAGS: -D warnings",
        "2026-10-23T01:09:25.7Z ##[endgroup]",
        "2026-10-23T01:09:30.0Z test tests::adds ... FAILED",
        "2026-10-23T01:09:30.1Z ##[error]Process completed with exit code 101.",
        "2026-10-23T01:09:30.2Z Post job cleanup.",
    ]
    .map(str::to_owned)
    .to_vec()
}

#[test]
fn a_shell_shows_the_failed_step_and_what_it_ran() {
    let text = banner(&failed_job(), &log(), None);
    assert!(
        text.contains("It failed at step 4: Unit tests (exit code 101)\r\n"),
        "{text}"
    );
    assert!(
        text.contains(
            "    cargo test --locked\r\n    shell: /usr/bin/bash -e {0}\r\n    env:\r\n      RUSTFLAGS: -D warnings\r\n"
        ),
        "{text}"
    );
    assert!(
        text.contains("You are in /home/runner/_work/app/app"),
        "{text}"
    );
    assert!(
        !text.contains('\u{1b}'),
        "colour codes are stripped: {text}"
    );
    assert!(
        !text.replace("\r\n", "").contains('\n'),
        "every line ends in CRLF: {text}"
    );
}

#[test]
fn a_shell_shows_another_step_when_asked() {
    let text = banner(&failed_job(), &log(), Some(3));
    assert!(
        text.contains("It shows step 3: Run actions/checkout@v7\r\n"),
        "{text}"
    );
    assert!(
        text.contains("    with:\r\n      fetch-depth: 1\r\n"),
        "{text}"
    );
    let text = banner(&failed_job(), &log(), Some(9));
    assert!(text.contains("The job has no such step."), "{text}");
}

/// A step as the runner logs it: its group, with the script's lines, then what it printed.
fn logged(command: &str, header: &[&str], output: &[&str]) -> Vec<String> {
    let stamp = |text: &str| format!("2026-11-09T00:16:00.1Z {text}");
    let mut lines = vec![stamp(&format!("##[group]Run {command}"))];
    lines.extend(header.iter().map(|line| stamp(line)));
    lines.push(stamp("##[endgroup]"));
    lines.extend(output.iter().map(|line| stamp(line)));
    lines
}

/// A job with steps `(command, conclusion)`, named as GitHub names a script step.
fn job_of(steps: &[(&str, &str)]) -> api::Job {
    let mut job = failed_job();
    job.steps = vec![step(1, "Set up job", "success")];
    for (number, (command, conclusion)) in (2..).zip(steps) {
        job.steps
            .push(step(number, &format!("Run {command}"), conclusion));
    }
    job
}

const ERROR: &str = "##[error]Process completed with exit code 1.";
const DENIED: &str = "mount: /mnt/data: permission denied";

/// What fretboard's runners logged when Sysbox lost their seccomp listener or failed an injection (jobs
/// 42539128682, 42331166731 and 42492465395).
const FAULTS: [&str; 4] = [
    "error during container init: error mounting \"cgroup\" to rootfs at \"/sys/fs/cgroup\": mount src=cgroup, dst=/sys/fs/cgroup, dstFd=/proc/thread-self/fd/15, flags=MS_NOSUID|MS_NODEV|MS_NOEXEC: function not implemented",
    "error setting cgroup config for procHooks process: openat2 /sys/fs/cgroup/docker/33152f90/cgroup.controllers: function not implemented",
    "failed to extract layer sha256:4115682a: failed to unmount /state/docker/containerd/daemon/tmpmounts/containerd-mount2793291316: function not implemented",
    "\u{1b}[31mopen sysctl net.ipv4.ip_unprivileged_port_start file: unsafe procfs detected: openat2 /proc/./sys/net/ipv4/ip_unprivileged_port_start: invalid argument\u{1b}[0m",
];

/// Whether `./gradlew check`, the failing step after a passing `checkout`, is the runner's fault for what it printed.
fn fault_in_output(output: &[&str]) -> bool {
    let job = job_of(&[
        ("actions/checkout@v7", "success"),
        ("./gradlew check", "failure"),
    ]);
    let mut log = logged(
        "actions/checkout@v7",
        &["with:", "  fetch-depth: 1"],
        &["Syncing"],
    );
    log.extend(logged("./gradlew check", &["shell: bash"], output));
    runner_fault(&job, &log)
}

#[test]
fn a_failing_step_that_logged_sysboxs_lost_listener_or_failed_injection_is_the_runners_fault() {
    for fault in FAULTS {
        assert!(fault_in_output(&[fault, ERROR]), "{fault}");
    }
    // As glibc's strerror writes it, capitalised.
    assert!(fault_in_output(&[
        "umount: /x: Function not implemented",
        ERROR
    ]));
}

#[test]
fn another_failure_in_the_failing_step_is_the_codes_whatever_it_looks_like() {
    let misread: Vec<&str> = [
        // `ENOSYS` from a call that is not a mount, umount or openat2.
        "Error: ENOSYS: function not implemented, copyfile 'a.txt' -> 'b.txt'",
        // A mount refused for another reason, and an unsafe procfs that is not an invalid argument.
        DENIED,
        "unsafe procfs detected: openat2 /proc/self/fd: operation not permitted",
        // A line about a mount that is not an error.
        "mounting the volume took 3s",
        // `mount` inside a repository's name, a hook's name and a file's.
        "Error: ENOSYS: function not implemented, copyfile '/home/runner/work/amount-api/amount-api/a.txt' -> 'b.txt'",
        "[Vue warn]: Error in mounted hook: \"Error: Function not implemented.\"",
        "src/paramount.c:12: error: function not implemented",
        // A path or a name that is `mount` itself.
        "Error: ENOSYS: function not implemented, copyfile '/home/runner/work/mount-api/mount-api/a.txt' -> 'b.txt'",
        "src/mount.c:12: error: function not implemented",
        "FAIL test_mount: function not implemented",
    ]
    .into_iter()
    .filter(|output| fault_in_output(&[output, ERROR]))
    .collect();
    assert_eq!(misread, Vec::<&str>::new(), "read as the runner's fault");
}

#[test]
fn the_steps_own_script_and_environment_are_not_what_it_printed() {
    let job = job_of(&[("grep -q 'mount.*function not implemented' out", "failure")]);
    let script = [
        "shell: /usr/bin/bash -e {0}",
        "grep -q 'mount.*function not implemented' out && echo sysbox",
        "env:",
        "  RETRY_ON: umount: function not implemented",
    ];
    let log = logged(
        "grep -q 'mount.*function not implemented' out",
        &script,
        &["assertion failed: 1 == 2", ERROR],
    );
    assert!(
        !runner_fault(&job, &log),
        "the title, the script and the environment are not output"
    );
}

#[test]
fn only_the_step_that_failed_is_read() {
    let signature = FAULTS[1];
    let assertion = ["assertion failed: 1 == 2", ERROR];
    let tests = |log: &mut Vec<String>| log.extend(logged("cargo test", &[], &assertion));

    // A step allowed to fail printed it, and the tests failed.
    let job = job_of(&[("./optional", "success"), ("cargo test", "failure")]);
    let mut log = logged("./optional", &[], &[signature, ERROR]);
    tests(&mut log);
    assert!(!runner_fault(&job, &log), "a step that did not fail");

    // A passing step printed it with an annotation, and the tests failed.
    let job = job_of(&[("./lint", "success"), ("cargo test", "failure")]);
    let mut log = logged("./lint", &[], &[signature, "##[error]lint found a problem"]);
    tests(&mut log);
    assert!(!runner_fault(&job, &log), "a passing step's annotation");

    // The tests failed, and a post step printed it after.
    let job = job_of(&[("cargo test", "failure")]);
    let mut log = logged("cargo test", &[], &assertion);
    log.push("2026-11-09T00:17:00.0Z Post job cleanup.".to_owned());
    log.push(format!("2026-11-09T00:17:00.1Z {signature}"));
    assert!(
        !runner_fault(&job, &log),
        "a post step is not the failing step"
    );

    // The failing step's own fault, though it prints a `::group::Run …` line afterwards.
    let job = job_of(&[("cargo test", "failure")]);
    let log = logged(
        "cargo test",
        &[],
        &[signature, "##[group]Run integration", ERROR],
    );
    assert!(runner_fault(&job, &log), "the fault came before the group");

    // Named by its author, so found by the exit code it ended with.
    let mut job = job_of(&[("cargo test", "failure")]);
    job.steps[1].name = "Integration tests".to_owned();
    let log = logged("cargo test", &[], &[signature, ERROR]);
    assert!(runner_fault(&job, &log), "a step named by its author");

    // No step failed: nothing to read, whatever the log has.
    let job = job_of(&[("cargo test", "success")]);
    let log = logged("cargo test", &[], &[signature]);
    assert!(!runner_fault(&job, &log), "no failed step");
}

/// The fixture logs of failures runnerd tells apart (`crates/fixtures/logs`), as the runner 2.338.1 writes them.
mod causes {
    use super::{failure_cause, step};
    use crate::api::{self, FailureCause};

    const ARCHIVE_DOWNLOAD: &str =
        include_str!("../../../fixtures/logs/action-archive-download.log");
    const ARCHIVE_INVALID: &str = include_str!("../../../fixtures/logs/action-archive-invalid.log");
    const RESOLVE: &str = include_str!("../../../fixtures/logs/action-resolve.log");
    const CHECKOUT: &str = include_str!("../../../fixtures/logs/checkout.log");
    const RECOVERED: &str = include_str!("../../../fixtures/logs/recovered-then-tests.log");

    fn lines(log: &str) -> Vec<String> {
        log.lines().map(str::to_owned).collect()
    }

    /// A job that failed in `Set up job`, as GitHub lists its steps then.
    fn failed_setting_up() -> api::Job {
        let mut job = super::failed_job();
        job.steps = vec![step(1, "Set up job", "failure")];
        job
    }

    /// A job that set up, then ran steps named `name` that concluded as `conclusions` say.
    fn failed_at(name: &str, conclusions: &[&str]) -> api::Job {
        let mut job = super::failed_job();
        job.steps = vec![step(1, "Set up job", "success")];
        for (number, conclusion) in (2..).zip(conclusions) {
            job.steps.push(step(number, name, conclusion));
        }
        job
    }

    #[test]
    fn a_job_whose_set_up_could_not_download_or_unpack_an_action_reads_as_an_action_archive_failure()
     {
        for log in [ARCHIVE_DOWNLOAD, ARCHIVE_INVALID] {
            assert_eq!(
                failure_cause(&failed_setting_up(), &lines(log)),
                Some(FailureCause::ActionArchive),
                "{log}"
            );
        }
    }

    #[test]
    fn a_job_whose_set_up_could_not_resolve_an_action_reads_as_a_resolve_failure_not_an_archive_one()
     {
        assert_eq!(
            failure_cause(&failed_setting_up(), &lines(RESOLVE)),
            Some(FailureCause::ActionResolve)
        );
    }

    #[test]
    fn a_failed_checkout_reads_as_checkout_by_the_action_it_runs_whatever_its_name() {
        let named = failed_at("checkout", &["failure"]);
        assert_eq!(
            failure_cause(&named, &lines(CHECKOUT)),
            Some(FailureCause::Checkout)
        );
        let unnamed = failed_at(
            "Run actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955",
            &["failure"],
        );
        assert_eq!(
            failure_cause(&unnamed, &lines(CHECKOUT)),
            Some(FailureCause::Checkout)
        );
    }

    #[test]
    fn a_download_that_recovered_on_a_retry_says_nothing_of_the_tests_that_failed_after_it() {
        let mut job = failed_at(
            "Run actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955",
            &["success"],
        );
        job.steps.push(step(3, "Run ./gradlew test", "failure"));
        assert_eq!(failure_cause(&job, &lines(RECOVERED)), None);
        // Nor does it make a failed set-up an archive failure when the set-up failed for another reason after it.
        let mut other = lines(RECOVERED);
        other.truncate(
            other
                .iter()
                .position(|line| line.contains("Complete job name"))
                .unwrap(),
        );
        other.extend(
            [
                "##[group]Pull down action image 'ghcr.io/halyard/lint:1'",
                "##[command]/usr/bin/docker pull ghcr.io/halyard/lint:1",
                "Error response from daemon: unauthorized",
                "##[endgroup]",
                "##[error]Docker pull failed with exit code 1",
            ]
            .map(|text| format!("2026-11-17T15:46:46.0000000Z {text}")),
        );
        assert_eq!(failure_cause(&failed_setting_up(), &other), None);
    }

    /// `log`'s lines up to `Complete job name`, then `tail`: a `Set up job` that went on after its retries and failed.
    fn set_up_then(log: &str, tail: &[&str]) -> Vec<String> {
        let mut lines = lines(log);
        if let Some(at) = lines
            .iter()
            .position(|line| line.contains("Complete job name"))
        {
            lines.truncate(at);
        }
        lines.extend(
            tail.iter()
                .map(|text| format!("2026-11-17T15:46:46.0000000Z {text}")),
        );
        lines
    }

    #[test]
    fn a_retry_that_recovered_says_nothing_of_a_set_up_that_failed_for_another_reason_right_after()
    {
        // The download's second attempt succeeded, quietly, and the action's manifest failed to load.
        let manifest = set_up_then(
            RECOVERED,
            &[
                "##[error]Can't find 'action.yml', 'action.yaml' or 'Dockerfile' under '/home/runner/_work/_actions/o/lint/v1'.",
            ],
        );
        assert_eq!(failure_cause(&failed_setting_up(), &manifest), None);
        // A resolve that recovered, then an immutable package and an image pull that failed.
        let resolved = set_up_then(
            RESOLVE,
            &[
                "##[group]Download immutable action package 'actions/setup-node@v5'",
                "##[endgroup]",
                "##[group]Pull down action image 'ghcr.io/halyard/lint:1'",
                "##[endgroup]",
                "##[error]Docker pull failed with exit code 1",
            ],
        );
        let resolved: Vec<String> = resolved
            .into_iter()
            .filter(|line| {
                !line.contains("##[error]Response status")
                    && !line.contains("##[error]Failed to resolve")
            })
            .collect();
        assert_eq!(failure_cause(&failed_setting_up(), &resolved), None);
    }

    /// A job that set up, checked out with `actions/checkout`, then ran `steps` (name, conclusion); its log has a
    /// section per step after the checkout, `sections`.
    fn after_checkout(steps: &[(&str, &str)], sections: &[Vec<String>]) -> (api::Job, Vec<String>) {
        let mut job = super::failed_job();
        job.steps = vec![
            step(1, "Set up job", "success"),
            step(2, "Run actions/checkout@v7", "success"),
        ];
        for (number, (name, conclusion)) in (3..).zip(steps) {
            job.steps.push(step(number, name, conclusion));
        }
        let mut log = lines(RECOVERED);
        log.truncate(
            log.iter()
                .position(|line| line.contains("Run ./gradlew"))
                .unwrap(),
        );
        for section in sections {
            log.extend(section.iter().cloned());
        }
        (job, log)
    }

    #[test]
    fn a_failed_step_reads_as_checkout_only_by_its_own_section_running_actions_checkout() {
        // A script step its workflow named as the checkout's display name: its own section runs a shell.
        let (job, log) = after_checkout(
            &[(
                "Run actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955",
                "failure",
            )],
            &[super::logged(
                "actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955",
                &["shell: /usr/bin/bash -e {0}"],
                &[super::ERROR],
            )],
        );
        assert_eq!(
            failure_cause(&job, &log),
            None,
            "a script, not the checkout"
        );
        // A composite action's first inner step checked out, its second failed: its sections are not one a step.
        let (job, log) = after_checkout(
            &[("Setup", "failure")],
            &[
                super::logged(
                    "actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955",
                    &["with:"],
                    &["Syncing repository: halyard/tools"],
                ),
                super::logged(
                    "actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020",
                    &["with:"],
                    &["##[error]Unable to find Node version '99'"],
                ),
            ],
        );
        assert_eq!(
            failure_cause(&job, &log),
            None,
            "the composite's setup-node failed"
        );
        // A checkout's post step failed after the job's steps passed.
        let mut job = super::failed_job();
        job.steps = vec![
            step(1, "Set up job", "success"),
            step(2, "Run actions/checkout@v7", "success"),
            step(3, "Post Run actions/checkout@v7", "failure"),
        ];
        let mut log = lines(RECOVERED);
        log.truncate(
            log.iter()
                .position(|line| line.contains("Run ./gradlew"))
                .unwrap(),
        );
        log.push("2026-11-17T15:47:31.5000000Z Post job cleanup.".to_owned());
        log.extend(super::logged(
            "actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955",
            &[],
            &["##[error]The process '/usr/bin/git' failed with exit code 128"],
        ));
        assert_eq!(
            failure_cause(&job, &log),
            None,
            "its post step, not the fetch"
        );
        // An earlier step allowed to fail ended with an exit code; the checkout after it failed.
        let (mut job, mut log) = after_checkout(
            &[("Run ./lint", "success")],
            &[super::logged(
                "./lint",
                &["shell: /usr/bin/bash -e {0}"],
                &[super::ERROR],
            )],
        );
        job.steps.push(step(4, "Checkout tools", "failure"));
        log.extend(
            lines(CHECKOUT)
                .into_iter()
                .skip_while(|line| !line.contains("##[group]Run actions/checkout")),
        );
        assert_eq!(
            failure_cause(&job, &log),
            Some(FailureCause::Checkout),
            "the checkout's own section failed"
        );
    }

    #[test]
    fn a_job_that_failed_with_no_cause_in_its_log_reads_as_none() {
        // Setting up failed with nothing logged, or a test failed: no rule claims it.
        assert_eq!(failure_cause(&failed_setting_up(), &[]), None);
        let job = failed_at("Run ./gradlew test", &["failure"]);
        let log = super::logged("./gradlew test", &[], &[super::ERROR]);
        assert_eq!(failure_cause(&job, &log), None);
        // No step failed.
        let job = failed_at("Run actions/checkout@v7", &["success"]);
        assert_eq!(failure_cause(&job, &lines(CHECKOUT)), None);
    }
}

#[test]
fn a_log_names_the_repositories_its_runner_downloaded_as_immutable_packages_and_nothing_else() {
    let log: Vec<String> = [
        "2026-11-20T10:00:00.0000000Z ##[group]Download immutable action package 'actions/checkout@v6'",
        "2026-11-20T10:00:00.0000000Z Version: 6.0.0",
        "2026-11-20T10:00:00.0000000Z Digest: sha256:abc",
        "2026-11-20T10:00:00.0000000Z ##[endgroup]",
        "2026-11-20T10:00:01.0000000Z Download action repository 'actions/setup-node@v5' (SHA:49933ea5288caeca8642d1e84afbd3f7d6820020)",
        "2026-11-20T10:00:02.0000000Z ##[group]Download immutable action package 'actions/checkout@v6'",
        "2026-11-20T10:00:03.0000000Z ##[group]Run echo \"##[group]Download immutable action package 'o/fake@v1'\"",
        "##[group]Download immutable action package 'Tailscale/github-action@v4'",
    ]
    .map(str::to_owned)
    .to_vec();
    assert_eq!(
        super::immutable_packages(&log),
        vec!["actions/checkout", "Tailscale/github-action"],
        "each package once, as written; a source download or a script's text is none"
    );
}