Skip to main content

allen_store_sqlite/
lib.rs

1//! Implements [`allen_store::AgentStore`] on local SQLite through a single-owner Tokio
2//! actor that enforces `BEGIN IMMEDIATE`, `PRAGMA synchronous = FULL`, and SHA-256
3//! checksummed startup migrations.
4//!
5//! # Architecture & Layer Role
6//!
7//! Within the Allen Open Agent Infrastructure Standard, `allen-store-sqlite` is the
8//! single-node Layer 1 persistence backend. Local binaries (the host authority daemon,
9//! `allen`, and standalone CLI consumers) pair it with `allen-runtime` for durable
10//! sessions, fenced run leases, effect journals, command deduplication receipts, and
11//! checked integer spend tracking without an external database service. It satisfies
12//! the same `allen_store::conformance` invariants as [`allen_store::InMemoryStore`] and
13//! external custom backends.
14//!
15//! # Quick Start
16//!
17//! Pass `":memory:"` for an isolated in-memory SQLite database (useful in tests) or a
18//! filesystem path for durable on-disk storage:
19//!
20//! ```rust
21//! use allen_store::{CommandStore, LeaseStore, OwnerId, SessionStore, StepCommit};
22//! use allen_store_sqlite::{JournalMode, SqliteAgentStore, SqliteStoreConfig};
23//! use allen_types::ids::{SessionId, SessionRevision, TenantId};
24//! use std::time::Duration;
25//!
26//! # tokio::runtime::Runtime::new().unwrap().block_on(async {
27//! let cfg = SqliteStoreConfig::try_new(":memory:")
28//!     .unwrap()
29//!     .with_journal_mode(JournalMode::Wal);
30//! let store = SqliteAgentStore::connect_and_migrate(cfg).await.unwrap();
31//!
32//! let tenant = TenantId::try_new("org:local").unwrap();
33//! let session = SessionId::try_new("sess:1").unwrap();
34//! let owner = OwnerId::try_new("node-1").unwrap();
35//!
36//! store.create_session(&tenant, &session, None).await.unwrap();
37//! let lease = store
38//!     .acquire_session_lease(&tenant, &session, &owner, Duration::from_secs(30))
39//!     .await
40//!     .unwrap();
41//! let committed = store
42//!     .commit_step(&lease, StepCommit::empty(SessionRevision::INITIAL))
43//!     .await
44//!     .unwrap();
45//! assert_eq!(committed.new_revision, SessionRevision::from_u64(1));
46//! # });
47//! ```
48//!
49//! # API Guide
50//!
51//! - [`SqliteStoreConfig`]: Validated database path and [`JournalMode`] configuration.
52//! - [`JournalMode`]: Choice between [`JournalMode::Wal`] (default) and
53//!   [`JournalMode::Delete`].
54//! - [`SqliteAgentStore`]: Cheaply cloneable handle to the single-owner SQLite actor
55//!   implementing [`allen_store::LeaseStore`], [`allen_store::CommandStore`],
56//!   [`allen_store::SessionStore`], [`allen_store::SpendStore`], and
57//!   [`allen_store::AgentStore`].
58//!
59//! # Durability & Concurrency Invariants
60//!
61//! - Enforces `#![forbid(unsafe_code)]`.
62//! - Owns one `sqlx::SqliteConnection` inside a dedicated Tokio task fed by a bounded
63//!   `mpsc` channel (capacity 256), serializing all writes to avoid `SQLITE_BUSY`
64//!   contention across concurrent tasks.
65//! - Configures `PRAGMA foreign_keys = ON`, `PRAGMA synchronous = FULL`, a 5-second
66//!   `busy_timeout`, and the requested [`JournalMode`] on startup.
67//! - Runs every mutating operation inside `BEGIN IMMEDIATE` with full rollback on
68//!   [`StoreError::StaleFence`], [`StoreError::RevisionConflict`],
69//!   [`StoreError::TenantMismatch`], [`StoreError::IllegalTransition`], or
70//!   [`StoreError::DuplicateIdempotencyKey`].
71//! - Applies append-only SQL migrations tracked in `schema_migrations` with SHA-256
72//!   checksums; any modified or mismatched applied migration fails closed on startup with
73//!   [`StoreError::SchemaDrift`].
74
75#![forbid(unsafe_code)]
76#![warn(missing_docs)]
77#![cfg_attr(docsrs, feature(doc_cfg))]
78
79#[cfg(feature = "durable")]
80#[cfg_attr(docsrs, doc(cfg(feature = "durable")))]
81pub mod durable;
82
83use allen_store::{
84    CommandReceipt, CommandStore, LeaseStore, LeaseToken, LoadedBranch, OwnerId, PoolName,
85    SessionStore, SpendStore, StepCommit, StepCommitResult, StoreError, TerminalRunStatus,
86};
87use allen_types::ids::{
88    CommandId, EffectId, EntryId, OwnerFence, RunId, ScopeEpochs, SessionId, SessionRevision,
89    TenantId,
90};
91use allen_types::journal::{EffectEvent, EffectRecord, EffectState, transition_effect};
92use allen_types::lifecycle::CommandSettlement;
93use allen_types::money::{BillingClass, MicroUsd};
94use allen_types::session::{SessionEntry, SessionEntryPayload};
95use futures_util::future::BoxFuture;
96use sha2::{Digest, Sha256};
97use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqliteSynchronous};
98use sqlx::{ConnectOptions, Row, SqliteConnection};
99use std::collections::HashMap;
100use std::fmt;
101use std::path::{Path, PathBuf};
102use std::sync::Arc;
103use std::sync::atomic::{AtomicU64, Ordering};
104use std::time::{Duration, SystemTime, UNIX_EPOCH};
105use tokio::sync::{mpsc, oneshot};
106
107static RUN_SEQ: AtomicU64 = AtomicU64::new(1);
108
109pub(crate) struct RuntimeMigration {
110    pub(crate) version: i64,
111    pub(crate) name: &'static str,
112    pub(crate) sql: &'static str,
113}
114
115pub(crate) const SQLITE_MIGRATIONS: &[RuntimeMigration] = &[RuntimeMigration {
116    version: 1,
117    name: "0001_initial",
118    sql: include_str!("../migrations/0001_initial.sql"),
119}];
120
121/// SQLite journal mode configured on the actor's database connection.
122#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
123pub enum JournalMode {
124    /// Write-ahead logging (`PRAGMA journal_mode = WAL`), the default for local durability
125    /// and low-latency checkpoint commits.
126    #[default]
127    Wal,
128    /// Rollback journal deleted after each transaction (`PRAGMA journal_mode = DELETE`),
129    /// avoiding `-wal` and `-shm` sidecar files on filesystems that disallow them.
130    Delete,
131}
132
133/// Validated connection configuration for [`SqliteAgentStore::connect_and_migrate`].
134#[derive(Clone, Debug, PartialEq, Eq)]
135pub struct SqliteStoreConfig {
136    path: PathBuf,
137    journal_mode: JournalMode,
138}
139
140impl SqliteStoreConfig {
141    /// Creates a configuration targeting `path` with [`JournalMode::Wal`].
142    ///
143    /// Pass `":memory:"` for an ephemeral in-memory database or a file path for durable
144    /// on-disk storage. Missing parent directories are created when
145    /// [`SqliteAgentStore::connect_and_migrate`] runs.
146    ///
147    /// # Errors
148    ///
149    /// Returns [`StoreError::Backend`] when `path` is empty.
150    pub fn try_new(path: impl Into<PathBuf>) -> Result<Self, StoreError> {
151        let path = path.into();
152        if path.as_os_str().is_empty() {
153            return Err(StoreError::Backend(
154                "sqlite database path must not be empty".to_owned(),
155            ));
156        }
157        Ok(Self {
158            path,
159            journal_mode: JournalMode::default(),
160        })
161    }
162
163    /// Selects the SQLite [`JournalMode`] applied when opening the database connection.
164    #[must_use]
165    pub fn with_journal_mode(mut self, mode: JournalMode) -> Self {
166        self.journal_mode = mode;
167        self
168    }
169
170    /// Returns the configured SQLite database file path (or `":memory:"`).
171    #[must_use]
172    pub fn path(&self) -> &Path {
173        &self.path
174    }
175
176    /// Returns the configured SQLite [`JournalMode`].
177    #[must_use]
178    pub const fn journal_mode(&self) -> JournalMode {
179        self.journal_mode
180    }
181}
182
183enum ActorReq {
184    EnqueueRun {
185        tenant_id: TenantId,
186        session_id: SessionId,
187        run_id: RunId,
188        pool_name: PoolName,
189        reply: oneshot::Sender<Result<(), StoreError>>,
190    },
191    AcquireSessionLease {
192        tenant_id: TenantId,
193        session_id: SessionId,
194        owner_id: OwnerId,
195        ttl: Duration,
196        reply: oneshot::Sender<Result<LeaseToken, StoreError>>,
197    },
198    ClaimQueuedRun {
199        owner_id: OwnerId,
200        pool_name: PoolName,
201        ttl: Duration,
202        reply: oneshot::Sender<Result<Option<LeaseToken>, StoreError>>,
203    },
204    ReclaimExpiredRun {
205        owner_id: OwnerId,
206        pool_name: PoolName,
207        ttl: Duration,
208        reply: oneshot::Sender<Result<Option<LeaseToken>, StoreError>>,
209    },
210    RenewLease {
211        lease: LeaseToken,
212        ttl: Duration,
213        reply: oneshot::Sender<Result<LeaseToken, StoreError>>,
214    },
215    FinishRun {
216        lease: LeaseToken,
217        status: TerminalRunStatus,
218        summary_code: Option<String>,
219        reply: oneshot::Sender<Result<(), StoreError>>,
220    },
221    RecoverExpiredRun {
222        tenant_id: TenantId,
223        run_id: RunId,
224        new_owner_id: OwnerId,
225        ttl: Duration,
226        reply: oneshot::Sender<Result<(LeaseToken, Vec<EffectRecord>), StoreError>>,
227    },
228    ForceRecoverRun {
229        tenant_id: TenantId,
230        run_id: RunId,
231        new_owner_id: OwnerId,
232        ttl: Duration,
233        reply: oneshot::Sender<Result<LeaseToken, StoreError>>,
234    },
235    LookupReceipt {
236        tenant_id: TenantId,
237        session_id: SessionId,
238        command_id: CommandId,
239        reply: oneshot::Sender<Result<Option<CommandReceipt>, StoreError>>,
240    },
241    CommitStep {
242        lease: LeaseToken,
243        commit: Box<StepCommit>,
244        reply: oneshot::Sender<Result<StepCommitResult, StoreError>>,
245    },
246    ListUnknownEffects {
247        tenant_id: TenantId,
248        run_id: RunId,
249        reply: oneshot::Sender<Result<Vec<EffectRecord>, StoreError>>,
250    },
251    ListClaimedEffects {
252        tenant_id: TenantId,
253        run_id: RunId,
254        reply: oneshot::Sender<Result<Vec<EffectRecord>, StoreError>>,
255    },
256    CreateSession {
257        tenant_id: TenantId,
258        session_id: SessionId,
259        parent_session_id: Option<SessionId>,
260        reply: oneshot::Sender<Result<StepCommitResult, StoreError>>,
261    },
262    LoadBranch {
263        tenant_id: TenantId,
264        session_id: SessionId,
265        leaf: Option<EntryId>,
266        reply: oneshot::Sender<Result<LoadedBranch, StoreError>>,
267    },
268    SumSpendSince {
269        tenant_id: TenantId,
270        since_ms: i64,
271        billing_class: Option<BillingClass>,
272        reply: oneshot::Sender<Result<MicroUsd, StoreError>>,
273    },
274    SumRunSpend {
275        tenant_id: TenantId,
276        run_id: RunId,
277        reply: oneshot::Sender<Result<MicroUsd, StoreError>>,
278    },
279}
280
281/// Cloneable handle to the single-owner SQLite Tokio actor implementing
282/// [`allen_store::AgentStore`].
283///
284/// Cloning this handle shares the same bounded command channel to the single actor task.
285/// When all clones are dropped, the channel closes and the actor exits cleanly after
286/// finishing any in-flight transaction.
287#[derive(Clone)]
288pub struct SqliteAgentStore {
289    tx: mpsc::Sender<ActorReq>,
290    path: Arc<Path>,
291    journal_mode: JournalMode,
292}
293
294impl fmt::Debug for SqliteAgentStore {
295    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296        f.debug_struct("SqliteAgentStore")
297            .field("path", &self.path)
298            .field("journal_mode", &self.journal_mode)
299            .field("closed", &self.tx.is_closed())
300            .finish()
301    }
302}
303
304impl SqliteAgentStore {
305    /// Opens the SQLite database described by `config`, spawns the single-owner Tokio
306    /// actor, and verifies or applies all append-only SQL migrations before returning.
307    ///
308    /// Creates missing parent directories for file-backed paths, enables foreign keys and
309    /// `PRAGMA synchronous = FULL`, and verifies SHA-256 checksums for every previously
310    /// applied migration in `schema_migrations`.
311    ///
312    /// # Errors
313    ///
314    /// Returns:
315    /// - [`StoreError::SchemaDrift`] if an already-applied migration's name or SHA-256
316    ///   checksum differs from the compiled migration set.
317    /// - [`StoreError::Backend`] if creating parent directories, opening SQLite, applying
318    ///   migrations, or initializing the actor task fails.
319    ///
320    /// # Examples
321    ///
322    /// ```rust
323    /// use allen_store_sqlite::{SqliteAgentStore, SqliteStoreConfig};
324    ///
325    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
326    /// let store = SqliteAgentStore::connect_and_migrate(
327    ///     SqliteStoreConfig::try_new(":memory:").unwrap(),
328    /// )
329    /// .await
330    /// .unwrap();
331    /// assert!(format!("{store:?}").contains("SqliteAgentStore"));
332    /// # });
333    /// ```
334    pub async fn connect_and_migrate(config: SqliteStoreConfig) -> Result<Self, StoreError> {
335        if let Some(parent) = config.path.parent()
336            && !parent.as_os_str().is_empty()
337        {
338            std::fs::create_dir_all(parent)
339                .map_err(|e| StoreError::Backend(format!("create sqlite dir failed: {e}")))?;
340        }
341        let sqlx_mode = match config.journal_mode {
342            JournalMode::Wal => SqliteJournalMode::Wal,
343            JournalMode::Delete => SqliteJournalMode::Delete,
344        };
345        let opts = SqliteConnectOptions::new()
346            .filename(&config.path)
347            .create_if_missing(true)
348            .foreign_keys(true)
349            .synchronous(SqliteSynchronous::Full)
350            .busy_timeout(Duration::from_secs(5))
351            .journal_mode(sqlx_mode);
352
353        let path: Arc<Path> = Arc::from(config.path.as_path());
354        let journal_mode = config.journal_mode;
355
356        let (tx, mut rx) = mpsc::channel::<ActorReq>(256);
357        let (ready_tx, ready_rx) = oneshot::channel::<Result<(), StoreError>>();
358        tokio::spawn(async move {
359            let mut conn = match opts.connect().await {
360                Ok(c) => c,
361                Err(e) => {
362                    let _ = ready_tx.send(Err(StoreError::Backend(format!(
363                        "sqlite connect failed: {e}"
364                    ))));
365                    return;
366                }
367            };
368            if let Err(e) = run_migrations(&mut conn).await {
369                let _ = ready_tx.send(Err(e));
370                return;
371            }
372            let _ = ready_tx.send(Ok(()));
373            let mut actor = SqliteActor { conn };
374            while let Some(req) = rx.recv().await {
375                actor.handle(req).await;
376            }
377        });
378
379        ready_rx
380            .await
381            .map_err(|_| StoreError::Backend("sqlite actor init task terminated".to_owned()))??;
382
383        Ok(Self {
384            tx,
385            path,
386            journal_mode,
387        })
388    }
389
390    async fn call<T>(
391        &self,
392        build: impl FnOnce(oneshot::Sender<Result<T, StoreError>>) -> ActorReq,
393    ) -> Result<T, StoreError> {
394        let (reply_tx, reply_rx) = oneshot::channel();
395        self.tx
396            .send(build(reply_tx))
397            .await
398            .map_err(|_| StoreError::Backend("sqlite actor closed".to_owned()))?;
399        reply_rx
400            .await
401            .map_err(|_| StoreError::Backend("sqlite actor dropped reply".to_owned()))?
402    }
403}
404
405fn now_ms() -> i64 {
406    i64::try_from(
407        SystemTime::now()
408            .duration_since(UNIX_EPOCH)
409            .unwrap_or_default()
410            .as_millis(),
411    )
412    .unwrap_or(i64::MAX)
413}
414
415fn expires_at_from(now: i64, ttl: Duration) -> i64 {
416    let ttl_ms = i64::try_from(ttl.as_millis()).unwrap_or(i64::MAX);
417    now.saturating_add(ttl_ms)
418}
419
420fn parse_u64_col(raw: i64, col: &str) -> Result<u64, StoreError> {
421    u64::try_from(raw)
422        .map_err(|_| StoreError::Backend(format!("corrupt negative {col} in sqlite: {raw}")))
423}
424
425fn to_sql_i64(value: u64, col: &str) -> Result<i64, StoreError> {
426    i64::try_from(value)
427        .map_err(|_| StoreError::Backend(format!("{col} exceeds sqlite i64 range: {value}")))
428}
429
430fn parse_owner_fence(raw: i64) -> Result<OwnerFence, StoreError> {
431    u64::try_from(raw)
432        .ok()
433        .and_then(OwnerFence::try_new)
434        .ok_or_else(|| StoreError::Backend(format!("invalid owner_epoch in sqlite: {raw}")))
435}
436
437fn advance_owner_fence(cur_epoch: i64) -> Result<(OwnerFence, i64), StoreError> {
438    let next = if cur_epoch == 0 {
439        OwnerFence::INITIAL
440    } else {
441        parse_owner_fence(cur_epoch)?
442            .next()
443            .ok_or_else(|| StoreError::Backend("fence overflow".to_owned()))?
444    };
445    let next_i64 = to_sql_i64(next.as_u64(), "owner_epoch")?;
446    Ok((next, next_i64))
447}
448
449fn sha256_hex(sql: &str) -> String {
450    let digest = Sha256::digest(sql.as_bytes());
451    let mut out = String::with_capacity(64);
452    for b in digest {
453        use std::fmt::Write as _;
454        let _ = write!(out, "{b:02x}");
455    }
456    out
457}
458
459fn db_err(e: sqlx::Error) -> StoreError {
460    if let sqlx::Error::Database(ref db_err) = e
461        && matches!(db_err.code().as_deref(), Some("1555" | "2067"))
462    {
463        return StoreError::DuplicateIdempotencyKey(db_err.message().to_owned());
464    }
465    StoreError::Backend(e.to_string())
466}
467
468fn verify_running_run_fence(
469    run_id: &RunId,
470    status: &str,
471    actual_epoch: i64,
472    expected: OwnerFence,
473) -> Result<(), StoreError> {
474    if actual_epoch > 0 {
475        let actual_fence = parse_owner_fence(actual_epoch)?;
476        if actual_fence != expected {
477            return Err(StoreError::StaleFence {
478                expected,
479                actual: actual_fence,
480            });
481        }
482    }
483    if status != "running" {
484        return Err(StoreError::Backend(format!(
485            "run {run_id} is not running (status: {status})"
486        )));
487    }
488    if actual_epoch <= 0 {
489        return Err(StoreError::Backend(format!(
490            "invalid owner_epoch in sqlite: {actual_epoch}"
491        )));
492    }
493    Ok(())
494}
495
496async fn transition_claimed_effects_tx(
497    conn: &mut SqliteConnection,
498    tenant: &TenantId,
499    run: &RunId,
500    next_fence: OwnerFence,
501    next_epoch: i64,
502) -> Result<Vec<EffectRecord>, StoreError> {
503    let claimed_rows = sqlx::query(
504        "SELECT effect_id, idempotency_key, action_sha256, result_digest
505         FROM effects WHERE tenant_id = ?1 AND run_id = ?2 AND state = 'claimed'
506         ORDER BY effect_id ASC",
507    )
508    .bind(tenant.as_str())
509    .bind(run.as_str())
510    .fetch_all(&mut *conn)
511    .await
512    .map_err(db_err)?;
513
514    let mut unknown = Vec::with_capacity(claimed_rows.len());
515    for r in claimed_rows {
516        let effect_id_raw: String = r.get("effect_id");
517        let next_state = transition_effect(EffectState::Claimed, EffectEvent::RecoverCrash)?;
518        sqlx::query("UPDATE effects SET state = ?1, owner_epoch = ?2 WHERE effect_id = ?3")
519            .bind(next_state.as_str())
520            .bind(next_epoch)
521            .bind(&effect_id_raw)
522            .execute(&mut *conn)
523            .await
524            .map_err(db_err)?;
525        let effect_id = EffectId::try_new(effect_id_raw)
526            .map_err(|e| StoreError::Backend(format!("corrupt effect_id in sqlite: {e}")))?;
527        unknown.push(EffectRecord {
528            tenant_id: tenant.clone(),
529            effect_id,
530            run_id: run.clone(),
531            idempotency_key: r.get("idempotency_key"),
532            fence: next_fence,
533            state: next_state,
534            action_sha256: r.get("action_sha256"),
535            result_digest: r.get("result_digest"),
536        });
537    }
538    Ok(unknown)
539}
540
541async fn run_migrations(conn: &mut SqliteConnection) -> Result<(), StoreError> {
542    sqlx::query(
543        "CREATE TABLE IF NOT EXISTS schema_migrations (
544            version INTEGER PRIMARY KEY,
545            name TEXT NOT NULL,
546            sha256 TEXT NOT NULL,
547            applied_at_ms INTEGER NOT NULL
548        )",
549    )
550    .execute(&mut *conn)
551    .await
552    .map_err(db_err)?;
553
554    for m in SQLITE_MIGRATIONS {
555        let expected_sha = sha256_hex(m.sql);
556        let existing: Option<(String, String)> =
557            sqlx::query_as("SELECT name, sha256 FROM schema_migrations WHERE version = ?1")
558                .bind(m.version)
559                .fetch_optional(&mut *conn)
560                .await
561                .map_err(db_err)?;
562
563        if let Some((name, sha)) = existing {
564            if name != m.name || sha != expected_sha {
565                return Err(StoreError::SchemaDrift(format!(
566                    "migration {} checksum/name drift: expected ({}, {}), found ({}, {})",
567                    m.version, m.name, expected_sha, name, sha
568                )));
569            }
570            continue;
571        }
572
573        sqlx::query("BEGIN IMMEDIATE")
574            .execute(&mut *conn)
575            .await
576            .map_err(db_err)?;
577
578        let apply_res = async {
579            sqlx::Executor::execute(&mut *conn, m.sql)
580                .await
581                .map_err(db_err)?;
582            sqlx::query(
583                "INSERT INTO schema_migrations(version, name, sha256, applied_at_ms) VALUES(?1, ?2, ?3, ?4)",
584            )
585            .bind(m.version)
586            .bind(m.name)
587            .bind(&expected_sha)
588            .bind(now_ms())
589            .execute(&mut *conn)
590            .await
591            .map_err(db_err)?;
592            Ok::<(), StoreError>(())
593        }
594        .await;
595
596        match apply_res {
597            Ok(()) => {
598                sqlx::query("COMMIT")
599                    .execute(&mut *conn)
600                    .await
601                    .map_err(db_err)?;
602            }
603            Err(err) => {
604                let _ = sqlx::query("ROLLBACK").execute(&mut *conn).await;
605                return Err(err);
606            }
607        }
608    }
609    Ok(())
610}
611
612struct SqliteActor {
613    conn: SqliteConnection,
614}
615
616impl SqliteActor {
617    async fn handle(&mut self, req: ActorReq) {
618        match req {
619            ActorReq::EnqueueRun {
620                tenant_id,
621                session_id,
622                run_id,
623                pool_name,
624                reply,
625            } => {
626                let _ = reply.send(
627                    self.enqueue_run(&tenant_id, &session_id, &run_id, &pool_name)
628                        .await,
629                );
630            }
631            ActorReq::AcquireSessionLease {
632                tenant_id,
633                session_id,
634                owner_id,
635                ttl,
636                reply,
637            } => {
638                let _ = reply.send(
639                    self.acquire_session_lease(&tenant_id, &session_id, &owner_id, ttl)
640                        .await,
641                );
642            }
643            ActorReq::ClaimQueuedRun {
644                owner_id,
645                pool_name,
646                ttl,
647                reply,
648            } => {
649                let _ = reply.send(self.claim_queued_run(&owner_id, &pool_name, ttl).await);
650            }
651            ActorReq::ReclaimExpiredRun {
652                owner_id,
653                pool_name,
654                ttl,
655                reply,
656            } => {
657                let _ = reply.send(self.reclaim_expired_run(&owner_id, &pool_name, ttl).await);
658            }
659            ActorReq::RenewLease { lease, ttl, reply } => {
660                let _ = reply.send(self.renew_lease(&lease, ttl).await);
661            }
662            ActorReq::FinishRun {
663                lease,
664                status,
665                summary_code,
666                reply,
667            } => {
668                let _ = reply.send(
669                    self.finish_run(&lease, status, summary_code.as_deref())
670                        .await,
671                );
672            }
673            ActorReq::RecoverExpiredRun {
674                tenant_id,
675                run_id,
676                new_owner_id,
677                ttl,
678                reply,
679            } => {
680                let _ = reply.send(
681                    self.recover_expired_run(&tenant_id, &run_id, &new_owner_id, ttl)
682                        .await,
683                );
684            }
685            ActorReq::ForceRecoverRun {
686                tenant_id,
687                run_id,
688                new_owner_id,
689                ttl,
690                reply,
691            } => {
692                let _ = reply.send(
693                    self.force_recover_run(&tenant_id, &run_id, &new_owner_id, ttl)
694                        .await,
695                );
696            }
697            ActorReq::LookupReceipt {
698                tenant_id,
699                session_id,
700                command_id,
701                reply,
702            } => {
703                let _ = reply.send(
704                    self.lookup_receipt(&tenant_id, &session_id, &command_id)
705                        .await,
706                );
707            }
708            ActorReq::CommitStep {
709                lease,
710                commit,
711                reply,
712            } => {
713                let _ = reply.send(self.commit_step(&lease, *commit).await);
714            }
715            ActorReq::ListUnknownEffects {
716                tenant_id,
717                run_id,
718                reply,
719            } => {
720                let _ = reply.send(self.list_unknown_effects(&tenant_id, &run_id).await);
721            }
722            ActorReq::ListClaimedEffects {
723                tenant_id,
724                run_id,
725                reply,
726            } => {
727                let _ = reply.send(self.list_claimed_effects(&tenant_id, &run_id).await);
728            }
729            ActorReq::CreateSession {
730                tenant_id,
731                session_id,
732                parent_session_id,
733                reply,
734            } => {
735                let _ = reply.send(
736                    self.create_session(&tenant_id, &session_id, parent_session_id.as_ref())
737                        .await,
738                );
739            }
740            ActorReq::LoadBranch {
741                tenant_id,
742                session_id,
743                leaf,
744                reply,
745            } => {
746                let _ = reply.send(
747                    self.load_branch(&tenant_id, &session_id, leaf.as_ref())
748                        .await,
749                );
750            }
751            ActorReq::SumSpendSince {
752                tenant_id,
753                since_ms,
754                billing_class,
755                reply,
756            } => {
757                let _ = reply.send(
758                    self.sum_spend_since(&tenant_id, since_ms, billing_class)
759                        .await,
760                );
761            }
762            ActorReq::SumRunSpend {
763                tenant_id,
764                run_id,
765                reply,
766            } => {
767                let _ = reply.send(self.sum_run_spend(&tenant_id, &run_id).await);
768            }
769        }
770    }
771
772    async fn with_immediate_tx<T, F>(&mut self, f: F) -> Result<T, StoreError>
773    where
774        F: for<'c> FnOnce(&'c mut SqliteConnection) -> BoxFuture<'c, Result<T, StoreError>>,
775    {
776        sqlx::query("BEGIN IMMEDIATE")
777            .execute(&mut self.conn)
778            .await
779            .map_err(db_err)?;
780        match f(&mut self.conn).await {
781            Ok(val) => {
782                sqlx::query("COMMIT")
783                    .execute(&mut self.conn)
784                    .await
785                    .map_err(db_err)?;
786                Ok(val)
787            }
788            Err(err) => {
789                let _ = sqlx::query("ROLLBACK").execute(&mut self.conn).await;
790                Err(err)
791            }
792        }
793    }
794
795    async fn create_session(
796        &mut self,
797        tenant_id: &TenantId,
798        session_id: &SessionId,
799        parent_session_id: Option<&SessionId>,
800    ) -> Result<StepCommitResult, StoreError> {
801        let tenant = tenant_id.as_str().to_owned();
802        let sess = session_id.as_str().to_owned();
803        let parent = parent_session_id.map(|p| p.as_str().to_owned());
804        self.with_immediate_tx(move |conn| {
805            Box::pin(async move {
806                let exists: Option<String> =
807                    sqlx::query_scalar("SELECT tenant_id FROM sessions WHERE session_id = ?1")
808                        .bind(&sess)
809                        .fetch_optional(&mut *conn)
810                        .await
811                        .map_err(db_err)?;
812                if exists.is_some() {
813                    return Err(StoreError::DuplicateIdempotencyKey(format!(
814                        "session {sess} already exists"
815                    )));
816                }
817                sqlx::query(
818                    "INSERT INTO sessions(tenant_id, session_id, parent_session_id, revision, branch_epoch, activity_epoch, active_leaf, created_at_ms)
819                     VALUES(?1, ?2, ?3, 0, 0, 0, NULL, ?4)",
820                )
821                .bind(&tenant)
822                .bind(&sess)
823                .bind(&parent)
824                .bind(now_ms())
825                .execute(&mut *conn)
826                .await
827                .map_err(db_err)?;
828                Ok(StepCommitResult {
829                    new_revision: SessionRevision::INITIAL,
830                    epochs: ScopeEpochs::default(),
831                })
832            })
833        })
834        .await
835    }
836
837    async fn enqueue_run(
838        &mut self,
839        tenant_id: &TenantId,
840        session_id: &SessionId,
841        run_id: &RunId,
842        pool_name: &PoolName,
843    ) -> Result<(), StoreError> {
844        let tenant = tenant_id.as_str().to_owned();
845        let sess = session_id.as_str().to_owned();
846        let run = run_id.as_str().to_owned();
847        let pool = pool_name.as_str().to_owned();
848        self.with_immediate_tx(move |conn| {
849            Box::pin(async move {
850                let row_tenant: Option<String> =
851                    sqlx::query_scalar("SELECT tenant_id FROM sessions WHERE session_id = ?1")
852                        .bind(&sess)
853                        .fetch_optional(&mut *conn)
854                        .await
855                        .map_err(db_err)?;
856                match row_tenant {
857                    None => return Err(StoreError::NotFound(format!("session {sess} not found"))),
858                    Some(t) if t != tenant => return Err(StoreError::TenantMismatch),
859                    Some(_) => {}
860                }
861                let dup: Option<String> =
862                    sqlx::query_scalar("SELECT run_id FROM runs WHERE run_id = ?1")
863                        .bind(&run)
864                        .fetch_optional(&mut *conn)
865                        .await
866                        .map_err(db_err)?;
867                if dup.is_some() {
868                    return Err(StoreError::DuplicateIdempotencyKey(format!(
869                        "run {run} already exists"
870                    )));
871                }
872                sqlx::query(
873                    "INSERT INTO runs(tenant_id, run_id, session_id, pool_name, status, owner_id, owner_epoch, expires_at_ms, summary_code, created_at_ms)
874                     VALUES(?1, ?2, ?3, ?4, 'queued', NULL, 0, 0, NULL, ?5)",
875                )
876                .bind(&tenant)
877                .bind(&run)
878                .bind(&sess)
879                .bind(&pool)
880                .bind(now_ms())
881                .execute(&mut *conn)
882                .await
883                .map_err(db_err)?;
884                Ok(())
885            })
886        })
887        .await
888    }
889
890    async fn acquire_session_lease(
891        &mut self,
892        tenant_id: &TenantId,
893        session_id: &SessionId,
894        owner_id: &OwnerId,
895        ttl: Duration,
896    ) -> Result<LeaseToken, StoreError> {
897        let tenant = tenant_id.clone();
898        let sess = session_id.clone();
899        let owner = owner_id.clone();
900        self.with_immediate_tx(move |conn| {
901            Box::pin(async move {
902                let row_tenant: Option<String> =
903                    sqlx::query_scalar("SELECT tenant_id FROM sessions WHERE session_id = ?1")
904                        .bind(sess.as_str())
905                        .fetch_optional(&mut *conn)
906                        .await
907                        .map_err(db_err)?;
908                match row_tenant {
909                    None => return Err(StoreError::NotFound(format!("session {sess} not found"))),
910                    Some(t) if t != tenant.as_str() => return Err(StoreError::TenantMismatch),
911                    Some(_) => {}
912                }
913
914                let now = now_ms();
915                let expires = expires_at_from(now, ttl);
916                let existing: Option<(String, Option<String>, i64, i64)> = sqlx::query_as(
917                    "SELECT run_id, owner_id, owner_epoch, expires_at_ms FROM runs
918                     WHERE tenant_id = ?1 AND session_id = ?2 AND status = 'running' LIMIT 1",
919                )
920                .bind(tenant.as_str())
921                .bind(sess.as_str())
922                .fetch_optional(&mut *conn)
923                .await
924                .map_err(db_err)?;
925
926                let (run_id, next_fence) = if let Some((rid, cur_owner, epoch, cur_exp)) = existing
927                {
928                    if cur_exp > now && cur_owner.as_deref() != Some(owner.as_str()) {
929                        return Err(StoreError::LeaseHeldByOther {
930                            expires_at_ms: cur_exp,
931                        });
932                    }
933                    let (next_fence, next_epoch) = advance_owner_fence(epoch)?;
934                    let updated = sqlx::query(
935                        "UPDATE runs SET owner_id = ?1, owner_epoch = ?2, expires_at_ms = ?3
936                         WHERE run_id = ?4 AND status = 'running' AND owner_epoch = ?5",
937                    )
938                    .bind(owner.as_str())
939                    .bind(next_epoch)
940                    .bind(expires)
941                    .bind(&rid)
942                    .bind(epoch)
943                    .execute(&mut *conn)
944                    .await
945                    .map_err(db_err)?;
946                    if updated.rows_affected() != 1 {
947                        return Err(StoreError::Backend(format!(
948                            "concurrent lease update on run {rid}"
949                        )));
950                    }
951                    let typed_rid = RunId::try_new(rid)
952                        .map_err(|e| StoreError::Backend(format!("corrupt run_id in sqlite: {e}")))?;
953                    let _ = transition_claimed_effects_tx(
954                        conn,
955                        &tenant,
956                        &typed_rid,
957                        next_fence,
958                        next_epoch,
959                    )
960                    .await?;
961                    (typed_rid, next_fence)
962                } else {
963                    let mut raw = [0u8; 16];
964                    let rid_str = if getrandom::fill(&mut raw).is_ok() {
965                        let mut hex = String::with_capacity(32);
966                        for b in raw {
967                            use std::fmt::Write as _;
968                            let _ = write!(&mut hex, "{b:02x}");
969                        }
970                        format!("run:sqlite:{hex}")
971                    } else {
972                        let seq = RUN_SEQ.fetch_add(1, Ordering::Relaxed);
973                        format!("run:sqlite:{now}:{seq}")
974                    };
975                    let rid = RunId::try_new(rid_str)
976                        .map_err(|e| StoreError::Backend(format!("generated invalid run id: {e}")))?;
977                    sqlx::query(
978                        "INSERT INTO runs(tenant_id, run_id, session_id, pool_name, status, owner_id, owner_epoch, expires_at_ms, summary_code, created_at_ms)
979                         VALUES(?1, ?2, ?3, NULL, 'running', ?4, 1, ?5, NULL, ?6)",
980                    )
981                    .bind(tenant.as_str())
982                    .bind(rid.as_str())
983                    .bind(sess.as_str())
984                    .bind(owner.as_str())
985                    .bind(expires)
986                    .bind(now)
987                    .execute(&mut *conn)
988                    .await
989                    .map_err(db_err)?;
990                    (rid, OwnerFence::INITIAL)
991                };
992
993                Ok(LeaseToken::from_backend(
994                    tenant,
995                    sess,
996                    run_id,
997                    owner,
998                    next_fence,
999                    expires,
1000                ))
1001            })
1002        })
1003        .await
1004    }
1005
1006    async fn claim_queued_run(
1007        &mut self,
1008        owner_id: &OwnerId,
1009        pool_name: &PoolName,
1010        ttl: Duration,
1011    ) -> Result<Option<LeaseToken>, StoreError> {
1012        let owner = owner_id.clone();
1013        let pool = pool_name.clone();
1014        self.with_immediate_tx(move |conn| {
1015            Box::pin(async move {
1016                let row: Option<(String, String, String, i64)> = sqlx::query_as(
1017                    "SELECT tenant_id, session_id, run_id, owner_epoch FROM runs
1018                     WHERE pool_name = ?1 AND status = 'queued'
1019                     ORDER BY created_at_ms ASC, run_id ASC LIMIT 1",
1020                )
1021                .bind(pool.as_str())
1022                .fetch_optional(&mut *conn)
1023                .await
1024                .map_err(db_err)?;
1025                let Some((tenant_raw, sess_raw, run_raw, epoch)) = row else {
1026                    return Ok(None);
1027                };
1028                let (next_fence, next_epoch) = advance_owner_fence(epoch)?;
1029                let expires = expires_at_from(now_ms(), ttl);
1030                sqlx::query(
1031                    "UPDATE runs SET status = 'running', owner_id = ?1, owner_epoch = ?2, expires_at_ms = ?3
1032                     WHERE run_id = ?4",
1033                )
1034                .bind(owner.as_str())
1035                .bind(next_epoch)
1036                .bind(expires)
1037                .bind(&run_raw)
1038                .execute(&mut *conn)
1039                .await
1040                .map_err(db_err)?;
1041
1042                let tenant_id = TenantId::try_new(tenant_raw).map_err(|e| {
1043                    StoreError::Backend(format!("corrupt tenant_id in sqlite: {e}"))
1044                })?;
1045                let session_id = SessionId::try_new(sess_raw).map_err(|e| {
1046                    StoreError::Backend(format!("corrupt session_id in sqlite: {e}"))
1047                })?;
1048                let run_id = RunId::try_new(run_raw)
1049                    .map_err(|e| StoreError::Backend(format!("corrupt run_id in sqlite: {e}")))?;
1050                Ok(Some(LeaseToken::from_backend(
1051                    tenant_id,
1052                    session_id,
1053                    run_id,
1054                    owner,
1055                    next_fence,
1056                    expires,
1057                )))
1058            })
1059        })
1060        .await
1061    }
1062
1063    async fn reclaim_expired_run(
1064        &mut self,
1065        owner_id: &OwnerId,
1066        pool_name: &PoolName,
1067        ttl: Duration,
1068    ) -> Result<Option<LeaseToken>, StoreError> {
1069        let owner = owner_id.clone();
1070        let pool = pool_name.clone();
1071        self.with_immediate_tx(move |conn| {
1072            Box::pin(async move {
1073                let now = now_ms();
1074                let row: Option<(String, String, String, i64)> = sqlx::query_as(
1075                    "SELECT tenant_id, session_id, run_id, owner_epoch FROM runs
1076                     WHERE pool_name = ?1 AND status = 'running' AND expires_at_ms <= ?2
1077                     ORDER BY expires_at_ms ASC, run_id ASC LIMIT 1",
1078                )
1079                .bind(pool.as_str())
1080                .bind(now)
1081                .fetch_optional(&mut *conn)
1082                .await
1083                .map_err(db_err)?;
1084                let Some((tenant_raw, sess_raw, run_raw, epoch)) = row else {
1085                    return Ok(None);
1086                };
1087                let (next_fence, next_epoch) = advance_owner_fence(epoch)?;
1088                let expires = expires_at_from(now, ttl);
1089                let updated = sqlx::query(
1090                    "UPDATE runs SET owner_id = ?1, owner_epoch = ?2, expires_at_ms = ?3
1091                     WHERE run_id = ?4 AND status = 'running' AND owner_epoch = ?5",
1092                )
1093                .bind(owner.as_str())
1094                .bind(next_epoch)
1095                .bind(expires)
1096                .bind(&run_raw)
1097                .bind(epoch)
1098                .execute(&mut *conn)
1099                .await
1100                .map_err(db_err)?;
1101                if updated.rows_affected() != 1 {
1102                    return Err(StoreError::Backend(format!(
1103                        "concurrent lease update on run {run_raw}"
1104                    )));
1105                }
1106
1107                let tenant_id = TenantId::try_new(tenant_raw).map_err(|e| {
1108                    StoreError::Backend(format!("corrupt tenant_id in sqlite: {e}"))
1109                })?;
1110                let session_id = SessionId::try_new(sess_raw).map_err(|e| {
1111                    StoreError::Backend(format!("corrupt session_id in sqlite: {e}"))
1112                })?;
1113                let run_id = RunId::try_new(run_raw)
1114                    .map_err(|e| StoreError::Backend(format!("corrupt run_id in sqlite: {e}")))?;
1115
1116                let _ = transition_claimed_effects_tx(
1117                    conn, &tenant_id, &run_id, next_fence, next_epoch,
1118                )
1119                .await?;
1120
1121                Ok(Some(LeaseToken::from_backend(
1122                    tenant_id, session_id, run_id, owner, next_fence, expires,
1123                )))
1124            })
1125        })
1126        .await
1127    }
1128
1129    async fn renew_lease(
1130        &mut self,
1131        lease: &LeaseToken,
1132        ttl: Duration,
1133    ) -> Result<LeaseToken, StoreError> {
1134        let lease_clone = lease.clone();
1135        self.with_immediate_tx(move |conn| {
1136            Box::pin(async move {
1137                let row: Option<(String, String, String, i64)> = sqlx::query_as(
1138                    "SELECT tenant_id, session_id, status, owner_epoch FROM runs WHERE run_id = ?1",
1139                )
1140                .bind(lease_clone.run_id().as_str())
1141                .fetch_optional(&mut *conn)
1142                .await
1143                .map_err(db_err)?;
1144                let Some((tenant, session, status, actual_epoch)) = row else {
1145                    return Err(StoreError::NotFound(format!(
1146                        "run {} not found",
1147                        lease_clone.run_id()
1148                    )));
1149                };
1150                if tenant != lease_clone.tenant_id().as_str()
1151                    || session != lease_clone.session_id().as_str()
1152                {
1153                    return Err(StoreError::TenantMismatch);
1154                }
1155                verify_running_run_fence(
1156                    lease_clone.run_id(),
1157                    &status,
1158                    actual_epoch,
1159                    lease_clone.fence(),
1160                )?;
1161                let expires = expires_at_from(now_ms(), ttl);
1162                let updated = sqlx::query(
1163                    "UPDATE runs SET expires_at_ms = ?1
1164                     WHERE run_id = ?2 AND status = 'running' AND owner_epoch = ?3",
1165                )
1166                .bind(expires)
1167                .bind(lease_clone.run_id().as_str())
1168                .bind(actual_epoch)
1169                .execute(&mut *conn)
1170                .await
1171                .map_err(db_err)?;
1172                if updated.rows_affected() != 1 {
1173                    return Err(StoreError::Backend(format!(
1174                        "lease renew lost race on run {}",
1175                        lease_clone.run_id()
1176                    )));
1177                }
1178                Ok(LeaseToken::from_backend(
1179                    lease_clone.tenant_id().clone(),
1180                    lease_clone.session_id().clone(),
1181                    lease_clone.run_id().clone(),
1182                    lease_clone.owner_id().clone(),
1183                    lease_clone.fence(),
1184                    expires,
1185                ))
1186            })
1187        })
1188        .await
1189    }
1190
1191    async fn finish_run(
1192        &mut self,
1193        lease: &LeaseToken,
1194        status: TerminalRunStatus,
1195        summary_code: Option<&str>,
1196    ) -> Result<(), StoreError> {
1197        let lease_clone = lease.clone();
1198        let summary = summary_code.map(str::to_owned);
1199        self.with_immediate_tx(move |conn| {
1200            Box::pin(async move {
1201                let row: Option<(String, String, String, i64)> = sqlx::query_as(
1202                    "SELECT tenant_id, session_id, status, owner_epoch FROM runs WHERE run_id = ?1",
1203                )
1204                .bind(lease_clone.run_id().as_str())
1205                .fetch_optional(&mut *conn)
1206                .await
1207                .map_err(db_err)?;
1208                let Some((tenant, session, cur_status, actual_epoch)) = row else {
1209                    return Err(StoreError::NotFound(format!(
1210                        "run {} not found",
1211                        lease_clone.run_id()
1212                    )));
1213                };
1214                if tenant != lease_clone.tenant_id().as_str()
1215                    || session != lease_clone.session_id().as_str()
1216                {
1217                    return Err(StoreError::TenantMismatch);
1218                }
1219                verify_running_run_fence(
1220                    lease_clone.run_id(),
1221                    &cur_status,
1222                    actual_epoch,
1223                    lease_clone.fence(),
1224                )?;
1225                let (_, next_epoch) = advance_owner_fence(actual_epoch)?;
1226                let updated = sqlx::query(
1227                    "UPDATE runs SET status = ?1, summary_code = ?2, expires_at_ms = 0, owner_epoch = ?3
1228                     WHERE run_id = ?4 AND status = 'running' AND owner_epoch = ?5",
1229                )
1230                .bind(status.as_str())
1231                .bind(&summary)
1232                .bind(next_epoch)
1233                .bind(lease_clone.run_id().as_str())
1234                .bind(actual_epoch)
1235                .execute(&mut *conn)
1236                .await
1237                .map_err(db_err)?;
1238                if updated.rows_affected() != 1 {
1239                    return Err(StoreError::Backend(format!(
1240                        "finish_run lost race on run {}",
1241                        lease_clone.run_id()
1242                    )));
1243                }
1244                Ok(())
1245            })
1246        })
1247        .await
1248    }
1249
1250    async fn recover_expired_run(
1251        &mut self,
1252        tenant_id: &TenantId,
1253        run_id: &RunId,
1254        new_owner_id: &OwnerId,
1255        ttl: Duration,
1256    ) -> Result<(LeaseToken, Vec<EffectRecord>), StoreError> {
1257        let tenant = tenant_id.clone();
1258        let run = run_id.clone();
1259        let owner = new_owner_id.clone();
1260        self.with_immediate_tx(move |conn| {
1261            Box::pin(async move {
1262                let row: Option<(String, String, String, i64, i64)> = sqlx::query_as(
1263                    "SELECT tenant_id, session_id, status, owner_epoch, expires_at_ms
1264                     FROM runs WHERE run_id = ?1",
1265                )
1266                .bind(run.as_str())
1267                .fetch_optional(&mut *conn)
1268                .await
1269                .map_err(db_err)?;
1270                let Some((row_tenant, sess_raw, cur_status, cur_epoch, cur_exp)) = row else {
1271                    return Err(StoreError::NotFound(format!("run {run} not found")));
1272                };
1273                if row_tenant != tenant.as_str() {
1274                    return Err(StoreError::TenantMismatch);
1275                }
1276                if cur_status != "running" {
1277                    return Err(StoreError::Backend(format!(
1278                        "cannot recover run {run} in status {cur_status}"
1279                    )));
1280                }
1281                let now = now_ms();
1282                if cur_exp > now {
1283                    return Err(StoreError::LeaseHeldByOther {
1284                        expires_at_ms: cur_exp,
1285                    });
1286                }
1287                let (next_fence, next_epoch) = advance_owner_fence(cur_epoch)?;
1288                let expires = expires_at_from(now, ttl);
1289                let updated = sqlx::query(
1290                    "UPDATE runs SET status = 'running', owner_id = ?1, owner_epoch = ?2, expires_at_ms = ?3
1291                     WHERE run_id = ?4 AND status = 'running' AND owner_epoch = ?5",
1292                )
1293                .bind(owner.as_str())
1294                .bind(next_epoch)
1295                .bind(expires)
1296                .bind(run.as_str())
1297                .bind(cur_epoch)
1298                .execute(&mut *conn)
1299                .await
1300                .map_err(db_err)?;
1301                if updated.rows_affected() != 1 {
1302                    return Err(StoreError::Backend(format!(
1303                        "recover_expired_run lost race on run {run}"
1304                    )));
1305                }
1306
1307                let unknown =
1308                    transition_claimed_effects_tx(conn, &tenant, &run, next_fence, next_epoch)
1309                        .await?;
1310
1311                let session_id = SessionId::try_new(sess_raw).map_err(|e| {
1312                    StoreError::Backend(format!("corrupt session_id in sqlite: {e}"))
1313                })?;
1314                Ok((
1315                    LeaseToken::from_backend(tenant, session_id, run, owner, next_fence, expires),
1316                    unknown,
1317                ))
1318            })
1319        })
1320        .await
1321    }
1322
1323    async fn force_recover_run(
1324        &mut self,
1325        tenant_id: &TenantId,
1326        run_id: &RunId,
1327        new_owner_id: &OwnerId,
1328        ttl: Duration,
1329    ) -> Result<LeaseToken, StoreError> {
1330        let tenant = tenant_id.clone();
1331        let run = run_id.clone();
1332        let owner = new_owner_id.clone();
1333        self.with_immediate_tx(move |conn| {
1334            Box::pin(async move {
1335                let row: Option<(String, String, String, i64)> = sqlx::query_as(
1336                    "SELECT tenant_id, session_id, status, owner_epoch FROM runs WHERE run_id = ?1",
1337                )
1338                .bind(run.as_str())
1339                .fetch_optional(&mut *conn)
1340                .await
1341                .map_err(db_err)?;
1342                let Some((row_tenant, sess_raw, cur_status, cur_epoch)) = row else {
1343                    return Err(StoreError::NotFound(format!("run {run} not found")));
1344                };
1345                if row_tenant != tenant.as_str() {
1346                    return Err(StoreError::TenantMismatch);
1347                }
1348                if !matches!(cur_status.as_str(), "running" | "waiting_approval") {
1349                    return Err(StoreError::Backend(format!(
1350                        "cannot force-recover run {run} in status {cur_status}"
1351                    )));
1352                }
1353                let (next_fence, next_epoch) = advance_owner_fence(cur_epoch)?;
1354                let expires = expires_at_from(now_ms(), ttl);
1355                let updated = sqlx::query(
1356                    "UPDATE runs SET status = 'running', owner_id = ?1, owner_epoch = ?2, expires_at_ms = ?3
1357                     WHERE run_id = ?4 AND owner_epoch = ?5",
1358                )
1359                .bind(owner.as_str())
1360                .bind(next_epoch)
1361                .bind(expires)
1362                .bind(run.as_str())
1363                .bind(cur_epoch)
1364                .execute(&mut *conn)
1365                .await
1366                .map_err(db_err)?;
1367                if updated.rows_affected() != 1 {
1368                    return Err(StoreError::Backend(format!(
1369                        "force_recover_run lost race on run {run}"
1370                    )));
1371                }
1372
1373                let _ = transition_claimed_effects_tx(conn, &tenant, &run, next_fence, next_epoch)
1374                    .await?;
1375
1376                let session_id = SessionId::try_new(sess_raw).map_err(|e| {
1377                    StoreError::Backend(format!("corrupt session_id in sqlite: {e}"))
1378                })?;
1379                Ok(LeaseToken::from_backend(
1380                    tenant, session_id, run, owner, next_fence, expires,
1381                ))
1382            })
1383        })
1384        .await
1385    }
1386
1387    async fn lookup_receipt(
1388        &mut self,
1389        tenant_id: &TenantId,
1390        session_id: &SessionId,
1391        command_id: &CommandId,
1392    ) -> Result<Option<CommandReceipt>, StoreError> {
1393        let row_tenant: Option<String> =
1394            sqlx::query_scalar("SELECT tenant_id FROM sessions WHERE session_id = ?1")
1395                .bind(session_id.as_str())
1396                .fetch_optional(&mut self.conn)
1397                .await
1398                .map_err(db_err)?;
1399        if let Some(t) = row_tenant
1400            && t != tenant_id.as_str()
1401        {
1402            return Err(StoreError::TenantMismatch);
1403        }
1404
1405        let row = sqlx::query(
1406            "SELECT settlement, resulting_revision, branch_epoch, activity_epoch, payload_json
1407             FROM command_receipts
1408             WHERE tenant_id = ?1 AND session_id = ?2 AND command_id = ?3",
1409        )
1410        .bind(tenant_id.as_str())
1411        .bind(session_id.as_str())
1412        .bind(command_id.as_str())
1413        .fetch_optional(&mut self.conn)
1414        .await
1415        .map_err(db_err)?;
1416
1417        let Some(r) = row else {
1418            return Ok(None);
1419        };
1420        let settlement_str: String = r.get("settlement");
1421        let settlement: CommandSettlement = serde_json::from_str(&format!("\"{settlement_str}\""))
1422            .map_err(|e| StoreError::Backend(format!("bad settlement: {e}")))?;
1423        let payload_str: String = r.get("payload_json");
1424        let payload_json = serde_json::from_str(&payload_str)
1425            .map_err(|e| StoreError::Backend(format!("bad receipt json: {e}")))?;
1426        let rev = parse_u64_col(r.get::<i64, _>("resulting_revision"), "resulting_revision")?;
1427        let branch_epoch = parse_u64_col(r.get::<i64, _>("branch_epoch"), "branch_epoch")?;
1428        let activity_epoch = parse_u64_col(r.get::<i64, _>("activity_epoch"), "activity_epoch")?;
1429        Ok(Some(CommandReceipt {
1430            tenant_id: tenant_id.clone(),
1431            session_id: session_id.clone(),
1432            command_id: command_id.clone(),
1433            settlement,
1434            resulting_revision: SessionRevision::from_u64(rev),
1435            epochs: ScopeEpochs::new(branch_epoch, activity_epoch),
1436            payload_json,
1437        }))
1438    }
1439
1440    async fn commit_step(
1441        &mut self,
1442        lease: &LeaseToken,
1443        commit: StepCommit,
1444    ) -> Result<StepCommitResult, StoreError> {
1445        let lease_clone = lease.clone();
1446        self.with_immediate_tx(move |conn| {
1447            Box::pin(async move {
1448                // 1. Verify run lease, status, & owner_epoch
1449                let run_row: Option<(String, String, String, i64)> = sqlx::query_as(
1450                    "SELECT tenant_id, session_id, status, owner_epoch FROM runs WHERE run_id = ?1",
1451                )
1452                .bind(lease_clone.run_id().as_str())
1453                .fetch_optional(&mut *conn)
1454                .await
1455                .map_err(db_err)?;
1456                let Some((r_tenant, r_sess, r_status, r_epoch)) = run_row else {
1457                    return Err(StoreError::NotFound(format!(
1458                        "run {} not found",
1459                        lease_clone.run_id()
1460                    )));
1461                };
1462                if r_tenant != lease_clone.tenant_id().as_str()
1463                    || r_sess != lease_clone.session_id().as_str()
1464                {
1465                    return Err(StoreError::TenantMismatch);
1466                }
1467                verify_running_run_fence(
1468                    lease_clone.run_id(),
1469                    &r_status,
1470                    r_epoch,
1471                    lease_clone.fence(),
1472                )?;
1473
1474                // 2. Verify session revision CAS
1475                let sess_row: Option<(String, i64, i64, i64, Option<String>)> = sqlx::query_as(
1476                    "SELECT tenant_id, revision, branch_epoch, activity_epoch, active_leaf
1477                     FROM sessions WHERE session_id = ?1",
1478                )
1479                .bind(lease_clone.session_id().as_str())
1480                .fetch_optional(&mut *conn)
1481                .await
1482                .map_err(db_err)?;
1483                let Some((s_tenant, s_rev, s_branch, s_act, cur_leaf)) = sess_row else {
1484                    return Err(StoreError::NotFound(format!(
1485                        "session {} not found",
1486                        lease_clone.session_id()
1487                    )));
1488                };
1489                if s_tenant != lease_clone.tenant_id().as_str() {
1490                    return Err(StoreError::TenantMismatch);
1491                }
1492                let cur_revision = SessionRevision::from_u64(parse_u64_col(s_rev, "revision")?);
1493                if cur_revision != commit.expected_revision {
1494                    return Err(StoreError::RevisionConflict {
1495                        expected: commit.expected_revision,
1496                        actual: cur_revision,
1497                    });
1498                }
1499                let cur_epochs = ScopeEpochs::new(
1500                    parse_u64_col(s_branch, "branch_epoch")?,
1501                    parse_u64_col(s_act, "activity_epoch")?,
1502                );
1503
1504                // 3. Insert entries
1505                let mut last_entry_id = None;
1506                for entry in &commit.entries {
1507                    if &entry.tenant_id != lease_clone.tenant_id()
1508                        || &entry.session_id != lease_clone.session_id()
1509                    {
1510                        return Err(StoreError::TenantMismatch);
1511                    }
1512                    let payload_json = serde_json::to_string(&entry.payload)
1513                        .map_err(|e| StoreError::Backend(e.to_string()))?;
1514                    sqlx::query(
1515                        "INSERT INTO session_entries(tenant_id, session_id, entry_id, parent_entry_id, run_id, created_at_ms, payload_json)
1516                         VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7)",
1517                    )
1518                    .bind(entry.tenant_id.as_str())
1519                    .bind(entry.session_id.as_str())
1520                    .bind(entry.entry_id.as_str())
1521                    .bind(entry.parent_entry_id.as_ref().map(EntryId::as_str))
1522                    .bind(entry.run_id.as_ref().map(RunId::as_str))
1523                    .bind(entry.created_at_ms)
1524                    .bind(&payload_json)
1525                    .execute(&mut *conn)
1526                    .await
1527                    .map_err(db_err)?;
1528                    last_entry_id = Some(entry.entry_id.as_str().to_owned());
1529                }
1530
1531                // 4. Prepare effects & apply transitions
1532                let lease_fence_i64 = to_sql_i64(lease_clone.fence().as_u64(), "owner_epoch")?;
1533                for eff in &commit.prepare_effects {
1534                    let dup: Option<String> = sqlx::query_scalar(
1535                        "SELECT effect_id FROM effects WHERE tenant_id = ?1 AND idempotency_key = ?2",
1536                    )
1537                    .bind(lease_clone.tenant_id().as_str())
1538                    .bind(&eff.idempotency_key)
1539                    .fetch_optional(&mut *conn)
1540                    .await
1541                    .map_err(db_err)?;
1542                    if dup.is_some() {
1543                        return Err(StoreError::DuplicateIdempotencyKey(
1544                            eff.idempotency_key.clone(),
1545                        ));
1546                    }
1547                    sqlx::query(
1548                        "INSERT INTO effects(tenant_id, effect_id, run_id, idempotency_key, owner_epoch, state, action_sha256, result_digest)
1549                         VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, NULL)",
1550                    )
1551                    .bind(lease_clone.tenant_id().as_str())
1552                    .bind(eff.effect_id.as_str())
1553                    .bind(lease_clone.run_id().as_str())
1554                    .bind(&eff.idempotency_key)
1555                    .bind(lease_fence_i64)
1556                    .bind(EffectState::Prepared.as_str())
1557                    .bind(&eff.action_sha256)
1558                    .execute(&mut *conn)
1559                    .await
1560                    .map_err(db_err)?;
1561                }
1562
1563                for tr in &commit.effect_transitions {
1564                    let row: Option<(String, String, String)> = sqlx::query_as(
1565                        "SELECT tenant_id, run_id, state FROM effects WHERE effect_id = ?1",
1566                    )
1567                    .bind(tr.effect_id.as_str())
1568                    .fetch_optional(&mut *conn)
1569                    .await
1570                    .map_err(db_err)?;
1571                    let Some((e_tenant, e_run, state_str)) = row else {
1572                        return Err(StoreError::NotFound(format!(
1573                            "effect {} not found",
1574                            tr.effect_id
1575                        )));
1576                    };
1577                    if e_tenant != lease_clone.tenant_id().as_str()
1578                        || e_run != lease_clone.run_id().as_str()
1579                    {
1580                        return Err(StoreError::TenantMismatch);
1581                    }
1582                    let cur_state = EffectState::parse(&state_str).ok_or_else(|| {
1583                        StoreError::Backend(format!("corrupt effect state: {state_str}"))
1584                    })?;
1585                    let next_state = transition_effect(cur_state, tr.event)?;
1586                    sqlx::query(
1587                        "UPDATE effects SET state = ?1, owner_epoch = ?2, result_digest = COALESCE(?3, result_digest)
1588                         WHERE effect_id = ?4",
1589                    )
1590                    .bind(next_state.as_str())
1591                    .bind(lease_fence_i64)
1592                    .bind(&tr.result_digest)
1593                    .bind(tr.effect_id.as_str())
1594                    .execute(&mut *conn)
1595                    .await
1596                    .map_err(db_err)?;
1597                }
1598
1599                // 5. Spend ledger rows (tenant/session/run derived from lease)
1600                for sp in &commit.spend {
1601                    let billing_str = match sp.billing_class {
1602                        BillingClass::Billable => "billable",
1603                        BillingClass::InternalNonBillable => "internal_non_billable",
1604                    };
1605                    let cat_json = serde_json::to_string(&sp.category)
1606                        .map_err(|e| StoreError::Backend(e.to_string()))?;
1607                    let basis_json = serde_json::to_string(&sp.basis)
1608                        .map_err(|e| StoreError::Backend(e.to_string()))?;
1609                    let cost_i64 = to_sql_i64(sp.cost.as_micros(), "cost_micro_usd")?;
1610                    sqlx::query(
1611                        "INSERT INTO spend_ledger(tenant_id, session_id, run_id, billing_class, category_json, cost_micro_usd, cost_basis, recorded_at_ms)
1612                         VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
1613                    )
1614                    .bind(lease_clone.tenant_id().as_str())
1615                    .bind(lease_clone.session_id().as_str())
1616                    .bind(lease_clone.run_id().as_str())
1617                    .bind(billing_str)
1618                    .bind(&cat_json)
1619                    .bind(cost_i64)
1620                    .bind(basis_json.trim_matches('"'))
1621                    .bind(sp.recorded_at_ms)
1622                    .execute(&mut *conn)
1623                    .await
1624                    .map_err(db_err)?;
1625                }
1626
1627                // 6. Advance session revision, epochs, and active_leaf
1628                let new_revision = cur_revision
1629                    .next()
1630                    .ok_or_else(|| StoreError::Backend("session revision overflow".into()))?;
1631                let mut new_epochs = cur_epochs;
1632                if commit.bump_branch_epoch {
1633                    new_epochs = new_epochs.bump_branch();
1634                }
1635                if commit.bump_activity_epoch {
1636                    new_epochs = new_epochs.bump_activity();
1637                }
1638                let new_rev = to_sql_i64(new_revision.as_u64(), "revision")?;
1639                let new_branch = to_sql_i64(new_epochs.branch_epoch(), "branch_epoch")?;
1640                let new_act = to_sql_i64(new_epochs.activity_epoch(), "activity_epoch")?;
1641                let final_leaf = if let Some(ref leaf) = commit.new_leaf {
1642                    let exists: Option<String> = sqlx::query_scalar(
1643                        "SELECT entry_id FROM session_entries WHERE session_id = ?1 AND entry_id = ?2",
1644                    )
1645                    .bind(lease_clone.session_id().as_str())
1646                    .bind(leaf.as_str())
1647                    .fetch_optional(&mut *conn)
1648                    .await
1649                    .map_err(db_err)?;
1650                    if exists.is_none() {
1651                        return Err(StoreError::NotFound(format!("leaf entry {leaf} not found")));
1652                    }
1653                    Some(leaf.as_str().to_owned())
1654                } else {
1655                    last_entry_id.or(cur_leaf)
1656                };
1657
1658                sqlx::query(
1659                    "UPDATE sessions SET revision = ?1, branch_epoch = ?2, activity_epoch = ?3, active_leaf = ?4
1660                     WHERE session_id = ?5 AND revision = ?6",
1661                )
1662                .bind(new_rev)
1663                .bind(new_branch)
1664                .bind(new_act)
1665                .bind(&final_leaf)
1666                .bind(lease_clone.session_id().as_str())
1667                .bind(s_rev)
1668                .execute(&mut *conn)
1669                .await
1670                .map_err(db_err)?;
1671
1672                // 7. Command receipt (reject duplicates; derive tenant/session/revision/epochs)
1673                if let Some(ref receipt) = commit.receipt {
1674                    let dup: Option<String> = sqlx::query_scalar(
1675                        "SELECT command_id FROM command_receipts
1676                         WHERE tenant_id = ?1 AND session_id = ?2 AND command_id = ?3",
1677                    )
1678                    .bind(lease_clone.tenant_id().as_str())
1679                    .bind(lease_clone.session_id().as_str())
1680                    .bind(receipt.command_id.as_str())
1681                    .fetch_optional(&mut *conn)
1682                    .await
1683                    .map_err(db_err)?;
1684                    if dup.is_some() {
1685                        return Err(StoreError::DuplicateIdempotencyKey(format!(
1686                            "command {} already committed",
1687                            receipt.command_id
1688                        )));
1689                    }
1690                    let settlement_str = match receipt.settlement {
1691                        CommandSettlement::Admitted => "admitted",
1692                        CommandSettlement::Completed => "completed",
1693                        CommandSettlement::Rejected => "rejected",
1694                    };
1695                    let payload_str = serde_json::to_string(&receipt.payload_json)
1696                        .map_err(|e| StoreError::Backend(e.to_string()))?;
1697                    sqlx::query(
1698                        "INSERT INTO command_receipts(tenant_id, session_id, command_id, settlement, resulting_revision, branch_epoch, activity_epoch, payload_json)
1699                         VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
1700                    )
1701                    .bind(lease_clone.tenant_id().as_str())
1702                    .bind(lease_clone.session_id().as_str())
1703                    .bind(receipt.command_id.as_str())
1704                    .bind(settlement_str)
1705                    .bind(new_rev)
1706                    .bind(new_branch)
1707                    .bind(new_act)
1708                    .bind(&payload_str)
1709                    .execute(&mut *conn)
1710                    .await
1711                    .map_err(db_err)?;
1712                }
1713
1714                Ok(StepCommitResult {
1715                    new_revision,
1716                    epochs: new_epochs,
1717                })
1718            })
1719        })
1720        .await
1721    }
1722
1723    async fn list_unknown_effects(
1724        &mut self,
1725        tenant_id: &TenantId,
1726        run_id: &RunId,
1727    ) -> Result<Vec<EffectRecord>, StoreError> {
1728        let row_tenant: Option<String> =
1729            sqlx::query_scalar("SELECT tenant_id FROM runs WHERE run_id = ?1")
1730                .bind(run_id.as_str())
1731                .fetch_optional(&mut self.conn)
1732                .await
1733                .map_err(db_err)?;
1734        if let Some(t) = row_tenant
1735            && t != tenant_id.as_str()
1736        {
1737            return Err(StoreError::TenantMismatch);
1738        }
1739
1740        let rows = sqlx::query(
1741            "SELECT effect_id, idempotency_key, owner_epoch, action_sha256, result_digest
1742             FROM effects WHERE tenant_id = ?1 AND run_id = ?2 AND state = 'unknown'",
1743        )
1744        .bind(tenant_id.as_str())
1745        .bind(run_id.as_str())
1746        .fetch_all(&mut self.conn)
1747        .await
1748        .map_err(db_err)?;
1749
1750        rows.into_iter()
1751            .map(|r| {
1752                let effect_id =
1753                    EffectId::try_new(r.get::<String, _>("effect_id")).map_err(|e| {
1754                        StoreError::Backend(format!("corrupt effect_id in sqlite: {e}"))
1755                    })?;
1756                let fence = parse_owner_fence(r.get::<i64, _>("owner_epoch"))?;
1757                Ok(EffectRecord {
1758                    tenant_id: tenant_id.clone(),
1759                    effect_id,
1760                    run_id: run_id.clone(),
1761                    idempotency_key: r.get("idempotency_key"),
1762                    fence,
1763                    state: EffectState::Unknown,
1764                    action_sha256: r.get("action_sha256"),
1765                    result_digest: r.get("result_digest"),
1766                })
1767            })
1768            .collect()
1769    }
1770
1771    async fn list_claimed_effects(
1772        &mut self,
1773        tenant_id: &TenantId,
1774        run_id: &RunId,
1775    ) -> Result<Vec<EffectRecord>, StoreError> {
1776        let row_tenant: Option<String> =
1777            sqlx::query_scalar("SELECT tenant_id FROM runs WHERE run_id = ?1")
1778                .bind(run_id.as_str())
1779                .fetch_optional(&mut self.conn)
1780                .await
1781                .map_err(db_err)?;
1782        if let Some(t) = row_tenant
1783            && t != tenant_id.as_str()
1784        {
1785            return Err(StoreError::TenantMismatch);
1786        }
1787
1788        let rows = sqlx::query(
1789            "SELECT effect_id, idempotency_key, owner_epoch, action_sha256, result_digest
1790             FROM effects WHERE tenant_id = ?1 AND run_id = ?2 AND state = 'claimed'",
1791        )
1792        .bind(tenant_id.as_str())
1793        .bind(run_id.as_str())
1794        .fetch_all(&mut self.conn)
1795        .await
1796        .map_err(db_err)?;
1797
1798        rows.into_iter()
1799            .map(|r| {
1800                let effect_id =
1801                    EffectId::try_new(r.get::<String, _>("effect_id")).map_err(|e| {
1802                        StoreError::Backend(format!("corrupt effect_id in sqlite: {e}"))
1803                    })?;
1804                let fence = parse_owner_fence(r.get::<i64, _>("owner_epoch"))?;
1805                Ok(EffectRecord {
1806                    tenant_id: tenant_id.clone(),
1807                    effect_id,
1808                    run_id: run_id.clone(),
1809                    idempotency_key: r.get("idempotency_key"),
1810                    fence,
1811                    state: EffectState::Claimed,
1812                    action_sha256: r.get("action_sha256"),
1813                    result_digest: r.get("result_digest"),
1814                })
1815            })
1816            .collect()
1817    }
1818
1819    async fn load_branch(
1820        &mut self,
1821        tenant_id: &TenantId,
1822        session_id: &SessionId,
1823        leaf: Option<&EntryId>,
1824    ) -> Result<LoadedBranch, StoreError> {
1825        let sess_row: Option<(String, i64, i64, i64, Option<String>)> = sqlx::query_as(
1826            "SELECT tenant_id, revision, branch_epoch, activity_epoch, active_leaf
1827             FROM sessions WHERE session_id = ?1",
1828        )
1829        .bind(session_id.as_str())
1830        .fetch_optional(&mut self.conn)
1831        .await
1832        .map_err(db_err)?;
1833        let Some((s_tenant, rev, b_ep, a_ep, active_leaf)) = sess_row else {
1834            return Err(StoreError::NotFound(format!(
1835                "session {session_id} not found"
1836            )));
1837        };
1838        if s_tenant != tenant_id.as_str() {
1839            return Err(StoreError::TenantMismatch);
1840        }
1841
1842        let target_leaf = leaf.map(|l| l.as_str().to_owned()).or(active_leaf);
1843        let rows = sqlx::query(
1844            "SELECT entry_id, parent_entry_id, run_id, created_at_ms, payload_json
1845             FROM session_entries WHERE tenant_id = ?1 AND session_id = ?2",
1846        )
1847        .bind(tenant_id.as_str())
1848        .bind(session_id.as_str())
1849        .fetch_all(&mut self.conn)
1850        .await
1851        .map_err(db_err)?;
1852
1853        let mut map: HashMap<String, SessionEntry> = HashMap::with_capacity(rows.len());
1854        for r in rows {
1855            let entry_id_raw: String = r.get("entry_id");
1856            let parent_entry_id_raw: Option<String> = r.get("parent_entry_id");
1857            let run_id_raw: Option<String> = r.get("run_id");
1858            let payload_str: String = r.get("payload_json");
1859            let payload: SessionEntryPayload = serde_json::from_str(&payload_str)
1860                .map_err(|e| StoreError::Backend(format!("corrupt entry payload: {e}")))?;
1861            let entry_id = EntryId::try_new(entry_id_raw.clone())
1862                .map_err(|e| StoreError::Backend(format!("corrupt entry_id in sqlite: {e}")))?;
1863            let parent_entry_id = parent_entry_id_raw
1864                .map(EntryId::try_new)
1865                .transpose()
1866                .map_err(|e| {
1867                    StoreError::Backend(format!("corrupt parent_entry_id in sqlite: {e}"))
1868                })?;
1869            let run_id = run_id_raw
1870                .map(RunId::try_new)
1871                .transpose()
1872                .map_err(|e| StoreError::Backend(format!("corrupt run_id in sqlite: {e}")))?;
1873            map.insert(
1874                entry_id_raw,
1875                SessionEntry {
1876                    tenant_id: tenant_id.clone(),
1877                    session_id: session_id.clone(),
1878                    entry_id,
1879                    parent_entry_id,
1880                    run_id,
1881                    created_at_ms: r.get("created_at_ms"),
1882                    payload,
1883                },
1884            );
1885        }
1886
1887        let mut chain = Vec::new();
1888        let mut cursor = target_leaf;
1889        let mut steps = 0usize;
1890        while let Some(id) = cursor {
1891            steps += 1;
1892            if steps > map.len() + 1 {
1893                return Err(StoreError::Backend("cycle detected in session tree".into()));
1894            }
1895            let entry = map
1896                .get(&id)
1897                .ok_or_else(|| StoreError::NotFound(format!("entry {id} not found")))?
1898                .clone();
1899            cursor = entry
1900                .parent_entry_id
1901                .as_ref()
1902                .map(|p| p.as_str().to_owned());
1903            chain.push(entry);
1904        }
1905        chain.reverse();
1906
1907        Ok(LoadedBranch {
1908            revision: SessionRevision::from_u64(parse_u64_col(rev, "revision")?),
1909            epochs: ScopeEpochs::new(
1910                parse_u64_col(b_ep, "branch_epoch")?,
1911                parse_u64_col(a_ep, "activity_epoch")?,
1912            ),
1913            entries: chain,
1914        })
1915    }
1916
1917    async fn sum_spend_since(
1918        &mut self,
1919        tenant_id: &TenantId,
1920        since_ms: i64,
1921        billing_class: Option<BillingClass>,
1922    ) -> Result<MicroUsd, StoreError> {
1923        let sum: i64 = if let Some(bc) = billing_class {
1924            let bc_str = match bc {
1925                BillingClass::Billable => "billable",
1926                BillingClass::InternalNonBillable => "internal_non_billable",
1927            };
1928            sqlx::query_scalar(
1929                "SELECT COALESCE(SUM(cost_micro_usd), 0) FROM spend_ledger
1930                 WHERE tenant_id = ?1 AND recorded_at_ms >= ?2 AND billing_class = ?3",
1931            )
1932            .bind(tenant_id.as_str())
1933            .bind(since_ms)
1934            .bind(bc_str)
1935            .fetch_one(&mut self.conn)
1936            .await
1937            .map_err(db_err)?
1938        } else {
1939            sqlx::query_scalar(
1940                "SELECT COALESCE(SUM(cost_micro_usd), 0) FROM spend_ledger
1941                 WHERE tenant_id = ?1 AND recorded_at_ms >= ?2",
1942            )
1943            .bind(tenant_id.as_str())
1944            .bind(since_ms)
1945            .fetch_one(&mut self.conn)
1946            .await
1947            .map_err(db_err)?
1948        };
1949        let micros = parse_u64_col(sum, "cost_micro_usd")?;
1950        Ok(MicroUsd::from_micros_clamped(micros))
1951    }
1952
1953    async fn sum_run_spend(
1954        &mut self,
1955        tenant_id: &TenantId,
1956        run_id: &RunId,
1957    ) -> Result<MicroUsd, StoreError> {
1958        let sum: i64 = sqlx::query_scalar(
1959            "SELECT COALESCE(SUM(cost_micro_usd), 0) FROM spend_ledger
1960             WHERE tenant_id = ?1 AND run_id = ?2",
1961        )
1962        .bind(tenant_id.as_str())
1963        .bind(run_id.as_str())
1964        .fetch_one(&mut self.conn)
1965        .await
1966        .map_err(db_err)?;
1967        let micros = parse_u64_col(sum, "cost_micro_usd")?;
1968        Ok(MicroUsd::from_micros_clamped(micros))
1969    }
1970}
1971
1972impl LeaseStore for SqliteAgentStore {
1973    fn enqueue_run<'a>(
1974        &'a self,
1975        tenant_id: &'a TenantId,
1976        session_id: &'a SessionId,
1977        run_id: &'a RunId,
1978        pool_name: &'a PoolName,
1979    ) -> BoxFuture<'a, Result<(), StoreError>> {
1980        Box::pin(async move {
1981            self.call(|reply| ActorReq::EnqueueRun {
1982                tenant_id: tenant_id.clone(),
1983                session_id: session_id.clone(),
1984                run_id: run_id.clone(),
1985                pool_name: pool_name.clone(),
1986                reply,
1987            })
1988            .await
1989        })
1990    }
1991
1992    fn acquire_session_lease<'a>(
1993        &'a self,
1994        tenant_id: &'a TenantId,
1995        session_id: &'a SessionId,
1996        owner_id: &'a OwnerId,
1997        ttl: Duration,
1998    ) -> BoxFuture<'a, Result<LeaseToken, StoreError>> {
1999        Box::pin(async move {
2000            self.call(|reply| ActorReq::AcquireSessionLease {
2001                tenant_id: tenant_id.clone(),
2002                session_id: session_id.clone(),
2003                owner_id: owner_id.clone(),
2004                ttl,
2005                reply,
2006            })
2007            .await
2008        })
2009    }
2010
2011    fn claim_queued_run<'a>(
2012        &'a self,
2013        owner_id: &'a OwnerId,
2014        pool_name: &'a PoolName,
2015        ttl: Duration,
2016    ) -> BoxFuture<'a, Result<Option<LeaseToken>, StoreError>> {
2017        Box::pin(async move {
2018            self.call(|reply| ActorReq::ClaimQueuedRun {
2019                owner_id: owner_id.clone(),
2020                pool_name: pool_name.clone(),
2021                ttl,
2022                reply,
2023            })
2024            .await
2025        })
2026    }
2027
2028    fn reclaim_expired_run<'a>(
2029        &'a self,
2030        owner_id: &'a OwnerId,
2031        pool_name: &'a PoolName,
2032        ttl: Duration,
2033    ) -> BoxFuture<'a, Result<Option<LeaseToken>, StoreError>> {
2034        Box::pin(async move {
2035            self.call(|reply| ActorReq::ReclaimExpiredRun {
2036                owner_id: owner_id.clone(),
2037                pool_name: pool_name.clone(),
2038                ttl,
2039                reply,
2040            })
2041            .await
2042        })
2043    }
2044
2045    fn renew_lease<'a>(
2046        &'a self,
2047        lease: &'a LeaseToken,
2048        ttl: Duration,
2049    ) -> BoxFuture<'a, Result<LeaseToken, StoreError>> {
2050        Box::pin(async move {
2051            self.call(|reply| ActorReq::RenewLease {
2052                lease: lease.clone(),
2053                ttl,
2054                reply,
2055            })
2056            .await
2057        })
2058    }
2059
2060    fn finish_run<'a>(
2061        &'a self,
2062        lease: &'a LeaseToken,
2063        status: TerminalRunStatus,
2064        summary_code: Option<&'a str>,
2065    ) -> BoxFuture<'a, Result<(), StoreError>> {
2066        Box::pin(async move {
2067            self.call(|reply| ActorReq::FinishRun {
2068                lease: lease.clone(),
2069                status,
2070                summary_code: summary_code.map(str::to_owned),
2071                reply,
2072            })
2073            .await
2074        })
2075    }
2076
2077    fn recover_expired_run<'a>(
2078        &'a self,
2079        tenant_id: &'a TenantId,
2080        run_id: &'a RunId,
2081        new_owner_id: &'a OwnerId,
2082        ttl: Duration,
2083    ) -> BoxFuture<'a, Result<(LeaseToken, Vec<EffectRecord>), StoreError>> {
2084        Box::pin(async move {
2085            self.call(|reply| ActorReq::RecoverExpiredRun {
2086                tenant_id: tenant_id.clone(),
2087                run_id: run_id.clone(),
2088                new_owner_id: new_owner_id.clone(),
2089                ttl,
2090                reply,
2091            })
2092            .await
2093        })
2094    }
2095
2096    fn force_recover_run<'a>(
2097        &'a self,
2098        tenant_id: &'a TenantId,
2099        run_id: &'a RunId,
2100        new_owner_id: &'a OwnerId,
2101        ttl: Duration,
2102    ) -> BoxFuture<'a, Result<LeaseToken, StoreError>> {
2103        Box::pin(async move {
2104            self.call(|reply| ActorReq::ForceRecoverRun {
2105                tenant_id: tenant_id.clone(),
2106                run_id: run_id.clone(),
2107                new_owner_id: new_owner_id.clone(),
2108                ttl,
2109                reply,
2110            })
2111            .await
2112        })
2113    }
2114}
2115
2116impl CommandStore for SqliteAgentStore {
2117    fn lookup_receipt<'a>(
2118        &'a self,
2119        tenant_id: &'a TenantId,
2120        session_id: &'a SessionId,
2121        command_id: &'a CommandId,
2122    ) -> BoxFuture<'a, Result<Option<CommandReceipt>, StoreError>> {
2123        Box::pin(async move {
2124            self.call(|reply| ActorReq::LookupReceipt {
2125                tenant_id: tenant_id.clone(),
2126                session_id: session_id.clone(),
2127                command_id: command_id.clone(),
2128                reply,
2129            })
2130            .await
2131        })
2132    }
2133
2134    fn commit_step<'a>(
2135        &'a self,
2136        lease: &'a LeaseToken,
2137        commit: StepCommit,
2138    ) -> BoxFuture<'a, Result<StepCommitResult, StoreError>> {
2139        Box::pin(async move {
2140            self.call(|reply| ActorReq::CommitStep {
2141                lease: lease.clone(),
2142                commit: Box::new(commit),
2143                reply,
2144            })
2145            .await
2146        })
2147    }
2148
2149    fn list_unknown_effects<'a>(
2150        &'a self,
2151        tenant_id: &'a TenantId,
2152        run_id: &'a RunId,
2153    ) -> BoxFuture<'a, Result<Vec<EffectRecord>, StoreError>> {
2154        Box::pin(async move {
2155            self.call(|reply| ActorReq::ListUnknownEffects {
2156                tenant_id: tenant_id.clone(),
2157                run_id: run_id.clone(),
2158                reply,
2159            })
2160            .await
2161        })
2162    }
2163
2164    fn list_claimed_effects<'a>(
2165        &'a self,
2166        tenant_id: &'a TenantId,
2167        run_id: &'a RunId,
2168    ) -> BoxFuture<'a, Result<Vec<EffectRecord>, StoreError>> {
2169        Box::pin(async move {
2170            self.call(|reply| ActorReq::ListClaimedEffects {
2171                tenant_id: tenant_id.clone(),
2172                run_id: run_id.clone(),
2173                reply,
2174            })
2175            .await
2176        })
2177    }
2178}
2179
2180impl SessionStore for SqliteAgentStore {
2181    fn create_session<'a>(
2182        &'a self,
2183        tenant_id: &'a TenantId,
2184        session_id: &'a SessionId,
2185        parent_session_id: Option<&'a SessionId>,
2186    ) -> BoxFuture<'a, Result<StepCommitResult, StoreError>> {
2187        Box::pin(async move {
2188            self.call(|reply| ActorReq::CreateSession {
2189                tenant_id: tenant_id.clone(),
2190                session_id: session_id.clone(),
2191                parent_session_id: parent_session_id.cloned(),
2192                reply,
2193            })
2194            .await
2195        })
2196    }
2197
2198    fn load_branch<'a>(
2199        &'a self,
2200        tenant_id: &'a TenantId,
2201        session_id: &'a SessionId,
2202        leaf: Option<&'a EntryId>,
2203    ) -> BoxFuture<'a, Result<LoadedBranch, StoreError>> {
2204        Box::pin(async move {
2205            self.call(|reply| ActorReq::LoadBranch {
2206                tenant_id: tenant_id.clone(),
2207                session_id: session_id.clone(),
2208                leaf: leaf.cloned(),
2209                reply,
2210            })
2211            .await
2212        })
2213    }
2214}
2215
2216impl SpendStore for SqliteAgentStore {
2217    fn sum_spend_since<'a>(
2218        &'a self,
2219        tenant_id: &'a TenantId,
2220        since_ms: i64,
2221        billing_class: Option<BillingClass>,
2222    ) -> BoxFuture<'a, Result<MicroUsd, StoreError>> {
2223        Box::pin(async move {
2224            self.call(|reply| ActorReq::SumSpendSince {
2225                tenant_id: tenant_id.clone(),
2226                since_ms,
2227                billing_class,
2228                reply,
2229            })
2230            .await
2231        })
2232    }
2233
2234    fn sum_run_spend<'a>(
2235        &'a self,
2236        tenant_id: &'a TenantId,
2237        run_id: &'a RunId,
2238    ) -> BoxFuture<'a, Result<MicroUsd, StoreError>> {
2239        Box::pin(async move {
2240            self.call(|reply| ActorReq::SumRunSpend {
2241                tenant_id: tenant_id.clone(),
2242                run_id: run_id.clone(),
2243                reply,
2244            })
2245            .await
2246        })
2247    }
2248}
2249
2250#[cfg(test)]
2251mod tests {
2252    use super::*;
2253
2254    #[test]
2255    fn sqlite_store_config_validates_path_and_builder_options() {
2256        assert!(SqliteStoreConfig::try_new("").is_err());
2257
2258        let cfg = SqliteStoreConfig::try_new("/tmp/test-allen.sqlite").unwrap();
2259        assert_eq!(cfg.path(), Path::new("/tmp/test-allen.sqlite"));
2260        assert_eq!(cfg.journal_mode(), JournalMode::Wal);
2261
2262        let cfg = cfg.with_journal_mode(JournalMode::Delete);
2263        assert_eq!(cfg.journal_mode(), JournalMode::Delete);
2264    }
2265
2266    #[tokio::test]
2267    async fn sqlite_store_passes_full_conformance_and_detects_schema_drift() {
2268        let dir = std::env::temp_dir().join(format!("allen-store-sqlite-{}", std::process::id()));
2269        let _ = std::fs::remove_dir_all(&dir);
2270        let db_path = dir.join("runtime.sqlite");
2271
2272        let cfg = SqliteStoreConfig::try_new(&db_path).expect("valid sqlite config");
2273        let store = SqliteAgentStore::connect_and_migrate(cfg)
2274            .await
2275            .expect("connect sqlite");
2276        let dbg = format!("{store:?}");
2277        assert!(dbg.contains("SqliteAgentStore"));
2278        assert!(dbg.contains("Wal"));
2279
2280        allen_store::conformance::run_all(&store).await;
2281        allen_store::conformance::run_concurrency(store.clone()).await;
2282        drop(store);
2283
2284        // Tamper with stored migration checksum -> startup must refuse with SchemaDrift
2285        let mut raw = SqliteConnectOptions::new()
2286            .filename(&db_path)
2287            .connect()
2288            .await
2289            .unwrap();
2290        sqlx::query("UPDATE schema_migrations SET sha256 = 'tampered' WHERE version = 1")
2291            .execute(&mut raw)
2292            .await
2293            .unwrap();
2294        drop(raw);
2295
2296        let err = SqliteAgentStore::connect_and_migrate(
2297            SqliteStoreConfig::try_new(&db_path).expect("valid sqlite config"),
2298        )
2299        .await
2300        .expect_err("must reject drifted schema");
2301        assert!(matches!(err, StoreError::SchemaDrift(_)));
2302
2303        let _ = std::fs::remove_dir_all(&dir);
2304    }
2305}