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
//! Bounded retention of old terminal Runs in the state database.
//!
//! Retention never drops:
//! - reusable executions in key history (`completed_at IS NOT NULL`),
//! - open Runs (`RUNNING` / `WAITING_HUMAN`) or Runs with unsettled requests (`QUEUED`,
//!   `RUNNING`, `WAITING_HUMAN`, `DEFERRED`),
//! - the newest terminal Run of every checkout directory that still exists on disk,
//! - the newest recorded attempt for every `(repo, eval_id)` in a live checkout,
//! - any execution still referenced by a retained request,
//! - any `definition_records` row still referenced by a retained Run's definitions.
//!
//! Each phase runs in its own short `connection.call` so concurrent Runs sharing the Verify
//! engine's SQLite connection are never stalled behind filesystem probes or multi-batch deletes.

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},
};

/// Seconds in one 24-hour day for `maxAgeDays` cutoff math.
const SECONDS_PER_DAY: i64 = 24 * 60 * 60;
/// Maximum Runs deleted inside one IMMEDIATE write transaction.
const RUN_DELETE_BATCH: usize = 32;
/// Maximum unreferenced non-reusable executions or orphan definition records deleted per transaction.
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 {
    /// Expire old terminal Runs beyond `policy` on this writer connection and reclaim free
    /// pages incrementally without holding long write locks.
    #[cfg(test)]
    pub(crate) async fn collect_retention(&self, policy: StateRetention) -> Result<Report, String> {
        self.collect_retention_with_candidates(policy, Vec::new())
            .await
    }

    /// Expire old terminal Runs beyond `policy`, also pruning any non-reusable executions in
    /// `extra_executions` (such as entries just evicted from key history) without scanning
    /// the full `executions` table.
    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();

        // Phase 1: short read-only snapshot to gather Run metadata.
        let runs = self
            .connection
            .call(read_saved_runs)
            .await
            .map_err(|e| e.to_string())?;

        // Phase 2: filesystem presence checks and pure selection off the DB worker thread.
        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?;

        // Phase 2b: protect the newest recorded attempt for every `(repo, eval_id)` in live
        // checkouts using the indexed `request_attempts` table, matching `status`'s lookup.
        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();

        // Phase 3: delete expired Runs in small IMMEDIATE batches, yielding between batches
        // and capturing candidate execution IDs from deleted requests via RETURNING.
        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);
        }

        // Phase 4: remove unreferenced, non-reusable, inactive executions strictly from the
        // captured candidate set (O(deleted + evicted), never a full-table scan over `executions`).
        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())?;
        }

        // Phase 5: remove definition_records no longer referenced by any retained run_definitions
        // row (only when Runs were actually removed).
        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 {
                // A newly admitted body could not be parsed; stop deleting immediately.
                break;
            };
            removed += batch_removed;
        }
        Ok(removed)
    }
}

/// Remove `<state>/runs/<id>` scratch trees for Runs deleted by retention, outside SQLite.
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()? {
        // Tolerate individual unreadable rows so one corrupt record cannot block retention.
        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)?;
    {
        // YELLOW Runs remain `'YELLOW'` in `runs.status` even after every Human sign-off
        // settles; the `NOT EXISTS` guard strictly protects any unsettled sign-off.
        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)
}

/// Pure retention selection over Runs ordered newest-first.
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;
        }
        // Always retain the newest terminal Run for every checkout that still exists on disk.
        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
}

/// For each live checkout, find the Run owning the newest recorded attempt for every `eval_id`
/// in `request_attempts` (ordered by `sequence DESC`, matching `status`'s `"last"` lookup).
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>,
}

/// Phase A (short read snapshot): collect all live hashes reachable from `run_definitions.body`
/// and all unreferenced hashes in `definition_records`. Returns `Ok(None)` if any live body is
/// missing or unparseable so retention never deletes potentially-referenced definition records.
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 }))
}

/// Phase B (short IMMEDIATE write): re-check that no newly admitted Run referenced any
/// candidate between Phase A and this commit before deleting. Returns `Ok(None)` if any
/// newly-seen body fails to parse.
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;