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
//! The state database and storage maintenance.

use std::path::{Path, PathBuf};

use crate::platform;

mod blocked;
pub mod definitions;
mod executions;
pub(crate) mod history;
mod human;
pub use human::HumanClaim;
mod catalog;
pub(crate) mod connection;
pub mod prune;
pub(crate) mod receipts;
mod result;
mod run_record;
mod runs;
mod snapshots;
mod touched;
mod unreadable;
mod validation;
pub use unreadable::{Unreadable, read_unreadable};
mod lifecycle;
pub(crate) mod migrations;
pub(crate) mod run_control;
mod run_read;
pub use lifecycle::{ExecutionState, GreenResult, PendingRequest, RequestState, RunState};
pub(crate) use result::tail as output_tail;
pub use result::{
    AgentIssue, ExecutionResult, HumanIssue, Issue, RuntimeIssue, RuntimeResult, exited_with,
};
pub use run_control::read_run_repo;
pub(crate) use run_read::{read_new_results, read_run_record, read_run_requests_only};
pub use run_read::{read_run, read_run_snapshot};
pub use snapshots::{
    ArtifactValidation, Blocker, ChildIdentity, EvalValidation, HumanDefinition, Validation,
    ValidationSnapshot,
};
mod wait_timeout;
pub(crate) use catalog::places as read_run_places;
pub use catalog::{
    CatalogRun, Signoff, read_catalog, read_catalog_run, read_open_run_ids, run_checkout,
    viewer_checkout,
};
pub use runs::{RunSummary, read_runs, read_scoped_runs};
pub(crate) mod reader;
mod removed;
pub use removed::retire_removed_signoffs;
mod requests;
pub(crate) use executions::read_profiled_executions;
pub use executions::{
    Capacity, Claim, Execution, ExecutionOptions, Origin, Producer, Provenance,
    read_keyed_executions, read_latest_cached,
};
#[cfg(any(test, feature = "test-support"))]
pub use receipts::OwnedReceipts;
pub use receipts::{
    DATABASE, EARLIER_STATE, LastRequest, QueueReason, Receipts, Request, Run, RunView,
    StoppedBackend, read_latest_requests, read_state_id, schema_error, state_schema,
};
pub(crate) use receipts::{read_attempts, read_deferred, regular_files as check_probe_files};
pub use requests::read_request_repo;
pub use requests::{
    RequestView, Shown, read_optional_request, read_original, read_original_as, read_request,
    read_request_as, read_request_batch, read_request_by_id, read_request_id, read_requests,
    read_requests_in, read_review_owner, read_run_requests, read_run_requests_by_id,
    read_session_request, read_waiting, read_waiting_originals,
};
pub(crate) use requests::{
    read_request_by_session, read_request_repo_by_id, read_requests_for_run, read_review_batch,
};

/// How long one database operation waits for the state other processes are writing before it
/// fails. Several Runs, the monitor and MCP servers share one state; a Run's write waits behind
/// theirs rather than failing the Run, while a lock that never frees still ends in an error.
pub(crate) const SQLITE_BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// How often a busy operation tries again. SQLite's own busy timeout backs off to 100 ms
/// between tries, so under steady writes from other connections, which try every 1–2 ms when
/// they start waiting, a long waiter rarely finds the lock free and runs out its time while
/// the others commit (#372). Trying at this pace keeps every waiter in the race.
const SQLITE_BUSY_POLL: std::time::Duration = std::time::Duration::from_millis(1);

/// Make `db` wait for a busy database, trying every [`SQLITE_BUSY_POLL`] for up to
/// [`SQLITE_BUSY_TIMEOUT`].
/// A path column, saved as its path text, read back as the same native path.
pub(crate) fn path_column(
    row: &rusqlite::Row<'_>,
    index: usize,
) -> rusqlite::Result<std::path::PathBuf> {
    let text: String = row.get(index)?;
    artifactize_tools::files::path_from_text(&text).map_err(|error| {
        rusqlite::Error::FromSqlConversionFailure(
            index,
            rusqlite::types::Type::Text,
            Box::new(error),
        )
    })
}

pub(crate) fn wait_when_busy(db: &rusqlite::Connection) -> rusqlite::Result<()> {
    db.busy_handler(Some(busy))
}

/// SQLite's busy handler: `tries` counts the earlier calls for this one wait, which runs on
/// the calling thread, so the wait's start is kept per thread.
fn busy(tries: i32) -> bool {
    thread_local! {
        static SINCE: std::cell::Cell<std::time::Instant> = std::cell::Cell::new(std::time::Instant::now());
    }
    let now = std::time::Instant::now();
    if tries == 0 {
        SINCE.set(now);
    }
    if now.duration_since(SINCE.get()) >= SQLITE_BUSY_TIMEOUT {
        return false;
    }
    std::thread::sleep(SQLITE_BUSY_POLL);
    true
}

/// Allow four short backoffs for a pending-delete handle to close, bounding the extra
/// latency of a real file-access failure to 80ms. This is a retry policy, not a test deadline.
const TRANSIENT_ACCESS_RETRIES: u32 = 5;
const TRANSIENT_ACCESS_BACKOFF: std::time::Duration = std::time::Duration::from_millis(20);

/// Retry `attempt` while `transient` says its error can clear on its own, before giving up
/// with its last error. `transient` decides alone: a non-transient error, or the bound run out,
/// both stop the loop and return that error immediately, never retried further.
fn retry<T, E>(
    mut attempt: impl FnMut() -> Result<T, E>,
    transient: impl Fn(&E) -> bool,
    mut before_retry: impl FnMut(),
) -> Result<T, E> {
    for remaining in (0..TRANSIENT_ACCESS_RETRIES).rev() {
        match attempt() {
            Ok(value) => return Ok(value),
            Err(error) if remaining > 0 && transient(&error) => {
                before_retry();
            }
            Err(error) => return Err(error),
        }
    }
    unreachable!("the loop above always returns by its last attempt")
}

/// Retry `attempt` past [`platform::transient_file_access`] (Windows transiently denying a
/// metadata or open probe while another handle finishes closing a just-deleted WAL sidecar)
/// before giving up with its last error. Every read-only state open reaches this through
/// [`receipts::check_files`]/[`check_probe_files`], which every reader calls first, so this is
/// the one place the retry needs to live.
pub(crate) fn retry_transient_access<T>(
    attempt: impl FnMut() -> std::io::Result<T>,
    before_retry: impl FnMut(),
) -> std::io::Result<T> {
    retry(attempt, platform::transient_file_access, before_retry)
}

#[cfg(test)]
#[path = "store/tests/retry.rs"]
mod retry_tests;

/// Resolve the single state directory without creating it.
pub fn state_dir(explicit: Option<&Path>) -> Result<PathBuf, String> {
    let path = match explicit {
        Some(path) => path.to_path_buf(),
        None => state_home().map_err(|e| e.to_string())?,
    };
    crate::platform::paths::resolve_target(&path).map_err(|e| e.to_string())
}

/// SQLite `user_version`; schema 9 keeps a Run's definitions in their own row, written once,
/// and numbers every change of a Run, request or execution row; schema 10 adds the open
/// WAITING_HUMAN Run and names a Run that ended with only sign-offs left YELLOW; schema 11
/// adds review drafts; schema 13 saves results as `{ verdict, kind, issues }`; schema 14
/// indexes attempts by repository and eval. Versions from schema 6 upgrade additively.
pub const STATE_SCHEMA_VERSION: u32 = 14;

#[derive(Debug, thiserror::Error)]
#[error("cannot resolve state home: set {}", state_home_variables())]
pub struct StateHomeError;

/// The variables `state_home` reads, in order, for the error that names them.
fn state_home_variables() -> String {
    let names: Vec<_> = platform::state_home_variables().collect();
    let (last, rest) = names.split_last().expect("constant names");
    format!("{}, or {last}", rest.join(", "))
}

/// Resolve the default state home without creating directories; empty variables are ignored.
/// The platform's state variables come after `ARTIFACTIZE_STATE_HOME` and before the home.
pub fn state_home() -> Result<PathBuf, StateHomeError> {
    platform::state_directory().ok_or(StateHomeError)
}

#[cfg(test)]
#[path = "store/tests/file.rs"]
mod file_tests;