Skip to main content

artifactize_core/
store.rs

1//! The state database and storage maintenance.
2
3use std::path::{Path, PathBuf};
4
5use crate::platform;
6
7mod blocked;
8pub mod definitions;
9mod executions;
10pub(crate) mod history;
11mod human;
12pub use human::HumanClaim;
13mod catalog;
14pub(crate) mod connection;
15pub mod prune;
16pub(crate) mod receipts;
17mod result;
18mod run_record;
19mod runs;
20mod snapshots;
21mod touched;
22mod unreadable;
23mod validation;
24pub use unreadable::{Unreadable, read_unreadable};
25mod lifecycle;
26pub(crate) mod migrations;
27pub(crate) mod run_control;
28mod run_read;
29pub use lifecycle::{ExecutionState, GreenResult, PendingRequest, RequestState, RunState};
30pub(crate) use result::tail as output_tail;
31pub use result::{
32    AgentIssue, ExecutionResult, HumanIssue, Issue, RuntimeIssue, RuntimeResult, exited_with,
33};
34pub use run_control::read_run_repo;
35pub(crate) use run_read::{read_new_results, read_run_record, read_run_requests_only};
36pub use run_read::{read_run, read_run_snapshot, read_run_sources};
37pub use snapshots::{
38    ArtifactValidation, Blocker, ChildIdentity, EvalValidation, HumanDefinition, Validation,
39    ValidationSnapshot,
40};
41mod wait_timeout;
42pub(crate) use catalog::places as read_run_places;
43pub use catalog::{
44    CatalogRun, Signoff, read_catalog, read_catalog_run, read_open_run_ids, run_checkout,
45    viewer_checkout,
46};
47pub use runs::{RunSummary, read_runs, read_scoped_runs};
48pub(crate) mod reader;
49mod removed;
50pub use removed::retire_removed_signoffs;
51mod requests;
52pub(crate) use executions::read_profiled_executions;
53pub use executions::{
54    Capacity, Claim, Execution, ExecutionOptions, Origin, Producer, Provenance,
55    read_keyed_executions, read_latest_cached,
56};
57#[cfg(any(test, feature = "test-support"))]
58pub use receipts::OwnedReceipts;
59pub use receipts::{
60    DATABASE, EARLIER_STATE, LastRequest, QueueReason, Receipts, Request, Run, RunView,
61    StoppedBackend, read_latest_requests, read_state_id, schema_error, state_schema,
62};
63pub(crate) use receipts::{read_attempts, read_deferred, regular_files as check_probe_files};
64pub use requests::read_request_repo;
65pub use requests::{
66    Batch, Mark, RequestView, Shown, Start, read_optional_request, read_original, read_original_as,
67    read_request, read_request_as, read_request_batch, read_request_by_id, read_request_id,
68    read_requests, read_requests_in, read_review_owner, read_run_requests, read_run_requests_by_id,
69    read_session_request, read_waiting, read_waiting_originals,
70};
71pub(crate) use requests::{
72    read_request_by_session, read_request_list, read_request_repo_by_id, read_review_batch,
73};
74
75/// How long one database operation waits for the state other processes are writing before it
76/// fails. Several Runs, the monitor and MCP servers share one state; a Run's write waits behind
77/// theirs rather than failing the Run, while a lock that never frees still ends in an error.
78pub(crate) const SQLITE_BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
79
80/// How often a busy operation tries again. SQLite's own busy timeout backs off to 100 ms
81/// between tries, so under steady writes from other connections, which try every 1–2 ms when
82/// they start waiting, a long waiter rarely finds the lock free and runs out its time while
83/// the others commit (#372). Trying at this pace keeps every waiter in the race.
84const SQLITE_BUSY_POLL: std::time::Duration = std::time::Duration::from_millis(1);
85
86/// Make `db` wait for a busy database, trying every [`SQLITE_BUSY_POLL`] for up to
87/// [`SQLITE_BUSY_TIMEOUT`].
88/// A path column, saved as its path text, read back as the same native path.
89pub(crate) fn path_column(
90    row: &rusqlite::Row<'_>,
91    index: usize,
92) -> rusqlite::Result<std::path::PathBuf> {
93    let text: String = row.get(index)?;
94    artifactize_tools::files::path_from_text(&text).map_err(|error| {
95        rusqlite::Error::FromSqlConversionFailure(
96            index,
97            rusqlite::types::Type::Text,
98            Box::new(error),
99        )
100    })
101}
102
103pub(crate) fn wait_when_busy(db: &rusqlite::Connection) -> rusqlite::Result<()> {
104    #[cfg(test)]
105    crate::performance::count_connection_sql(db)?;
106    db.busy_handler(Some(busy))
107}
108
109/// SQLite's busy handler: `tries` counts the earlier calls for this one wait, which runs on
110/// the calling thread, so the wait's start is kept per thread.
111fn busy(tries: i32) -> bool {
112    thread_local! {
113        static SINCE: std::cell::Cell<std::time::Instant> = std::cell::Cell::new(std::time::Instant::now());
114    }
115    let now = std::time::Instant::now();
116    if tries == 0 {
117        SINCE.set(now);
118    }
119    if now.duration_since(SINCE.get()) >= SQLITE_BUSY_TIMEOUT {
120        return false;
121    }
122    std::thread::sleep(SQLITE_BUSY_POLL);
123    true
124}
125
126/// Allow four short backoffs for a pending-delete handle to close, bounding the extra
127/// latency of a real file-access failure to 80ms. This is a retry policy, not a test deadline.
128const TRANSIENT_ACCESS_RETRIES: u32 = 5;
129const TRANSIENT_ACCESS_BACKOFF: std::time::Duration = std::time::Duration::from_millis(20);
130
131/// Retry `attempt` while `transient` says its error can clear on its own, before giving up
132/// with its last error. `transient` decides alone: a non-transient error, or the bound run out,
133/// both stop the loop and return that error immediately, never retried further.
134fn retry<T, E>(
135    mut attempt: impl FnMut() -> Result<T, E>,
136    transient: impl Fn(&E) -> bool,
137    mut before_retry: impl FnMut(),
138) -> Result<T, E> {
139    for remaining in (0..TRANSIENT_ACCESS_RETRIES).rev() {
140        match attempt() {
141            Ok(value) => return Ok(value),
142            Err(error) if remaining > 0 && transient(&error) => {
143                before_retry();
144            }
145            Err(error) => return Err(error),
146        }
147    }
148    unreachable!("the loop above always returns by its last attempt")
149}
150
151/// Retry `attempt` past [`platform::transient_file_access`] (Windows transiently denying a
152/// metadata or open probe while another handle finishes closing a just-deleted WAL sidecar)
153/// before giving up with its last error. Every read-only state open reaches this through
154/// [`receipts::check_files`]/[`check_probe_files`], which every reader calls first, so this is
155/// the one place the retry needs to live.
156pub(crate) fn retry_transient_access<T>(
157    attempt: impl FnMut() -> std::io::Result<T>,
158    before_retry: impl FnMut(),
159) -> std::io::Result<T> {
160    retry(attempt, platform::transient_file_access, before_retry)
161}
162
163#[cfg(test)]
164#[path = "store/tests/retry.rs"]
165mod retry_tests;
166
167/// Resolve the single state directory without creating it.
168pub fn state_dir(explicit: Option<&Path>) -> Result<PathBuf, String> {
169    let path = match explicit {
170        Some(path) => path.to_path_buf(),
171        None => state_home().map_err(|e| e.to_string())?,
172    };
173    crate::platform::paths::resolve_target(&path).map_err(|e| e.to_string())
174}
175
176/// SQLite `user_version`; schema 9 keeps a Run's definitions in their own row, written once,
177/// and numbers every change of a Run, request or execution row; schema 10 adds the open
178/// WAITING_HUMAN Run and names a Run that ended with only sign-offs left YELLOW; schema 11
179/// adds review drafts; schema 13 saves results as `{ verdict, kind, issues }`; schema 14
180/// indexes attempts by repository and eval; schema 15 saves Run definitions once in shared
181/// records and indexes requests in Review order. Versions from schema 6 upgrade additively.
182pub const STATE_SCHEMA_VERSION: u32 = 15;
183
184#[derive(Debug, thiserror::Error)]
185#[error("cannot resolve state home: set {}", state_home_variables())]
186pub struct StateHomeError;
187
188/// The variables `state_home` reads, in order, for the error that names them.
189fn state_home_variables() -> String {
190    let names: Vec<_> = platform::state_home_variables().collect();
191    let (last, rest) = names.split_last().expect("constant names");
192    format!("{}, or {last}", rest.join(", "))
193}
194
195/// Resolve the default state home without creating directories; empty variables are ignored.
196/// The platform's state variables come after `ARTIFACTIZE_STATE_HOME` and before the home.
197pub fn state_home() -> Result<PathBuf, StateHomeError> {
198    platform::state_directory().ok_or(StateHomeError)
199}
200
201#[cfg(test)]
202#[path = "store/tests/file.rs"]
203mod file_tests;