use std::{
path::{Path, PathBuf},
time::Duration,
};
use rusqlite::OpenFlags;
use serde::Serialize;
use time::OffsetDateTime;
use super::{DATABASE, STATE_SCHEMA_VERSION, receipts::check_files};
use crate::{platform, process, workspace};
#[derive(Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PruneReport {
#[serde(serialize_with = "crate::platform::serialize_paths")]
pub removed: Vec<PathBuf>,
#[serde(serialize_with = "crate::platform::serialize_paths")]
pub would_remove: Vec<PathBuf>,
pub skipped_runs: Vec<crate::types::RunId>,
pub removed_sessions: Vec<crate::types::SessionId>,
pub would_remove_sessions: Vec<crate::types::SessionId>,
}
const SECONDS_PER_MINUTE: u64 = 60;
const SECONDS_PER_HOUR: u64 = 60 * SECONDS_PER_MINUTE;
const SECONDS_PER_DAY: u64 = 24 * SECONDS_PER_HOUR;
const SECONDS_PER_WEEK: u64 = 7 * SECONDS_PER_DAY;
pub fn parse_duration(value: &str) -> Result<Duration, String> {
let error = || "Use a whole-number duration with s, m, h, d or w (for example 7d).".to_owned();
let split = value
.find(|c: char| !c.is_ascii_digit())
.ok_or_else(error)?;
let multiplier = match &value[split..] {
"s" => 1,
"m" => SECONDS_PER_MINUTE,
"h" => SECONDS_PER_HOUR,
"d" => SECONDS_PER_DAY,
"w" => SECONDS_PER_WEEK,
_ => return Err(error()),
};
let seconds = value[..split]
.parse::<u64>()
.ok()
.and_then(|amount| amount.checked_mul(multiplier))
.filter(|seconds| *seconds <= i64::MAX as u64)
.ok_or_else(error)?;
Ok(Duration::from_secs(seconds))
}
pub fn prune(
state: &Path,
repo: Option<&Path>,
older_than: Option<Duration>,
dry_run: bool,
) -> Result<PruneReport, String> {
let state = platform::resolve_system_aliases(state).map_err(|e| e.to_string())?;
let state = workspace::canonical_target(&real_path(&state)?).map_err(|e| e.to_string())?;
let mut report = PruneReport::default();
let mut repositories = Vec::new();
if let Some(repo) = repo {
repositories.push(workspace::canonical_target(repo).map_err(|e| e.to_string())?);
}
for repo in &repositories {
workspace::outside_workspace(repo, &state).map_err(|e| e.to_string())?;
}
check_files(&state)?;
let bounds = crate::limits::Limits::read(&state)?.agent_sessions();
let sessions = crate::agent::session::collect(&state, bounds, dry_run)?;
if dry_run {
report.would_remove_sessions = sessions.removed.into_iter().collect();
} else {
report.removed_sessions = sessions.removed.into_iter().collect();
}
if !state
.join(DATABASE)
.try_exists()
.map_err(|e| e.to_string())?
{
return Ok(report);
}
let mut db = rusqlite::Connection::open_with_flags(
state.join(DATABASE),
OpenFlags::SQLITE_OPEN_READ_ONLY,
)
.map_err(|e| e.to_string())?;
super::wait_when_busy(&db).map_err(|e| e.to_string())?;
let cutoff = older_than
.map(|age| {
time::Duration::try_from(age)
.ok()
.and_then(|age| OffsetDateTime::now_utc().checked_sub(age))
.ok_or_else(|| "Prune duration is too large.".to_owned())
})
.transpose()?;
let runs_dir = state.join("runs");
let existing_run_dirs = if directory(&runs_dir)? {
list_run_dir_ids(&runs_dir)?
} else {
Vec::new()
};
struct RawRunRow {
id: crate::types::RunId,
repo_text: String,
data: String,
status: crate::types::RunStatus,
requests_terminal: bool,
has_active_execution: bool,
execution_owners: Vec<process::ChildIdentity>,
}
let (raw_rows, known_runs) = {
let transaction = db.transaction().map_err(|e| e.to_string())?;
let version: u32 = transaction
.pragma_query_value(None, "user_version", |row| row.get(0))
.map_err(|e| e.to_string())?;
if version != STATE_SCHEMA_VERSION {
return Err(super::schema_error(version));
}
let mut active_runs = std::collections::BTreeSet::<crate::types::RunId>::new();
{
let mut statement = transaction
.prepare(
"SELECT json_extract(data,'$.provenance.runId') FROM executions WHERE status IN ('RUNNING','WAITING_HUMAN') AND json_valid(data)",
)
.map_err(|e| e.to_string())?;
let rows = statement
.query_map([], |row| row.get::<_, Option<String>>(0))
.map_err(|e| e.to_string())?;
for row in rows {
if let Some(id) = row
.map_err(|e| e.to_string())?
.and_then(|text| text.parse().ok())
{
active_runs.insert(id);
}
}
}
let runs = {
let mut statement = transaction
.prepare("SELECT id,repo,data,status FROM runs ORDER BY id")
.map_err(|e| e.to_string())?;
statement
.query_map([], |row| {
Ok((
row.get::<_, crate::types::RunId>(0)?,
row.get::<_, String>(1)?,
row.get::<_, String>(2)?,
row.get::<_, crate::types::RunStatus>(3)?,
))
})
.map_err(|e| e.to_string())?
.collect::<Result<Vec<_>, _>>()
.map_err(|e| e.to_string())?
};
let mut terminal_check = transaction
.prepare(
"SELECT NOT EXISTS(SELECT 1 FROM requests WHERE run_id=? AND status NOT IN ('GREEN','RED','ERROR','INCOMPLETE','BLOCKED','BUDGET_EXHAUSTED'))",
)
.map_err(|e| e.to_string())?;
let mut execution_owners_query = transaction
.prepare(
"SELECT DISTINCT e.owner_pid,e.owner_start_time,e.status
FROM requests q JOIN executions e ON e.id=q.execution_id
WHERE q.run_id=? AND q.execution_id IS NOT NULL",
)
.map_err(|e| e.to_string())?;
let mut known_runs = std::collections::BTreeSet::new();
let mut raw_rows = Vec::with_capacity(runs.len());
for (id, repo_text, data, status) in runs {
known_runs.insert(id.clone());
let mut has_active_execution = active_runs.contains(&id);
let status_terminal = matches!(
status,
crate::types::RunStatus::Green
| crate::types::RunStatus::Red
| crate::types::RunStatus::Error
| crate::types::RunStatus::Incomplete
);
let requests_terminal = if status_terminal {
terminal_check
.query_row([&id], |row| row.get(0))
.map_err(|e| e.to_string())?
} else {
false
};
let mut execution_owners = Vec::new();
if status_terminal && requests_terminal && !has_active_execution {
let rows = execution_owners_query
.query_map([&id], |row| {
let pid: u32 = row.get(0)?;
let start_time = row.get::<_, i64>(1)? as u64;
let owner =
std::num::NonZeroU32::new(pid).map(|pid| process::ChildIdentity {
pid: process::ProcessId::from(pid),
start_time,
});
Ok((owner, row.get::<_, crate::types::ExecutionStatus>(2)?))
})
.map_err(|e| e.to_string())?;
for row in rows {
let (owner, execution_status) = row.map_err(|e| e.to_string())?;
if !matches!(
execution_status,
crate::types::ExecutionStatus::Green
| crate::types::ExecutionStatus::Red
| crate::types::ExecutionStatus::Error
) {
has_active_execution = true;
}
if let Some(owner) = owner {
execution_owners.push(owner);
}
}
}
raw_rows.push(RawRunRow {
id,
repo_text,
data,
status,
requests_terminal,
has_active_execution,
execution_owners,
});
}
drop(terminal_check);
drop(execution_owners_query);
transaction.commit().map_err(|e| e.to_string())?;
(raw_rows, known_runs)
};
drop(db);
let mut eligible = Vec::new();
let mut alive_cache = std::collections::BTreeMap::<(u32, u64), bool>::new();
for row in raw_rows {
let repo =
artifactize_tools::files::path_from_text(&row.repo_text).map_err(|e| e.to_string())?;
let repo = workspace::canonical_target(&repo).map_err(|e| e.to_string())?;
workspace::outside_workspace(&repo, &state).map_err(|e| e.to_string())?;
repositories.push(repo);
let Some(run) = super::unreadable::evidence::<super::Run>("run", &row.data) else {
report.skipped_runs.push(row.id);
continue;
};
let finished = run.completed_at().map(crate::types::Timestamp::time);
let mut owners = row.execution_owners;
if let Some(control) = &run.control {
match control.worker {
crate::runs::Worker::Starting { launcher } => owners.push(launcher),
crate::runs::Worker::Admitted { owner } => owners.push(owner),
crate::runs::Worker::Legacy => {}
}
owners.extend(control.supervisor);
}
let mut owned = row.has_active_execution;
if !owned
&& row.requests_terminal
&& finished.is_some_and(|date| cutoff.is_none_or(|cutoff| date <= cutoff))
{
for owner in owners {
let key = (owner.pid.get(), owner.start_time);
let alive = match alive_cache.get(&key) {
Some(&alive) => alive,
None => {
let alive = process::is_alive(Some(owner)).map_err(|e| e.to_string())?;
alive_cache.insert(key, alive);
alive
}
};
if alive {
owned = true;
break;
}
}
}
if !eligible_to_prune(row.status, finished, cutoff, row.requests_terminal, owned) {
report.skipped_runs.push(row.id);
} else {
eligible.push(row.id);
}
}
if !directory(&runs_dir)? {
return Ok(report);
}
let mut targets = Vec::new();
for id in eligible {
let path = runs_dir.join(id.as_str());
if directory(&path)? {
collect(&path, &mut targets)?;
}
}
for id in existing_run_dirs {
if known_runs.contains(&id) {
continue;
}
let path = runs_dir.join(id.as_str());
if !directory(&path)? {
continue;
}
if let Some(cutoff) = cutoff {
let modified = std::fs::symlink_metadata(&path)
.ok()
.and_then(|meta| meta.modified().ok())
.map(OffsetDateTime::from);
if !modified.is_some_and(|time| time <= cutoff) {
continue;
}
}
targets.push(path);
}
for path in &targets {
validate_tree(path, &runs_dir, &repositories)?;
}
for path in targets {
if dry_run {
report.would_remove.push(path);
} else {
real_path(&path)?;
validate_tree(&path, &runs_dir, &repositories)?;
platform::remove_tree(&path)
.map_err(|e| format!("Cannot prune {}: {e}", crate::platform::path_text(&path)))?;
report.removed.push(path);
}
}
Ok(report)
}
pub(super) fn remove_expired_run_dirs(
state: &Path,
ids: &[crate::types::RunId],
) -> Result<(), String> {
let state = platform::resolve_system_aliases(state).map_err(|e| e.to_string())?;
let state = workspace::canonical_target(&real_path(&state)?).map_err(|e| e.to_string())?;
let runs_dir = state.join("runs");
if !directory(&runs_dir)? {
return Ok(());
}
for id in ids {
let path = runs_dir.join(id.as_str());
if !directory(&path)? {
continue;
}
real_path(&path)?;
validate_tree(&path, &runs_dir, &[])?;
platform::remove_tree(&path).map_err(|e| {
format!(
"Cannot remove expired Run directory {}: {e}",
crate::platform::path_text(&path)
)
})?;
}
Ok(())
}
fn list_run_dir_ids(runs_dir: &Path) -> Result<Vec<crate::types::RunId>, String> {
let handle = platform::open_directory(runs_dir).map_err(|e| e.to_string())?;
let mut ids = Vec::new();
for entry in platform::read_dir(&handle).map_err(|e| e.to_string())? {
let entry = entry.map_err(|e| e.to_string())?;
let name = entry.file_name();
if let Some(text) = crate::platform::os_text(&name)
&& let Ok(id) = text.parse::<crate::types::RunId>()
{
ids.push(id);
}
}
ids.sort();
Ok(ids)
}
fn eligible_to_prune(
status: crate::types::RunStatus,
finished: Option<time::OffsetDateTime>,
cutoff: Option<time::OffsetDateTime>,
requests_terminal: bool,
owned: bool,
) -> bool {
use crate::types::RunStatus;
matches!(
status,
RunStatus::Green | RunStatus::Red | RunStatus::Error | RunStatus::Incomplete
) && finished.is_some_and(|date| cutoff.is_none_or(|cutoff| date <= cutoff))
&& requests_terminal
&& !owned
}
fn segment(value: &str) -> bool {
!value.is_empty()
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
}
fn prefixed(name: &str, prefix: &str) -> bool {
name.strip_prefix(prefix).is_some_and(segment)
}
fn collect(parent: &Path, targets: &mut Vec<PathBuf>) -> Result<(), String> {
let parent_handle = platform::open_directory(parent).map_err(|e| e.to_string())?;
let mut entries = platform::read_dir(&parent_handle)
.map_err(|e| e.to_string())?
.collect::<Result<Vec<_>, _>>()
.map_err(|e| e.to_string())?;
entries.sort_by_key(|entry| entry.file_name());
for entry in entries {
let name = entry.file_name();
let Some(name) = crate::platform::os_text(&name) else {
continue;
};
let path = parent.join(entry.file_name());
if matches!(name, "output" | "tmp" | "home" | "cache" | "human-tools")
|| ["tool-output-", "tool-"]
.iter()
.any(|prefix| prefixed(name, prefix))
{
if directory(&path)? {
targets.push(path);
}
} else if ["runtime-", "fingerprint-"]
.iter()
.any(|prefix| prefixed(name, prefix))
&& directory(&path)?
{
collect(&path, targets)?;
}
}
Ok(())
}
fn directory(path: &Path) -> Result<bool, String> {
match platform::path_kind(path) {
Ok(platform::FileKind::Directory) => {
reject_repository(path)?;
Ok(true)
}
Ok(_) => Err(format!(
"Prune requires a real directory, not a symlink or file: {}",
crate::platform::path_text(path)
)),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error.to_string()),
}
}
fn real_path(path: &Path) -> Result<PathBuf, String> {
platform::paths::absolute_without_links(path).map_err(|refusal| match refusal {
platform::paths::LinkedPath::ParentTraversal => {
"Prune paths must not contain parent traversal.".to_owned()
}
platform::paths::LinkedPath::Link(path) => {
format!("Prune refuses symlinks: {}", platform::path_text(&path))
}
platform::paths::LinkedPath::Io(error) => error.to_string(),
})
}
fn reject_repository(path: &Path) -> Result<(), String> {
if workspace::has_artifact_marker(path).map_err(|error| error.to_string())? {
return Err(format!(
"Prune refuses repository content: {}",
crate::platform::path_text(path)
));
}
match platform::path_kind(&path.join(".git")) {
Ok(_) => Err(format!(
"Prune refuses repository content: {}",
crate::platform::path_text(path)
)),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.to_string()),
}
}
fn validate_tree(path: &Path, runs: &Path, repositories: &[PathBuf]) -> Result<(), String> {
let kind = platform::path_kind(path).map_err(|e| e.to_string())?;
if matches!(
kind,
platform::FileKind::Symlink | platform::FileKind::Other
) {
return Err(format!(
"Prune refuses symlinks: {}",
crate::platform::path_text(path)
));
}
if !platform::is_within(path, runs)
|| platform::paths_equal(path, runs)
|| repositories
.iter()
.any(|repo| platform::is_within(path, repo) || platform::is_within(repo, path))
{
return Err(format!(
"Prune target is outside Run output or overlaps a repository: {}",
crate::platform::path_text(path)
));
}
if kind == platform::FileKind::Directory {
reject_repository(path)?;
let directory = platform::open_directory(path).map_err(|e| e.to_string())?;
for entry in platform::read_dir(&directory).map_err(|e| e.to_string())? {
validate_tree(
&path.join(entry.map_err(|e| e.to_string())?.file_name()),
runs,
repositories,
)?;
}
}
Ok(())
}