artifactize-core 0.27.2

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
use std::{
    collections::BTreeMap,
    ffi::OsString,
    io,
    path::PathBuf,
    sync::{
        Arc,
        atomic::{AtomicU32, Ordering},
    },
    time::Duration,
};

use artifactize_core::process::{self, ChildIdentity, Command};
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);

fn command(program: &str, args: &[&str]) -> Command {
    Command {
        program: program.into(),
        args: args.iter().map(OsString::from).collect(),
        cwd: support::os::temp_root(),
        env: BTreeMap::from([("PATH".into(), support::os::path())]),
        timeout: TEST_TIMEOUT,
    }
}

async fn execute(command: Command) -> process::Output {
    let cancellation = CancellationToken::new();
    let execution = process::run(command, cancellation.clone(), |_| async { Ok(()) });
    tokio::pin!(execution);
    match timeout(
        support::os::patience(TEST_TIMEOUT + Duration::from_secs(2)),
        &mut execution,
    )
    .await
    {
        Ok(output) => output.unwrap(),
        Err(_) => {
            // Settle the process and its supervisor before the fixture folders go.
            cancellation.cancel();
            let _ = execution.await;
            panic!("runner must settle");
        }
    }
}

#[tokio::test]
async fn explicit_environment_and_literal_argv_are_preserved() {
    let mut env = command(&support::os::env_program(), &[]);
    env.env = BTreeMap::from([("ONLY_EXPLICIT".into(), "value".into())]);
    assert_eq!(execute(env).await.stdout, b"ONLY_EXPLICIT=value\n");
    let result = execute(command(
        &support::os::printf_program(),
        &["%s\n", "$(id); $AUTHOR_VALUE * a b", "{artifact}/path"],
    ))
    .await;
    assert_eq!(
        result.stdout,
        b"$(id); $AUTHOR_VALUE * a b\n{artifact}/path\n"
    );
}

#[tokio::test]
async fn registration_observes_inert_group_leader_before_exec() {
    let scratch = Scratch::new();
    let marker = scratch.0.join("started");
    let mut command = command(
        &support::os::steps(),
        &["write", "started", "started", "cwd"],
    );
    command.cwd = scratch.0.clone();
    let expected_cwd = scratch.0.clone();
    let (registered, identity) = oneshot::channel();
    let (release, held) = oneshot::channel();
    let cancellation = CancellationToken::new();
    let work = process::run(command, cancellation.clone(), move |child| async move {
        assert!(!marker.exists());
        support::os::assert_group(child.pid.get());
        assert_eq!(support::os::start_time(child.pid.get()), child.start_time);
        registered.send(child).unwrap();
        held.await.unwrap();
        assert!(
            !marker.exists(),
            "user code ran before registration finished"
        );
        Ok(())
    });
    support::os::scoped(cancellation, work, async |running| {
        let child = identity.await.unwrap();
        assert!(support::os::running(child.pid.get()));
        assert!(!scratch.0.join("started").exists());
        release.send(()).unwrap();
        let output = running.await.unwrap().unwrap();
        assert!(output.status.success());
        assert_eq!(
            String::from_utf8(output.stdout).unwrap().trim(),
            support::os::path_text(&support::os::canonical(&expected_cwd))
        );
        assert_eq!(
            std::fs::read(scratch.0.join("started")).unwrap(),
            b"started"
        );
    })
    .await;
}

#[tokio::test]
async fn failed_registration_never_executes_and_reaps_the_child() {
    let scratch = Scratch::new();
    let mut command = command(&support::os::steps(), &["touch", "started"]);
    command.cwd = scratch.0.clone();
    let pid = Arc::new(AtomicU32::new(0));
    let observed = pid.clone();
    let result = process::run(command, CancellationToken::new(), move |child| async move {
        observed.store(child.pid.get(), Ordering::SeqCst);
        Err(io::Error::other("registration rejected"))
    })
    .await;
    assert!(matches!(result, Err(process::Error::Registration(_))));
    assert_gone(pid.load(Ordering::SeqCst)).await;
    assert!(!scratch.0.join("started").exists());
}

#[tokio::test]
async fn dropping_the_caller_during_registration_does_not_release_the_gate() {
    let scratch = Scratch::new();
    let mut command = command(&support::os::steps(), &["touch", "started"]);
    command.cwd = scratch.0.clone();
    let (registered, child) = oneshot::channel::<ChildIdentity>();
    let cancellation = CancellationToken::new();
    let work = process::run(command, cancellation.clone(), |child| async move {
        registered.send(child).unwrap();
        std::future::pending().await
    });
    support::os::scoped(cancellation, work, async |running| {
        let child = child.await.unwrap();
        let _owner = support::os::OwnedProcess {
            pid: child.pid.get(),
            birth: child.start_time,
        };
        // Dropping the caller is what is under test: abort it rather than cancel it.
        running.abort();
        assert_gone(child.pid.get()).await;
        assert!(!scratch.0.join("started").exists());
    })
    .await;
}

// The paused clock moves only when the test advances it: the held child keeps tokio from
// advancing it on its own, so the deadline passes once registration is underway.
#[tokio::test(start_paused = true)]
async fn registration_is_covered_by_the_deadline() {
    let scratch = Scratch::new();
    let mut command = command(&support::os::steps(), &["touch", "started"]);
    command.cwd = scratch.0.clone();
    command.timeout = Duration::from_secs(60);
    let (registered, pid) = oneshot::channel();
    let cancellation = CancellationToken::new();
    let work = process::run(
        command,
        cancellation.clone(),
        |child: ChildIdentity| async move {
            registered.send(child.pid).unwrap();
            std::future::pending().await
        },
    );
    support::os::scoped(cancellation, work, async |running| {
        let pid = pid.await.unwrap();
        tokio::time::advance(Duration::from_secs(60)).await;
        assert!(matches!(
            running.await.unwrap(),
            Err(process::Error::Timeout)
        ));
        assert!(!scratch.0.join("started").exists());
        assert_gone(pid.get()).await;
    })
    .await;
}

#[tokio::test]
async fn invalid_cwd_is_a_spawn_error_before_registration() {
    let mut command = command(&support::os::true_program(), &[]);
    let scratch = Scratch::new();
    command.cwd = scratch.0.join("nonexistent-directory");
    let result = timeout(
        Duration::from_secs(2),
        process::run(command, CancellationToken::new(), |_| async {
            panic!("an invalid cwd must not reach registration")
        }),
    )
    .await
    .unwrap();
    // Windows reports a missing working directory as ERROR_DIRECTORY.
    assert!(matches!(
        result,
        Err(process::Error::Spawn(error)) if support::os::missing_program(&error)
    ));
}

#[tokio::test]
async fn stdout_and_stderr_are_drained_concurrently_after_capture_limit() {
    let result = execute(command(
        &support::os::steps(),
        &["fill", "262144", "0", "262144", "0"],
    ))
    .await;
    assert!(result.status.success());
    assert_eq!(result.stdout.len(), 128 * 1024);
    assert_eq!(result.stderr.len(), 128 * 1024);
    assert!(result.truncated);
}

#[tokio::test]
async fn owned_human_runs_exit_before_fixture_removal_on_success_and_unwind() {
    use artifactize_core::{runs::Worker, types::RequestStatus};

    for unwinding in [false, true] {
        let root = support::os::tempdir();
        let directory = root.path().to_owned();
        let repo = root.path().join("repo");
        let state = root.path().join("state");
        std::fs::create_dir(&repo).unwrap();
        support::declaration::write(
            &repo,
            repo.join("index.artf"),
            "name = \"app\"\nfingerprint = {}\n[evals.review]\ntitle = \"Review\"\n\
             profile = { kind = \"human\" }\n[evals.review.payload]\ninstruction = \"Inspect.\"\n",
        )
        .unwrap();
        let fixture = support::runs::RepoLease::new(root, &state, &repo);
        let run = support::runs::record_deferred(&repo, &state, &"app/review".parse().unwrap())
            .await
            .unwrap();
        assert_eq!(run.requests[0].status(), RequestStatus::Deferred);
        let Worker::Admitted { owner } = run.run.control.unwrap().worker else {
            panic!("the fixture worker was admitted");
        };
        assert!(support::os::same_process_running(
            owner.pid.get(),
            owner.start_time
        ));
        fixture.release().unwrap();
        assert!(!support::os::same_process_running(
            owner.pid.get(),
            owner.start_time
        ));
        assert!(
            repo.join(".artifactize/app.artf").is_file(),
            "explicit release retains inputs"
        );
        assert!(fixture.path().is_dir());
        assert_eq!(
            artifactize_core::store::read_run_snapshot(&state, &run.run.id)
                .await
                .unwrap()
                .run
                .status(),
            artifactize_core::types::RunStatus::Error
        );
        // Explicit teardown must not disarm ownership of later submissions.
        let later = support::runs::record_deferred(&repo, &state, &"app/review".parse().unwrap())
            .await
            .unwrap();
        assert_eq!(later.requests[0].status(), RequestStatus::Deferred);
        assert_ne!(run.run.id, later.run.id);
        let Worker::Admitted { owner } = later.run.control.unwrap().worker else {
            panic!("the later fixture worker was admitted");
        };
        // Move ownership into the unwind boundary, so no fixture is reused after a panic.
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let fixture = fixture;
            if unwinding {
                panic!("scripted fixture unwind");
            }
            drop(fixture);
        }));
        if unwinding {
            assert_eq!(
                result.unwrap_err().downcast_ref::<&str>(),
                Some(&"scripted fixture unwind")
            );
        } else {
            result.unwrap();
        }
        assert!(!support::os::same_process_running(
            owner.pid.get(),
            owner.start_time
        ));
        assert!(
            !directory.exists(),
            "only released fixture state is removed"
        );
    }
}

#[tokio::test]
async fn fixture_stops_owned_workers_and_removes_inputs_without_readable_receipts() {
    use artifactize_core::runs::Worker;
    for unwinding in [false, true] {
        let root = support::os::tempdir();
        let directory = root.path().to_owned();
        let repo = directory.join("repo");
        let state = directory.join("state");
        std::fs::create_dir(&repo).unwrap();
        support::declaration::write(
            &repo,
            repo.join("index.artf"),
            "name = 'app'\nfingerprint = {}\n[evals.review]\ntitle = 'Review'\nprofile = { kind = 'human' }\n[evals.review.payload]\ninstruction = 'Inspect.'\n",
        ).unwrap();
        let lease = support::runs::RepoLease::new(root, &state, &repo);
        let run = support::runs::record_deferred(&repo, &state, &"app/review".parse().unwrap())
            .await
            .unwrap();
        let control = run.run.control.unwrap();
        let Worker::Admitted { owner } = control.worker else {
            panic!("fixture recorded an admitted worker");
        };
        let supervisor = control.supervisor.unwrap();
        assert!(support::os::same_process_running(
            owner.pid.get(),
            owner.start_time
        ));
        let db = rusqlite::Connection::open(state.join(artifactize_core::store::DATABASE)).unwrap();
        db.pragma_update(None, "user_version", 0).unwrap();
        drop(db);
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let lease = lease;
            if unwinding {
                panic!("scripted original panic");
            }
            drop(lease);
        }));
        let panic = result.unwrap_err();
        if unwinding {
            assert_eq!(
                panic.downcast_ref::<&str>(),
                Some(&"scripted original panic")
            );
        } else {
            assert!(
                panic
                    .downcast_ref::<String>()
                    .unwrap()
                    .contains("Unsupported state schema version: 0.")
            );
        }
        for worker in [owner, supervisor] {
            assert!(!support::os::same_process_running(
                worker.pid.get(),
                worker.start_time
            ));
        }
        assert!(
            !directory.exists(),
            "unreadable receipts do not retain the owned fixture"
        );
    }
}

#[tokio::test]
async fn a_fixture_leases_the_supervisor_before_observing_saved_admission() {
    use artifactize_core::{
        project::{VerifyOptions, selection::Selection},
        runs, store,
    };
    let root = support::os::tempdir();
    let directory = root.path().to_path_buf();
    let repo = directory.join("repo");
    let state = directory.join("state");
    std::fs::create_dir(&repo).unwrap();
    support::declaration::write(&repo, repo.join("index.artf"),
        "name = 'app'\n[evals.review]\ntitle = 'Review'\nprofile = { kind = 'human' }\n[evals.review.payload]\ninstruction = 'Inspect.'\n",
    ).unwrap();
    // The worker executable is declared before the lease, so the lease (dropped first) stops
    // the supervisor before the executable it runs is removed.
    let worker = support::os::library_worker();
    let lease = support::runs::RepoLease::new(root, &state, &repo);
    let gate = state.join("fixture-admission");
    std::fs::create_dir_all(&gate).unwrap();
    let context = runs::Context::new(&repo, Some(&state), worker.path()).unwrap();
    let accepted =
        support::runs::submit_fixture(&context, &Selection::All, &VerifyOptions::default())
            .await
            .unwrap();
    wait_for(|| gate.join("held").is_file()).await;
    // Inspect the birth identity without going through the fixture's observation barrier.
    let saved = store::read_run_snapshot(&state, &accepted.run)
        .await
        .unwrap();
    let supervisor = saved.run.control.unwrap().supervisor.unwrap();
    let db = rusqlite::Connection::open(state.join(store::DATABASE)).unwrap();
    db.pragma_update(None, "user_version", 0).unwrap();
    drop(db);
    let failure =
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(lease))).unwrap_err();
    assert!(
        failure
            .downcast_ref::<String>()
            .unwrap()
            .contains("Unsupported state schema")
    );
    assert!(!support::os::same_process_running(
        supervisor.pid.get(),
        supervisor.start_time
    ));
    assert!(!directory.exists());
}

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");
}

struct Scratch(
    PathBuf,
    #[expect(
        dead_code,
        reason = "owns the temporary fixture for the duration of the test"
    )]
    tempfile::TempDir,
);

impl Scratch {
    fn new() -> Self {
        let root = support::os::tempdir();
        Self(root.path().to_owned(), root)
    }
}