Skip to main content

artifactize_core/store/receipts/
latest.rs

1//! Read the saved attempts used by a current-input status forecast.
2
3use super::{Error, Request, Run, schema_initialized};
4use crate::{
5    store,
6    types::{EvalId, ExecutionId, Fingerprint, RequestId, RequestStatus, RunId},
7    workspace::{canonical_target, outside_workspace},
8};
9use rusqlite::{OptionalExtension, params};
10use serde::Serialize;
11use std::{
12    collections::{BTreeMap, BTreeSet, btree_map::Entry},
13    path::Path,
14};
15
16/// A Run inserts all its requests in its admission transaction. Keep that order in a
17/// narrow index, independent of what SQLite does to implicit rowids during compaction.
18pub(in crate::store) const ATTEMPTS: &str = "
19    CREATE TABLE IF NOT EXISTS request_attempts(
20        sequence INTEGER PRIMARY KEY, repo TEXT NOT NULL, eval_id TEXT NOT NULL,
21        request_id TEXT UNIQUE NOT NULL
22    );
23    CREATE INDEX IF NOT EXISTS request_attempt_order ON request_attempts(repo,eval_id);
24    CREATE TRIGGER IF NOT EXISTS request_attempt_insert AFTER INSERT ON requests BEGIN
25        INSERT INTO request_attempts(repo,eval_id,request_id)
26        SELECT repo,NEW.eval_id,NEW.id FROM runs WHERE id=NEW.run_id;
27    END;
28    CREATE TRIGGER IF NOT EXISTS request_attempt_delete AFTER DELETE ON requests BEGIN
29        DELETE FROM request_attempts WHERE request_id=OLD.id;
30    END;
31    CREATE INDEX IF NOT EXISTS deferred_request_execution ON requests(execution_id,eval_id,run_id)
32        WHERE status='DEFERRED';";
33
34/// Backfill in the Run order used by the previous last-attempt lookup.
35pub(in crate::store) const BACKFILL_ATTEMPTS: &str = "
36    INSERT OR IGNORE INTO request_attempts(repo,eval_id,request_id)
37    SELECT r.repo,q.eval_id,q.id FROM runs r JOIN requests q ON q.run_id=r.id ORDER BY r.rowid;";
38
39#[derive(Debug, Clone, Serialize)]
40#[serde(rename_all = "camelCase")]
41pub struct LastRequest {
42    pub run_id: RunId,
43    pub verdict: RequestStatus,
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub fingerprint: Option<Fingerprint>,
46}
47
48#[derive(Default)]
49pub(crate) struct Attempts {
50    pub latest: BTreeMap<EvalId, LastRequest>,
51    pub unreadable: Vec<store::Unreadable>,
52}
53
54/// Last attempts are audit pointers, never evidence for a new current-input query.
55pub async fn read_latest_requests(
56    state: &Path,
57    repo: &Path,
58) -> Result<BTreeMap<EvalId, LastRequest>, String> {
59    let attempts = read(state, repo, |db, repo| {
60        let evals = db
61            .prepare("SELECT DISTINCT eval_id FROM request_attempts WHERE repo=?")?
62            .query_map([repo], |row| row.get::<_, EvalId>(0))?
63            .collect::<Result<Vec<_>, _>>()?;
64        attempts(db, repo, evals, false)
65    })
66    .await?;
67    for error in &attempts.unreadable {
68        store::unreadable::skipped(error);
69    }
70    Ok(attempts.latest)
71}
72
73/// Read only the newest attempt for each required Eval and report unreadable records
74/// encountered there. Opening a saved Run, not forecasting status, audits its definitions.
75pub(crate) async fn read_attempts(
76    state: &Path,
77    repo: &Path,
78    evals: Vec<EvalId>,
79) -> Result<Attempts, String> {
80    read(state, repo, move |db, repo| attempts(db, repo, evals, true)).await
81}
82
83fn attempts(
84    db: &rusqlite::Transaction<'_>,
85    repo: &str,
86    evals: Vec<EvalId>,
87    report_executions: bool,
88) -> Result<Attempts, Error> {
89    let mut latest = db.prepare_cached(
90        "SELECT q.id,q.run_id,q.execution_id,q.data FROM requests q WHERE q.id=(
91            SELECT request_id FROM request_attempts WHERE repo=? AND eval_id=?
92            ORDER BY sequence DESC LIMIT 1
93        )",
94    )?;
95    let mut run_data = db.prepare_cached("SELECT data FROM runs WHERE id=?")?;
96    let mut execution_data = db.prepare_cached("SELECT data FROM executions WHERE id=?")?;
97    let mut readable = BTreeMap::new();
98    let mut executions = BTreeSet::new();
99    let mut attempts = Attempts::default();
100    for eval in evals {
101        let attempt = latest
102            .query_row(params![repo, eval], |row| {
103                Ok((
104                    row.get::<_, RequestId>(0)?,
105                    row.get::<_, RunId>(1)?,
106                    row.get::<_, Option<ExecutionId>>(2)?,
107                    row.get::<_, String>(3)?,
108                ))
109            })
110            .optional()?;
111        let Some((id, run, execution, data)) = attempt else {
112            continue;
113        };
114        let run_readable = match readable.entry(run) {
115            Entry::Occupied(entry) => *entry.get(),
116            Entry::Vacant(entry) => {
117                let run = entry.key();
118                let data = run_data.query_row([run], |row| row.get::<_, String>(0))?;
119                let readable = match store::unreadable::decode::<Run>("run", run.as_str(), &data) {
120                    Ok(_) => true,
121                    Err(error) => {
122                        attempts.unreadable.push(error);
123                        false
124                    }
125                };
126                *entry.insert(readable)
127            }
128        };
129        if report_executions
130            && let Some(execution) = execution
131            && executions.insert(execution.clone())
132            && let Some(data) = execution_data
133                .query_row([&execution], |row| row.get::<_, String>(0))
134                .optional()?
135            && let Err(error) = store::unreadable::decode::<store::Execution>(
136                "execution",
137                execution.as_str(),
138                &data,
139            )
140        {
141            attempts.unreadable.push(error);
142        }
143        match store::unreadable::decode::<Request>("request", id.as_str(), &data) {
144            Ok(request) if run_readable => {
145                attempts.latest.insert(
146                    request.eval_id.clone(),
147                    LastRequest {
148                        run_id: request.run_id.clone(),
149                        verdict: request.status(),
150                        fingerprint: request.fingerprint,
151                    },
152                );
153            }
154            Ok(_) => {}
155            Err(error) => attempts.unreadable.push(error),
156        }
157    }
158    attempts
159        .unreadable
160        .sort_by(|a, b| (&a.kind, &a.id).cmp(&(&b.kind, &b.id)));
161    Ok(attempts)
162}
163
164/// Determine which current Human waiters were deferred in this worktree. Start at the
165/// matching execution, not at the repository's queue or its Run history.
166pub(crate) async fn read_deferred(
167    state: &Path,
168    repo: &Path,
169    candidates: Vec<(EvalId, ExecutionId)>,
170) -> Result<BTreeSet<EvalId>, String> {
171    if candidates.is_empty() {
172        return Ok(BTreeSet::new());
173    }
174    read(state, repo, move |db, repo| {
175        let mut deferred = BTreeSet::new();
176        let mut waiting = db.prepare_cached(
177            "SELECT q.data FROM requests q JOIN runs r ON r.id=q.run_id
178             WHERE q.status='DEFERRED' AND q.execution_id=? AND q.eval_id=? AND r.repo=?",
179        )?;
180        for (eval, execution) in candidates {
181            let rows = waiting.query_map(params![execution, eval, repo], |row| {
182                row.get::<_, String>(0)
183            })?;
184            for data in rows {
185                let request = store::unreadable::evidence::<Request>("request", &data?);
186                if request.is_some_and(|request| {
187                    request.status() == RequestStatus::Deferred
188                        && request.eval_id == eval
189                        && request.execution_id.as_ref() == Some(&execution)
190                }) {
191                    deferred.insert(eval);
192                    break;
193                }
194            }
195        }
196        Ok(deferred)
197    })
198    .await
199}
200
201async fn read<T: Default + Send + 'static>(
202    state: &Path,
203    repo: &Path,
204    query: impl FnOnce(&rusqlite::Transaction<'_>, &str) -> Result<T, Error> + Send + 'static,
205) -> Result<T, String> {
206    let state = canonical_target(state).map_err(|e| e.to_string())?;
207    outside_workspace(repo, &state).map_err(|e| e.to_string())?;
208    let Some(connection) = store::requests::open_read(&state).await? else {
209        return Ok(T::default());
210    };
211    let repo = crate::platform::path_text(repo);
212    let result = connection
213        .call(move |db| -> Result<_, Error> {
214            store::wait_when_busy(db)?;
215            let transaction = db.transaction()?;
216            if !schema_initialized(&transaction)? {
217                return Ok(T::default());
218            }
219            let value = query(&transaction, &repo)?;
220            transaction.commit()?;
221            Ok(value)
222        })
223        .await
224        .map_err(|e| e.to_string());
225    store::connection::finish(connection, result).await
226}