artifactize-core 0.14.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
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
use std::{
    collections::BTreeMap,
    ffi::OsString,
    io,
    path::{Path, PathBuf},
    time::Duration,
};

use artifactize_core::{
    process,
    runtime::{self, Command, Error, Outcome, Verdict},
};
use support::os::{private_dir, symlink_dir};
use tokio::{sync::oneshot, time::timeout};
use tokio_util::sync::CancellationToken;

mod support;

// A stalled fixture fails within this watchdog; ordering and expiry use handshakes or paused time.
const TEST_TIMEOUT: Duration = Duration::from_secs(5);

struct Scratch(tempfile::TempDir);

impl Scratch {
    fn new() -> Self {
        let scratch = Self(support::os::tempdir());
        std::fs::create_dir(scratch.workspace()).unwrap();
        scratch
    }

    fn workspace(&self) -> PathBuf {
        self.0.path().join("workspace")
    }

    fn run_dir(&self) -> PathBuf {
        self.0.path().join("runs")
    }

    fn command(&self, program: &str, args: &[&str], timeout_ms: Option<u32>) -> Command {
        Command::prepare(
            program.into(),
            args.iter().map(OsString::from).collect(),
            &self.workspace(),
            &self.run_dir(),
            timeout_ms.map(|ms| Duration::from_millis(ms.into())),
        )
        .unwrap()
    }
}

async fn execute(command: Command) -> Outcome {
    timeout(
        support::os::patience(TEST_TIMEOUT + Duration::from_secs(2)),
        runtime::execute(command, CancellationToken::new(), |_| async { Ok(()) }),
    )
    .await
    .expect("runner must settle")
}

fn completed(outcome: Outcome) -> runtime::ReviewResult {
    match outcome {
        Outcome::Completed(result) => result,
        other => panic!("expected a verdict, got {other:?}"),
    }
}

#[tokio::test]
async fn ordinary_zero_exit_is_green_with_actual_output() {
    let scratch = Scratch::new();
    let result = completed(
        execute(scratch.command(
            &support::os::shell(),
            &["-c", "printf out; printf err >&2"],
            None,
        ))
        .await,
    );
    assert_eq!(result.verdict, Verdict::Green);
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.output.stdout, b"out");
    assert_eq!(result.output.stderr, b"err");
    assert!(!result.output.truncated);
}

#[tokio::test]
async fn ordinary_nonzero_exit_is_red() {
    let scratch = Scratch::new();
    let result =
        completed(execute(scratch.command(&support::os::shell(), &["-c", "exit 127"], None)).await);
    assert_eq!(result.verdict, Verdict::Red);
    assert_eq!(result.exit_code, 127);
}

#[tokio::test]
async fn missing_binary_is_an_operational_error_not_red() {
    let scratch = Scratch::new();
    assert!(matches!(
        execute(scratch.command(scratch.workspace().join("nonexistent-binary").to_str().unwrap(), &[], None)).await,
        Outcome::OperationalError(Error::Process(process::Error::Spawn(error)))
            if error.kind() == io::ErrorKind::NotFound
    ));
}

// Only Unix ends a process with a signal; Windows reports exit codes.
#[cfg(unix)]
#[tokio::test]
async fn signal_is_an_operational_error() {
    let scratch = Scratch::new();
    assert!(matches!(
        execute(scratch.command(
            &support::os::shell(),
            &["-c", support::os::SELF_TERMINATE],
            None
        ))
        .await,
        Outcome::OperationalError(Error::AbnormalExit {
            signal: Some(support::os::SIGTERM),
            ..
        })
    ));
}

// Windows ends every process with an exit code, so a status that would mean a crash or
// Ctrl-C elsewhere is still an ordinary RED verdict, never a signal.
#[cfg(windows)]
#[tokio::test]
async fn windows_exit_statuses_are_verdicts_not_signals() {
    let scratch = Scratch::new();
    let (program, args, expected) = support::os::control_c_exit();
    let args: Vec<_> = args.iter().map(String::as_str).collect();
    let result = completed(execute(scratch.command(&program, &args, None)).await);
    assert_eq!(result.verdict, Verdict::Red);
    assert_eq!(result.exit_code, expected);
}

// The held child keeps the paused clock still until registration has handed over its PID;
// the test then advances the clock past the deadline.
#[tokio::test(start_paused = true)]
async fn timeout_is_an_operational_error_and_reaps_the_leader() {
    let scratch = Scratch::new();
    let command = scratch.command(
        &support::os::shell(),
        &["-c", support::os::LINGERING],
        Some(1000),
    );
    let (registered, child) = oneshot::channel();
    let running = support::spawn(runtime::execute(
        command,
        CancellationToken::new(),
        |child| async move {
            registered.send(child.pid).unwrap();
            Ok(())
        },
    ));
    let pid = child.await.unwrap();
    tokio::time::advance(Duration::from_millis(1000)).await;
    let outcome = running.await.unwrap();
    assert!(
        matches!(
            outcome,
            Outcome::OperationalError(Error::Process(process::Error::Timeout))
        ),
        "{outcome:?}"
    );
    assert_gone(pid.get()).await;
}

#[tokio::test]
async fn cancellation_is_an_operational_error_and_cleans_up() {
    let scratch = Scratch::new();
    let cancellation = CancellationToken::new();
    let (registered, child) = oneshot::channel();
    // exec keeps the observed PID stable while the final long-lived command runs.
    let script = support::os::cancellation_script();
    let command = scratch.command(&support::os::shell(), &["-c", script], None);
    let running = support::spawn(runtime::execute(
        command,
        cancellation.clone(),
        |child| async move {
            registered.send(child).unwrap();
            Ok(())
        },
    ));
    let child = child.await.unwrap();
    wait_for(|| scratch.workspace().join("started").exists()).await;
    cancellation.cancel();
    let outcome = timeout(support::os::patience(TEST_TIMEOUT), running)
        .await
        .unwrap()
        .unwrap();
    assert!(
        matches!(
            outcome,
            Outcome::OperationalError(Error::Process(process::Error::Cancelled))
        ),
        "{outcome:?}"
    );
    assert_gone(child.pid.get()).await;
}

#[tokio::test]
async fn pre_cancelled_commands_never_register() {
    let scratch = Scratch::new();
    let cancellation = CancellationToken::new();
    cancellation.cancel();
    let outcome = runtime::execute(
        scratch.command(&support::os::true_program(), &[], None),
        cancellation,
        |_| async { panic!("pre-cancelled commands must not spawn") },
    )
    .await;
    assert!(matches!(
        outcome,
        Outcome::OperationalError(Error::Process(process::Error::Cancelled))
    ));
}

#[tokio::test]
async fn literal_argv_is_preserved() {
    let scratch = Scratch::new();
    let result = completed(
        execute(scratch.command(
            &support::os::printf_program(),
            &["%s\n", "$(id); $AUTHOR_VALUE * a b", "{artifact}/path"],
            None,
        ))
        .await,
    );
    assert_eq!(
        result.output.stdout,
        b"$(id); $AUTHOR_VALUE * a b\n{artifact}/path\n"
    );
}

#[test]
fn runtime_timeout_defaults_and_bounds_match_current_source() {
    let scratch = Scratch::new();
    assert_eq!(
        scratch
            .command(&support::os::true_program(), &[], None)
            .timeout(),
        Duration::from_secs(30)
    );
    for ms in [1, 2_147_483_647] {
        assert_eq!(
            scratch
                .command(&support::os::true_program(), &[], Some(ms))
                .timeout(),
            Duration::from_millis(ms.into())
        );
    }
    for ms in [0, 2_147_483_648, u32::MAX] {
        let run_dir = scratch.0.path().join("invalid-timeout");
        assert!(matches!(
            Command::prepare(
                support::os::true_program().into(),
                vec![],
                &scratch.workspace(),
                &run_dir,
                Some(Duration::from_millis(ms.into()))
            ),
            Err(Error::InvalidTimeout)
        ));
        assert!(!run_dir.exists());
    }
}

#[tokio::test]
async fn runtime_has_independent_private_external_directories() {
    let scratch = Scratch::new();
    let command = scratch.command(&support::os::env_program(), &[], None);
    let directory = command.directory().to_owned();
    let tmp = directory.join("tmp");
    let other = scratch.command(&support::os::true_program(), &[], None);
    assert_ne!(directory, other.directory());
    let result = completed(execute(command).await);
    let text = String::from_utf8(result.output.stdout).unwrap();
    let environment: BTreeMap<_, _> = text
        .lines()
        .map(|line| line.split_once('=').unwrap())
        .collect();
    assert_eq!(
        environment["ARTIFACTIZE_WORKSPACE_DIR"],
        support::os::canonical(&scratch.workspace())
            .to_str()
            .unwrap()
    );
    for (variable, name) in support::os::runtime_directories() {
        let path = Path::new(environment[variable]);
        assert_eq!(path, directory.join(name));
        assert!(!path.starts_with(scratch.workspace()));
        if name != "tmp" {
            assert!(private_dir(path));
        }
    }
    // The temporary directory is the command's scratch space and goes with the run; the output
    // directory stays for receipts and pruning.
    assert!(!tmp.exists());
    assert!(directory.join("output").is_dir());
    for path in [&directory, &scratch.run_dir()] {
        assert!(private_dir(path));
    }
    assert!(
        directory.exists(),
        "caller-owned runtime output persists after exit"
    );
}

#[test]
fn output_inside_workspace_is_rejected_before_creation_even_through_symlinks() {
    let scratch = Scratch::new();
    let alias = scratch.0.path().join("alias");
    let workspace_alias = scratch.0.path().join("workspace-alias");
    support::os::link_dir(&scratch.workspace(), &alias);
    support::os::link_dir(&scratch.workspace(), &workspace_alias);
    // A symbolic link, where creating one is allowed, is refused like the links above.
    let symlink = scratch.0.path().join("symlink");
    if symlink_dir(scratch.workspace(), &symlink).is_some() {
        let result = Command::prepare(
            support::os::true_program().into(),
            vec![],
            &workspace_alias,
            &symlink.join("new/nested"),
            None,
        );
        assert!(
            matches!(result, Err(Error::OutputInsideWorkspace)),
            "{result:?}"
        );
    }
    for output in [
        scratch.workspace(),
        scratch.workspace().join("new/nested"),
        alias.join("new/nested"),
        scratch.0.path().join("missing/../workspace/new"),
    ] {
        let result = Command::prepare(
            support::os::true_program().into(),
            vec![],
            &workspace_alias,
            &output,
            None,
        );
        assert!(
            matches!(result, Err(Error::OutputInsideWorkspace)),
            "{output:?}: {result:?}"
        );
    }
    assert!(!scratch.workspace().join("new").exists());
    assert!(!scratch.0.path().join("missing").exists());
}

#[tokio::test]
async fn external_symlinked_output_uses_canonical_existing_ancestors() {
    let scratch = Scratch::new();
    let external = scratch.0.path().join("external");
    std::fs::create_dir(&external).unwrap();
    let alias = scratch.0.path().join("alias");
    support::os::link_dir(&external, &alias);
    let command = Command::prepare(
        support::os::env_program().into(),
        vec![],
        &scratch.workspace(),
        &alias.join("new/nested"),
        None,
    )
    .unwrap();
    assert!(
        command
            .directory()
            .starts_with(support::os::canonical(&external.join("new/nested")))
    );
    assert_eq!(completed(execute(command).await).verdict, Verdict::Green);
}

#[test]
fn runtime_child_runs_in_the_authors_environment_without_artifactize_variables() {
    // The probe's PATH has no compiler, so build the Windows stand-ins first.
    support::os::env_program();
    let root = support::os::tempdir();
    let author_home = root.path().join("author-home");
    std::fs::create_dir(&author_home).unwrap();
    // Set the parent environment in another process, never mutate this test runner's env.
    let result = support::os::run_test(
        "environment_subprocess_probe",
        &[
            ("ARTIFACTIZE_ENV_PROBE", "enabled".into()),
            ("ARTIFACTIZE_REMOTE_TOKEN", "azt_not-for-the-command".into()),
            ("ARTIFACTIZE_REMOTE", "https://store.invalid".into()),
            ("AUTHOR_VARIABLE", "from-the-terminal".into()),
            (support::os::home_env(), author_home.into_os_string()),
            ("PATH", support::os::system_path()),
            ("LANG", "C".into()),
        ],
    );
    assert!(
        result.status.success(),
        "{}{}",
        String::from_utf8_lossy(&result.stdout),
        String::from_utf8_lossy(&result.stderr)
    );
}

#[tokio::test]
async fn environment_subprocess_probe() {
    if support::os::environment_variable("ARTIFACTIZE_ENV_PROBE").is_none() {
        return;
    }
    assert_eq!(
        support::os::environment_variable("ARTIFACTIZE_REMOTE_TOKEN").unwrap(),
        "azt_not-for-the-command"
    );
    // Capture the controlled parent input before executing the product's child environment.
    let author_home = support::os::environment_variable(support::os::home_env()).unwrap();
    let scratch = Scratch::new();
    let result = completed(execute(scratch.command(&support::os::env_program(), &[], None)).await);
    let output = String::from_utf8(result.output.stdout).unwrap();
    let lines: Vec<&str> = output.lines().collect();
    // The author's own environment: path, locale, real home and any variable of theirs.
    assert!(support::os::has_variable(
        &lines,
        "PATH",
        support::os::system_path().to_str().unwrap()
    ));
    assert!(support::os::has_variable(&lines, "LANG", "C"));
    assert!(support::os::has_variable(
        &lines,
        "AUTHOR_VARIABLE",
        "from-the-terminal"
    ));
    assert!(support::os::has_variable(
        &lines,
        support::os::home_env(),
        author_home.to_str().unwrap()
    ));
    // Artifactize's credentials and settings stay out; only its per-run variables are set.
    for forbidden in [
        "ARTIFACTIZE_REMOTE_TOKEN",
        "ARTIFACTIZE_REMOTE=",
        "ARTIFACTIZE_ENV_PROBE",
        "azt_not-for-the-command",
    ] {
        assert!(!output.contains(forbidden), "{forbidden}");
    }
    for own in [
        "ARTIFACTIZE_WORKSPACE_DIR=",
        "ARTIFACTIZE_OUTPUT_DIR=",
        "ARTIFACTIZE_TMP_DIR=",
    ] {
        assert!(output.contains(own), "{own}");
    }
}

#[tokio::test]
async fn runtime_cleans_ansi_and_controls_without_changing_whitespace_or_del() {
    let scratch = Scratch::new();
    let result = completed(
        execute(scratch.command(
            &support::os::printf_program(),
            &["\\033[31mred\\033[0m\\000\\001\\010\\013\\014\\016\\037\\t\\n\\r\\177\\377\\033[?25l\\033[1 qend"],
            None,
        ))
        .await,
    );
    assert_eq!(result.output.stdout, "red\t\n\r\x7f\u{fffd}end".as_bytes());
    assert!(!result.output.truncated);
    let stderr = completed(
        execute(scratch.command(
            &support::os::shell(),
            &["-c", "printf '\\033[31merror\\033[0m\\001' >&2"],
            None,
        ))
        .await,
    );
    assert_eq!(stderr.output.stderr, b"error");
}

#[tokio::test]
async fn both_streams_are_bounded_before_cleaning_and_keep_truncation_metadata() {
    let scratch = Scratch::new();
    let result = completed(
        execute(scratch.command(
            &support::os::shell(),
            &["-c", &support::os::letter_output(262144, 262144)],
            None,
        ))
        .await,
    );
    assert_eq!(result.verdict, Verdict::Green);
    assert_eq!(result.output.stdout, vec![b'x'; 128 * 1024]);
    assert_eq!(result.output.stderr, vec![b'y'; 128 * 1024]);
    assert!(result.output.truncated);
    let result = completed(
        execute(scratch.command(
            &support::os::shell(),
            &["-c", &support::os::capped_output(131072)],
            None,
        ))
        .await,
    );
    assert!(result.output.stdout.is_empty());
    assert!(result.output.truncated);
}

// The paused clock reaches the deadline only when the test advances it, once the
// grandchild has started.
#[tokio::test(start_paused = true)]
async fn timeout_kills_a_grandchild_even_when_the_leader_ignores_term() {
    let scratch = Scratch::new();
    let command = scratch.command(
        &support::os::shell(),
        &["-c", support::os::LINGERING_GRANDCHILD],
        Some(1000),
    );
    let marker = command.directory().join("output/grandchild");
    let running = support::spawn(runtime::execute(
        command,
        CancellationToken::new(),
        |_| async { Ok(()) },
    ));
    let pid = grandchild(&marker, &running).await;
    tokio::time::advance(Duration::from_millis(1000)).await;
    let outcome = running.await.unwrap();
    assert!(
        matches!(
            outcome,
            Outcome::OperationalError(Error::Process(process::Error::Timeout))
        ),
        "{outcome:?}"
    );
    assert_gone(pid).await;
}

/// The PID the lingering grandchild wrote to `marker`, once it has. The test yields rather
/// than sleeps while it waits, so that a paused clock stands still.
async fn grandchild(marker: &Path, running: &tokio_util::task::AbortOnDropHandle<Outcome>) -> u32 {
    let failure_deadline = std::time::Instant::now() + support::os::patience(TEST_TIMEOUT);
    loop {
        let written = std::fs::read_to_string(marker).ok();
        if let Some(pid) = written
            .as_deref()
            .and_then(|text| text.strip_suffix('\n'))
            .and_then(|text| text.trim().parse().ok())
        {
            return pid;
        }
        assert!(
            !running.is_finished(),
            "execution ended before its grandchild started"
        );
        assert!(
            std::time::Instant::now() < failure_deadline,
            "the grandchild did not start"
        );
        tokio::task::yield_now().await;
    }
}

#[tokio::test]
async fn normal_exit_also_kills_a_background_descendant() {
    let scratch = Scratch::new();
    let result = completed(
        execute(scratch.command(
            &support::os::shell(),
            &["-c", &format!("{} & echo $!", support::os::LINGERING)],
            None,
        ))
        .await,
    );
    assert_eq!(result.verdict, Verdict::Green);
    let pid = String::from_utf8(result.output.stdout)
        .unwrap()
        .trim()
        .parse()
        .unwrap();
    assert_gone(pid).await;
}

#[tokio::test]
async fn dropping_an_active_caller_cleans_its_grandchild() {
    let scratch = Scratch::new();
    let command = scratch.command(
        &support::os::shell(),
        &["-c", support::os::LINGERING_GRANDCHILD],
        None,
    );
    let marker = command.directory().join("output/grandchild");
    let (registered, child) = oneshot::channel();
    let running = support::spawn(runtime::execute(
        command,
        CancellationToken::new(),
        |child| async move {
            registered.send(child).unwrap();
            Ok(())
        },
    ));
    let child = child.await.unwrap();
    wait_for(|| {
        std::fs::read_to_string(&marker).is_ok_and(|text| text.trim().parse::<u32>().is_ok())
    })
    .await;
    let pid = std::fs::read_to_string(marker)
        .unwrap()
        .trim()
        .parse()
        .unwrap();
    drop(running);
    assert_gone(child.pid.get()).await;
    assert_gone(pid).await;
}

#[tokio::test(start_paused = true)]
async fn deadline_is_not_reset_after_registration() {
    let scratch = Scratch::new();
    let command = scratch.command(
        &support::os::shell(),
        &[
            "-c",
            "touch started; while [ ! -e release ]; do sleep 0.01; done",
        ],
        Some(1000),
    );
    let (registered, child) = oneshot::channel();
    let (release, held) = oneshot::channel();
    let running = support::spawn(runtime::execute(
        command,
        CancellationToken::new(),
        |child| async move {
            registered.send(child).unwrap();
            held.await.unwrap();
            Ok(())
        },
    ));
    let child = child.await.unwrap();
    // Consume most of the one deadline while user code is still behind registration.
    tokio::time::advance(Duration::from_millis(600)).await;
    release.send(()).unwrap();
    while !scratch.workspace().join("started").exists() {
        assert!(
            !running.is_finished(),
            "registration failed before execution"
        );
        tokio::task::yield_now().await;
    }
    // Only 400 ms remains. A reset at registration would leave this process running.
    tokio::time::advance(Duration::from_millis(401)).await;
    tokio::task::yield_now().await;
    let failure_deadline = std::time::Instant::now() + support::os::patience(TEST_TIMEOUT);
    while !running.is_finished() {
        assert!(
            std::time::Instant::now() < failure_deadline,
            "execution reset the registration deadline"
        );
        tokio::task::yield_now().await;
    }
    assert!(
        running.is_finished(),
        "execution reset the registration deadline"
    );
    let outcome = running.await.unwrap();
    assert!(
        matches!(
            outcome,
            Outcome::OperationalError(Error::Process(process::Error::Timeout))
        ),
        "{outcome:?}"
    );
    assert_gone(child.pid.get()).await;
}

async fn assert_gone(pid: u32) {
    assert!(pid > 0, "must have observed a real process");
    wait_for(|| support::os::gone(pid)).await;
}

async fn wait_for(condition: impl Fn() -> bool) {
    timeout(support::os::patience(TEST_TIMEOUT), async {
        while !condition() {
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .expect("process did not reach the expected state");
}