alba-engine 0.2.1

Orchestration engine for Alba: scheduling, caching, affected runs, and watch mode
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
//! Behaviour tests for the skip-only cache, driven through
//! [`alba_engine::run`] with a `FakeExecutor` and a real temporary
//! directory for both the input files and the `.alba/cache` state.
//!
//! `load_str` gives every beam `dir == "."`; each test rewrites the beams'
//! `dir` to its own temporary directory so glob expansion and the cache
//! never touch the process's working directory.

use std::path::Path;
use std::sync::Arc;
use std::time::Duration;

use alba_core::{BeamId, ExecutorKind, load_str};
use alba_engine::{
    BeamStatus, CacheOptions, Executors, RunEvent, RunOptions, RunSummary, Targets, run,
};
use alba_executors::{FakeBehavior, FakeExecutor};
use tokio_util::sync::CancellationToken;

struct Outcome {
    summary: RunSummary,
    events: Vec<RunEvent>,
    executor: Arc<FakeExecutor>,
}

impl Outcome {
    fn executed(&self) -> Vec<String> {
        self.executor
            .calls()
            .into_iter()
            .map(|c| c.command)
            .collect()
    }

    /// Every stderr line this run emitted, live or replayed — where the
    /// cache tells the user why a beam is running uncached.
    fn stderr(&self) -> Vec<String> {
        self.events
            .iter()
            .filter_map(|event| match event {
                RunEvent::BeamOutput { line, .. }
                    if line.stream == alba_executors::Stream::Stderr =>
                {
                    Some(line.text.clone())
                }
                _ => None,
            })
            .collect()
    }
}

fn options(dir: &Path, force: bool) -> RunOptions {
    RunOptions {
        jobs: 4,
        keep_going: false,
        params: Vec::new(),
        cache: Some(CacheOptions {
            dir: dir.join(".alba").join("cache"),
            force,
        }),
        extra_env: Vec::new(),
    }
}

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

fn ids(bucket: &[BeamId]) -> Vec<&str> {
    bucket.iter().map(|id| id.0.as_str()).collect()
}

/// One run with a fresh executor, against a shared project dir (and thus
/// a shared cache). `params` are the target's positional arguments.
async fn run_once(
    source: &str,
    target: &str,
    dir: &Path,
    options: RunOptions,
    executor: FakeExecutor,
) -> Outcome {
    run_prepared(source, target, dir, options, executor, |_| {}).await
}

/// [`run_once`] with a hook to amend the loaded project, for a scenario
/// that cannot be spelled in a Beamfile any more — loading now rejects a
/// pattern that will not compile, so reaching the engine with one takes a
/// [`alba_core::Project`] built by hand, as any library consumer may.
async fn run_prepared(
    source: &str,
    target: &str,
    dir: &Path,
    options: RunOptions,
    executor: FakeExecutor,
    prepare: impl FnOnce(&mut alba_core::Project),
) -> Outcome {
    let mut project = load_str(source).expect("the test Beamfile must load");
    for beam in &mut project.beams {
        beam.dir = dir.to_path_buf();
    }
    prepare(&mut project);
    let executor = Arc::new(executor);
    let (events_tx, mut events_rx) = tokio::sync::mpsc::unbounded_channel();

    let summary = run(
        &project,
        &Targets::beam(BeamId(target.to_string())),
        options,
        Executors::uniform(executor.clone()),
        events_tx,
        CancellationToken::new(),
    )
    .await
    .expect("the run must not fail");

    let mut events = Vec::new();
    while let Ok(event) = events_rx.try_recv() {
        events.push(event);
    }
    Outcome {
        summary,
        events,
        executor,
    }
}

const GEN: &str = r#"
beam gen {
  inputs ["data.txt"]
  run "generate"
}
"#;

#[tokio::test]
async fn a_second_unchanged_run_is_cached() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");

    let first = run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    let second = run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    assert_eq!(first.executed().len(), 1);
    assert!(
        second.executed().is_empty(),
        "the second run must not execute"
    );
    assert_eq!(ids(&second.summary.cached), vec!["gen"]);
    assert!(
        second
            .events
            .iter()
            .any(|event| matches!(event, RunEvent::BeamCached { id } if id.0 == "gen"))
    );
    assert!(
        !second
            .events
            .iter()
            .any(|event| matches!(event, RunEvent::BeamStarted { id } if id.0 == "gen"))
    );
}

#[tokio::test]
async fn a_changed_input_file_reruns() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");

    run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    write(dir.path(), "data.txt", "v2");
    let second = run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    assert_eq!(second.executed().len(), 1);
    assert!(second.summary.cached.is_empty());
}

#[tokio::test]
async fn a_changed_command_reruns() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");
    let changed = GEN.replace("generate", "generate --verbose");

    run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    let second = run_once(
        &changed,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    assert_eq!(second.executed(), vec!["generate --verbose"]);
}

#[tokio::test]
async fn a_changed_env_block_reruns() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");
    let with_env = |value: &str| {
        format!(
            "beam gen {{\n  inputs [\"data.txt\"]\n  env {{ MODE = \"{value}\" }}\n  run \"generate\"\n}}\n"
        )
    };

    run_once(
        &with_env("debug"),
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    let second = run_once(
        &with_env("release"),
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    assert_eq!(second.executed().len(), 1);
}

#[tokio::test]
async fn changed_arguments_rerun() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");
    const PARAM: &str = r#"
beam deploy(target) {
  inputs ["data.txt"]
  run "deploy {target}"
}
"#;
    let with_args = |args: &[&str]| {
        let mut options = options(dir.path(), false);
        options.params = args.iter().map(|a| a.to_string()).collect();
        options
    };

    run_once(
        PARAM,
        "deploy",
        dir.path(),
        with_args(&["staging"]),
        FakeExecutor::new(),
    )
    .await;
    let same = run_once(
        PARAM,
        "deploy",
        dir.path(),
        with_args(&["staging"]),
        FakeExecutor::new(),
    )
    .await;
    let different = run_once(
        PARAM,
        "deploy",
        dir.path(),
        with_args(&["production"]),
        FakeExecutor::new(),
    )
    .await;

    assert!(same.executed().is_empty(), "same arguments must hit");
    assert_eq!(different.executed(), vec!["deploy production"]);
}

#[tokio::test]
async fn a_beam_without_inputs_always_runs() {
    let dir = tempfile::tempdir().unwrap();
    const NO_INPUTS: &str = r#"beam gen { run "generate" }"#;

    run_once(
        NO_INPUTS,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    let second = run_once(
        NO_INPUTS,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    assert_eq!(second.executed().len(), 1);
    assert!(second.summary.cached.is_empty());
}

#[tokio::test]
async fn no_cache_configuration_disables_caching() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");
    let disabled = || RunOptions {
        jobs: 4,
        keep_going: false,
        params: Vec::new(),
        cache: None,
        extra_env: Vec::new(),
    };

    run_once(GEN, "gen", dir.path(), disabled(), FakeExecutor::new()).await;
    let second = run_once(GEN, "gen", dir.path(), disabled(), FakeExecutor::new()).await;

    assert_eq!(second.executed().len(), 1);
}

#[tokio::test]
async fn missing_outputs_force_a_rerun() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");
    const WITH_OUTPUT: &str = r#"
beam gen {
  inputs ["data.txt"]
  outputs ["out.txt"]
  run "generate"
}
"#;
    // FakeExecutor touches no files, so the "produced" output is created
    // by hand: present for the second run, deleted before the third.
    write(dir.path(), "out.txt", "produced");

    run_once(
        WITH_OUTPUT,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    let with_output = run_once(
        WITH_OUTPUT,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    std::fs::remove_file(dir.path().join("out.txt")).unwrap();
    let without_output = run_once(
        WITH_OUTPUT,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    assert!(with_output.executed().is_empty(), "outputs present: hit");
    assert_eq!(without_output.executed().len(), 1, "outputs missing: rerun");
}

#[tokio::test]
async fn a_failed_beam_writes_no_manifest() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");

    let failing = FakeExecutor::new().on(
        "generate",
        FakeBehavior {
            exit_code: 1,
            ..Default::default()
        },
    );
    let first = run_once(GEN, "gen", dir.path(), options(dir.path(), false), failing).await;
    let second = run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    assert_eq!(ids(&first.summary.failed), vec!["gen"]);
    assert_eq!(second.executed().len(), 1, "a failure must not have cached");
}

#[tokio::test]
async fn an_allowed_failure_writes_no_manifest_either() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");
    const ALLOWED: &str = r#"
beam gen {
  allow_failure true
  inputs ["data.txt"]
  run "generate"
}
"#;

    let failing = FakeExecutor::new().on(
        "generate",
        FakeBehavior {
            exit_code: 1,
            ..Default::default()
        },
    );
    run_once(
        ALLOWED,
        "gen",
        dir.path(),
        options(dir.path(), false),
        failing,
    )
    .await;
    let second = run_once(
        ALLOWED,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    assert_eq!(second.executed().len(), 1);
}

#[tokio::test]
async fn force_reruns_and_rewrites_the_manifest() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");

    run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    let forced = run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), true),
        FakeExecutor::new(),
    )
    .await;
    let after = run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    assert_eq!(forced.executed().len(), 1, "--force must execute");
    assert!(forced.summary.cached.is_empty());
    assert!(
        after.executed().is_empty(),
        "the forced run must have rewritten the entry"
    );
}

#[tokio::test]
async fn a_really_changed_dependency_invalidates_its_dependents() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "codegen.txt", "v1");
    write(dir.path(), "app.txt", "v1");
    const CHAIN: &str = r#"
beam codegen {
  inputs ["codegen.txt"]
  run "generate"
}

beam build {
  needs [codegen]
  inputs ["app.txt"]
  run "compile"
}
"#;

    run_once(
        CHAIN,
        "build",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    let unchanged = run_once(
        CHAIN,
        "build",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    write(dir.path(), "codegen.txt", "v2");
    let changed = run_once(
        CHAIN,
        "build",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    assert!(
        unchanged.executed().is_empty(),
        "nothing changed: both cached"
    );
    assert_eq!(ids(&unchanged.summary.cached), vec!["codegen", "build"]);
    assert_eq!(
        changed.executed(),
        vec!["generate", "compile"],
        "a changed dependency fingerprint must cascade to its dependents"
    );
}

#[tokio::test]
async fn a_non_cacheable_dependency_does_not_poison_its_dependents() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "app.txt", "v1");
    const MIXED: &str = r#"
beam always {
  run "prepare"
}

beam build {
  needs [always]
  inputs ["app.txt"]
  run "compile"
}
"#;

    run_once(
        MIXED,
        "build",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    let second = run_once(
        MIXED,
        "build",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    assert_eq!(
        second.executed(),
        vec!["prepare"],
        "the input-less beam still runs"
    );
    assert_eq!(ids(&second.summary.cached), vec!["build"]);
}

#[tokio::test]
async fn a_corrupted_cache_entry_is_a_miss() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");

    run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    for entry in std::fs::read_dir(dir.path().join(".alba/cache")).unwrap() {
        std::fs::write(entry.unwrap().path(), "garbage").unwrap();
    }
    let second = run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    assert_eq!(second.executed().len(), 1);
}

#[tokio::test]
async fn the_cached_duration_is_the_original_runs() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");

    let slow = FakeExecutor::new().on(
        "generate",
        FakeBehavior {
            delay: Duration::from_millis(150),
            ..Default::default()
        },
    );
    run_once(GEN, "gen", dir.path(), options(dir.path(), false), slow).await;
    let second = run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    let duration = second.events.iter().find_map(|event| match event {
        RunEvent::BeamFinished {
            status: BeamStatus::Cached,
            duration,
            ..
        } => Some(*duration),
        _ => None,
    });
    assert!(
        duration.expect("a cached BeamFinished must exist") >= Duration::from_millis(100),
        "the reported duration must be the original run's, not the replay's"
    );
}

#[tokio::test]
async fn a_changed_cwd_reruns() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");
    let with_cwd = |where_in: &str| {
        format!(
            "beam gen {{\n  cwd \"{where_in}\"\n  inputs [\"data.txt\"]\n  run \"generate\"\n}}\n"
        )
    };

    run_once(
        &with_cwd("build"),
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    let same = run_once(
        &with_cwd("build"),
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    let different = run_once(
        &with_cwd("dist"),
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    assert!(same.executed().is_empty(), "the same cwd must hit");
    assert_eq!(
        different.executed().len(),
        1,
        "a beam that now runs somewhere else must rerun"
    );
}

/// A cached beam's manifest was computed under one executor; replaying it
/// after the beam switched to the other must not happen, because the two
/// executors can run the very same command differently (the whole reason
/// `system_shell` exists as an opt-out). `unchanged` is the control: it
/// proves the cache really does hit here absent the switch, so the
/// `switched` assertion is not vacuous.
#[tokio::test]
async fn switching_executor_kind_invalidates_the_cache() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");

    run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    let unchanged = run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    let switched = run_prepared(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
        |project| project.beams[0].executor = ExecutorKind::SystemShell,
    )
    .await;

    assert!(
        unchanged.executed().is_empty(),
        "precondition: an unchanged rerun must still hit"
    );
    assert_eq!(
        switched.executed(),
        vec!["generate"],
        "switching a beam's executor must invalidate its cache entry rather than replay it"
    );
}

/// A beam holding a valid manifest must still report `Cancelled` once
/// fail-fast has stopped the run: a hit is not a licence to keep walking a
/// subgraph the run has abandoned.
///
/// `build` is gated behind `slow` so the assertion does not depend on
/// which of two independent beams its task happens to be polled first —
/// the cache decision is taken as soon as a beam's dependencies are
/// satisfied, so an ungated sibling would race `broken`'s failure. The
/// control run in the middle proves the manifest really is a hit, without
/// which the last assertion would hold vacuously.
#[tokio::test]
async fn a_pending_hit_is_cancelled_when_the_run_is_already_stopping() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "app.txt", "v1");
    const SOURCE: &str = r#"
beam broken {
  run "explode"
}

beam slow {
  run "wait"
}

beam build {
  needs [slow]
  inputs ["app.txt"]
  run "compile"
}

beam all {
  needs [broken, build]
  run "finish"
}
"#;
    let gated = || {
        FakeExecutor::new().on(
            "wait",
            FakeBehavior {
                delay: Duration::from_millis(200),
                ..Default::default()
            },
        )
    };

    run_once(
        SOURCE,
        "all",
        dir.path(),
        options(dir.path(), false),
        gated(),
    )
    .await;
    let control = run_once(
        SOURCE,
        "all",
        dir.path(),
        options(dir.path(), false),
        gated(),
    )
    .await;
    let stopping = run_once(
        SOURCE,
        "all",
        dir.path(),
        options(dir.path(), false),
        gated().on(
            "explode",
            FakeBehavior {
                exit_code: 1,
                ..Default::default()
            },
        ),
    )
    .await;

    assert_eq!(ids(&control.summary.cached), vec!["build"]);
    assert_eq!(ids(&stopping.summary.failed), vec!["broken"]);
    assert!(
        stopping.summary.cached.is_empty(),
        "a stopping run must report no hit"
    );
    assert_eq!(ids(&stopping.summary.cancelled), vec!["build", "all"]);
    assert!(
        !stopping
            .events
            .iter()
            .any(|event| matches!(event, RunEvent::BeamCached { .. }))
    );
}

#[tokio::test]
async fn a_hit_replays_the_stored_output_lines() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");

    let talkative = FakeExecutor::new().on(
        "generate",
        FakeBehavior {
            output_lines: vec![
                alba_executors::OutputLine {
                    stream: alba_executors::Stream::Stdout,
                    text: "generated 12 files".to_string(),
                },
                alba_executors::OutputLine {
                    stream: alba_executors::Stream::Stderr,
                    text: "warning: deprecated".to_string(),
                },
            ],
            ..Default::default()
        },
    );
    run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        talkative,
    )
    .await;
    let second = run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    let replayed: Vec<(&str, bool)> = second
        .events
        .iter()
        .filter_map(|event| match event {
            RunEvent::BeamOutput { line, replayed, .. } => Some((line.text.as_str(), *replayed)),
            _ => None,
        })
        .collect();
    assert_eq!(
        replayed,
        vec![("generated 12 files", true), ("warning: deprecated", true)],
        "stored lines must replay, in order, marked as replayed"
    );
}

#[tokio::test]
async fn live_output_is_not_marked_replayed() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");

    let talkative = FakeExecutor::new().on(
        "generate",
        FakeBehavior {
            output_lines: vec![alba_executors::OutputLine {
                stream: alba_executors::Stream::Stdout,
                text: "generated".to_string(),
            }],
            ..Default::default()
        },
    );
    let first = run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        talkative,
    )
    .await;

    assert!(first.events.iter().any(|event| matches!(
        event,
        RunEvent::BeamOutput {
            replayed: false,
            ..
        }
    )));
    assert!(
        !first
            .events
            .iter()
            .any(|event| matches!(event, RunEvent::BeamOutput { replayed: true, .. }))
    );
}

/// The replay order contract: `BeamCached`, then every replayed line,
/// then `BeamFinished` — mirroring a live beam's started/output/finished.
#[tokio::test]
async fn replayed_lines_sit_between_cached_and_finished() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");

    let talkative = FakeExecutor::new().on(
        "generate",
        FakeBehavior {
            output_lines: vec![alba_executors::OutputLine {
                stream: alba_executors::Stream::Stdout,
                text: "generated".to_string(),
            }],
            ..Default::default()
        },
    );
    run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        talkative,
    )
    .await;
    let second = run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    let index = |predicate: &dyn Fn(&RunEvent) -> bool| {
        second
            .events
            .iter()
            .position(predicate)
            .expect("event must exist")
    };
    let cached = index(&|e| matches!(e, RunEvent::BeamCached { .. }));
    let output = index(&|e| matches!(e, RunEvent::BeamOutput { replayed: true, .. }));
    let finished = index(&|e| matches!(e, RunEvent::BeamFinished { .. }));
    assert!(cached < output && output < finished);
}

/// The four tests below share one shape: a beam that declares `inputs`
/// but, for four different ordinary reasons, resolved none of the files
/// the author meant. Each once produced a permanently cached beam — the
/// fingerprint of an empty file list is a constant, so the first run
/// succeeded, wrote a manifest, and every later run replayed it however
/// much the sources changed. A beam whose `inputs` resolve to nothing is
/// not cacheable for that run, and says so.
const SRC: &str = r#"
beam gen {
  inputs ["src/**/*.rs"]
  run "generate"
}
"#;

/// One pattern that will not compile must not silence the ones that do:
/// the globset is built per pattern, so `src/**/*.rs` still resolves.
#[tokio::test]
async fn a_pattern_that_will_not_compile_does_not_silence_its_siblings() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "src/a.rs", "v1");
    let broken = |project: &mut alba_core::Project| {
        project.beams[0].inputs = vec!["src/**/*.rs".to_string(), "a[b".to_string()];
    };

    run_prepared(
        SRC,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
        broken,
    )
    .await;
    write(dir.path(), "src/a.rs", "v2");
    let second = run_prepared(
        SRC,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
        broken,
    )
    .await;

    assert_eq!(
        second.executed().len(),
        1,
        "an uncompilable sibling must not make every pattern match nothing"
    );
}

/// An input directory the project's own `.gitignore` excludes resolves to
/// nothing: glob expansion is deliberately `.gitignore`-aware.
#[tokio::test]
async fn an_ignored_input_directory_is_not_cached_silently() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), ".gitignore", "src/\n");
    write(dir.path(), "src/a.rs", "v1");

    run_once(
        SRC,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    write(dir.path(), "src/a.rs", "v2");
    let second = run_once(
        SRC,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    assert_eq!(
        second.executed().len(),
        1,
        "an ignored input must not cache"
    );
    assert!(second.summary.cached.is_empty());
}

/// A misspelled path matches nothing, and the beam is told so where the
/// user is already looking rather than caching forever in silence.
#[tokio::test]
async fn a_misspelled_input_path_is_not_cached_silently() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "src/a.rs", "v1");
    const MISSPELLED: &str = r#"
beam gen {
  inputs ["scr/**/*.rs"]
  run "generate"
}
"#;

    run_once(
        MISSPELLED,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    write(dir.path(), "src/a.rs", "v2");
    let second = run_once(
        MISSPELLED,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    assert_eq!(second.executed().len(), 1);
    assert!(
        second
            .stderr()
            .iter()
            .any(|line| line.starts_with("cache:") && line.contains("running without cache")),
        "a beam whose inputs matched nothing must say so, got {:?}",
        second.stderr()
    );
}

/// An input reached through a symbolic link is a real input: it is
/// followed and hashed by content, so an unchanged run still hits and a
/// change to the link's target still reruns.
#[cfg(unix)]
#[tokio::test]
async fn an_input_reached_through_a_symbolic_link_is_hashed() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "real/a.rs", "v1");
    std::fs::create_dir_all(dir.path().join("src")).unwrap();
    std::os::unix::fs::symlink("../real/a.rs", dir.path().join("src/a.rs")).unwrap();

    run_once(
        SRC,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    let unchanged = run_once(
        SRC,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    write(dir.path(), "real/a.rs", "v2");
    let changed = run_once(
        SRC,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    assert_eq!(
        ids(&unchanged.summary.cached),
        vec!["gen"],
        "the linked file is a real input, so an unchanged run hits"
    );
    assert_eq!(
        changed.executed().len(),
        1,
        "a change behind the link must rerun"
    );
}

/// An input that exists but cannot be read is the other way the cache
/// degrades rather than fails: the beam runs, uncached, and says why.
///
/// Unix only — `chmod` is what makes a file unreadable here — and skipped
/// where the mode turns out not to be enforced, which is the case for
/// root and would make the whole scenario vacuous. Probed rather than
/// deduced from the user id: the question is whether the read fails, and
/// that is exactly what the probe asks.
#[cfg(unix)]
#[tokio::test]
async fn an_unreadable_input_runs_the_beam_uncached_with_a_notice() {
    use std::os::unix::fs::PermissionsExt;

    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");
    let input = dir.path().join("data.txt");
    std::fs::set_permissions(&input, std::fs::Permissions::from_mode(0o000)).unwrap();
    if std::fs::read(&input).is_ok() {
        return;
    }

    let first = run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    let second = run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;

    assert_eq!(ids(&first.summary.succeeded), vec!["gen"]);
    assert!(
        first
            .stderr()
            .iter()
            .any(|line| line.starts_with("cache: cannot hash input `data.txt`")),
        "an unhashable input must say so, got {:?}",
        first.stderr()
    );
    assert_eq!(
        second.executed().len(),
        1,
        "an unhashable input leaves nothing to hit on"
    );
}

/// The TUI and a pipe run the same beam with different `extra_env`; the
/// second must still be a hit, or switching front ends would rebuild the
/// world.
#[tokio::test]
async fn extra_env_does_not_change_the_fingerprint() {
    let dir = tempfile::tempdir().unwrap();
    write(dir.path(), "data.txt", "v1");

    let first = run_once(
        GEN,
        "gen",
        dir.path(),
        options(dir.path(), false),
        FakeExecutor::new(),
    )
    .await;
    assert_eq!(first.executed(), vec!["generate"]);

    let mut forced = options(dir.path(), false);
    forced.extra_env = vec![("FORCE_COLOR".to_string(), "1".to_string())];
    let second = run_once(GEN, "gen", dir.path(), forced, FakeExecutor::new()).await;
    assert_eq!(
        second.executed(),
        Vec::<String>::new(),
        "a hit runs nothing"
    );
    assert_eq!(ids(&second.summary.cached), vec!["gen"]);
}