artifactize-core 0.33.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! Opening, versioning and joining state database connections.
use super::Error;
use crate::{
    store::{self as store, STATE_SCHEMA_VERSION},
    workspace::{canonical_target, prepare_directory},
};
use rusqlite::OptionalExtension;
use std::{path::Path, time::Duration};
use tokio_rusqlite::Connection;

pub const DATABASE: &str = "state.sqlite";
/// Yield between WAL initialization races instead of spinning, still within the
/// shared SQLite contention deadline used by the outer initialization loop.
const INITIALIZATION_RETRY_INTERVAL: Duration = Duration::from_millis(20);
/// Run a non-blocking PASSIVE WAL checkpoint after this many write calls so the WAL stays
/// bounded without stalling individual commits via SQLite's default autocheckpoint.
const CHECKPOINT_WRITE_INTERVAL: u64 = 256;
/// Bound how many pages one incremental vacuum step reclaims so maintenance stays brief.
pub(in crate::store) const INCREMENTAL_VACUUM_PAGES: u32 = 256;

/// Where a request sorts in the Review list, newest first: when it started, else when
/// it was created, or empty when its record does not read. Saved timestamps are UTC RFC3339;
/// without the trailing Z, a whole second sorts before a fractional value in that second.
macro_rules! listed {
    () => {
        "CASE WHEN json_valid(data) THEN coalesce(rtrim(coalesce(json_extract(data,'$.startedAt'),json_extract(data,'$.createdAt')),'Z'),'') ELSE '' END"
    };
}

/// The six tables of a state and the indexes its lookups use.
///
/// - `runs`: one row per Run, its changing state without its definitions.
/// - `run_definitions`: one row per Run with definitions: the Artifacts, evals and relations it
///   was started with. They are fixed for the Run's life, written once with the Run and never
///   updated, so a change of the Run never rewrites them. `data` holds what is the Run's own,
///   and `body` names the rest in `definition_records`; without a body, `data` holds them all.
/// - `definition_records`: saved definition text by its SHA-256, written once however many
///   Runs share it: definition bodies, and the Artifacts, evals and relations they name.
/// - `requests`: one row per eval of a Run, at its `ordinal` in the Run's selection order;
///   `claimed_by` and `claimed_at` hold the Human claim of a waiting request, and `listed`
///   its place in the Review order (`listed!`).
/// - `executions`: one row per execution. `backend` names the Agent backend it runs on, and
///   a RUNNING execution with a backend holds one of that backend's machine-wide slots. A
///   completed GREEN/RED execution with a key is a record of the key's history while
///   `completed_at` (sortable), `bytes` and `last_used` are set; the cache GC and `cache rm`
///   clear them, and the execution stays.
/// - `state_meta`: named values of the state itself: `id`, a random UUID made when the
///   database is created, which identifies the state in Agent session references.
///
/// `runs`, `requests` and `executions` carry a `revision` that [`REVISIONS`] raises on every
/// update of the row, so a reader learns which rows changed by comparing numbers.
const SCHEMA: &str = concat!(
    "CREATE TABLE runs(id TEXT PRIMARY KEY, repo TEXT NOT NULL, status TEXT NOT NULL, data TEXT NOT NULL, request_key TEXT, revision INTEGER NOT NULL DEFAULT 0);
    CREATE UNIQUE INDEX run_request_key ON runs(repo,request_key) WHERE request_key IS NOT NULL;
    CREATE TABLE run_definitions(run_id TEXT PRIMARY KEY REFERENCES runs(id), data TEXT NOT NULL, body TEXT);
    CREATE TABLE definition_records(hash TEXT PRIMARY KEY, data TEXT NOT NULL);
    CREATE TABLE requests(id TEXT PRIMARY KEY, run_id TEXT NOT NULL REFERENCES runs(id), eval_id TEXT NOT NULL, ordinal INTEGER NOT NULL, execution_id TEXT REFERENCES executions(id), status TEXT NOT NULL, claimed_by TEXT, claimed_at TEXT, data TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 0, listed TEXT GENERATED ALWAYS AS (",
    listed!(),
    ") VIRTUAL, UNIQUE(run_id, eval_id), UNIQUE(run_id, ordinal));
    CREATE INDEX request_listed ON requests(listed DESC, run_id DESC, ordinal);
    CREATE TABLE executions(id TEXT PRIMARY KEY, key TEXT, eval_def_hash TEXT NOT NULL, status TEXT NOT NULL, owner_pid INTEGER NOT NULL, owner_start_time INTEGER NOT NULL, backend TEXT, profile_identity TEXT, completed_at TEXT, bytes INTEGER, last_used TEXT, data TEXT NOT NULL, revision INTEGER NOT NULL DEFAULT 0);
    CREATE TABLE state_meta(name TEXT PRIMARY KEY, value TEXT NOT NULL);
    CREATE INDEX active_request_execution ON requests(execution_id) WHERE status IN ('QUEUED','RUNNING','WAITING_HUMAN');
    CREATE UNIQUE INDEX active_key ON executions(key,profile_identity) WHERE key IS NOT NULL AND status IN ('RUNNING','WAITING_HUMAN');
    CREATE INDEX key_history ON executions(key, completed_at);
    CREATE INDEX definition_history ON executions(eval_def_hash, completed_at);
    CREATE INDEX running_backend ON executions(backend) WHERE status='RUNNING';"
);

/// Shared Run definitions and the Review order of requests, added in state schema 15.
pub(in crate::store) const SHARED_DEFINITIONS: &str = concat!(
    "CREATE TABLE definition_records(hash TEXT PRIMARY KEY, data TEXT NOT NULL);
    ALTER TABLE run_definitions ADD COLUMN body TEXT;
    ALTER TABLE requests ADD COLUMN listed TEXT GENERATED ALWAYS AS (",
    listed!(),
    ") VIRTUAL;
    CREATE INDEX request_listed ON requests(listed DESC, run_id DESC, ordinal);"
);

/// Raise a row's `revision` on every update that does not set it. Writers need not know about
/// it: the trigger's own update leaves `revision` changed, so it never fires again. The indexes
/// let readers count, list and compare revisions without reading a record's data:
/// `request_status` counts a Run's requests by status, `request_marks` and `execution_marks`
/// hold the revisions of a Run's requests and their executions, `request_claim` the Human
/// claims, and `request_execution` names the Runs an execution's change touches.
pub(in crate::store) const REVISIONS: &str =
    "CREATE TRIGGER run_revision AFTER UPDATE ON runs FOR EACH ROW WHEN NEW.revision=OLD.revision BEGIN UPDATE runs SET revision=OLD.revision+1 WHERE rowid=NEW.rowid; END;
    CREATE TRIGGER request_revision AFTER UPDATE ON requests FOR EACH ROW WHEN NEW.revision=OLD.revision BEGIN UPDATE requests SET revision=OLD.revision+1 WHERE rowid=NEW.rowid; END;
    CREATE TRIGGER execution_revision AFTER UPDATE ON executions FOR EACH ROW WHEN NEW.revision=OLD.revision BEGIN UPDATE executions SET revision=OLD.revision+1 WHERE rowid=NEW.rowid; END;
    CREATE INDEX request_status ON requests(status,run_id);
    CREATE INDEX request_marks ON requests(run_id,ordinal,id,execution_id,revision);
    CREATE INDEX request_execution ON requests(execution_id,run_id);
    CREATE INDEX request_claim ON requests(execution_id,id,revision) WHERE claimed_by IS NOT NULL;
    CREATE INDEX execution_marks ON executions(id,revision);";

/// Versions before the supported additive upgrade boundary are refused.
pub const EARLIER_STATE: &str = "This state was written by an earlier artifactize. Start a new state (set ARTIFACTIZE_STATE_HOME or move the old one away). Only schema 6 and later supported versions can be upgraded.";

/// Why a state database of schema `version`, neither this one nor uninitialized, is refused.
pub fn schema_error(version: u32) -> String {
    match version {
        0 => "Unsupported state schema version: 0.".into(),
        version if version < STATE_SCHEMA_VERSION => EARLIER_STATE.into(),
        version => {
            format!("Unsupported state schema version: {version}; a newer artifactize wrote it.")
        }
    }
}

#[derive(Clone)]
pub struct Receipts {
    pub(in crate::store) connection: NotifyingConnection,
}

#[cfg(any(test, feature = "test-support"))]
#[path = "connection/tests/owned.rs"]
mod owned;
#[cfg(any(test, feature = "test-support"))]
pub use owned::OwnedReceipts;

#[cfg(test)]
#[path = "connection/tests/ownership.rs"]
mod ownership_tests;

/// Notify at the DB-worker completion boundary, even if the awaiting caller was cancelled.
/// total_changes is conservative (rolled-back changes can invalidate harmlessly). Only a
/// finished autocommit edge can publish; no event is an audit record or proof of success.
#[derive(Clone)]
pub(crate) struct NotifyingConnection {
    inner: Connection,
    publisher: crate::changes::Publisher,
    /// The connection notes which Runs its writes touch ([`store::touched`]).
    noting: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// Counts write calls on this connection to pace explicit PASSIVE WAL checkpoints.
    writes: std::sync::Arc<std::sync::atomic::AtomicU64>,
}
impl NotifyingConnection {
    pub(in crate::store) async fn finish<T>(self, result: Result<T, String>) -> Result<T, String> {
        if self.writes.load(std::sync::atomic::Ordering::Relaxed) > 0 {
            let _ = self
                .inner
                .call(|db| -> Result<(), rusqlite::Error> {
                    let _ = db.execute_batch("PRAGMA wal_checkpoint(PASSIVE);");
                    Ok(())
                })
                .await;
        }
        store::connection::finish(self.inner, result).await
    }
    pub(crate) fn new(inner: Connection, state: &Path) -> Self {
        Self {
            inner,
            publisher: crate::changes::Publisher::new(state),
            noting: Default::default(),
            writes: Default::default(),
        }
    }
    pub(crate) async fn call<F, R, E>(&self, function: F) -> Result<R, tokio_rusqlite::Error<E>>
    where
        F: FnOnce(&mut rusqlite::Connection) -> Result<R, E> + Send + 'static,
        R: Send + 'static,
        E: Send + 'static,
    {
        let publisher = self.publisher.clone();
        let noting = self.noting.clone();
        let writes = self.writes.clone();
        self.inner
            .call(move |db| {
                if !noting.load(std::sync::atomic::Ordering::Relaxed)
                    && db.is_autocommit()
                    && store::touched::install(db).unwrap_or(false)
                {
                    noting.store(true, std::sync::atomic::Ordering::Relaxed);
                }
                let before = db.total_changes();
                let result = function(db);
                if db.is_autocommit() && db.total_changes() != before {
                    for change in store::touched::take(db) {
                        publisher.notify(change);
                    }
                    let count = writes.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
                    if count.is_multiple_of(CHECKPOINT_WRITE_INTERVAL) {
                        // Best-effort PASSIVE checkpoint: never blocks active readers or fails
                        // the already-committed write.
                        let _ = db.execute_batch("PRAGMA wal_checkpoint(PASSIVE);");
                    }
                }
                result
            })
            .await
    }
}

impl Receipts {
    /// Close the shared SQLite connection before releasing its state files. Any cloned
    /// receipts also become closed; call this only after all operations on them finish.
    pub async fn close(self) -> Result<(), String> {
        self.connection.finish(Ok(())).await
    }

    pub async fn open(state: &Path, repo: &Path) -> Result<Self, String> {
        let state = prepare_directory(state, repo).map_err(|e| e.to_string())?;
        Self::open_prepared(state).await
    }

    /// Open the state database for the repository-independent Verify engine daemon; each
    /// submitted Run still checks that `state` stays outside its repository.
    pub(crate) async fn open_state(state: &Path) -> Result<Self, String> {
        let state = crate::platform::paths::resolve_target(state).map_err(|e| e.to_string())?;
        crate::platform::create_private_dir_all(&state).map_err(|e| e.to_string())?;
        let state = canonical_target(&state).map_err(|e| e.to_string())?;
        Self::open_prepared(state).await
    }

    async fn open_prepared(state: std::path::PathBuf) -> Result<Self, String> {
        check_files(&state)?;
        let state_id: crate::types::StateId = crate::agent::uuid()?.parse()?;
        let connection = Connection::open(state.join(DATABASE))
            .await
            .map_err(|e| e.to_string())?;
        let connection = NotifyingConnection::new(connection, &state);
        // WAL initialization retries share the database contention budget.
        let deadline = tokio::time::Instant::now() + store::SQLITE_BUSY_TIMEOUT;
        loop {
            let state_id = state_id.clone();
            let initialized = connection
                .call(move |db| -> Result<(), Error> {
                    store::wait_when_busy(db)?;
                    configure_wal_writer(db)?;
                    let version: u32 =
                        db.pragma_query_value(None, "user_version", |row| row.get(0))?;
                    if version != 0
                        && !(store::migrations::FIRST_VERSION..=STATE_SCHEMA_VERSION)
                            .contains(&version)
                    {
                        return Err(Error::Invalid(schema_error(version)));
                    }
                    // Fast path: already-initialized WAL databases with every additive index
                    // avoid taking a write lock on open.
                    if version == STATE_SCHEMA_VERSION && is_wal_and_indexed(db)? {
                        return Ok(());
                    }
                    if version == 0 {
                        // Must precede the first table creation to enable incremental page
                        // reclamation for newly created state databases.
                        let _ = db.pragma_update(None, "auto_vacuum", "INCREMENTAL");
                    }
                    db.pragma_update(None, "journal_mode", "WAL")?;
                    let transaction =
                        db.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
                    // Publish the schema, the state's id and the version together; readers see
                    // an empty snapshot until commit.
                    store::migrations::apply(&transaction)?;
                    if !schema_initialized(&transaction)? {
                        transaction.execute_batch(SCHEMA)?;
                        transaction.execute_batch(store::migrations::WORKSPACES)?;
                        transaction.execute_batch(REVISIONS)?;
                        transaction.execute_batch(super::ATTEMPTS)?;
                        store::executions::index_eval_history(&transaction)?;
                        transaction.execute(
                            "INSERT INTO state_meta(name,value) VALUES ('id',?)",
                            [&state_id],
                        )?;
                        transaction.pragma_update(None, "user_version", STATE_SCHEMA_VERSION)?;
                    }
                    transaction.commit()?;
                    // Create each missing additive index in its own short IMMEDIATE transaction
                    // followed by a PASSIVE WAL checkpoint so upgrading a large database never
                    // builds all indexes inside one giant write transaction.
                    for (name, sql) in store::migrations::ADDITIVE_INDEXES {
                        let exists: bool = db.query_row(
                            "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='index' AND name=?1)",
                            [name],
                            |row| row.get(0),
                        )?;
                        if !exists {
                            let tx = db.transaction_with_behavior(
                                rusqlite::TransactionBehavior::Immediate,
                            )?;
                            tx.execute_batch(sql)?;
                            tx.commit()?;
                            let _ = db.execute_batch("PRAGMA wal_checkpoint(PASSIVE);");
                        }
                    }
                    Ok(())
                })
                .await;
            match initialized {
                Ok(()) => break,
                Err(tokio_rusqlite::Error::Error(Error::Sql(rusqlite::Error::SqliteFailure(
                    error,
                    _,
                )))) if error.code == rusqlite::ErrorCode::DatabaseBusy
                    && tokio::time::Instant::now() < deadline =>
                {
                    // Concurrent first opens can race when enabling WAL despite the busy handler.
                    tokio::time::sleep(INITIALIZATION_RETRY_INTERVAL).await;
                }
                Err(error) => return connection.finish(Err(error.to_string())).await,
            }
        }
        Ok(Self { connection })
    }

    /// This state's stable id ([`read_state_id`]).
    pub async fn state_id(&self) -> Result<crate::types::StateId, String> {
        self.connection
            .call(|db| -> Result<crate::types::StateId, Error> {
                Ok(
                    db.query_row("SELECT value FROM state_meta WHERE name='id'", [], |row| {
                        row.get(0)
                    })?,
                )
            })
            .await
            .map_err(|e| e.to_string())
    }

    /// Reclaim WAL frames without blocking active readers.
    pub(crate) async fn checkpoint_passive(&self) -> Result<(), String> {
        self.connection
            .call(|db| -> Result<(), Error> {
                db.execute_batch("PRAGMA wal_checkpoint(PASSIVE);")?;
                Ok(())
            })
            .await
            .map_err(|e| e.to_string())
    }

    /// Checkpoint and truncate the WAL file when no readers pin older frames.
    pub(crate) async fn checkpoint_truncate(&self) -> Result<(), String> {
        self.connection
            .call(|db| -> Result<(), Error> {
                db.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
                Ok(())
            })
            .await
            .map_err(|e| e.to_string())
    }
}

/// Configure per-connection WAL writer pragmas: crash-safe NORMAL durability without per-commit
/// fsync stalls, and explicit checkpoint control instead of unpredictable autocheckpoints.
pub(in crate::store) fn configure_wal_writer(db: &rusqlite::Connection) -> Result<(), Error> {
    db.pragma_update(None, "foreign_keys", true)?;
    db.pragma_update(None, "synchronous", "NORMAL")?;
    db.pragma_update(None, "wal_autocheckpoint", 0)?;
    Ok(())
}

fn is_wal_and_indexed(db: &rusqlite::Connection) -> Result<bool, Error> {
    let mode: String = db.pragma_query_value(None, "journal_mode", |row| row.get(0))?;
    if !mode.eq_ignore_ascii_case("wal") {
        return Ok(false);
    }
    let expected = store::migrations::ADDITIVE_INDEX_NAMES.len() as i64;
    let present: i64 = db.query_row(
        "SELECT count(*) FROM sqlite_master WHERE type='index' AND name IN (SELECT value FROM json_each(?))",
        [serde_json::to_string(&store::migrations::ADDITIVE_INDEX_NAMES)?],
        |row| row.get(0),
    )?;
    Ok(present == expected)
}

pub(in crate::store) fn schema_initialized(
    transaction: &rusqlite::Transaction<'_>,
) -> Result<bool, Error> {
    let version: u32 = transaction.pragma_query_value(None, "user_version", |row| row.get(0))?;
    // Check both in one snapshot: initialization may commit between separate reads.
    if version == 0
        && !transaction.query_row("SELECT EXISTS(SELECT 1 FROM sqlite_master)", [], |row| {
            row.get::<_, bool>(0)
        })?
    {
        return Ok(false);
    }
    if version != STATE_SCHEMA_VERSION {
        return Err(Error::Invalid(schema_error(version)));
    }
    Ok(true)
}

/// Reject non-regular state files and an unsupported database schema without creating or
/// modifying any files on disk.
pub(crate) fn check_existing_state(state: &Path) -> Result<(), String> {
    match read_schema_version_readonly(state)? {
        Some(version)
            if version != 0
                && !(store::migrations::FIRST_VERSION..=STATE_SCHEMA_VERSION)
                    .contains(&version) =>
        {
            Err(schema_error(version))
        }
        _ => Ok(()),
    }
}

/// Reject non-regular state files and a database of another schema before any read or write.
pub(in crate::store) fn check_files(state: &Path) -> Result<(), String> {
    match state_schema(state)? {
        Some(version)
            if (store::migrations::FIRST_VERSION..STATE_SCHEMA_VERSION).contains(&version) =>
        {
            store::migrations::open_existing(state)
        }
        Some(version) if version != 0 && version != STATE_SCHEMA_VERSION => {
            Err(schema_error(version))
        }
        _ => Ok(()),
    }
}

/// Read `user_version` strictly read-only without running schema upgrades or creating files.
fn read_schema_version_readonly(state: &Path) -> Result<Option<u32>, String> {
    let state = canonical_target(state).map_err(|e| e.to_string())?;
    regular_files(&state)?;
    let database = state.join(DATABASE);
    if !crate::platform::paths::target_exists(&database).map_err(|e| e.to_string())? {
        return Ok(None);
    }
    let db = rusqlite::Connection::open_with_flags(
        &database,
        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
    )
    .map_err(|e| e.to_string())?;
    store::wait_when_busy(&db).map_err(|e| e.to_string())?;
    db.pragma_query_value(None, "user_version", |row| row.get(0))
        .map(Some)
        .map_err(|e| e.to_string())
}

/// The state database's schema version, read without creating it; `None` without a database.
/// `doctor` reports it.
pub fn state_schema(state: &Path) -> Result<Option<u32>, String> {
    let Some(version) = read_schema_version_readonly(state)? else {
        return Ok(None);
    };
    if (store::migrations::FIRST_VERSION..STATE_SCHEMA_VERSION).contains(&version) {
        let state = canonical_target(state).map_err(|e| e.to_string())?;
        store::migrations::open_existing(&state)?;
        return read_schema_version_readonly(&state);
    }
    Ok(Some(version))
}

/// The state's stable id, read without creating anything; `None` until a command that writes
/// the state has opened it.
pub fn read_state_id(state: &Path) -> Result<Option<crate::types::StateId>, String> {
    let state = canonical_target(state).map_err(|e| e.to_string())?;
    check_files(&state)?;
    let database = state.join(DATABASE);
    if !crate::platform::paths::target_exists(&database).map_err(|e| e.to_string())? {
        return Ok(None);
    }
    let read = || -> Result<Option<crate::types::StateId>, Error> {
        let mut db = rusqlite::Connection::open_with_flags(
            &database,
            rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
        )?;
        store::wait_when_busy(&db)?;
        let transaction = db.transaction()?;
        if !schema_initialized(&transaction)? {
            return Ok(None);
        }
        Ok(transaction
            .query_row("SELECT value FROM state_meta WHERE name='id'", [], |row| {
                row.get(0)
            })
            .optional()?)
    };
    read().map_err(|e| e.to_string())
}

pub(crate) fn regular_files(state: &Path) -> Result<(), String> {
    regular_files_with_retry(state, || {
        std::thread::sleep(store::TRANSIENT_ACCESS_BACKOFF);
    })
}

/// The probe and retry path is shared with the seam test; only the between-attempt effect
/// differs, so a fixture can release a pending-delete handle exactly after a failed probe.
pub(in crate::store) fn regular_files_with_retry(
    state: &Path,
    mut before_retry: impl FnMut(),
) -> Result<(), String> {
    for suffix in ["", "-wal", "-shm"] {
        let path = state.join(format!("{DATABASE}{suffix}"));
        match store::retry_transient_access(|| crate::platform::path_kind(&path), &mut before_retry)
        {
            Ok(kind) if kind != crate::platform::FileKind::File => {
                return Err(format!(
                    "State files must be regular files: {}",
                    crate::platform::path_text(&path)
                ));
            }
            Err(error) if error.kind() != std::io::ErrorKind::NotFound => {
                return Err(error.to_string());
            }
            _ => {}
        }
    }
    Ok(())
}