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
//! The key history: every completed GREEN/RED execution of a reuse key whose history columns
//! (`completed_at`, `bytes`, `last_used`) are set. The latest by completion time is the one
//! reused; the cache GC and `cache rm` clear the columns and keep the execution.

use std::path::Path;

use rusqlite::{OpenFlags, params};
use serde::Serialize;
use tokio_rusqlite::Connection;

use super::{
    DATABASE, Execution,
    receipts::{Error, NotifyingConnection, schema_initialized},
};

/// Bound the history no checkout reuses now: records a newer one of the same eval and checkout
/// replaced, and the records of checkouts that are gone. Eviction preserves execution audit.
pub const MAX_ENTRIES: i64 = 10_000;
/// Bound those records' JSON payload bytes independently of the record-count ceiling.
pub const MAX_BYTES: i64 = 1024 * 1024 * 1024;
/// Refuse one oversized reusable record rather than letting it monopolize cache storage.
pub const MAX_ENTRY_BYTES: usize = 16 * 1024 * 1024;
/// Bound each eviction write batch so cache collection never holds the SQLite write lock
/// for long stretches while other operations are active.
const EVICT_BATCH: usize = 256;

/// A record of the key history, of executions `e`.
pub(super) const RECORD: &str =
    "e.completed_at IS NOT NULL AND e.status IN ('GREEN','RED') AND e.key IS NOT NULL";

/// The latest record of a key first: the newest completion, then the most recently stored.
pub(super) const LATEST: &str = "e.completed_at DESC, e.rowid DESC";

/// One record of a key's history, or with `cache list` the latest record of each key.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Entry {
    pub key: crate::types::ReuseKey,
    pub eval_def_hash: crate::types::DefinitionHash,
    pub execution_id: crate::types::ExecutionId,
    pub verdict: crate::types::ExecutionStatus,
    #[serde(with = "crate::platform::path_serde")]
    pub repo_path: std::path::PathBuf,
    pub eval_id: crate::types::EvalId,
    /// The target Artifact's fingerprint.
    pub fingerprint: Option<crate::types::Fingerprint>,
    pub completed_at: Option<crate::types::Timestamp>,
    /// `user@host` of the machine that produced the result.
    pub producer: Option<crate::types::ProducerId>,
    /// The named profile a Run chose instead of the eval's own, on results saved before
    /// profiles chose their settings from the environment.
    pub variant: Option<crate::config::ProfileName>,
    /// The remote store URL of a mirrored record.
    pub origin: Option<crate::types::StoreUrl>,
    /// How many records the key holds.
    pub records: i64,
    pub bytes: i64,
    pub last_used: crate::types::Timestamp,
}

async fn open(state: &Path, writable: bool) -> Result<Option<NotifyingConnection>, String> {
    let state = crate::workspace::canonical_target(state).map_err(|e| e.to_string())?;
    super::receipts::check_files(&state)?;
    let path = state.join(DATABASE);
    if !path.try_exists().map_err(|e| e.to_string())? {
        return Ok(None);
    }
    let connection = Connection::open_with_flags(
        path,
        if writable {
            OpenFlags::SQLITE_OPEN_READ_WRITE
        } else {
            OpenFlags::SQLITE_OPEN_READ_ONLY
        },
    )
    .await
    .map_err(|e| e.to_string())?;
    let connection = NotifyingConnection::new(connection, &state);
    let initialized = connection
        .call(move |db| -> Result<bool, Error> {
            super::wait_when_busy(db)?;
            if writable {
                super::receipts::connection::configure_wal_writer(db)?;
                // Standalone cache removal is infrequent; prefer FULL durability before exit.
                db.pragma_update(None, "synchronous", "FULL")?;
            }
            let transaction = db.transaction()?;
            schema_initialized(&transaction)
        })
        .await
        .map_err(|e| e.to_string());
    match initialized {
        Ok(true) => Ok(Some(connection)),
        result => connection.finish(result.map(|_| None)).await,
    }
}

/// The latest record of every key, or with `history` every record, latest first per key.
pub async fn list(state: &Path, history: bool) -> Result<Vec<Entry>, String> {
    let Some(connection) = open(state, false).await? else {
        return Ok(Vec::new());
    };
    let result = connection
        .call(move |db| -> Result<_, Error> {
            let mut statement = db.prepare(&format!(
                "SELECT * FROM (SELECT e.key,e.eval_def_hash,e.id,e.status,json_extract(e.data,'$.provenance.repoPath'),json_extract(e.data,'$.provenance.evalId'),json_extract(e.data,'$.fingerprint'),json_extract(e.data,'$.completedAt'),json_extract(e.data,'$.origin.store'),count(*) OVER (PARTITION BY e.key),e.bytes,e.last_used,row_number() OVER (PARTITION BY e.key ORDER BY {LATEST}) AS rank,e.data FROM executions e WHERE {RECORD}) WHERE ?1 OR rank=1 ORDER BY 1,rank"
            ))?;
            Ok(statement
                .query_map([history], |row| {
                    let id: crate::types::ExecutionId = row.get(2)?;
                    let data: String = row.get(13)?;
                    let Some(execution) =
                        super::unreadable::evidence::<Execution>("execution", &data)
                    else {
                        return Ok(None);
                    };
                    Ok(Some(Entry {
                        key: row.get(0)?,
                        eval_def_hash: row.get(1)?,
                        execution_id: id,
                        verdict: row.get(3)?,
                        repo_path: row.get::<_, String>(4)?.into(),
                        eval_id: row.get(5)?,
                        fingerprint: row.get(6)?,
                        completed_at: row.get(7)?,
                        producer: execution.producer.map(|producer| producer.name),
                        variant: execution.options.variant,
                        origin: row.get(8)?,
                        records: row.get(9)?,
                        bytes: row.get(10)?,
                        last_used: row.get(11)?,
                    }))
                })?
                .filter_map(|row| row.transpose())
                .collect::<Result<_, _>>()?)
        })
        .await
        .map_err(|e| e.to_string());
    connection.finish(result).await
}

/// A key's records, latest first; without `history` only the latest.
pub async fn show(state: &Path, key: &str, history: bool) -> Result<Vec<Execution>, String> {
    let Some(connection) = open(state, false).await? else {
        return Ok(Vec::new());
    };
    let Ok(key) = key.parse::<crate::types::ReuseKey>() else {
        return connection.finish(Ok(Vec::new())).await;
    };
    let result = connection
        .call(move |db| -> Result<_, Error> {
            let mut statement = db.prepare(&format!(
                "SELECT e.data FROM executions e WHERE e.key=? AND {RECORD} ORDER BY {LATEST} LIMIT ?"
            ))?;
            statement
                .query_map(params![key, if history { -1 } else { 1 }], |row| {
                    row.get::<_, String>(0)
                })?
                .filter_map(|row| match row {
                    Ok(data) => super::unreadable::evidence("execution", &data).map(Ok),
                    Err(error) => Some(Err(Error::Sql(error))),
                })
                .collect()
        })
        .await
        .map_err(|e| e.to_string());
    connection.finish(result).await
}

/// The latest locally produced record (never a mirror) of each key after `after`, in key order.
pub(crate) async fn local(
    state: &Path,
    after: Option<crate::types::ReuseKey>,
    limit: usize,
) -> Result<Vec<(crate::types::ReuseKey, Execution)>, String> {
    let Some(connection) = open(state, false).await? else {
        return Ok(Vec::new());
    };
    let result = connection
        .call(move |db| -> Result<_, Error> {
            let mut statement = db.prepare(&format!(
                "SELECT key,data FROM (SELECT e.key,e.data,row_number() OVER (PARTITION BY e.key ORDER BY {LATEST}) AS rank FROM executions e WHERE {RECORD} AND json_extract(e.data,'$.origin') IS NULL AND e.key>?) WHERE rank=1 ORDER BY key LIMIT ?"
            ))?;
            let mut rows = statement.query(params![
                after.as_ref().map_or("", crate::types::ReuseKey::as_str),
                limit as i64
            ])?;
            let mut page = Vec::new();
            while let Some(row) = rows.next()? {
                let key: crate::types::ReuseKey = row.get(0)?;
                let data: String = row.get(1)?;
                let execution: Execution = super::unreadable::decode("execution", key.as_str(), &data)
                    .map_err(Error::Unreadable)?;
                if execution.key.as_ref() != Some(&key) {
                    return Err(Error::Invalid(format!("Cached execution {} does not have its indexed reuse key {key}.", execution.id)));
                }
                page.push((key, execution));
            }
            Ok(page)
        })
        .await
        .map_err(|e| e.to_string());
    connection.finish(result).await
}

/// Remove every record of an unused key from its history, preserving executions and Runs.
pub async fn remove(state: &Path, key: &str) -> Result<bool, String> {
    let Some(connection) = open(state, true).await? else {
        return Ok(false);
    };
    let Ok(key) = key.parse::<crate::types::ReuseKey>() else {
        return connection.finish(Ok(false)).await;
    };
    let result = connection
        .call(move |db| -> Result<bool, Error> {
            let transaction =
                db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
            let in_use: bool = transaction.query_row(
                "SELECT EXISTS(SELECT 1 FROM executions WHERE key=?1 AND status IN ('RUNNING','WAITING_HUMAN')) OR EXISTS(SELECT 1 FROM requests q JOIN executions e ON e.id=q.execution_id WHERE e.key=?1 AND e.completed_at IS NOT NULL AND q.status IN ('QUEUED','RUNNING','WAITING_HUMAN'))",
                [&key],
                |row| row.get(0),
            )?;
            if in_use {
                return Err(Error::Invalid(format!(
                    "Key {key} is in use by an active execution or waiter."
                )));
            }
            let removed = transaction.execute(
                "UPDATE executions SET completed_at=NULL,bytes=NULL,last_used=NULL WHERE key=? AND completed_at IS NOT NULL",
                [&key],
            )?;
            transaction.commit()?;
            Ok(removed != 0)
        })
        .await
        .map_err(|e| e.to_string());
    connection.finish(result).await
}

/// The history columns of a completed record: its sortable completion time and size, or
/// `None` when it does not join its key's history (no key, no verdict, or over the entry
/// limit).
pub(super) fn columns(
    execution: &Execution,
    bytes: usize,
) -> Result<Option<(crate::types::Timestamp, i64)>, Error> {
    let (Some(_), Some(_), Some(completed_at)) = (
        &execution.key,
        execution.verdict(),
        &execution.completed_at(),
    ) else {
        return Ok(None);
    };
    if bytes > MAX_ENTRY_BYTES {
        return Ok(None);
    }
    Ok(Some((*completed_at, bytes as i64)))
}

/// Mark a reused record as used now.
pub(super) fn touch(
    db: &rusqlite::Connection,
    execution_id: &crate::types::ExecutionId,
    at: crate::types::Timestamp,
) -> Result<(), Error> {
    db.execute(
        "UPDATE executions SET last_used=? WHERE id=? AND completed_at IS NOT NULL",
        params![at, execution_id],
    )?;
    Ok(())
}

/// The caps [`collect`] keeps the history no checkout reuses now within.
#[derive(Debug, Clone, Copy)]
struct Caps {
    entries: i64,
    bytes: i64,
}

const CAPS: Caps = Caps {
    entries: MAX_ENTRIES,
    bytes: MAX_BYTES,
};

/// Collect the key history once a Run has finished. The newest record of each eval in each
/// checkout that still exists is what that checkout's next verify reuses, so it stays whatever
/// the caps: one large project evicts neither another project's results nor its own. The
/// other records stay within [`MAX_ENTRIES`] and [`MAX_BYTES`], the least recently used
/// leaving first and Human sign-offs last. Records of a key with an active execution, and
/// records an in-flight request waits for, stay as well.
impl super::Receipts {
    /// Collect key history on this writer connection without opening a second connection or
    /// blocking the SQLite worker thread across filesystem checks or large write batches.
    /// Returns the execution IDs evicted from key history in this pass.
    pub(crate) async fn collect_history(&self) -> Result<Vec<crate::types::ExecutionId>, String> {
        let records = self
            .connection
            .call(read_history_records)
            .await
            .map_err(|e| e.to_string())?;
        let evicted = crate::task::blocking(move || {
            let present = live_checkouts(&records);
            eviction_candidates(&records, &present, CAPS)
                .into_iter()
                .map(|record| (record.id.clone(), record.last_used_raw.clone()))
                .collect::<Vec<_>>()
        })
        .await?;
        let mut removed = Vec::new();
        for batch in evicted.chunks(EVICT_BATCH) {
            let batch = batch.to_vec();
            let batch_removed = self
                .connection
                .call(move |db| evict_batch(db, &batch))
                .await
                .map_err(|e| e.to_string())?;
            removed.extend(batch_removed);
        }
        Ok(removed)
    }
}

/// A record as collection weighs it.
struct Record {
    id: crate::types::ExecutionId,
    checkout: Option<std::path::PathBuf>,
    /// The eval it reviewed; a saved id that no longer reads is no eval's latest record.
    eval: Option<crate::types::EvalId>,
    human: bool,
    bytes: i64,
    last_used: crate::types::Timestamp,
    /// Exact SQLite TEXT spelling of `last_used` for TOCTOU-safe compare-and-evict.
    last_used_raw: String,
    held: bool,
}

fn read_history_records(db: &mut rusqlite::Connection) -> Result<Vec<Record>, Error> {
    let transaction = db.transaction()?;
    // Latest first: the first record seen of an eval in a checkout is the one it reuses.
    let records = transaction
        .prepare(&format!(
            "SELECT e.id,json_extract(e.data,'$.provenance.repoPath'),json_extract(e.data,'$.provenance.evalId'),
             coalesce(json_extract(e.data,'$.profile.kind')='human',0),e.bytes,e.last_used,
             EXISTS(SELECT 1 FROM executions a WHERE a.key=e.key AND a.status IN ('RUNNING','WAITING_HUMAN'))
             OR EXISTS(SELECT 1 FROM requests q WHERE q.execution_id=e.id AND q.status IN ('QUEUED','RUNNING','WAITING_HUMAN'))
             FROM executions e WHERE {RECORD} ORDER BY {LATEST}"
        ))?
        .query_map([], |row| {
            let last_used_raw: String = row.get(5)?;
            let last_used: crate::types::Timestamp = row.get(5)?;
            Ok(Record {
                id: row.get(0)?,
                checkout: row.get::<_, Option<String>>(1)?.map(Into::into),
                eval: row
                    .get::<_, Option<String>>(2)?
                    .and_then(|eval| eval.parse().ok()),
                human: row.get(3)?,
                bytes: row.get(4)?,
                last_used,
                last_used_raw,
                held: row.get(6)?,
            })
        })?
        .collect::<Result<Vec<_>, _>>()?;
    transaction.commit()?;
    Ok(records)
}

fn live_checkouts(records: &[Record]) -> std::collections::BTreeSet<&Path> {
    records
        .iter()
        .filter_map(|record| record.checkout.as_deref())
        .collect::<std::collections::BTreeSet<_>>()
        .into_iter()
        .filter(|checkout| checkout.is_dir())
        .collect()
}

fn evict_batch(
    db: &mut rusqlite::Connection,
    batch: &[(crate::types::ExecutionId, String)],
) -> Result<Vec<crate::types::ExecutionId>, Error> {
    let mut removed = Vec::new();
    let transaction = db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
    {
        // Execution and receipt rows stay; only their place in the history goes. Checking
        // `last_used = ?2` prevents evicting an entry that another Run just reused between
        // Phase 1 and this commit.
        let mut evict = transaction.prepare_cached(
            "UPDATE executions SET completed_at=NULL,bytes=NULL,last_used=NULL
             WHERE id=?1 AND completed_at IS NOT NULL AND last_used=?2
               AND NOT EXISTS(SELECT 1 FROM executions a WHERE a.key=executions.key AND a.status IN ('RUNNING','WAITING_HUMAN'))
               AND NOT EXISTS(SELECT 1 FROM requests q WHERE q.execution_id=executions.id AND q.status IN ('QUEUED','RUNNING','WAITING_HUMAN'))",
        )?;
        for (id, last_used_raw) in batch {
            if evict.execute(params![id, last_used_raw])? == 1 {
                removed.push(id.clone());
            }
        }
    }
    transaction.commit()?;
    Ok(removed)
}

#[cfg(test)]
fn collect_within(db: &mut rusqlite::Connection, caps: Caps) -> Result<(), Error> {
    let records = read_history_records(db)?;
    let present = live_checkouts(&records);
    let evicted: Vec<_> = eviction_candidates(&records, &present, caps)
        .into_iter()
        .map(|record| (record.id.clone(), record.last_used_raw.clone()))
        .collect();
    for batch in evicted.chunks(EVICT_BATCH) {
        evict_batch(db, batch)?;
    }
    Ok(())
}

fn eviction_candidates<'a>(
    records: &'a [Record],
    present: &std::collections::BTreeSet<&Path>,
    caps: Caps,
) -> Vec<&'a Record> {
    let mut reused = std::collections::BTreeSet::new();
    let mut history = Vec::new();
    let mut evicted = Vec::new();
    for record in records {
        let newest = match (&record.checkout, &record.eval) {
            (Some(checkout), Some(eval)) => {
                reused.insert((checkout, eval)) && present.contains(checkout.as_path())
            }
            _ => false,
        };
        if record.held {
            continue;
        }
        if record.bytes > MAX_ENTRY_BYTES as i64 {
            evicted.push(record);
        } else if !newest {
            history.push(record);
        }
    }
    // Human sign-offs leave last; among the rest the least recently used leave first.
    history.sort_by(|a, b| {
        b.human
            .cmp(&a.human)
            .then_with(|| b.last_used.cmp(&a.last_used))
    });
    let (mut entries, mut bytes) = (0, 0);
    for record in history {
        if entries < caps.entries && bytes + record.bytes <= caps.bytes {
            entries += 1;
            bytes += record.bytes;
        } else {
            evicted.push(record);
        }
    }
    evicted
}

#[cfg(test)]
mod tests;