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();
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();
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();
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();
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();
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();
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"
);
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"
);
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"
);
}
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,
));
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();
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,
));
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();
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();
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"))
);
remove_run_directories(&state, report.removed_run_ids)
.await
.unwrap();
assert!(!settled_dir.exists());
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,
));
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();
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();
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();
}