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