Skip to main content

allen_store/
lib.rs

1//! Defines the storage-agnostic Layer 1 persistence contract ([`AgentStore`]), a
2//! reference [`InMemoryStore`], and a shared backend conformance suite for durable,
3//! multi-tenant agent runtimes.
4//!
5//! # Architecture & Layer Role
6//!
7//! Within the Allen Open Agent Infrastructure Standard, `allen-store` is the abstract
8//! interface of Layer 1 (Persistence). It depends only on pure Layer 0 (`allen-types`)
9//! and carries zero SQL drivers or filesystem I/O. Layer 4 (`allen-runtime`) is generic
10//! over [`AgentStore`], while concrete backends (`allen-store-sqlite` for single-node
11//! local execution and external custom backends for multi-replica deployments)
12//! implement the four sub-traits and verify behavioral parity through the shared
13//! conformance suite.
14//!
15//! # Quick Start
16//!
17//! ```rust
18//! use allen_store::{
19//!     CommandStore, InMemoryStore, LeaseStore, OwnerId, SessionStore, StepCommit, StoreError,
20//! };
21//! use allen_types::ids::{EntryId, SessionId, SessionRevision, TenantId};
22//! use allen_types::session::{ContentBlock, SessionEntry, SessionEntryPayload};
23//! use std::time::Duration;
24//!
25//! # tokio::runtime::Runtime::new().unwrap().block_on(async {
26//! let store = InMemoryStore::new();
27//! let tenant = TenantId::try_new("org:demo").unwrap();
28//! let session = SessionId::try_new("sess:1").unwrap();
29//! let owner = OwnerId::try_new("worker-1").unwrap();
30//!
31//! // 1. Create a session and acquire an exclusive fenced lease.
32//! store.create_session(&tenant, &session, None).await.unwrap();
33//! let lease = store
34//!     .acquire_session_lease(&tenant, &session, &owner, Duration::from_secs(30))
35//!     .await
36//!     .unwrap();
37//!
38//! // 2. Commit a session entry atomically under optimistic revision CAS.
39//! let mut commit = StepCommit::empty(SessionRevision::INITIAL);
40//! commit.entries.push(SessionEntry {
41//!     tenant_id: tenant.clone(),
42//!     session_id: session.clone(),
43//!     entry_id: EntryId::try_new("entry:1").unwrap(),
44//!     parent_entry_id: None,
45//!     run_id: Some(lease.run_id().clone()),
46//!     created_at_ms: 1_000,
47//!     payload: SessionEntryPayload::UserMessage {
48//!         blocks: vec![ContentBlock::text("hello")],
49//!         origin: None,
50//!         delivery: None,
51//!     },
52//! });
53//! let committed = store.commit_step(&lease, commit).await.unwrap();
54//! assert_eq!(committed.new_revision, SessionRevision::from_u64(1));
55//!
56//! // 3. Reusing the stale expected_revision fails closed with RevisionConflict.
57//! let conflict = store
58//!     .commit_step(&lease, StepCommit::empty(SessionRevision::INITIAL))
59//!     .await
60//!     .unwrap_err();
61//! assert!(matches!(conflict, StoreError::RevisionConflict { .. }));
62//!
63//! // 4. Load the committed branch from root to active leaf.
64//! let branch = store.load_branch(&tenant, &session, None).await.unwrap();
65//! assert_eq!(branch.entries.len(), 1);
66//! # });
67//! ```
68//!
69//! # Feature Flags
70//!
71//! - `conformance`: Exposes the `conformance` module (`conformance::run_all` and
72//!   `conformance::run_concurrency`) outside this crate's unit tests so backend crates
73//!   can test their [`AgentStore`] implementations against the standard invariant suite.
74//!   Disabled by default.
75//!
76//! # Module Guide
77//!
78//! - Root module:
79//!   - Traits: [`LeaseStore`], [`CommandStore`], [`SessionStore`], [`SpendStore`], and
80//!     their blanket supertrait [`AgentStore`].
81//!   - Identifiers & tokens: [`OwnerId`], [`PoolName`], [`LeaseToken`], and
82//!     [`TerminalRunStatus`].
83//!   - Atomic checkpoint payloads: [`StepCommit`], [`StepCommitResult`], [`NewEffect`],
84//!     [`EffectTransition`], [`NewSpendEntry`], [`PendingCommandReceipt`],
85//!     [`CommandReceipt`], and [`LoadedBranch`].
86//!   - Error surface: [`StoreError`].
87//! - [`prelude`]: Re-exports the core persistence traits, checkpoint payloads, [`StoreError`],
88//!   and [`InMemoryStore`] for a single `use allen_store::prelude::*;` import.
89//! - [`memory`]: Reference [`InMemoryStore`] implementation for ephemeral runs and tests.
90//! - `conformance` (requires feature `conformance`): Shared functional and concurrent
91//!   contention verification suite.
92//!
93//! # Safety & Durability Invariants
94//!
95//! - Enforces `#![forbid(unsafe_code)]`, zero SQL drivers, and zero filesystem I/O.
96//! - Requires a backend-issued [`LeaseToken`] on every mutating run or step operation
97//!   and checks its monotonic [`OwnerFence`] atomically so superseded workers fail
98//!   closed with [`StoreError::StaleFence`].
99//! - Commits session entries, active leaf updates, scope epoch bumps, effect journal
100//!   mutations, checked integer [`MicroUsd`] spend rows, and command deduplication
101//!   receipts in one atomic [`CommandStore::commit_step`] transaction fenced by
102//!   optimistic [`SessionRevision`] compare-and-swap.
103//! - Transitions in-flight `Claimed` effects to `Unknown` atomically whenever a lease
104//!   is recovered or superseded so side-effecting actions are reconciled before retry.
105//! - Enforces tenant isolation on every read and write, failing closed with
106//!   [`StoreError::TenantMismatch`] or [`StoreError::NotFound`].
107
108#![forbid(unsafe_code)]
109#![warn(missing_docs)]
110#![cfg_attr(docsrs, feature(doc_cfg))]
111#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used))]
112
113#[cfg(any(test, feature = "conformance"))]
114#[cfg_attr(docsrs, doc(cfg(feature = "conformance")))]
115pub mod conformance;
116pub mod memory;
117
118/// Re-exports the core Layer 1 persistence traits, checkpoint payloads, [`StoreError`], and
119/// [`InMemoryStore`] for concise imports (`use allen_store::prelude::*;`).
120///
121/// # Examples
122///
123/// ```rust
124/// use allen_store::prelude::*;
125/// use allen_types::ids::{SessionId, SessionRevision, TenantId};
126///
127/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
128/// let store = InMemoryStore::new();
129/// let tenant = TenantId::try_new("org:demo").unwrap();
130/// let session = SessionId::try_new("sess:prelude").unwrap();
131/// let created = store.create_session(&tenant, &session, None).await.unwrap();
132/// assert_eq!(created.new_revision, SessionRevision::INITIAL);
133/// # });
134/// ```
135pub mod prelude {
136    pub use crate::{
137        AgentStore, CommandReceipt, CommandStore, EffectTransition, InMemoryStore, LeaseStore,
138        LeaseToken, LoadedBranch, NewEffect, NewSpendEntry, OwnerId, PendingCommandReceipt,
139        PoolName, SessionStore, SpendStore, StepCommit, StepCommitResult, StoreError,
140        TerminalRunStatus,
141    };
142}
143
144use allen_types::ids::{
145    CommandId, EffectId, EntryId, InvalidIdError, OwnerFence, RunId, ScopeEpochs, SessionId,
146    SessionRevision, TenantId,
147};
148use allen_types::journal::{EffectEvent, EffectRecord, IllegalEffectTransition};
149use allen_types::lifecycle::CommandSettlement;
150use allen_types::money::{BillingClass, CostBasis, MicroUsd, SpendCategory};
151use allen_types::session::{RunStatus, SessionEntry};
152use futures_util::future::BoxFuture;
153use serde::{Deserialize, Serialize};
154use std::fmt;
155use std::str::FromStr;
156use std::time::Duration;
157
158pub use memory::InMemoryStore;
159
160macro_rules! store_string_id {
161    ($(#[$meta:meta])* $name:ident) => {
162        $(#[$meta])*
163        #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
164        #[serde(try_from = "String", into = "String")]
165        pub struct $name(String);
166
167        impl $name {
168            /// Validates and constructs a non-empty identifier containing no NUL bytes.
169            ///
170            /// # Errors
171            ///
172            /// Returns [`InvalidIdError::Empty`] if `value` is empty or whitespace-only,
173            /// or [`InvalidIdError::ContainsNul`] if `value` contains `'\0'`.
174            pub fn try_new(value: impl Into<String>) -> Result<Self, InvalidIdError> {
175                let value = value.into();
176                if value.trim().is_empty() {
177                    return Err(InvalidIdError::Empty);
178                }
179                if value.contains('\0') {
180                    return Err(InvalidIdError::ContainsNul);
181                }
182                Ok(Self(value))
183            }
184
185            /// Borrows the underlying validated string slice.
186            #[must_use]
187            pub fn as_str(&self) -> &str {
188                &self.0
189            }
190
191            /// Consumes the identifier and returns the owned inner `String`.
192            #[must_use]
193            pub fn into_inner(self) -> String {
194                self.0
195            }
196        }
197
198        impl fmt::Display for $name {
199            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200                f.write_str(&self.0)
201            }
202        }
203
204        impl AsRef<str> for $name {
205            fn as_ref(&self) -> &str {
206                &self.0
207            }
208        }
209
210        impl TryFrom<String> for $name {
211            type Error = InvalidIdError;
212
213            fn try_from(value: String) -> Result<Self, Self::Error> {
214                Self::try_new(value)
215            }
216        }
217
218        impl TryFrom<&str> for $name {
219            type Error = InvalidIdError;
220
221            fn try_from(value: &str) -> Result<Self, Self::Error> {
222                Self::try_new(value)
223            }
224        }
225
226        impl FromStr for $name {
227            type Err = InvalidIdError;
228
229            fn from_str(s: &str) -> Result<Self, Self::Err> {
230                Self::try_new(s)
231            }
232        }
233
234        impl From<$name> for String {
235            fn from(value: $name) -> Self {
236                value.0
237            }
238        }
239    };
240}
241
242store_string_id!(
243    /// Identifier of a worker process or host holding an exclusive run or session lease.
244    OwnerId
245);
246
247store_string_id!(
248    /// Named worker pool from which background workers claim queued or expired runs.
249    PoolName
250);
251
252/// Terminal run statuses accepted by [`LeaseStore::finish_run`].
253///
254/// Restricting the parameter type to this enum excludes non-terminal states
255/// (`Queued`, `Running`, `WaitingApproval`) at compile time.
256#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
257#[serde(rename_all = "snake_case")]
258pub enum TerminalRunStatus {
259    /// The run reached its intended completion state without unrecovered errors.
260    Completed,
261    /// The run terminated due to an unrecoverable error or policy failure.
262    Failed,
263    /// The run was explicitly cancelled before natural completion.
264    Cancelled,
265    /// The run paused in a durable terminal-until-resumed state (such as awaiting external intervention).
266    Parked,
267}
268
269impl TerminalRunStatus {
270    /// Converts this terminal status into its corresponding [`RunStatus`] variant.
271    #[must_use]
272    pub const fn as_run_status(self) -> RunStatus {
273        match self {
274            Self::Completed => RunStatus::Completed,
275            Self::Failed => RunStatus::Failed,
276            Self::Cancelled => RunStatus::Cancelled,
277            Self::Parked => RunStatus::Parked,
278        }
279    }
280
281    /// Returns the canonical `snake_case` wire and database representation of this status.
282    #[must_use]
283    pub const fn as_str(self) -> &'static str {
284        self.as_run_status().as_str()
285    }
286}
287
288impl From<TerminalRunStatus> for RunStatus {
289    fn from(status: TerminalRunStatus) -> Self {
290        status.as_run_status()
291    }
292}
293
294impl fmt::Display for TerminalRunStatus {
295    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296        f.write_str(self.as_str())
297    }
298}
299
300/// Exclusive ownership capability for one active run or interactive session.
301///
302/// Every mutating store operation takes a `&LeaseToken` and verifies its monotonic
303/// [`OwnerFence`] atomically against persisted run state. Fields are private so runtime
304/// callers cannot mutate a token's fence or tenant scope after issuance.
305#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
306pub struct LeaseToken {
307    tenant_id: TenantId,
308    session_id: SessionId,
309    run_id: RunId,
310    owner_id: OwnerId,
311    fence: OwnerFence,
312    expires_at_ms: i64,
313}
314
315impl LeaseToken {
316    /// Constructs a lease token from persisted backend state.
317    ///
318    /// Intended for [`LeaseStore`] backend implementations. Runtime callers should obtain
319    /// tokens from [`LeaseStore`] methods rather than constructing them directly.
320    #[must_use]
321    pub fn from_backend(
322        tenant_id: TenantId,
323        session_id: SessionId,
324        run_id: RunId,
325        owner_id: OwnerId,
326        fence: OwnerFence,
327        expires_at_ms: i64,
328    ) -> Self {
329        Self {
330            tenant_id,
331            session_id,
332            run_id,
333            owner_id,
334            fence,
335            expires_at_ms,
336        }
337    }
338
339    /// Returns the tenant that owns the leased session and run.
340    #[must_use]
341    pub fn tenant_id(&self) -> &TenantId {
342        &self.tenant_id
343    }
344
345    /// Returns the session bound to this lease.
346    #[must_use]
347    pub fn session_id(&self) -> &SessionId {
348        &self.session_id
349    }
350
351    /// Returns the run owned by this lease.
352    #[must_use]
353    pub fn run_id(&self) -> &RunId {
354        &self.run_id
355    }
356
357    /// Returns the worker or host identifier that currently owns this lease.
358    #[must_use]
359    pub fn owner_id(&self) -> &OwnerId {
360        &self.owner_id
361    }
362
363    /// Returns the monotonic [`OwnerFence`] verified on every fenced mutation.
364    #[must_use]
365    pub const fn fence(&self) -> OwnerFence {
366        self.fence
367    }
368
369    /// Returns the Unix epoch timestamp in milliseconds when this lease expires unless renewed.
370    #[must_use]
371    pub const fn expires_at_ms(&self) -> i64 {
372        self.expires_at_ms
373    }
374}
375
376/// Persisted command deduplication receipt returned by [`CommandStore::lookup_receipt`].
377#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
378pub struct CommandReceipt {
379    /// Tenant owning the session on which the command settled.
380    pub tenant_id: TenantId,
381    /// Session on which the command settled.
382    pub session_id: SessionId,
383    /// Caller-supplied idempotency identifier of the settled command.
384    pub command_id: CommandId,
385    /// Terminal disposition recorded when the command settled.
386    pub settlement: CommandSettlement,
387    /// Session revision produced by the [`CommandStore::commit_step`] that persisted this receipt.
388    pub resulting_revision: SessionRevision,
389    /// Session branch and activity epochs immediately after the commit.
390    pub epochs: ScopeEpochs,
391    /// Structured JSON outcome payload returned to retrying callers.
392    pub payload_json: serde_json::Value,
393}
394
395/// Command deduplication receipt staged for atomic persistence inside [`StepCommit`].
396///
397/// The backend derives `tenant_id`, `session_id`, `resulting_revision`, and `epochs` from
398/// the active [`LeaseToken`] and post-commit session state.
399#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
400pub struct PendingCommandReceipt {
401    /// Unique idempotency identifier for the command within `(tenant_id, session_id)`.
402    pub command_id: CommandId,
403    /// Terminal disposition to record for the command.
404    pub settlement: CommandSettlement,
405    /// Structured JSON outcome payload persisted alongside the receipt.
406    pub payload_json: serde_json::Value,
407}
408
409/// New external side-effect record prepared atomically inside [`StepCommit`].
410///
411/// Backends insert each prepared effect in `EffectState::Prepared` scoped to the active
412/// [`LeaseToken`]'s tenant, run, and [`OwnerFence`].
413#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
414pub struct NewEffect {
415    /// Unique identifier for the prepared effect record.
416    pub effect_id: EffectId,
417    /// Tenant-unique idempotency key preventing duplicate execution of the same external action.
418    pub idempotency_key: String,
419    /// SHA-256 hex digest describing the canonical action payload to be executed.
420    pub action_sha256: String,
421}
422
423/// State-machine transition applied to an existing or newly prepared effect inside [`StepCommit`].
424#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
425pub struct EffectTransition {
426    /// Identifier of the effect record to transition.
427    pub effect_id: EffectId,
428    /// Journal event validated against the effect's current state by `allen_types::journal::transition_effect`.
429    pub event: EffectEvent,
430    /// Optional SHA-256 or opaque digest of the observed external result to record on the effect.
431    pub result_digest: Option<String>,
432}
433
434/// Checked integer spend ledger row staged for atomic persistence inside [`StepCommit`].
435///
436/// Backends derive `tenant_id`, `session_id`, and `run_id` from the active [`LeaseToken`].
437#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
438pub struct NewSpendEntry {
439    /// Whether this charge is billable to the tenant or internal/non-billable overhead.
440    pub billing_class: BillingClass,
441    /// Structured spend category (inference tokens, sandbox compute, or external tool usage).
442    pub category: SpendCategory,
443    /// Non-negative cost amount in micro-USD (`10^-6` USD).
444    pub cost: MicroUsd,
445    /// Provenance of `cost` (for example, provider-reported vs. catalog-estimated).
446    pub basis: CostBasis,
447    /// Unix epoch timestamp in milliseconds when the spend was recorded.
448    pub recorded_at_ms: i64,
449}
450
451/// Atomic durable checkpoint committed by [`CommandStore::commit_step`].
452///
453/// Backends execute the entire checkpoint inside one transaction (for example, SQLite
454/// `BEGIN IMMEDIATE` or a single PostgreSQL transaction), verifying the lease's
455/// [`OwnerFence`] and the session's `expected_revision` before applying any change.
456/// If any check or constraint fails, all entries, leaf changes, effects, spend rows, and
457/// receipts in the commit roll back together.
458#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
459pub struct StepCommit {
460    /// Expected current [`SessionRevision`] checked by optimistic compare-and-swap.
461    pub expected_revision: SessionRevision,
462    /// Session tree entries to append in order; each must match the lease's tenant and session.
463    pub entries: Vec<SessionEntry>,
464    /// Explicit active leaf to select after appending `entries`; when `None`, the last entry
465    /// in `entries` (if any) becomes the active leaf.
466    pub new_leaf: Option<EntryId>,
467    /// When `true`, increments the session's branch epoch (used on branch switch or fork).
468    pub bump_branch_epoch: bool,
469    /// When `true`, increments the session's activity epoch (used when observable turn state advances).
470    pub bump_activity_epoch: bool,
471    /// New effects to insert in `EffectState::Prepared` before applying `effect_transitions`.
472    pub prepare_effects: Vec<NewEffect>,
473    /// Effect state transitions validated and applied in order after `prepare_effects`.
474    pub effect_transitions: Vec<EffectTransition>,
475    /// Spend ledger entries appended atomically with this step.
476    pub spend: Vec<NewSpendEntry>,
477    /// Optional command deduplication receipt recorded atomically with this step.
478    pub receipt: Option<PendingCommandReceipt>,
479}
480
481impl StepCommit {
482    /// Creates an empty [`StepCommit`] expecting `expected_revision` with no entries,
483    /// epoch bumps, effects, spend rows, or command receipt.
484    ///
485    /// Committing an empty step still validates the lease fence and advances the session
486    /// revision by one.
487    #[must_use]
488    pub fn empty(expected_revision: SessionRevision) -> Self {
489        Self {
490            expected_revision,
491            entries: Vec::new(),
492            new_leaf: None,
493            bump_branch_epoch: false,
494            bump_activity_epoch: false,
495            prepare_effects: Vec::new(),
496            effect_transitions: Vec::new(),
497            spend: Vec::new(),
498            receipt: None,
499        }
500    }
501}
502
503/// Post-commit session metadata returned by [`SessionStore::create_session`] and
504/// [`CommandStore::commit_step`].
505#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
506pub struct StepCommitResult {
507    /// Session revision persisted after the operation succeeded.
508    pub new_revision: SessionRevision,
509    /// Branch and activity epochs persisted after the operation succeeded.
510    pub epochs: ScopeEpochs,
511}
512
513/// Root-to-leaf session branch snapshot returned by [`SessionStore::load_branch`].
514#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
515pub struct LoadedBranch {
516    /// Current persisted [`SessionRevision`] of the session at read time.
517    pub revision: SessionRevision,
518    /// Current persisted [`ScopeEpochs`] of the session at read time.
519    pub epochs: ScopeEpochs,
520    /// Ordered entries from the root entry to the requested (or active) leaf.
521    pub entries: Vec<SessionEntry>,
522}
523
524/// Failure returned by [`AgentStore`] operations across all backends.
525#[non_exhaustive]
526#[derive(Clone, Debug, PartialEq, Eq)]
527pub enum StoreError {
528    /// A referenced session, run, entry, or effect does not exist.
529    NotFound(String),
530    /// A caller supplied a tenant or session scope that does not match the target record.
531    TenantMismatch,
532    /// The supplied [`LeaseToken`] carries an older [`OwnerFence`] than the persisted run.
533    StaleFence {
534        /// Fence carried by the caller's stale [`LeaseToken`].
535        expected: OwnerFence,
536        /// Current authoritative fence stored on the run.
537        actual: OwnerFence,
538    },
539    /// Optimistic compare-and-swap in [`CommandStore::commit_step`] observed a newer revision.
540    RevisionConflict {
541        /// Revision expected by the caller's [`StepCommit`].
542        expected: SessionRevision,
543        /// Current authoritative revision stored on the session.
544        actual: SessionRevision,
545    },
546    /// Another owner holds an unexpired lease on the target session or run.
547    LeaseHeldByOther {
548        /// Unix epoch timestamp in milliseconds when the competing lease expires.
549        expires_at_ms: i64,
550    },
551    /// An [`EffectTransition`] violated the Layer 0 effect state machine.
552    IllegalTransition(IllegalEffectTransition),
553    /// A unique session ID, run ID, command receipt, effect ID, or effect idempotency key already exists.
554    DuplicateIdempotencyKey(String),
555    /// Startup migration verification detected a checksum or name mismatch against an applied SQL migration.
556    SchemaDrift(String),
557    /// Backend-specific storage, serialization, invariant, or lifecycle error.
558    Backend(String),
559}
560
561impl From<IllegalEffectTransition> for StoreError {
562    fn from(err: IllegalEffectTransition) -> Self {
563        Self::IllegalTransition(err)
564    }
565}
566
567impl fmt::Display for StoreError {
568    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
569        match self {
570            Self::NotFound(msg)
571            | Self::DuplicateIdempotencyKey(msg)
572            | Self::SchemaDrift(msg)
573            | Self::Backend(msg) => f.write_str(msg),
574            Self::IllegalTransition(err) => err.fmt(f),
575            Self::TenantMismatch => f.write_str("tenant mismatch"),
576            Self::StaleFence { expected, actual } => {
577                write!(f, "stale owner fence: expected {expected}, actual {actual}")
578            }
579            Self::RevisionConflict { expected, actual } => write!(
580                f,
581                "session revision conflict: expected {expected}, actual {actual}"
582            ),
583            Self::LeaseHeldByOther { expires_at_ms } => {
584                write!(f, "lease held by another owner until {expires_at_ms}")
585            }
586        }
587    }
588}
589
590impl std::error::Error for StoreError {
591    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
592        match self {
593            Self::IllegalTransition(err) => Some(err),
594            _ => None,
595        }
596    }
597}
598
599/// Sub-trait 1: Exclusive run and session leasing for interactive sessions and pull-queue workers.
600pub trait LeaseStore: Send + Sync {
601    /// Enqueues a new background run in `Queued` status for workers polling `pool_name`.
602    ///
603    /// # Errors
604    ///
605    /// Returns [`StoreError::NotFound`] if `session_id` does not exist,
606    /// [`StoreError::TenantMismatch`] if `session_id` belongs to another tenant,
607    /// [`StoreError::DuplicateIdempotencyKey`] if `run_id` already exists, or
608    /// [`StoreError::Backend`] on storage failure.
609    fn enqueue_run<'a>(
610        &'a self,
611        tenant_id: &'a TenantId,
612        session_id: &'a SessionId,
613        run_id: &'a RunId,
614        pool_name: &'a PoolName,
615    ) -> BoxFuture<'a, Result<(), StoreError>>;
616
617    /// Acquires or supersedes an exclusive lease on an interactive session for `owner_id`.
618    ///
619    /// Creates a new interactive run when none is running on `session_id`, or supersedes an
620    /// existing running lease held by `owner_id` (or an expired lease held by another owner)
621    /// by advancing [`OwnerFence`] and transitioning any `Claimed` effects on that run to
622    /// `Unknown` atomically.
623    ///
624    /// # Errors
625    ///
626    /// Returns [`StoreError::NotFound`] if `session_id` does not exist,
627    /// [`StoreError::TenantMismatch`] if `session_id` belongs to another tenant,
628    /// [`StoreError::LeaseHeldByOther`] if a different owner holds an unexpired lease on
629    /// `session_id`, or [`StoreError::Backend`] on storage failure.
630    fn acquire_session_lease<'a>(
631        &'a self,
632        tenant_id: &'a TenantId,
633        session_id: &'a SessionId,
634        owner_id: &'a OwnerId,
635        ttl: Duration,
636    ) -> BoxFuture<'a, Result<LeaseToken, StoreError>>;
637
638    /// Atomically claims at most one `Queued` run from `pool_name` for `owner_id` with lease
639    /// lifetime `ttl`.
640    ///
641    /// Multi-replica backends use non-blocking row locking (such as `FOR UPDATE SKIP LOCKED`
642    /// in PostgreSQL) so concurrent workers never claim the same run twice. Returns `Ok(None)`
643    /// when no queued run is available in `pool_name`.
644    ///
645    /// # Errors
646    ///
647    /// Returns [`StoreError::Backend`] on storage or fence overflow failures.
648    fn claim_queued_run<'a>(
649        &'a self,
650        owner_id: &'a OwnerId,
651        pool_name: &'a PoolName,
652        ttl: Duration,
653    ) -> BoxFuture<'a, Result<Option<LeaseToken>, StoreError>>;
654
655    /// Atomically claims one expired running lease in `pool_name`
656    /// (`status = 'running' AND expires_at_ms <= now_ms`), advances [`OwnerFence`], updates
657    /// ownership and expiry to `owner_id` / `ttl`, and transitions all `Claimed` effects on
658    /// that run to `Unknown`.
659    ///
660    /// Live leases with `expires_at_ms > now_ms` are never touched. Returns `Ok(None)` when
661    /// no expired running lease exists in `pool_name`.
662    ///
663    /// # Errors
664    ///
665    /// Returns [`StoreError::IllegalTransition`] or [`StoreError::Backend`] on invariant or
666    /// storage failures.
667    fn reclaim_expired_run<'a>(
668        &'a self,
669        owner_id: &'a OwnerId,
670        pool_name: &'a PoolName,
671        ttl: Duration,
672    ) -> BoxFuture<'a, Result<Option<LeaseToken>, StoreError>>;
673
674    /// Extends the expiration timestamp of an active `lease` by `ttl` without changing its
675    /// [`OwnerFence`].
676    ///
677    /// # Errors
678    ///
679    /// Returns [`StoreError::NotFound`] if the run does not exist,
680    /// [`StoreError::TenantMismatch`] if the token's tenant or session does not match,
681    /// [`StoreError::StaleFence`] if another owner or [`Self::finish_run`] advanced the fence,
682    /// or [`StoreError::Backend`] if the run is not in `Running` status or storage fails.
683    fn renew_lease<'a>(
684        &'a self,
685        lease: &'a LeaseToken,
686        ttl: Duration,
687    ) -> BoxFuture<'a, Result<LeaseToken, StoreError>>;
688
689    /// Marks the leased run with a terminal [`TerminalRunStatus`] and optional `summary_code`,
690    /// advancing [`OwnerFence`] so subsequent calls using `lease` fail closed with
691    /// [`StoreError::StaleFence`].
692    ///
693    /// # Errors
694    ///
695    /// Returns [`StoreError::NotFound`], [`StoreError::TenantMismatch`],
696    /// [`StoreError::StaleFence`], or [`StoreError::Backend`] when the run is missing,
697    /// fenced out, or not in `Running` status.
698    fn finish_run<'a>(
699        &'a self,
700        lease: &'a LeaseToken,
701        status: TerminalRunStatus,
702        summary_code: Option<&'a str>,
703    ) -> BoxFuture<'a, Result<(), StoreError>>;
704
705    /// Reclaims a specific expired running lease (`status = 'running' AND expires_at_ms <= now_ms`)
706    /// for `new_owner_id`, returning the new [`LeaseToken`] and all `Claimed` effects that
707    /// transitioned atomically to `Unknown`.
708    ///
709    /// Refuses live unexpired leases with [`StoreError::LeaseHeldByOther`] and refuses
710    /// queued or terminal runs with [`StoreError::Backend`].
711    ///
712    /// # Errors
713    ///
714    /// Returns [`StoreError::NotFound`], [`StoreError::TenantMismatch`],
715    /// [`StoreError::LeaseHeldByOther`], [`StoreError::IllegalTransition`], or
716    /// [`StoreError::Backend`].
717    fn recover_expired_run<'a>(
718        &'a self,
719        tenant_id: &'a TenantId,
720        run_id: &'a RunId,
721        new_owner_id: &'a OwnerId,
722        ttl: Duration,
723    ) -> BoxFuture<'a, Result<(LeaseToken, Vec<EffectRecord>), StoreError>>;
724
725    /// Forces operator or conformance takeover of a non-terminal (`Running` or
726    /// `WaitingApproval`) run regardless of whether its lease has expired.
727    ///
728    /// Advances [`OwnerFence`] and transitions all `Claimed` effects on `run_id` to
729    /// `Unknown` in one atomic transaction. Refuses `Queued` and terminal runs
730    /// (`Completed`, `Failed`, `Cancelled`, `Parked`).
731    ///
732    /// # Errors
733    ///
734    /// Returns [`StoreError::NotFound`], [`StoreError::TenantMismatch`],
735    /// [`StoreError::IllegalTransition`], or [`StoreError::Backend`].
736    fn force_recover_run<'a>(
737        &'a self,
738        tenant_id: &'a TenantId,
739        run_id: &'a RunId,
740        new_owner_id: &'a OwnerId,
741        ttl: Duration,
742    ) -> BoxFuture<'a, Result<LeaseToken, StoreError>>;
743}
744
745/// Sub-trait 2: Atomic step checkpoints, command deduplication receipts, and effect inspection.
746pub trait CommandStore: Send + Sync {
747    /// Looks up a previously committed [`CommandReceipt`] for `(tenant_id, session_id, command_id)`.
748    ///
749    /// Returns `Ok(None)` if `command_id` has not been committed for that session.
750    ///
751    /// # Errors
752    ///
753    /// Returns [`StoreError::TenantMismatch`] if `session_id` belongs to another tenant,
754    /// or [`StoreError::Backend`] on storage or deserialization failure.
755    fn lookup_receipt<'a>(
756        &'a self,
757        tenant_id: &'a TenantId,
758        session_id: &'a SessionId,
759        command_id: &'a CommandId,
760    ) -> BoxFuture<'a, Result<Option<CommandReceipt>, StoreError>>;
761
762    /// Atomically verifies `lease` and `commit.expected_revision`, then persists all entries,
763    /// leaf pointer updates, epoch bumps, effect journal mutations, spend entries, and the
764    /// optional command receipt in a single transaction.
765    ///
766    /// On any error, backends roll back the entire checkpoint so no partial entries, effects,
767    /// spend rows, or receipts become visible.
768    ///
769    /// # Errors
770    ///
771    /// Returns:
772    /// - [`StoreError::NotFound`] if the run, session, target `new_leaf`, or transitioned
773    ///   effect does not exist.
774    /// - [`StoreError::TenantMismatch`] if any entry, effect, run, or session crosses tenant
775    ///   or session boundaries.
776    /// - [`StoreError::StaleFence`] if `lease` no longer holds the authoritative [`OwnerFence`].
777    /// - [`StoreError::RevisionConflict`] if the session's revision differs from
778    ///   `commit.expected_revision`.
779    /// - [`StoreError::IllegalTransition`] if an [`EffectTransition`] violates the Layer 0
780    ///   effect state machine.
781    /// - [`StoreError::DuplicateIdempotencyKey`] if an entry ID, effect ID, effect
782    ///   idempotency key, or command receipt ID collides with an existing record.
783    /// - [`StoreError::Backend`] on storage or serialization failure.
784    fn commit_step<'a>(
785        &'a self,
786        lease: &'a LeaseToken,
787        commit: StepCommit,
788    ) -> BoxFuture<'a, Result<StepCommitResult, StoreError>>;
789
790    /// Lists every effect in `EffectState::Unknown` belonging to `(tenant_id, run_id)`.
791    ///
792    /// Runtimes query this method after crash recovery to reconcile ambiguous external
793    /// side effects before scheduling new actions.
794    ///
795    /// # Errors
796    ///
797    /// Returns [`StoreError::TenantMismatch`] if `run_id` belongs to another tenant, or
798    /// [`StoreError::Backend`] on storage or deserialization failure.
799    fn list_unknown_effects<'a>(
800        &'a self,
801        tenant_id: &'a TenantId,
802        run_id: &'a RunId,
803    ) -> BoxFuture<'a, Result<Vec<EffectRecord>, StoreError>>;
804
805    /// Lists every effect currently in `EffectState::Claimed` belonging to `(tenant_id, run_id)`.
806    ///
807    /// # Errors
808    ///
809    /// Returns [`StoreError::TenantMismatch`] if `run_id` belongs to another tenant, or
810    /// [`StoreError::Backend`] on storage or deserialization failure.
811    fn list_claimed_effects<'a>(
812        &'a self,
813        tenant_id: &'a TenantId,
814        run_id: &'a RunId,
815    ) -> BoxFuture<'a, Result<Vec<EffectRecord>, StoreError>>;
816}
817
818/// Sub-trait 3: Durable session tree creation and root-to-leaf branch loading.
819pub trait SessionStore: Send + Sync {
820    /// Creates a new empty session at [`SessionRevision::INITIAL`] with default [`ScopeEpochs`].
821    ///
822    /// Optional `parent_session_id` records lineage when spawning child or forked sessions.
823    ///
824    /// # Errors
825    ///
826    /// Returns [`StoreError::DuplicateIdempotencyKey`] if `session_id` already exists, or
827    /// [`StoreError::Backend`] on storage failure.
828    fn create_session<'a>(
829        &'a self,
830        tenant_id: &'a TenantId,
831        session_id: &'a SessionId,
832        parent_session_id: Option<&'a SessionId>,
833    ) -> BoxFuture<'a, Result<StepCommitResult, StoreError>>;
834
835    /// Loads the ordered root-to-leaf [`SessionEntry`] chain for `session_id`.
836    ///
837    /// When `leaf` is `None`, loads the session's current active leaf (returning an empty
838    /// `entries` vector for a brand-new session). Detects parent-pointer cycles and rejects
839    /// cross-tenant reads.
840    ///
841    /// # Errors
842    ///
843    /// Returns [`StoreError::NotFound`] if the session or a referenced entry does not exist,
844    /// [`StoreError::TenantMismatch`] if `session_id` belongs to another tenant, or
845    /// [`StoreError::Backend`] on cycle detection or storage/deserialization failure.
846    fn load_branch<'a>(
847        &'a self,
848        tenant_id: &'a TenantId,
849        session_id: &'a SessionId,
850        leaf: Option<&'a EntryId>,
851    ) -> BoxFuture<'a, Result<LoadedBranch, StoreError>>;
852}
853
854/// Sub-trait 4: Checked integer [`MicroUsd`] spend ledger queries.
855///
856/// Writes enter the spend ledger exclusively through atomic [`CommandStore::commit_step`]
857/// checkpoints so spend accounting rolls back alongside failed steps.
858pub trait SpendStore: Send + Sync {
859    /// Sums all spend rows recorded for `tenant_id` with `recorded_at_ms >= since_ms`,
860    /// optionally restricted to a single [`BillingClass`].
861    ///
862    /// Uses saturating [`MicroUsd`] addition so sums never wrap.
863    ///
864    /// # Errors
865    ///
866    /// Returns [`StoreError::Backend`] on storage or corrupt-row failures.
867    fn sum_spend_since<'a>(
868        &'a self,
869        tenant_id: &'a TenantId,
870        since_ms: i64,
871        billing_class: Option<BillingClass>,
872    ) -> BoxFuture<'a, Result<MicroUsd, StoreError>>;
873
874    /// Sums all spend rows recorded for `(tenant_id, run_id)` across all billing classes.
875    ///
876    /// # Errors
877    ///
878    /// Returns [`StoreError::Backend`] on storage or corrupt-row failures.
879    fn sum_run_spend<'a>(
880        &'a self,
881        tenant_id: &'a TenantId,
882        run_id: &'a RunId,
883    ) -> BoxFuture<'a, Result<MicroUsd, StoreError>>;
884}
885
886/// Unified Layer 1 persistence supertrait combining [`LeaseStore`], [`CommandStore`],
887/// [`SessionStore`], and [`SpendStore`].
888///
889/// Any type implementing all four sub-traits (including [`InMemoryStore`],
890/// `SqliteAgentStore`, external custom backends, and `Arc<T>`) implements `AgentStore`
891/// automatically via the blanket implementation.
892pub trait AgentStore: LeaseStore + CommandStore + SessionStore + SpendStore {}
893impl<T: LeaseStore + CommandStore + SessionStore + SpendStore> AgentStore for T {}
894
895impl<T: LeaseStore + ?Sized> LeaseStore for std::sync::Arc<T> {
896    fn enqueue_run<'a>(
897        &'a self,
898        tenant_id: &'a TenantId,
899        session_id: &'a SessionId,
900        run_id: &'a RunId,
901        pool_name: &'a PoolName,
902    ) -> BoxFuture<'a, Result<(), StoreError>> {
903        (**self).enqueue_run(tenant_id, session_id, run_id, pool_name)
904    }
905    fn acquire_session_lease<'a>(
906        &'a self,
907        tenant_id: &'a TenantId,
908        session_id: &'a SessionId,
909        owner_id: &'a OwnerId,
910        ttl: Duration,
911    ) -> BoxFuture<'a, Result<LeaseToken, StoreError>> {
912        (**self).acquire_session_lease(tenant_id, session_id, owner_id, ttl)
913    }
914    fn claim_queued_run<'a>(
915        &'a self,
916        owner_id: &'a OwnerId,
917        pool_name: &'a PoolName,
918        ttl: Duration,
919    ) -> BoxFuture<'a, Result<Option<LeaseToken>, StoreError>> {
920        (**self).claim_queued_run(owner_id, pool_name, ttl)
921    }
922    fn reclaim_expired_run<'a>(
923        &'a self,
924        owner_id: &'a OwnerId,
925        pool_name: &'a PoolName,
926        ttl: Duration,
927    ) -> BoxFuture<'a, Result<Option<LeaseToken>, StoreError>> {
928        (**self).reclaim_expired_run(owner_id, pool_name, ttl)
929    }
930    fn renew_lease<'a>(
931        &'a self,
932        lease: &'a LeaseToken,
933        ttl: Duration,
934    ) -> BoxFuture<'a, Result<LeaseToken, StoreError>> {
935        (**self).renew_lease(lease, ttl)
936    }
937    fn finish_run<'a>(
938        &'a self,
939        lease: &'a LeaseToken,
940        status: TerminalRunStatus,
941        summary_code: Option<&'a str>,
942    ) -> BoxFuture<'a, Result<(), StoreError>> {
943        (**self).finish_run(lease, status, summary_code)
944    }
945    fn recover_expired_run<'a>(
946        &'a self,
947        tenant_id: &'a TenantId,
948        run_id: &'a RunId,
949        new_owner_id: &'a OwnerId,
950        ttl: Duration,
951    ) -> BoxFuture<'a, Result<(LeaseToken, Vec<EffectRecord>), StoreError>> {
952        (**self).recover_expired_run(tenant_id, run_id, new_owner_id, ttl)
953    }
954    fn force_recover_run<'a>(
955        &'a self,
956        tenant_id: &'a TenantId,
957        run_id: &'a RunId,
958        new_owner_id: &'a OwnerId,
959        ttl: Duration,
960    ) -> BoxFuture<'a, Result<LeaseToken, StoreError>> {
961        (**self).force_recover_run(tenant_id, run_id, new_owner_id, ttl)
962    }
963}
964
965impl<T: CommandStore + ?Sized> CommandStore for std::sync::Arc<T> {
966    fn lookup_receipt<'a>(
967        &'a self,
968        tenant_id: &'a TenantId,
969        session_id: &'a SessionId,
970        command_id: &'a CommandId,
971    ) -> BoxFuture<'a, Result<Option<CommandReceipt>, StoreError>> {
972        (**self).lookup_receipt(tenant_id, session_id, command_id)
973    }
974    fn commit_step<'a>(
975        &'a self,
976        lease: &'a LeaseToken,
977        commit: StepCommit,
978    ) -> BoxFuture<'a, Result<StepCommitResult, StoreError>> {
979        (**self).commit_step(lease, commit)
980    }
981    fn list_unknown_effects<'a>(
982        &'a self,
983        tenant_id: &'a TenantId,
984        run_id: &'a RunId,
985    ) -> BoxFuture<'a, Result<Vec<EffectRecord>, StoreError>> {
986        (**self).list_unknown_effects(tenant_id, run_id)
987    }
988
989    fn list_claimed_effects<'a>(
990        &'a self,
991        tenant_id: &'a TenantId,
992        run_id: &'a RunId,
993    ) -> BoxFuture<'a, Result<Vec<EffectRecord>, StoreError>> {
994        (**self).list_claimed_effects(tenant_id, run_id)
995    }
996}
997
998impl<T: SessionStore + ?Sized> SessionStore for std::sync::Arc<T> {
999    fn create_session<'a>(
1000        &'a self,
1001        tenant_id: &'a TenantId,
1002        session_id: &'a SessionId,
1003        parent_session_id: Option<&'a SessionId>,
1004    ) -> BoxFuture<'a, Result<StepCommitResult, StoreError>> {
1005        (**self).create_session(tenant_id, session_id, parent_session_id)
1006    }
1007    fn load_branch<'a>(
1008        &'a self,
1009        tenant_id: &'a TenantId,
1010        session_id: &'a SessionId,
1011        leaf: Option<&'a EntryId>,
1012    ) -> BoxFuture<'a, Result<LoadedBranch, StoreError>> {
1013        (**self).load_branch(tenant_id, session_id, leaf)
1014    }
1015}
1016
1017impl<T: SpendStore + ?Sized> SpendStore for std::sync::Arc<T> {
1018    fn sum_spend_since<'a>(
1019        &'a self,
1020        tenant_id: &'a TenantId,
1021        since_ms: i64,
1022        billing_class: Option<BillingClass>,
1023    ) -> BoxFuture<'a, Result<MicroUsd, StoreError>> {
1024        (**self).sum_spend_since(tenant_id, since_ms, billing_class)
1025    }
1026    fn sum_run_spend<'a>(
1027        &'a self,
1028        tenant_id: &'a TenantId,
1029        run_id: &'a RunId,
1030    ) -> BoxFuture<'a, Result<MicroUsd, StoreError>> {
1031        (**self).sum_run_spend(tenant_id, run_id)
1032    }
1033}
1034
1035#[cfg(test)]
1036mod tests {
1037    use super::*;
1038
1039    #[test]
1040    fn owner_id_and_pool_name_reject_empty_whitespace_and_nul() {
1041        assert_eq!(OwnerId::try_new(""), Err(InvalidIdError::Empty));
1042        assert_eq!(OwnerId::try_new(" \t\n "), Err(InvalidIdError::Empty));
1043        assert_eq!(
1044            OwnerId::try_new("worker\0id"),
1045            Err(InvalidIdError::ContainsNul)
1046        );
1047        assert_eq!(PoolName::try_new(""), Err(InvalidIdError::Empty));
1048        assert_eq!(
1049            PoolName::try_new("pool\0name"),
1050            Err(InvalidIdError::ContainsNul)
1051        );
1052
1053        let owner = OwnerId::try_new("worker-1").unwrap();
1054        assert_eq!(owner.as_str(), "worker-1");
1055        let pool = PoolName::try_new("scanner-pool").unwrap();
1056        assert_eq!(pool.as_str(), "scanner-pool");
1057
1058        assert!(serde_json::from_str::<OwnerId>("\"\"").is_err());
1059        assert!(serde_json::from_str::<PoolName>("\"   \"").is_err());
1060    }
1061
1062    #[test]
1063    fn terminal_run_status_maps_only_terminal_statuses() {
1064        assert_eq!(
1065            TerminalRunStatus::Completed.as_run_status(),
1066            RunStatus::Completed
1067        );
1068        assert_eq!(TerminalRunStatus::Failed.as_run_status(), RunStatus::Failed);
1069        assert_eq!(
1070            TerminalRunStatus::Cancelled.as_run_status(),
1071            RunStatus::Cancelled
1072        );
1073        assert_eq!(TerminalRunStatus::Parked.as_run_status(), RunStatus::Parked);
1074    }
1075}