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