use std::{
collections::{BTreeMap, BTreeSet},
path::{Path, PathBuf},
};
use rusqlite::{Connection, OptionalExtension, params};
use time::OffsetDateTime;
use crate::{
limits::StateRetention,
store::{
Receipts,
receipts::{Error, connection::INCREMENTAL_VACUUM_PAGES},
run_record,
},
types::{ExecutionId, RunId, RunStatus, Sha256Digest, Timestamp},
};
const SECONDS_PER_DAY: i64 = 24 * 60 * 60;
const RUN_DELETE_BATCH: usize = 32;
const ORPHAN_DELETE_BATCH: usize = 512;
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub(crate) struct Report {
pub runs_removed: usize,
pub removed_run_ids: Vec<RunId>,
pub executions_removed: usize,
pub definition_records_removed: usize,
}
#[derive(Debug)]
struct SavedRun {
id: RunId,
repo: PathBuf,
status: RunStatus,
completed_at: Option<Timestamp>,
has_unsettled: bool,
}
impl Receipts {
#[cfg(test)]
pub(crate) async fn collect_retention(&self, policy: StateRetention) -> Result<Report, String> {
self.collect_retention_with_candidates(policy, Vec::new())
.await
}
pub(crate) async fn collect_retention_with_candidates(
&self,
policy: StateRetention,
extra_executions: Vec<ExecutionId>,
) -> Result<Report, String> {
if !policy.enabled() {
return Ok(Report::default());
}
let now = OffsetDateTime::now_utc();
let runs = self
.connection
.call(read_saved_runs)
.await
.map_err(|e| e.to_string())?;
let (mut expired, live_repos) = crate::task::blocking(move || {
let live_repos: BTreeSet<PathBuf> = runs
.iter()
.map(|run| &run.repo)
.collect::<BTreeSet<_>>()
.into_iter()
.filter(|repo| repo.is_dir())
.cloned()
.collect();
let expired = expired_runs(&runs, &live_repos, policy, now);
(expired, live_repos)
})
.await?;
if !expired.is_empty() && !live_repos.is_empty() {
let protected = self
.connection
.call(move |db| latest_eval_runs(db, &live_repos))
.await
.map_err(|e| e.to_string())?;
expired.retain(|id| !protected.contains(id));
}
let mut report = Report::default();
let mut candidate_executions: BTreeSet<ExecutionId> =
extra_executions.into_iter().collect();
for batch in expired.chunks(RUN_DELETE_BATCH) {
let batch = batch.to_vec();
let (removed_ids, deleted_execs) = self
.connection
.call(move |db| delete_run_batch(db, &batch))
.await
.map_err(|e| e.to_string())?;
report.runs_removed += removed_ids.len();
report.removed_run_ids.extend(removed_ids);
candidate_executions.extend(deleted_execs);
}
let candidates: Vec<ExecutionId> = candidate_executions.into_iter().collect();
for batch in candidates.chunks(ORPHAN_DELETE_BATCH) {
let batch = batch.to_vec();
report.executions_removed += self
.connection
.call(move |db| delete_orphan_execution_batch(db, &batch))
.await
.map_err(|e| e.to_string())?;
}
if report.runs_removed > 0 {
report.definition_records_removed = self.collect_orphan_definitions().await?;
}
if report.runs_removed > 0
|| report.executions_removed > 0
|| report.definition_records_removed > 0
{
let _ = self
.connection
.call(|db| -> Result<(), Error> {
let _ = db.execute_batch(&format!(
"PRAGMA incremental_vacuum({INCREMENTAL_VACUUM_PAGES});
PRAGMA wal_checkpoint(PASSIVE);"
));
Ok(())
})
.await;
}
Ok(report)
}
async fn collect_orphan_definitions(&self) -> Result<usize, String> {
let Some(OrphanDefinitions { live, orphans }) = self
.connection
.call(find_orphan_definitions)
.await
.map_err(|e| e.to_string())?
else {
return Ok(0);
};
if orphans.is_empty() {
return Ok(0);
}
let live = std::sync::Arc::new(live);
let mut removed = 0;
for batch in orphans.chunks(ORPHAN_DELETE_BATCH) {
let live = live.clone();
let batch = batch.to_vec();
let Some(batch_removed) = self
.connection
.call(move |db| delete_orphan_definition_batch(db, &live, &batch))
.await
.map_err(|e| e.to_string())?
else {
break;
};
removed += batch_removed;
}
Ok(removed)
}
}
pub(crate) async fn remove_run_directories(state: &Path, ids: Vec<RunId>) -> Result<(), String> {
if ids.is_empty() {
return Ok(());
}
let state = state.to_path_buf();
crate::task::blocking(move || super::prune::remove_expired_run_dirs(&state, &ids)).await?
}
fn read_saved_runs(db: &mut Connection) -> Result<Vec<SavedRun>, Error> {
let transaction = db.transaction()?;
let mut statement = transaction.prepare(
"SELECT r.id, r.repo, r.status,
CASE WHEN json_valid(r.data) THEN json_extract(r.data,'$.completedAt') END,
EXISTS(SELECT 1 FROM requests q WHERE q.run_id=r.id
AND q.status IN ('QUEUED','RUNNING','WAITING_HUMAN','DEFERRED'))
FROM runs r
ORDER BY r.rowid DESC",
)?;
let mut runs = Vec::new();
let mut rows = statement.query([])?;
while let Some(row) = rows.next()? {
let Ok(id) = row.get::<_, RunId>(0) else {
continue;
};
let Ok(repo) = super::path_column(row, 1) else {
continue;
};
let Ok(status) = row.get::<_, RunStatus>(2) else {
continue;
};
let completed: Option<String> = row.get(3).ok().flatten();
let completed_at = completed.and_then(|text| text.parse::<Timestamp>().ok());
let has_unsettled: bool = row.get(4)?;
runs.push(SavedRun {
id,
repo,
status,
completed_at,
has_unsettled,
});
}
drop(rows);
drop(statement);
transaction.commit()?;
Ok(runs)
}
fn delete_run_batch(
db: &mut Connection,
batch: &[RunId],
) -> Result<(Vec<RunId>, Vec<ExecutionId>), Error> {
let mut removed_ids = Vec::new();
let mut candidate_executions = Vec::new();
let transaction = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
{
let mut still_safe = transaction.prepare_cached(
"SELECT status IN ('GREEN','RED','YELLOW','ERROR','INCOMPLETE')
AND NOT EXISTS(SELECT 1 FROM requests q WHERE q.run_id=?1
AND q.status IN ('QUEUED','RUNNING','WAITING_HUMAN','DEFERRED'))
FROM runs WHERE id=?1",
)?;
let mut delete_requests = transaction
.prepare_cached("DELETE FROM requests WHERE run_id=?1 RETURNING execution_id")?;
let mut delete_defs =
transaction.prepare_cached("DELETE FROM run_definitions WHERE run_id=?1")?;
let mut delete_run = transaction.prepare_cached("DELETE FROM runs WHERE id=?1")?;
for id in batch {
let ok: bool = still_safe
.query_row([id], |row| row.get(0))
.optional()?
.unwrap_or(false);
if !ok {
continue;
}
let exec_rows =
delete_requests.query_map([id], |row| row.get::<_, Option<ExecutionId>>(0))?;
for exec_id in exec_rows {
if let Some(exec_id) = exec_id? {
candidate_executions.push(exec_id);
}
}
delete_defs.execute([id])?;
if delete_run.execute([id])? == 1 {
removed_ids.push(id.clone());
}
}
}
transaction.commit()?;
Ok((removed_ids, candidate_executions))
}
fn delete_orphan_execution_batch(
db: &mut Connection,
batch: &[ExecutionId],
) -> Result<usize, Error> {
let transaction = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
let mut removed = 0;
{
let mut delete = transaction.prepare_cached(
"DELETE FROM executions
WHERE id=?1
AND completed_at IS NULL
AND status NOT IN ('RUNNING','WAITING_HUMAN')
AND NOT EXISTS(SELECT 1 FROM requests q WHERE q.execution_id=executions.id)",
)?;
for id in batch {
removed += delete.execute([id])?;
}
}
transaction.commit()?;
Ok(removed)
}
fn expired_runs(
runs: &[SavedRun],
live_repos: &BTreeSet<PathBuf>,
policy: StateRetention,
now: OffsetDateTime,
) -> Vec<RunId> {
let cutoff = now - time::Duration::seconds(policy.max_age_days() as i64 * SECONDS_PER_DAY);
let mut kept_newest_for_repo: BTreeSet<&PathBuf> = BTreeSet::new();
let mut kept_terminal: u64 = 0;
let mut expired = Vec::new();
for run in runs {
let terminal = matches!(
run.status,
RunStatus::Green
| RunStatus::Red
| RunStatus::Yellow
| RunStatus::Error
| RunStatus::Incomplete
);
if !terminal || run.has_unsettled {
continue;
}
if live_repos.contains(&run.repo) && kept_newest_for_repo.insert(&run.repo) {
kept_terminal += 1;
continue;
}
let too_old = run
.completed_at
.is_some_and(|completed| completed.time() < cutoff);
if kept_terminal >= policy.max_runs() || too_old {
expired.push(run.id.clone());
} else {
kept_terminal += 1;
}
}
expired
}
fn latest_eval_runs(
db: &mut Connection,
live_repos: &BTreeSet<PathBuf>,
) -> Result<BTreeSet<RunId>, Error> {
let transaction = db.transaction()?;
let mut evals_for_repo =
transaction.prepare("SELECT DISTINCT eval_id FROM request_attempts WHERE repo=?1")?;
let mut latest_run = transaction.prepare(
"SELECT q.run_id
FROM request_attempts a
JOIN requests q ON q.id = a.request_id
WHERE a.repo = ?1 AND a.eval_id = ?2
ORDER BY a.sequence DESC
LIMIT 1",
)?;
let mut protected = BTreeSet::new();
for repo in live_repos {
let repo_text = crate::platform::path_text(repo);
let eval_ids = evals_for_repo
.query_map([&repo_text], |row| row.get::<_, String>(0))?
.collect::<Result<Vec<_>, _>>()?;
for eval_id in eval_ids {
if let Some(run_id) = latest_run
.query_row(params![&repo_text, &eval_id], |row| row.get::<_, RunId>(0))
.optional()?
{
protected.insert(run_id);
}
}
}
drop(latest_run);
drop(evals_for_repo);
transaction.commit()?;
Ok(protected)
}
struct OrphanDefinitions {
live: BTreeSet<String>,
orphans: Vec<String>,
}
fn find_orphan_definitions(db: &mut Connection) -> Result<Option<OrphanDefinitions>, Error> {
let transaction = db.transaction()?;
let bodies: Vec<String> = {
let mut statement = transaction
.prepare("SELECT DISTINCT body FROM run_definitions WHERE body IS NOT NULL")?;
statement
.query_map([], |row| row.get(0))?
.collect::<Result<Vec<_>, _>>()?
};
let mut live = BTreeSet::<String>::new();
let complete = {
let mut read_body =
transaction.prepare("SELECT data FROM definition_records WHERE hash=?1")?;
let mut ok = true;
for body_hash in &bodies {
live.insert(body_hash.clone());
let Some(body_text): Option<String> = read_body
.query_row([body_hash], |row| row.get(0))
.optional()?
else {
ok = false;
break;
};
let Ok(referenced) = run_record::records::all_referenced(&body_text) else {
ok = false;
break;
};
for hash in referenced {
live.insert(Sha256Digest::as_str(&hash).to_owned());
}
}
ok
};
if !complete {
transaction.commit()?;
return Ok(None);
}
let mut orphans = Vec::new();
{
let mut all_hashes = transaction.prepare("SELECT hash FROM definition_records")?;
let rows = all_hashes.query_map([], |row| row.get::<_, String>(0))?;
for row in rows {
let hash = row?;
if !live.contains(&hash) {
orphans.push(hash);
}
}
}
transaction.commit()?;
Ok(Some(OrphanDefinitions { live, orphans }))
}
fn delete_orphan_definition_batch(
db: &mut Connection,
known_live: &BTreeSet<String>,
batch: &[String],
) -> Result<Option<usize>, Error> {
let transaction = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
let newly_referenced: BTreeMap<String, ()> = {
let mut statement = transaction
.prepare("SELECT DISTINCT body FROM run_definitions WHERE body IS NOT NULL")?;
let mut extra = BTreeMap::new();
let rows = statement.query_map([], |row| row.get::<_, String>(0))?;
let mut read_body =
transaction.prepare("SELECT data FROM definition_records WHERE hash=?1")?;
for row in rows {
let body_hash = row?;
if known_live.contains(&body_hash) {
continue;
}
extra.insert(body_hash.clone(), ());
let Some(body_text): Option<String> = read_body
.query_row([&body_hash], |row| row.get::<_, String>(0))
.optional()?
else {
return Ok(None);
};
let Ok(referenced) = run_record::records::all_referenced(&body_text) else {
return Ok(None);
};
for hash in referenced {
extra.insert(hash.as_str().to_owned(), ());
}
}
extra
};
let mut removed = 0;
{
let mut delete =
transaction.prepare_cached("DELETE FROM definition_records WHERE hash=?1")?;
for hash in batch {
if !newly_referenced.contains_key(hash) {
removed += delete.execute([hash])?;
}
}
}
transaction.commit()?;
Ok(Some(removed))
}
#[cfg(test)]
#[path = "tests/retention.rs"]
mod tests;