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};
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(crate) use receipts::regular_files as check_probe_files;
60pub use receipts::{
61    DATABASE, EARLIER_STATE, LastRequest, QueueReason, Receipts, Request, Run, RunView,
62    StoppedBackend, read_latest_requests, read_state_id, schema_error, state_schema,
63};
64pub use requests::read_request_repo;
65pub use requests::{
66    RequestView, Shown, read_optional_request, read_original, read_original_as, read_request,
67    read_request_as, read_request_batch, read_request_by_id, read_request_id, read_requests,
68    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_repo_by_id, read_requests_for_run, 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    db.busy_handler(Some(busy))
105}
106
107/// SQLite's busy handler: `tries` counts the earlier calls for this one wait, which runs on
108/// the calling thread, so the wait's start is kept per thread.
109fn busy(tries: i32) -> bool {
110    thread_local! {
111        static SINCE: std::cell::Cell<std::time::Instant> = std::cell::Cell::new(std::time::Instant::now());
112    }
113    let now = std::time::Instant::now();
114    if tries == 0 {
115        SINCE.set(now);
116    }
117    if now.duration_since(SINCE.get()) >= SQLITE_BUSY_TIMEOUT {
118        return false;
119    }
120    std::thread::sleep(SQLITE_BUSY_POLL);
121    true
122}
123
124/// Allow four short backoffs for a pending-delete handle to close, bounding the extra
125/// latency of a real file-access failure to 80ms. This is a retry policy, not a test deadline.
126const TRANSIENT_ACCESS_RETRIES: u32 = 5;
127const TRANSIENT_ACCESS_BACKOFF: std::time::Duration = std::time::Duration::from_millis(20);
128
129/// Retry `attempt` while `transient` says its error can clear on its own, before giving up
130/// with its last error. `transient` decides alone: a non-transient error, or the bound run out,
131/// both stop the loop and return that error immediately, never retried further.
132fn retry<T, E>(
133    mut attempt: impl FnMut() -> Result<T, E>,
134    transient: impl Fn(&E) -> bool,
135    mut before_retry: impl FnMut(),
136) -> Result<T, E> {
137    for remaining in (0..TRANSIENT_ACCESS_RETRIES).rev() {
138        match attempt() {
139            Ok(value) => return Ok(value),
140            Err(error) if remaining > 0 && transient(&error) => {
141                before_retry();
142            }
143            Err(error) => return Err(error),
144        }
145    }
146    unreachable!("the loop above always returns by its last attempt")
147}
148
149/// Retry `attempt` past [`platform::transient_file_access`] (Windows transiently denying a
150/// metadata or open probe while another handle finishes closing a just-deleted WAL sidecar)
151/// before giving up with its last error. Every read-only state open reaches this through
152/// [`receipts::check_files`]/[`check_probe_files`], which every reader calls first, so this is
153/// the one place the retry needs to live.
154pub(crate) fn retry_transient_access<T>(
155    attempt: impl FnMut() -> std::io::Result<T>,
156    before_retry: impl FnMut(),
157) -> std::io::Result<T> {
158    retry(attempt, platform::transient_file_access, before_retry)
159}
160
161#[cfg(test)]
162#[path = "store/tests/retry.rs"]
163mod retry_tests;
164
165/// Resolve the single state directory without creating it.
166pub fn state_dir(explicit: Option<&Path>) -> Result<PathBuf, String> {
167    let path = match explicit {
168        Some(path) => path.to_path_buf(),
169        None => state_home().map_err(|e| e.to_string())?,
170    };
171    crate::platform::paths::resolve_target(&path).map_err(|e| e.to_string())
172}
173
174/// SQLite `user_version`; schema 9 keeps a Run's definitions in their own row, written once,
175/// and numbers every change of a Run, request or execution row; schema 10 adds the open
176/// WAITING_HUMAN Run and names a Run that ended with only sign-offs left YELLOW; schema 11
177/// adds review drafts; schema 13 saves results as `{ verdict, kind, issues }`. Versions from
178/// schema 6 upgrade additively.
179pub const STATE_SCHEMA_VERSION: u32 = 13;
180
181#[derive(Debug, thiserror::Error)]
182#[error("cannot resolve state home: set {}", state_home_variables())]
183pub struct StateHomeError;
184
185/// The variables `state_home` reads, in order, for the error that names them.
186fn state_home_variables() -> String {
187    let names: Vec<_> = platform::state_home_variables().collect();
188    let (last, rest) = names.split_last().expect("constant names");
189    format!("{}, or {last}", rest.join(", "))
190}
191
192/// Resolve the default state home without creating directories; empty variables are ignored.
193/// The platform's state variables come after `ARTIFACTIZE_STATE_HOME` and before the home.
194pub fn state_home() -> Result<PathBuf, StateHomeError> {
195    platform::state_directory().ok_or(StateHomeError)
196}
197
198#[cfg(test)]
199#[path = "store/tests/file.rs"]
200mod file_tests;