artifactize-core 0.27.2

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
//! Read the saved attempts used by a current-input status forecast.

use super::{Error, Request, Run, schema_initialized};
use crate::{
    store,
    types::{EvalId, ExecutionId, Fingerprint, RequestId, RequestStatus, RunId},
    workspace::{canonical_target, outside_workspace},
};
use rusqlite::{OptionalExtension, params};
use serde::Serialize;
use std::{
    collections::{BTreeMap, BTreeSet, btree_map::Entry},
    path::Path,
};

/// A Run inserts all its requests in its admission transaction. Keep that order in a
/// narrow index, independent of what SQLite does to implicit rowids during compaction.
pub(in crate::store) const ATTEMPTS: &str = "
    CREATE TABLE IF NOT EXISTS request_attempts(
        sequence INTEGER PRIMARY KEY, repo TEXT NOT NULL, eval_id TEXT NOT NULL,
        request_id TEXT UNIQUE NOT NULL
    );
    CREATE INDEX IF NOT EXISTS request_attempt_order ON request_attempts(repo,eval_id);
    CREATE TRIGGER IF NOT EXISTS request_attempt_insert AFTER INSERT ON requests BEGIN
        INSERT INTO request_attempts(repo,eval_id,request_id)
        SELECT repo,NEW.eval_id,NEW.id FROM runs WHERE id=NEW.run_id;
    END;
    CREATE TRIGGER IF NOT EXISTS request_attempt_delete AFTER DELETE ON requests BEGIN
        DELETE FROM request_attempts WHERE request_id=OLD.id;
    END;
    CREATE INDEX IF NOT EXISTS deferred_request_execution ON requests(execution_id,eval_id,run_id)
        WHERE status='DEFERRED';";

/// Backfill in the Run order used by the previous last-attempt lookup.
pub(in crate::store) const BACKFILL_ATTEMPTS: &str = "
    INSERT OR IGNORE INTO request_attempts(repo,eval_id,request_id)
    SELECT r.repo,q.eval_id,q.id FROM runs r JOIN requests q ON q.run_id=r.id ORDER BY r.rowid;";

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LastRequest {
    pub run_id: RunId,
    pub verdict: RequestStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fingerprint: Option<Fingerprint>,
}

#[derive(Default)]
pub(crate) struct Attempts {
    pub latest: BTreeMap<EvalId, LastRequest>,
    pub unreadable: Vec<store::Unreadable>,
}

/// Last attempts are audit pointers, never evidence for a new current-input query.
pub async fn read_latest_requests(
    state: &Path,
    repo: &Path,
) -> Result<BTreeMap<EvalId, LastRequest>, String> {
    let attempts = read(state, repo, |db, repo| {
        let evals = db
            .prepare("SELECT DISTINCT eval_id FROM request_attempts WHERE repo=?")?
            .query_map([repo], |row| row.get::<_, EvalId>(0))?
            .collect::<Result<Vec<_>, _>>()?;
        attempts(db, repo, evals, false)
    })
    .await?;
    for error in &attempts.unreadable {
        store::unreadable::skipped(error);
    }
    Ok(attempts.latest)
}

/// Read only the newest attempt for each required Eval and report unreadable records
/// encountered there. Opening a saved Run, not forecasting status, audits its definitions.
pub(crate) async fn read_attempts(
    state: &Path,
    repo: &Path,
    evals: Vec<EvalId>,
) -> Result<Attempts, String> {
    read(state, repo, move |db, repo| attempts(db, repo, evals, true)).await
}

fn attempts(
    db: &rusqlite::Transaction<'_>,
    repo: &str,
    evals: Vec<EvalId>,
    report_executions: bool,
) -> Result<Attempts, Error> {
    let mut latest = db.prepare_cached(
        "SELECT q.id,q.run_id,q.execution_id,q.data FROM requests q WHERE q.id=(
            SELECT request_id FROM request_attempts WHERE repo=? AND eval_id=?
            ORDER BY sequence DESC LIMIT 1
        )",
    )?;
    let mut run_data = db.prepare_cached("SELECT data FROM runs WHERE id=?")?;
    let mut execution_data = db.prepare_cached("SELECT data FROM executions WHERE id=?")?;
    let mut readable = BTreeMap::new();
    let mut executions = BTreeSet::new();
    let mut attempts = Attempts::default();
    for eval in evals {
        let attempt = latest
            .query_row(params![repo, eval], |row| {
                Ok((
                    row.get::<_, RequestId>(0)?,
                    row.get::<_, RunId>(1)?,
                    row.get::<_, Option<ExecutionId>>(2)?,
                    row.get::<_, String>(3)?,
                ))
            })
            .optional()?;
        let Some((id, run, execution, data)) = attempt else {
            continue;
        };
        let run_readable = match readable.entry(run) {
            Entry::Occupied(entry) => *entry.get(),
            Entry::Vacant(entry) => {
                let run = entry.key();
                let data = run_data.query_row([run], |row| row.get::<_, String>(0))?;
                let readable = match store::unreadable::decode::<Run>("run", run.as_str(), &data) {
                    Ok(_) => true,
                    Err(error) => {
                        attempts.unreadable.push(error);
                        false
                    }
                };
                *entry.insert(readable)
            }
        };
        if report_executions
            && let Some(execution) = execution
            && executions.insert(execution.clone())
            && let Some(data) = execution_data
                .query_row([&execution], |row| row.get::<_, String>(0))
                .optional()?
            && let Err(error) = store::unreadable::decode::<store::Execution>(
                "execution",
                execution.as_str(),
                &data,
            )
        {
            attempts.unreadable.push(error);
        }
        match store::unreadable::decode::<Request>("request", id.as_str(), &data) {
            Ok(request) if run_readable => {
                attempts.latest.insert(
                    request.eval_id.clone(),
                    LastRequest {
                        run_id: request.run_id.clone(),
                        verdict: request.status(),
                        fingerprint: request.fingerprint,
                    },
                );
            }
            Ok(_) => {}
            Err(error) => attempts.unreadable.push(error),
        }
    }
    attempts
        .unreadable
        .sort_by(|a, b| (&a.kind, &a.id).cmp(&(&b.kind, &b.id)));
    Ok(attempts)
}

/// Determine which current Human waiters were deferred in this worktree. Start at the
/// matching execution, not at the repository's queue or its Run history.
pub(crate) async fn read_deferred(
    state: &Path,
    repo: &Path,
    candidates: Vec<(EvalId, ExecutionId)>,
) -> Result<BTreeSet<EvalId>, String> {
    if candidates.is_empty() {
        return Ok(BTreeSet::new());
    }
    read(state, repo, move |db, repo| {
        let mut deferred = BTreeSet::new();
        let mut waiting = db.prepare_cached(
            "SELECT q.data FROM requests q JOIN runs r ON r.id=q.run_id
             WHERE q.status='DEFERRED' AND q.execution_id=? AND q.eval_id=? AND r.repo=?",
        )?;
        for (eval, execution) in candidates {
            let rows = waiting.query_map(params![execution, eval, repo], |row| {
                row.get::<_, String>(0)
            })?;
            for data in rows {
                let request = store::unreadable::evidence::<Request>("request", &data?);
                if request.is_some_and(|request| {
                    request.status() == RequestStatus::Deferred
                        && request.eval_id == eval
                        && request.execution_id.as_ref() == Some(&execution)
                }) {
                    deferred.insert(eval);
                    break;
                }
            }
        }
        Ok(deferred)
    })
    .await
}

async fn read<T: Default + Send + 'static>(
    state: &Path,
    repo: &Path,
    query: impl FnOnce(&rusqlite::Transaction<'_>, &str) -> Result<T, Error> + Send + 'static,
) -> Result<T, String> {
    let state = canonical_target(state).map_err(|e| e.to_string())?;
    outside_workspace(repo, &state).map_err(|e| e.to_string())?;
    let Some(connection) = store::requests::open_read(&state).await? else {
        return Ok(T::default());
    };
    let repo = crate::platform::path_text(repo);
    let result = connection
        .call(move |db| -> Result<_, Error> {
            store::wait_when_busy(db)?;
            let transaction = db.transaction()?;
            if !schema_initialized(&transaction)? {
                return Ok(T::default());
            }
            let value = query(&transaction, &repo)?;
            transaction.commit()?;
            Ok(value)
        })
        .await
        .map_err(|e| e.to_string());
    store::connection::finish(connection, result).await
}