artifactize-core 0.33.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
use super::*;
use crate::{
    config::{Field, ProfileKind, StoredProfile},
    store::{
        Execution, ExecutionOptions, ExecutionState, Producer, Provenance, Request, RequestState,
        Run, RunState,
    },
    types::{
        ArtifactName, DefinitionHash, EvalId, ExecutionId, RequestId, ReuseKey, RunId, Timestamp,
    },
};
use std::collections::{BTreeMap, BTreeSet};

fn sample_run(id: &str, repo: &std::path::Path, state: &std::path::Path, status: RunState) -> Run {
    let created_at = Timestamp::now();
    Run {
        modes: Default::default(),
        control: None,
        request_key: None,
        request_args_hash: None,
        origin: None,
        comment: None,
        id: id.parse().unwrap(),
        repo_path: repo.to_path_buf(),
        repository: Default::default(),
        state_dir: state.to_path_buf(),
        state: status,
        created_at,
        selection: crate::project::selection::Selection::All,
        definitions: Default::default(),
        jobs: None,
        fingerprint_jobs: None,
        max_executions: None,
        executions_started: 0,
        wait_timeout_ms: None,
        wait_timed_out: false,
        reuse_only: BTreeSet::new(),
        recursive: false,
        force: false,
        validation: Default::default(),
        stopped_backends: Vec::new(),
        evidence: BTreeMap::new(),
    }
}

fn sample_request(
    run_id: &RunId,
    suffix: &str,
    state: RequestState,
    execution_id: Option<ExecutionId>,
) -> Request {
    let eval_id: EvalId = "app/check".parse().unwrap();
    let target: ArtifactName = "app".parse().unwrap();
    let profile = StoredProfile::Runtime {
        command: "true".into(),
        args: Vec::new(),
        timeout_ms: Field::Missing,
    };
    let eval_def_hash: DefinitionHash =
        "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
            .parse()
            .unwrap();
    Request {
        state,
        id: format!("{run_id}-{suffix}").parse::<RequestId>().unwrap(),
        run_id: run_id.clone(),
        eval_id,
        target,
        title: "Check".into(),
        profile: profile.clone(),
        requested_profile: profile,
        eval_def_hash,
        options: ExecutionOptions::default(),
        execution_id,
        provenance: None,
        usage: None,
        reused_usage: None,
        joined: false,
        producer: None,
        reviewer: None,
        origin: None,
        session_id: None,
        session: None,
        review_notes: None,
        human_definition: None,
        payload: serde_json::from_value(serde_json::json!({"instruction": "Check."})).unwrap(),
        references: BTreeMap::new(),
        deps: Vec::new(),
        force: false,
        fingerprint: None,
        key: None,
        fingerprints: BTreeMap::new(),
        created_at: Timestamp::now(),
        started_at: None,
        cwd: PathBuf::from("."),
        run_dir: None,
        argv: None,
        child: None,
        blocked_reason: None,
        blocked_by: Vec::new(),
    }
}

fn sample_execution(
    id: &str,
    run_id: &RunId,
    key: Option<ReuseKey>,
    reusable: bool,
    at: Timestamp,
) -> Execution {
    let eval_id: EvalId = "app/check".parse().unwrap();
    let eval_def_hash: DefinitionHash =
        "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
            .parse()
            .unwrap();
    let state = if reusable {
        ExecutionState::Completed {
            result: crate::store::ExecutionResult::Runtime(crate::store::RuntimeResult::exited(
                0,
                String::new,
                std::time::Duration::from_millis(1),
            )),
            at,
        }
    } else {
        ExecutionState::Failed {
            error: "boom".into(),
            code: None,
            at,
        }
    };
    Execution {
        state,
        id: id.parse().unwrap(),
        key,
        fingerprint: None,
        fingerprints: BTreeMap::new(),
        artifact_kinds: BTreeMap::new(),
        eval_def_hash: eval_def_hash.clone(),
        owner: Some(crate::process::child_identity(std::process::id()).unwrap()),
        profile: StoredProfile::Runtime {
            command: "true".into(),
            args: Vec::new(),
            timeout_ms: Field::Missing,
        },
        options: ExecutionOptions::default(),
        usage: None,
        provenance: Provenance {
            repo_path: PathBuf::from("."),
            run_id: run_id.clone(),
            request_id: format!("{run_id}-1").parse().unwrap(),
            eval_id,
            eval_def_hash,
            completed_at: Some(at),
            execution_paths: Default::default(),
        },
        started_at: at,
        producer: Some(Producer::current()),
        reviewer: None,
        origin: None,
        manifest: None,
    }
}

#[tokio::test]
async fn retention_expires_old_terminal_runs_while_preserving_reuse_keys_open_and_waiting_runs() {
    let root = crate::test_os::tempdir();
    let live_repo = root.path().join("live-repo");
    let removed_repo = root.path().join("gone-repo");
    let state = root.path().join("state");
    std::fs::create_dir(&live_repo).unwrap();
    std::fs::create_dir(&removed_repo).unwrap();

    let receipts = Receipts::open(&state, &live_repo).await.unwrap();
    let now = OffsetDateTime::now_utc();
    let old_ts = Timestamp::new(now - time::Duration::days(120)).unwrap();
    let recent_ts = Timestamp::new(now - time::Duration::days(1)).unwrap();

    // 1. Old terminal Run in a removed checkout holding a reusable execution key.
    let old_run = sample_run(
        "run-old001",
        &removed_repo,
        &state,
        RunState::Green { at: old_ts },
    );
    let reuse_key: ReuseKey = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        .parse()
        .unwrap();
    let reusable_exec = sample_execution(
        "execution-reusable-1",
        &old_run.id,
        Some(reuse_key.clone()),
        true,
        old_ts,
    );
    let old_req = sample_request(
        &old_run.id,
        "1",
        RequestState::completed(reusable_exec.result().unwrap().clone(), old_ts),
        Some(reusable_exec.id.clone()),
    );
    let mut running_exec = reusable_exec.clone();
    running_exec.state = ExecutionState::Running;
    receipts
        .create_run(&old_run, std::slice::from_ref(&old_req))
        .await
        .unwrap();
    receipts
        .claim_execution(&running_exec, true, None, true, None)
        .await
        .unwrap();
    receipts
        .complete_execution(&reusable_exec, &old_req)
        .await
        .unwrap();

    // 2. Old terminal Run in a removed checkout holding a non-reusable ERROR execution.
    let err_run = sample_run(
        "run-old002",
        &removed_repo,
        &state,
        RunState::Error {
            at: old_ts,
            error: Some("failed".into()),
        },
    );
    let err_exec = sample_execution("execution-err-1", &err_run.id, None, false, old_ts);
    let err_req = sample_request(
        &err_run.id,
        "1",
        RequestState::failed("boom".into(), None, old_ts),
        Some(err_exec.id.clone()),
    );
    receipts
        .create_run(&err_run, std::slice::from_ref(&err_req))
        .await
        .unwrap();
    receipts
        .complete_execution(&err_exec, &err_req)
        .await
        .unwrap();

    // 3. Old Run with a DEFERRED Human request — must NEVER be expired.
    let deferred_run = sample_run(
        "run-defer1",
        &removed_repo,
        &state,
        RunState::Yellow { at: old_ts },
    );
    let mut deferred_req = sample_request(&deferred_run.id, "1", RequestState::Deferred, None);
    deferred_req.profile = StoredProfile::Human {};
    deferred_req.requested_profile = StoredProfile::Human {};
    assert_eq!(deferred_req.profile.kind(), ProfileKind::Human);
    receipts
        .create_run(&deferred_run, &[deferred_req])
        .await
        .unwrap();

    // 4. Open RUNNING Run — must NEVER be expired.
    let open_run = sample_run("run-open01", &removed_repo, &state, RunState::Running);
    let open_req = sample_request(&open_run.id, "1", RequestState::Running, None);
    receipts.create_run(&open_run, &[open_req]).await.unwrap();

    // 5. Oldest (and only) terminal Run in a live checkout — must NEVER be expired.
    let live_run = sample_run(
        "run-live01",
        &live_repo,
        &state,
        RunState::Green { at: old_ts },
    );
    let live_req = sample_request(
        &live_run.id,
        "1",
        RequestState::completed(reusable_exec.result().unwrap().clone(), recent_ts),
        None,
    );
    receipts.create_run(&live_run, &[live_req]).await.unwrap();

    // Remove `removed_repo` from disk so its old terminal Runs are eligible.
    std::fs::remove_dir(&removed_repo).unwrap();

    let policy = StateRetention::new(true, 1, 30).unwrap();
    let report = receipts.collect_retention(policy).await.unwrap();
    assert_eq!(report.runs_removed, 2, "expired old_run and err_run");
    assert_eq!(
        report.executions_removed, 1,
        "non-reusable orphan error execution removed"
    );

    // Reusable key execution is STILL cached and reusable!
    let cached = receipts.lookup_cached(&reuse_key).await.unwrap();
    assert_eq!(
        cached.map(|execution| execution.id),
        Some(reusable_exec.id),
        "reusable execution must never be dropped by retention"
    );

    // Protected Runs remain readable.
    for kept in [&deferred_run.id, &open_run.id, &live_run.id] {
        assert!(
            crate::store::read_run(&state, kept).await.is_ok(),
            "protected Run {kept} must remain"
        );
    }
    // Expired Runs are gone.
    for gone in [&old_run.id, &err_run.id] {
        assert!(
            crate::store::read_run(&state, gone).await.is_err(),
            "expired Run {gone} should be removed"
        );
    }

    receipts.close().await.unwrap();
}

#[tokio::test]
async fn retention_preserves_newest_terminal_run_per_eval_in_live_checkout() {
    let root = crate::test_os::tempdir();
    let state = root.path().join("state");
    let repo = root.path().join("repo");
    std::fs::create_dir_all(&repo).unwrap();

    let receipts = Receipts::open(&state, &repo).await.unwrap();
    let old_ts = Timestamp::new(OffsetDateTime::now_utc() - time::Duration::days(120)).unwrap();
    let recent_ts = Timestamp::now();
    let ok_result = crate::store::ExecutionResult::Runtime(crate::store::RuntimeResult::exited(
        0,
        String::new,
        std::time::Duration::ZERO,
    ));

    // Old full Run covering evals `app/a` and `app/b`.
    let old_full = sample_run("run-full01", &repo, &state, RunState::Green { at: old_ts });
    let mut req_a = sample_request(
        &old_full.id,
        "a",
        RequestState::completed(ok_result.clone(), old_ts),
        None,
    );
    req_a.eval_id = "app/a".parse().unwrap();
    let mut req_b = sample_request(
        &old_full.id,
        "b",
        RequestState::completed(ok_result.clone(), old_ts),
        None,
    );
    req_b.eval_id = "app/b".parse().unwrap();
    receipts
        .create_run(&old_full, &[req_a, req_b])
        .await
        .unwrap();

    // Newer targeted Run covering only `app/a`.
    let targeted = sample_run(
        "run-part01",
        &repo,
        &state,
        RunState::Green { at: recent_ts },
    );
    let mut req_a2 = sample_request(
        &targeted.id,
        "a",
        RequestState::completed(ok_result, recent_ts),
        None,
    );
    req_a2.eval_id = "app/a".parse().unwrap();
    receipts.create_run(&targeted, &[req_a2]).await.unwrap();

    let policy = StateRetention::new(true, 1, 30).unwrap();
    let report = receipts.collect_retention(policy).await.unwrap();
    assert_eq!(
        report.runs_removed, 0,
        "old full Run is still the newest terminal Run for app/b in a live checkout"
    );
    assert!(crate::store::read_run(&state, &old_full.id).await.is_ok());
    assert!(crate::store::read_run(&state, &targeted.id).await.is_ok());
    receipts.close().await.unwrap();
}

#[tokio::test]
async fn retention_expires_settled_yellow_reclaims_defs_and_dirs_and_prune_removes_orphans() {
    let root = crate::test_os::tempdir();
    let state = root.path().join("state");
    let live_repo = root.path().join("live-repo");
    let gone_repo = root.path().join("gone-repo");
    std::fs::create_dir_all(&live_repo).unwrap();
    std::fs::create_dir_all(&gone_repo).unwrap();

    let receipts = Receipts::open(&state, &live_repo).await.unwrap();
    let old_ts = Timestamp::new(OffsetDateTime::now_utc() - time::Duration::days(120)).unwrap();
    let recent_ts = Timestamp::now();
    let ok_result = crate::store::ExecutionResult::Runtime(crate::store::RuntimeResult::exited(
        0,
        String::new,
        std::time::Duration::ZERO,
    ));

    // 1. Settled YELLOW Run (status=YELLOW, all requests terminal) — MUST expire.
    let mut settled_yellow = sample_run(
        "run-yel001",
        &gone_repo,
        &state,
        RunState::Yellow { at: old_ts },
    );
    settled_yellow.definitions = serde_json::from_value(serde_json::json!({
        "version": 5,
        "artifacts": {
            "old-art": {
                "path": "old-only.md",
                "kind": "file"
            }
        },
        "evals": [],
        "relations": []
    }))
    .unwrap();
    let settled_req = sample_request(
        &settled_yellow.id,
        "1",
        RequestState::completed(ok_result.clone(), old_ts),
        None,
    );
    receipts
        .create_run(&settled_yellow, &[settled_req])
        .await
        .unwrap();
    let settled_dir = state.join("runs").join(settled_yellow.id.as_str());
    std::fs::create_dir_all(settled_dir.join("output")).unwrap();
    std::fs::write(settled_dir.join("output/log.txt"), "expired").unwrap();

    // 2. Unsettled YELLOW Run (status=YELLOW, WAITING_HUMAN request) — MUST stay protected.
    let unsettled_yellow = sample_run(
        "run-yel002",
        &gone_repo,
        &state,
        RunState::Yellow { at: old_ts },
    );
    let mut waiting_req =
        sample_request(&unsettled_yellow.id, "1", RequestState::WaitingHuman, None);
    waiting_req.profile = StoredProfile::Human {};
    waiting_req.requested_profile = StoredProfile::Human {};
    receipts
        .create_run(&unsettled_yellow, &[waiting_req])
        .await
        .unwrap();

    // 3. Retained live Run with its own definition record — MUST keep its definition records.
    let mut live_run = sample_run(
        "run-live02",
        &live_repo,
        &state,
        RunState::Green { at: recent_ts },
    );
    live_run.definitions = serde_json::from_value(serde_json::json!({
        "version": 5,
        "artifacts": {
            "live-art": {
                "path": "live-only.md",
                "kind": "file"
            }
        },
        "evals": [],
        "relations": []
    }))
    .unwrap();
    let live_req = sample_request(
        &live_run.id,
        "1",
        RequestState::completed(ok_result, recent_ts),
        None,
    );
    receipts.create_run(&live_run, &[live_req]).await.unwrap();

    std::fs::remove_dir(&gone_repo).unwrap();

    let policy = StateRetention::new(true, 1, 30).unwrap();
    let report = receipts.collect_retention(policy).await.unwrap();
    assert_eq!(report.runs_removed, 1, "only settled YELLOW Run expires");
    assert_eq!(report.removed_run_ids, vec![settled_yellow.id.clone()]);
    assert!(
        report.definition_records_removed >= 1,
        "unreferenced definition_records from expired Run must be reclaimed"
    );
    assert!(
        crate::store::read_run(&state, &settled_yellow.id)
            .await
            .is_err()
    );
    assert!(
        crate::store::read_run(&state, &unsettled_yellow.id)
            .await
            .is_ok()
    );
    let live_loaded = crate::store::read_run(&state, &live_run.id).await.unwrap();
    assert!(
        live_loaded
            .run
            .definitions
            .graph()
            .and_then(|graph| graph.artifacts.value())
            .is_some_and(|artifacts| artifacts.contains_key("live-art"))
    );

    // Directory cleanup removes the expired Run's `<state>/runs/<id>` tree.
    remove_run_directories(&state, report.removed_run_ids)
        .await
        .unwrap();
    assert!(!settled_dir.exists());

    // Close receipts and verify `prune` also discovers orphaned `<state>/runs/run-*` directories
    // absent from SQLite without mutating `state.sqlite`.
    receipts.close().await.unwrap();
    let orphan_dir = state.join("runs").join("run-orphan01");
    std::fs::create_dir_all(orphan_dir.join("output")).unwrap();
    std::fs::write(orphan_dir.join("output/leftover.txt"), "orphan").unwrap();
    let db_before = std::fs::read(state.join(crate::store::DATABASE)).unwrap();
    let pruned = crate::store::prune::prune(&state, None, None, false).unwrap();
    assert!(
        pruned
            .removed
            .iter()
            .any(|path| path.ends_with("run-orphan01")),
        "prune must remove orphaned run-* directories: {:?}",
        pruned.removed
    );
    assert!(!orphan_dir.exists());
    assert_eq!(
        std::fs::read(state.join(crate::store::DATABASE)).unwrap(),
        db_before,
        "prune must leave state.sqlite byte-for-byte unchanged"
    );
}

#[tokio::test]
async fn retention_preserves_latest_request_attempt_by_sequence_not_completion_time() {
    let root = crate::test_os::tempdir();
    let state = root.path().join("state");
    let repo = root.path().join("repo");
    std::fs::create_dir_all(&repo).unwrap();

    let receipts = Receipts::open(&state, &repo).await.unwrap();
    let earlier_completion =
        Timestamp::new(OffsetDateTime::now_utc() - time::Duration::days(100)).unwrap();
    let later_completion =
        Timestamp::new(OffsetDateTime::now_utc() - time::Duration::days(99)).unwrap();
    let ok_result = crate::store::ExecutionResult::Runtime(crate::store::RuntimeResult::exited(
        0,
        String::new,
        std::time::Duration::ZERO,
    ));

    // Run A is admitted first (lower `sequence`) for `app/a`, but finished later.
    let run_a = sample_run(
        "run-seq001",
        &repo,
        &state,
        RunState::Green {
            at: later_completion,
        },
    );
    let mut req_a = sample_request(
        &run_a.id,
        "a",
        RequestState::completed(ok_result.clone(), later_completion),
        None,
    );
    req_a.eval_id = "app/a".parse().unwrap();
    receipts.create_run(&run_a, &[req_a]).await.unwrap();

    // Run B is admitted second (higher `sequence` — the true `"last"` attempt for `status`)
    // even though its completion timestamp is earlier than Run A's.
    let run_b = sample_run(
        "run-seq002",
        &repo,
        &state,
        RunState::Green {
            at: earlier_completion,
        },
    );
    let mut req_b = sample_request(
        &run_b.id,
        "a",
        RequestState::completed(ok_result, earlier_completion),
        None,
    );
    req_b.eval_id = "app/a".parse().unwrap();
    receipts.create_run(&run_b, &[req_b]).await.unwrap();

    // Run C is a newer Run for a DIFFERENT eval (`app/b`) so it takes the per-repo newest slot.
    let run_c = sample_run(
        "run-seq003",
        &repo,
        &state,
        RunState::Green {
            at: Timestamp::now(),
        },
    );
    let mut req_c = sample_request(
        &run_c.id,
        "b",
        RequestState::completed(
            crate::store::ExecutionResult::Runtime(crate::store::RuntimeResult::exited(
                0,
                String::new,
                std::time::Duration::ZERO,
            )),
            Timestamp::now(),
        ),
        None,
    );
    req_c.eval_id = "app/b".parse().unwrap();
    receipts.create_run(&run_c, &[req_c]).await.unwrap();

    let policy = StateRetention::new(true, 1, 30).unwrap();
    let report = receipts.collect_retention(policy).await.unwrap();
    assert_eq!(report.runs_removed, 1, "only superseded Run A expires");
    assert_eq!(report.removed_run_ids, vec![run_a.id.clone()]);
    assert!(
        crate::store::read_run(&state, &run_b.id).await.is_ok(),
        "Run B has the highest request_attempts.sequence for app/a and must stay"
    );
    assert!(crate::store::read_run(&state, &run_c.id).await.is_ok());
    receipts.close().await.unwrap();
}