Skip to main content

conversation_api/execution/
storage.rs

1//! Persistence contracts expressed in Agent consistency semantics.
2
3use async_trait::async_trait;
4use serde::{Deserialize, Serialize};
5use thiserror::Error;
6
7use crate::execution::{
8    ConversationSurface, DurableEvent, InvocationContext, Message, QueuedRun, RunId, SpaceContext,
9    ThreadId,
10};
11
12/// Monotonic revision used for optimistic concurrency control.
13#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
14#[serde(transparent)]
15pub struct Revision(pub u64);
16
17impl Revision {
18    /// Revision expected when creating a new thread record.
19    pub const INITIAL: Self = Self(0);
20
21    /// Returns the next revision, if representable.
22    #[must_use]
23    pub fn next(self) -> Option<Self> {
24        self.0.checked_add(1).map(Self)
25    }
26}
27
28/// Fully scoped key for one durable Agent thread.
29#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
30pub struct ThreadKey {
31    /// Authorization and persistence scope.
32    #[serde(with = "super::stored::space")]
33    pub scope: SpaceContext,
34    /// Canonical Conversation-space identity and delivery route.
35    pub surface_id: ConversationSurface,
36    /// Thread identifier within the scope.
37    pub thread_id: ThreadId,
38}
39
40/// Opaque control-state checkpoint bytes owned and versioned by Runtime.
41///
42/// Prompt-visible history is intentionally stored separately as an append-only journal so a
43/// control transition does not rewrite every preceding message.
44#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
45pub struct Checkpoint {
46    /// Runtime checkpoint schema version.
47    pub format_version: u32,
48    /// Serialized checkpoint payload.
49    pub bytes: Vec<u8>,
50}
51
52/// Materialized Runtime state used when seeding or exporting one thread generation.
53#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
54pub struct RuntimeSnapshot {
55    /// Small mutable execution-control checkpoint.
56    pub checkpoint: Checkpoint,
57    /// Prompt-visible history materialized from the append-only journal.
58    pub history: Vec<Message>,
59}
60
61/// Current durable state of one thread.
62#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
63pub struct ThreadRecord {
64    /// Current optimistic concurrency revision.
65    pub revision: Revision,
66    /// Latest Runtime checkpoint.
67    pub checkpoint: Checkpoint,
68    /// Prompt-visible history materialized from the append-only journal.
69    pub history: Vec<Message>,
70    /// Event committed with this generation but not yet acknowledged by the downstream consumer.
71    pub pending_event: Option<DurableEvent>,
72}
73
74/// Prompt-history mutation committed atomically with Runtime control state.
75#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
76#[serde(tag = "type", content = "messages", rename_all = "snake_case")]
77pub enum HistoryMutation {
78    /// Adds rows to the currently materialized history.
79    Append(Vec<Message>),
80    /// Replaces the materialized history after deterministic window truncation.
81    Replace(Vec<Message>),
82}
83
84/// One atomic state transition requested by Runtime.
85#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
86pub struct ThreadCommit {
87    /// Lease fencing token required by distributed implementations.
88    pub fencing_token: Option<u64>,
89    /// Replacement Runtime checkpoint.
90    pub checkpoint: Checkpoint,
91    /// Atomic prompt-history append or replacement.
92    pub history: HistoryMutation,
93    /// Exact pending event durably acknowledged by the downstream consumer.
94    pub acknowledge_event: Option<crate::execution::EventId>,
95    /// Event that becomes durable with the checkpoint revision.
96    pub event: Option<DurableEvent>,
97    /// Context indexed by distributed deployments while this checkpoint or its outbox needs recovery.
98    /// `None` removes the thread from the runnable recovery index.
99    pub recovery_context: Option<InvocationContext>,
100}
101
102/// Outcome of an optimistic thread commit.
103#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
104#[serde(tag = "type", rename_all = "snake_case")]
105pub enum CommitOutcome {
106    /// The transition was committed at the returned revision.
107    Applied {
108        /// Newly committed revision.
109        revision: Revision,
110    },
111    /// Another writer advanced the thread before this commit.
112    Conflict {
113        /// Current durable revision.
114        actual: Revision,
115    },
116    /// The writer no longer owns the distributed execution lease.
117    StaleFence {
118        /// Current fencing token observed by the storage implementation.
119        actual: u64,
120    },
121}
122
123/// Stable persistence failure independent of File, `SQLite`, S3, or `DynamoDB` details.
124#[derive(Clone, Debug, Error, Eq, PartialEq)]
125pub enum StoreError {
126    /// The requested state transition violates the storage contract.
127    #[error("invalid durable state transition: {message}")]
128    InvalidInput {
129        /// Safe diagnostic message.
130        message: String,
131    },
132    /// Durable state cannot be decoded or fails integrity validation.
133    #[error("corrupt durable state: {message}")]
134    Corrupt {
135        /// Safe diagnostic message.
136        message: String,
137    },
138    /// The authenticated scope cannot access the requested state.
139    #[error("durable state access denied")]
140    PermissionDenied,
141    /// The storage dependency is temporarily unavailable.
142    #[error("durable state unavailable: {message}")]
143    Unavailable {
144        /// Safe diagnostic message.
145        message: String,
146    },
147    /// The adapter failed without a more specific stable classification.
148    #[error("durable state failure: {message}")]
149    Internal {
150        /// Safe diagnostic message.
151        message: String,
152    },
153}
154
155/// Atomic thread state repository.
156#[async_trait]
157pub trait ThreadStore: Send + Sync {
158    /// Loads the current thread record.
159    async fn load(&self, key: &ThreadKey) -> Result<Option<ThreadRecord>, StoreError>;
160
161    /// Commits a checkpoint and its optional durable event if `expected` and the fencing token are current.
162    ///
163    /// Distributed implementations must validate `fencing_token` against the authoritative lease,
164    /// so a paused former owner cannot commit after a new owner acquires the thread.
165    async fn commit(
166        &self,
167        key: &ThreadKey,
168        expected: Revision,
169        transition: ThreadCommit,
170    ) -> Result<CommitOutcome, StoreError>;
171}
172
173/// Versioned process-local execution queue kept separate from both the durable
174/// user waiting queue and the Runtime checkpoint.
175#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
176pub struct QueueSnapshot {
177    /// Current optimistic concurrency revision.
178    pub revision: Revision,
179    /// Requests waiting to enter the Runtime loop.
180    pub items: Vec<QueuedRun>,
181}
182
183/// Outcome of claiming the next queued request without destructively removing it.
184#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
185#[serde(tag = "type", rename_all = "snake_case")]
186pub enum ClaimNextOutcome {
187    /// The queue was empty at the expected revision.
188    Empty,
189    /// The head request was claimed and returned.
190    Claimed {
191        /// New queue revision after recording the claim.
192        revision: Revision,
193        /// Claimed request. It remains in process memory until `ack_started` succeeds.
194        request: Box<QueuedRun>,
195    },
196    /// Another writer changed the queue first.
197    Conflict {
198        /// Current queue revision.
199        actual: Revision,
200    },
201}
202
203/// Process-local execution admission queue for one thread.
204///
205/// The deployment-owned user waiting queue is not this interface: `MeowCore` and
206/// Lion persist it before dispatching one attempt into Runtime. Losing this
207/// store loses the attempt and must never trigger cross-process replay.
208#[async_trait]
209pub trait QueueStore: Send + Sync {
210    /// Loads the current queue snapshot.
211    async fn load(&self, key: &ThreadKey) -> Result<QueueSnapshot, StoreError>;
212
213    /// Enqueues a run idempotently by `operation_id` and `run_id`.
214    ///
215    /// Implementations preserve idempotency for the lifetime of the process.
216    async fn enqueue(
217        &self,
218        key: &ThreadKey,
219        request: QueuedRun,
220    ) -> Result<QueueSnapshot, StoreError>;
221
222    /// Claims the first unclaimed queue item at `expected` revision.
223    ///
224    /// `claimant` identifies the single process-local driver attempt. A lost
225    /// attempt is failed by the deployment owner and is never reclaimed here.
226    async fn claim_next(
227        &self,
228        key: &ThreadKey,
229        expected: Revision,
230        claimant: &str,
231    ) -> Result<ClaimNextOutcome, StoreError>;
232
233    /// Removes an item after the same run has been committed as the active thread checkpoint.
234    ///
235    /// Implementations must make repeated acknowledgements for the same run idempotent.
236    async fn ack_started(
237        &self,
238        key: &ThreadKey,
239        run_id: &RunId,
240    ) -> Result<QueueSnapshot, StoreError>;
241
242    /// Removes a queued run idempotently and returns the updated snapshot.
243    async fn remove(&self, key: &ThreadKey, run_id: &RunId) -> Result<QueueSnapshot, StoreError>;
244}
245
246/// Process-local cooperative cancellation signal for a live execution attempt.
247#[async_trait]
248pub trait RunControl: Send + Sync {
249    /// Requests cancellation idempotently.
250    ///
251    /// The full invocation context prevents collisions between users, scopes,
252    /// threads, and runs inside one process.
253    async fn request_cancel(
254        &self,
255        key: &ThreadKey,
256        context: &InvocationContext,
257    ) -> Result<(), StoreError>;
258
259    /// Returns whether cancellation has been requested.
260    async fn is_cancel_requested(
261        &self,
262        key: &ThreadKey,
263        run_id: &RunId,
264    ) -> Result<bool, StoreError>;
265
266    /// Waits until cancellation is requested, allowing Runtime to drop an in-flight external
267    /// operation and stop the execution attempt.
268    async fn wait_for_cancel(&self, key: &ThreadKey, run_id: &RunId) -> Result<(), StoreError>;
269
270    /// Clears the cancellation signal after a run has settled.
271    async fn clear_cancel(&self, key: &ThreadKey, run_id: &RunId) -> Result<(), StoreError>;
272}
273
274/// Lease proving exclusive ownership of a thread run.
275#[derive(Clone, Debug, Eq, PartialEq)]
276pub struct RunLease {
277    /// Thread guarded by the lease.
278    pub key: ThreadKey,
279    /// Owning run.
280    pub run_id: RunId,
281    /// Opaque fencing token that increases across owners.
282    pub fencing_token: u64,
283    /// Absolute Unix expiration in milliseconds.
284    pub expires_at_unix_ms: u64,
285}
286
287/// Coordinates exclusive execution of one thread inside one live process.
288#[async_trait]
289pub trait RunCoordinator: Send + Sync {
290    /// Attempts to acquire a process-local lease for a run.
291    async fn acquire(
292        &self,
293        key: &ThreadKey,
294        run_id: &RunId,
295        lease_ms: u64,
296    ) -> Result<Option<RunLease>, StoreError>;
297
298    /// Renews a lease if the caller still owns its fencing token.
299    async fn renew(&self, lease: &RunLease, lease_ms: u64) -> Result<Option<RunLease>, StoreError>;
300
301    /// Releases a lease if the caller still owns its fencing token.
302    async fn release(&self, lease: &RunLease) -> Result<(), StoreError>;
303}