Skip to main content

adk_session/
mongodb_runtime.rs

1//! MongoDB-backed [`LeaseStore`](adk_core::LeaseStore), [`DurableRunStore`](adk_core::DurableRunStore), [`ScheduleStore`](adk_core::ScheduleStore), and
2//! [`GovernanceStateStore`](adk_core::GovernanceStateStore).
3//!
4//! Every store works on a standalone `mongod` as well as on a replica set or sharded
5//! cluster. Run enqueues use a multi-document transaction where the server supports one
6//! (see [Enqueue paths](#enqueue-paths)); every other guarantee rests on a
7//! single-document atomic write — a filtered `findOneAndUpdate`, a revision-filtered
8//! replace, or a unique index.
9//!
10//! # Collections
11//!
12//! | Collection | `_id` | Contents |
13//! |------------|-------|----------|
14//! | `adk_leases` | Resource name | `owner`, `epoch`, `expires_us`, `released` |
15//! | `adk_runs` | Run ID (UUID v4) | `record` (the [`RunRecord`](adk_core::run_store::RunRecord) as JSON, the source of truth) plus the queried fields `queue`, `seq`, `state`, `ready_us`, `finished_us`, `idempotency_key`, `concurrency_key`, `app_name`, `user_id`, `session_id`, `revision` |
16//! | `adk_run_counters` | `seq` | The counter that orders runs by enqueue |
17//! | `adk_run_keys` | Hex of the queue and the concurrency key | `holders`: unfinished runs holding the key, in admission order; `pending_cancel` while an `Interrupt` is applied |
18//! | `adk_schedules` | Schedule ID | `schedule` (JSON), `paused`, `due_us`, `revision` |
19//! | `adk_governance` | [`GovernanceScope::key`](adk_core::governance_state::GovernanceScope::key) | `state` (JSON), `epoch` |
20//!
21//! Times are stored as integer microseconds since the epoch; stores truncate their
22//! clock to microseconds, so records read back exactly.
23//!
24//! # Atomicity
25//!
26//! | Operation | Mechanism |
27//! |-----------|-----------|
28//! | Lease `acquire` | `findOneAndUpdate` with `upsert`, filtered on `released`, expiry, or the same owner; a duplicate-key error on the upsert means another owner holds the lease |
29//! | Lease `renew`, `release` | `findOneAndUpdate` / `updateOne` filtered on `epoch` and `owner` |
30//! | Idempotent `enqueue` | Unique partial index on `(queue, idempotency_key)`; a duplicate-key error returns the existing run |
31//! | `claim`, fenced writes, `wake`, `request_cancel` | Read the record, apply the transition, and replace it filtered on its `revision`; a lost compare-and-swap re-reads |
32//! | Concurrency keys | The key's `adk_run_keys` document: only its first unfinished holder is claimable while `Queued`; `Reject` admits a run only while `holders` is empty; `Interrupt` swaps `holders` by exact match and parks the cancelled runs in `pending_cancel`, which every reader applies before deciding |
33//! | Schedule `upsert`, `advance`, `set_paused` | Replace filtered on `revision`; an insert for revision 1 |
34//! | Governance `set` | `insertOne` for epoch 0, `updateOne` filtered on `epoch` otherwise |
35//!
36//! # Enqueue paths
37//!
38//! | Server | Enqueue | Guarantee |
39//! |--------|---------|-----------|
40//! | Replica set (one node is enough) or sharded cluster | One multi-document transaction: idempotency check, key holders' policy, insert, and admission to the key commit together | No window: a caller never receives a run that is later withdrawn, and a key never admits a second run under `Reject` |
41//! | Standalone `mongod` (fallback) | Single-document steps: insert, then admission to the key | Weaker; see below |
42//!
43//! [`MongoRunStore::supports_transactions`] picks the path from the server's `hello`
44//! reply, or from [`MongoRunStore::with_transactions`].
45//!
46//! On the standalone fallback a keyed run is inserted before it is admitted to its key,
47//! which leaves two windows:
48//!
49//! - A `Reject` enqueue that loses the admission check deletes the run it inserted. A
50//!   concurrent enqueue with the same idempotency key can receive that run as
51//!   [`Enqueued::Existing`](adk_core::run_store::Enqueued::Existing) in the moment before it is deleted.
52//! - A process that stops between inserting a keyed run and admitting it leaves the
53//!   run `Queued` but not yet admitted; a claim admits it at the back of its key once it
54//!   is a minute old. An `Interrupt` lost this way does not cancel the earlier holders.
55
56use std::sync::Arc;
57use std::time::Duration;
58
59use adk_core::governance_state::{
60    GovernanceScope, GovernanceState, GovernanceStateStore, governance_conflict_error,
61};
62use adk_core::lease::{Lease, LeaseStore, lease_stale_epoch_error};
63use adk_core::principal::SubjectRef;
64use adk_core::run_store::{
65    ClaimedRun, DurableRunStore, Enqueued, NewRun, OnConflict, RunCheckpointRef, RunFilter,
66    RunOutcome, RunRecord, RunState, run_not_found_error,
67};
68use adk_core::schedule::{Schedule, ScheduleStore, schedule_not_found_error};
69use adk_core::{Clock, Result, SystemClock};
70use async_trait::async_trait;
71use chrono::{DateTime, Utc};
72use mongodb::bson::{Bson, Document, doc};
73use mongodb::error::{TRANSIENT_TRANSACTION_ERROR, UNKNOWN_TRANSACTION_COMMIT_RESULT};
74use mongodb::options::{IndexOptions, ReturnDocument};
75use mongodb::{ClientSession, Collection, Database, IndexModel};
76
77use crate::durable_common::{
78    GOVERNANCE_STORAGE, LEASE_STORAGE, RUN_STORAGE, SCHEDULE_STORAGE, deadline, hex,
79    same_definition, state_name, storage_error, stored_now,
80};
81use crate::durable_transitions::{
82    ClaimStep, apply_cancel, apply_checkpoint, apply_claim, apply_exhaust, apply_finish,
83    apply_heartbeat, apply_wait, apply_wake, check_fence, claim_step, ready_micros,
84};
85use crate::mongodb_stores::{connect, is_duplicate_key, read_i64};
86
87const LEASES: &str = "adk_leases";
88const RUNS: &str = "adk_runs";
89const RUN_COUNTERS: &str = "adk_run_counters";
90const RUN_KEYS: &str = "adk_run_keys";
91const SCHEDULES: &str = "adk_schedules";
92const GOVERNANCE: &str = "adk_governance";
93
94/// Compare-and-swap attempts before an operation reports contention as a failure.
95const MAX_CAS_ATTEMPTS: u32 = 64;
96
97/// Candidates a claim reads per query.
98const CLAIM_PAGE: i64 = 64;
99
100/// How old a keyed run that was never admitted to its key must be before a claim
101/// admits it, so an enqueue still in flight is left to finish.
102const ADMIT_GRACE: chrono::TimeDelta = chrono::TimeDelta::seconds(60);
103
104fn micros(at: DateTime<Utc>) -> i64 {
105    at.timestamp_micros()
106}
107
108/// The smallest whole microsecond at or after `at`, so `stored < at` is `stored_us < ceil`.
109fn ceil_micros(at: DateTime<Utc>) -> i64 {
110    let floor = at.timestamp_micros();
111    if at.timestamp_subsec_nanos().is_multiple_of(1_000) { floor } else { floor.saturating_add(1) }
112}
113
114fn from_micros(value: i64, code: &'static str) -> Result<DateTime<Utc>> {
115    DateTime::from_timestamp_micros(value)
116        .ok_or_else(|| storage_error(code, format!("stored time {value} is out of range")))
117}
118
119async fn ping(db: &Database, code: &'static str) -> Result<()> {
120    db.run_command(doc! { "ping": 1 })
121        .await
122        .map(|_| ())
123        .map_err(|e| storage_error(code, format!("mongodb ping failed: {e}")))
124}
125
126async fn open(
127    connection_string: &str,
128    database_name: &str,
129    code: &'static str,
130) -> Result<Database> {
131    connect(connection_string, database_name)
132        .await
133        .map_err(|e| storage_error(code, format!("mongodb connection failed: {e}")))
134}
135
136async fn create_index(
137    collection: &Collection<Document>,
138    keys: Document,
139    options: IndexOptions,
140    code: &'static str,
141) -> Result<()> {
142    collection
143        .create_index(IndexModel::builder().keys(keys).options(options).build())
144        .await
145        .map(|_| ())
146        .map_err(|e| storage_error(code, format!("mongodb index creation failed: {e}")))
147}
148
149fn named(name: &str) -> IndexOptions {
150    IndexOptions::builder().name(name.to_string()).build()
151}
152
153async fn collect(
154    mut cursor: mongodb::Cursor<Document>,
155    code: &'static str,
156) -> Result<Vec<Document>> {
157    let mut documents = Vec::new();
158    while cursor.advance().await.map_err(|e| storage_error(code, e))? {
159        documents.push(cursor.deserialize_current().map_err(|e| storage_error(code, e))?);
160    }
161    Ok(documents)
162}
163
164fn field_str<'a>(document: &'a Document, field: &str, code: &'static str) -> Result<&'a str> {
165    document
166        .get_str(field)
167        .map_err(|_| storage_error(code, format!("stored field '{field}' is missing or corrupt")))
168}
169
170fn field_i64(document: &Document, field: &str, code: &'static str) -> Result<i64> {
171    read_i64(document, field)
172        .ok_or_else(|| storage_error(code, format!("stored field '{field}' is missing or corrupt")))
173}
174
175fn decode<T: serde::de::DeserializeOwned>(
176    document: &Document,
177    field: &str,
178    code: &'static str,
179) -> Result<T> {
180    serde_json::from_str(field_str(document, field, code)?)
181        .map_err(|e| storage_error(code, format!("stored field '{field}' is corrupt: {e}")))
182}
183
184fn encode<T: serde::Serialize>(value: &T, code: &'static str) -> Result<String> {
185    serde_json::to_string(value).map_err(|e| storage_error(code, format!("serialize failed: {e}")))
186}
187
188fn to_i64(value: u64, code: &'static str) -> Result<i64> {
189    i64::try_from(value).map_err(|_| storage_error(code, format!("{value} does not fit in i64")))
190}
191
192fn optional(value: Option<&str>) -> Bson {
193    value.map_or(Bson::Null, |value| Bson::String(value.to_string()))
194}
195
196// ---------------------------------------------------------------------------
197// Leases
198// ---------------------------------------------------------------------------
199
200/// MongoDB-backed [`LeaseStore`].
201///
202/// One `adk_leases` document per resource, kept after release so epochs never repeat.
203/// Expiry is compared inside each filtered write, never left to a TTL index.
204///
205/// # Example
206///
207/// ```rust,no_run
208/// use std::time::Duration;
209/// use adk_core::LeaseStore;
210/// use adk_session::MongoLeaseStore;
211///
212/// # async fn demo() -> adk_core::Result<()> {
213/// let store = MongoLeaseStore::new("mongodb://localhost:27017", "adk").await?;
214/// store.migrate().await?;
215/// let lease = store.acquire("scheduler", "worker-1", Duration::from_secs(30)).await?;
216/// # let _ = lease;
217/// # Ok(())
218/// # }
219/// ```
220#[derive(Debug, Clone)]
221pub struct MongoLeaseStore {
222    db: Database,
223    clock: Arc<dyn Clock>,
224}
225
226impl MongoLeaseStore {
227    /// Connects to `connection_string` and uses `database_name`.
228    ///
229    /// # Errors
230    ///
231    /// Returns `session.lease_store.storage` when the connection string is invalid.
232    pub async fn new(connection_string: &str, database_name: &str) -> Result<Self> {
233        Ok(Self::from_database(open(connection_string, database_name, LEASE_STORAGE).await?))
234    }
235
236    /// Uses an existing database handle, such as one shared with other stores.
237    pub fn from_database(db: Database) -> Self {
238        Self { db, clock: Arc::new(SystemClock) }
239    }
240
241    /// Sets the clock that decides expiry.
242    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
243        self.clock = clock;
244        self
245    }
246
247    /// Checks that the server is reachable. Leases need no index beyond `_id`.
248    ///
249    /// # Errors
250    ///
251    /// Returns `session.lease_store.storage` when the server cannot be reached.
252    pub async fn migrate(&self) -> Result<()> {
253        ping(&self.db, LEASE_STORAGE).await
254    }
255
256    fn collection(&self) -> Collection<Document> {
257        self.db.collection(LEASES)
258    }
259}
260
261fn lease_from(resource: &str, document: &Document) -> Result<Lease> {
262    let epoch = field_i64(document, "epoch", LEASE_STORAGE)?;
263    Ok(Lease {
264        resource: resource.to_string(),
265        owner: field_str(document, "owner", LEASE_STORAGE)?.to_string(),
266        epoch: u64::try_from(epoch).map_err(|_| {
267            storage_error(LEASE_STORAGE, format!("stored epoch {epoch} is negative"))
268        })?,
269        expires_at: from_micros(field_i64(document, "expires_us", LEASE_STORAGE)?, LEASE_STORAGE)?,
270    })
271}
272
273#[async_trait]
274impl LeaseStore for MongoLeaseStore {
275    async fn acquire(&self, resource: &str, owner: &str, ttl: Duration) -> Result<Option<Lease>> {
276        let now = stored_now(self.clock.now());
277        let expires_at = deadline(now, ttl, "lease.invalid_ttl")?;
278        let result = self
279            .collection()
280            .find_one_and_update(
281                doc! {
282                    "_id": resource,
283                    "$or": [
284                        { "released": true },
285                        { "expires_us": { "$lte": micros(now) } },
286                        { "owner": owner },
287                    ],
288                },
289                doc! {
290                    "$inc": { "epoch": 1_i64 },
291                    "$set": { "owner": owner, "expires_us": micros(expires_at), "released": false },
292                },
293            )
294            .upsert(true)
295            .return_document(ReturnDocument::After)
296            .await;
297        match result {
298            Ok(Some(document)) => lease_from(resource, &document).map(Some),
299            Ok(None) => Ok(None),
300            // The resource exists and another owner holds it, so the upsert's insert collided.
301            Err(error) if is_duplicate_key(&error) => Ok(None),
302            Err(error) => {
303                Err(storage_error(LEASE_STORAGE, format!("lease acquire failed: {error}")))
304            }
305        }
306    }
307
308    async fn renew(&self, lease: &Lease, ttl: Duration) -> Result<Lease> {
309        let expires_at = deadline(stored_now(self.clock.now()), ttl, "lease.invalid_ttl")?;
310        let renewed = self
311            .collection()
312            .find_one_and_update(
313                doc! {
314                    "_id": &lease.resource,
315                    "epoch": to_i64(lease.epoch, LEASE_STORAGE)?,
316                    "owner": &lease.owner,
317                    "released": false,
318                },
319                doc! { "$set": { "expires_us": micros(expires_at) } },
320            )
321            .return_document(ReturnDocument::After)
322            .await
323            .map_err(|e| storage_error(LEASE_STORAGE, format!("lease renew failed: {e}")))?;
324        match renewed {
325            Some(document) => lease_from(&lease.resource, &document),
326            None => Err(lease_stale_epoch_error(&lease.resource, lease.epoch)),
327        }
328    }
329
330    async fn release(&self, lease: &Lease) -> Result<()> {
331        let Ok(epoch) = i64::try_from(lease.epoch) else {
332            return Ok(());
333        };
334        self.collection()
335            .update_one(
336                doc! { "_id": &lease.resource, "epoch": epoch, "owner": &lease.owner },
337                doc! { "$set": { "released": true } },
338            )
339            .await
340            .map_err(|e| storage_error(LEASE_STORAGE, format!("lease release failed: {e}")))?;
341        Ok(())
342    }
343
344    async fn current(&self, resource: &str) -> Result<Option<Lease>> {
345        let now = stored_now(self.clock.now());
346        let Some(document) = self
347            .collection()
348            .find_one(doc! { "_id": resource })
349            .await
350            .map_err(|e| storage_error(LEASE_STORAGE, format!("lease read failed: {e}")))?
351        else {
352            return Ok(None);
353        };
354        if document.get_bool("released").unwrap_or(false) {
355            return Ok(None);
356        }
357        let lease = lease_from(resource, &document)?;
358        Ok((lease.expires_at > now).then_some(lease))
359    }
360}
361
362// ---------------------------------------------------------------------------
363// Runs
364// ---------------------------------------------------------------------------
365
366/// MongoDB-backed [`DurableRunStore`].
367///
368/// See the [module documentation](self) for the collections and how each guarantee is
369/// kept without transactions. Claims return the oldest claimable run by enqueue order.
370///
371/// # Example
372///
373/// ```rust,no_run
374/// use std::time::Duration;
375/// use adk_core::{DurableRunStore, NewRun};
376/// use adk_session::MongoRunStore;
377///
378/// # async fn demo() -> adk_core::Result<()> {
379/// let store = MongoRunStore::new("mongodb://localhost:27017", "adk").await?;
380/// store.migrate().await?;
381/// store.enqueue(NewRun::new("default", "app", "user", "agent", serde_json::json!({}))).await?;
382/// let claimed = store.claim("default", "worker-1", Duration::from_secs(30)).await?;
383/// # let _ = claimed;
384/// # Ok(())
385/// # }
386/// ```
387#[derive(Debug, Clone)]
388pub struct MongoRunStore {
389    db: Database,
390    clock: Arc<dyn Clock>,
391    /// Set by `with_transactions`; otherwise detected from the server's `hello` reply.
392    transactions: Option<bool>,
393    detected: Arc<tokio::sync::OnceCell<bool>>,
394}
395
396/// Why a transactional enqueue attempt stopped.
397enum TxFailure {
398    Mongo(mongodb::error::Error),
399    Store(adk_core::AdkError),
400    /// A document changed under the attempt; the transaction is retried.
401    Retry,
402}
403
404impl From<mongodb::error::Error> for TxFailure {
405    fn from(error: mongodb::error::Error) -> Self {
406        Self::Mongo(error)
407    }
408}
409
410impl From<adk_core::AdkError> for TxFailure {
411    fn from(error: adk_core::AdkError) -> Self {
412        Self::Store(error)
413    }
414}
415
416fn run_document(record: &RunRecord, seq: i64) -> Result<Document> {
417    let terminal = record.state.is_terminal();
418    let mut document = doc! {
419        "_id": &record.run_id,
420        "record": encode(record, RUN_STORAGE)?,
421        "queue": &record.queue,
422        "seq": seq,
423        "state": state_name(record.state),
424        "ready_us": if terminal { Bson::Null } else { Bson::Int64(ready_micros(record)) },
425        "finished_us": if terminal { Bson::Int64(micros(record.updated_at)) } else { Bson::Null },
426        "concurrency_key": optional(record.concurrency_key.as_deref()),
427        "app_name": &record.app_name,
428        "user_id": &record.user_id,
429        "session_id": optional(record.session_id.as_deref()),
430        "revision": to_i64(record.revision, RUN_STORAGE)?,
431    };
432    // Absent rather than null, so the partial unique index skips runs without a key.
433    if let Some(key) = &record.idempotency_key {
434        document.insert("idempotency_key", key.as_str());
435    }
436    Ok(document)
437}
438
439fn parse_run(document: &Document) -> Result<(RunRecord, i64)> {
440    Ok((decode(document, "record", RUN_STORAGE)?, field_i64(document, "seq", RUN_STORAGE)?))
441}
442
443/// The `_id` of a concurrency key's gate document.
444fn gate_id(queue: &str, key: &str) -> String {
445    format!("{}:{}", hex(queue), hex(key))
446}
447
448fn string_array(document: &Document, field: &str) -> Option<Vec<String>> {
449    document.get_array(field).ok().map(|values| {
450        values.iter().filter_map(|value| value.as_str().map(str::to_string)).collect()
451    })
452}
453
454fn storage(error: impl std::fmt::Display) -> adk_core::AdkError {
455    storage_error(RUN_STORAGE, error)
456}
457
458impl MongoRunStore {
459    /// Connects to `connection_string` and uses `database_name`.
460    ///
461    /// # Errors
462    ///
463    /// Returns `session.run_store.storage` when the connection string is invalid.
464    pub async fn new(connection_string: &str, database_name: &str) -> Result<Self> {
465        Ok(Self::from_database(open(connection_string, database_name, RUN_STORAGE).await?))
466    }
467
468    /// Uses an existing database handle, such as one shared with other stores.
469    pub fn from_database(db: Database) -> Self {
470        Self {
471            db,
472            clock: Arc::new(SystemClock),
473            transactions: None,
474            detected: Arc::new(tokio::sync::OnceCell::new()),
475        }
476    }
477
478    /// Sets the clock that decides delays, waits, and lease expiry.
479    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
480        self.clock = clock;
481        self
482    }
483
484    /// Forces the enqueue path: `true` runs every enqueue in a multi-document
485    /// transaction (needs a replica set or a sharded cluster), `false` uses the
486    /// single-document fallback. Without it the store asks the server with `hello`.
487    pub fn with_transactions(mut self, enabled: bool) -> Self {
488        self.transactions = Some(enabled);
489        self
490    }
491
492    /// Whether enqueues run in a multi-document transaction: the
493    /// [`with_transactions`](Self::with_transactions) setting, or detected once from
494    /// `hello` — a replica set member (`setName`) or a `mongos` router supports
495    /// transactions, a standalone server does not.
496    ///
497    /// # Example
498    ///
499    /// ```rust,no_run
500    /// use adk_session::MongoRunStore;
501    ///
502    /// # async fn demo() -> adk_core::Result<()> {
503    /// let store = MongoRunStore::new("mongodb://localhost:27017/?replicaSet=rs0", "adk").await?;
504    /// assert!(store.supports_transactions().await?);
505    /// # Ok(())
506    /// # }
507    /// ```
508    ///
509    /// # Errors
510    ///
511    /// Returns `session.run_store.storage` when the server cannot be asked.
512    pub async fn supports_transactions(&self) -> Result<bool> {
513        if let Some(enabled) = self.transactions {
514            return Ok(enabled);
515        }
516        self.detected
517            .get_or_try_init(|| async {
518                let hello = self
519                    .db
520                    .run_command(doc! { "hello": 1 })
521                    .await
522                    .map_err(|e| storage(format!("mongodb hello failed: {e}")))?;
523                Ok(crate::mongodb::hello_supports_transactions(&hello))
524            })
525            .await
526            .copied()
527    }
528
529    /// Creates the unique idempotency index and the indexes claims, listings, and
530    /// pruning read through, and detects whether the server supports transactions.
531    ///
532    /// # Errors
533    ///
534    /// Returns `session.run_store.storage` when an index cannot be created.
535    pub async fn migrate(&self) -> Result<()> {
536        let runs = self.runs();
537        create_index(
538            &runs,
539            doc! { "queue": 1, "idempotency_key": 1 },
540            IndexOptions::builder()
541                .name("adk_runs_idempotency".to_string())
542                .unique(true)
543                .partial_filter_expression(doc! { "idempotency_key": { "$type": "string" } })
544                .build(),
545            RUN_STORAGE,
546        )
547        .await?;
548        create_index(
549            &runs,
550            doc! { "queue": 1, "seq": 1 },
551            named("adk_runs_queue_seq"),
552            RUN_STORAGE,
553        )
554        .await?;
555        create_index(
556            &runs,
557            doc! { "queue": 1, "ready_us": 1 },
558            named("adk_runs_queue_ready"),
559            RUN_STORAGE,
560        )
561        .await?;
562        create_index(&runs, doc! { "finished_us": 1 }, named("adk_runs_finished"), RUN_STORAGE)
563            .await?;
564        self.supports_transactions().await.map(drop)
565    }
566
567    fn runs(&self) -> Collection<Document> {
568        self.db.collection(RUNS)
569    }
570
571    fn gates(&self) -> Collection<Document> {
572        self.db.collection(RUN_KEYS)
573    }
574
575    fn now(&self) -> DateTime<Utc> {
576        stored_now(self.clock.now())
577    }
578
579    async fn next_seq(&self) -> Result<i64> {
580        for _ in 0..2 {
581            let result = self
582                .db
583                .collection::<Document>(RUN_COUNTERS)
584                .find_one_and_update(doc! { "_id": "seq" }, doc! { "$inc": { "seq": 1_i64 } })
585                .upsert(true)
586                .return_document(ReturnDocument::After)
587                .await;
588            match result {
589                Ok(Some(document)) => return field_i64(&document, "seq", RUN_STORAGE),
590                Ok(None) => {}
591                // Two first enqueues raced to create the counter; the retry increments it.
592                Err(error) if is_duplicate_key(&error) => {}
593                Err(error) => return Err(storage(format!("run counter update failed: {error}"))),
594            }
595        }
596        Err(storage("run counter could not be created"))
597    }
598
599    async fn read(&self, run_id: &str) -> Result<Option<(RunRecord, i64)>> {
600        self.runs()
601            .find_one(doc! { "_id": run_id })
602            .await
603            .map_err(|e| storage(format!("run read failed: {e}")))?
604            .as_ref()
605            .map(parse_run)
606            .transpose()
607    }
608
609    /// Replaces the run when its stored revision is still `expected`.
610    async fn swap(&self, record: &RunRecord, seq: i64, expected: u64) -> Result<bool> {
611        let replaced = self
612            .runs()
613            .replace_one(
614                doc! { "_id": &record.run_id, "revision": to_i64(expected, RUN_STORAGE)? },
615                run_document(record, seq)?,
616            )
617            .await
618            .map_err(|e| storage(format!("run write failed: {e}")))?;
619        Ok(replaced.matched_count == 1)
620    }
621
622    /// Reads the run, lets `change` decide, and writes the result under a revision
623    /// compare-and-swap, re-reading when another write landed first. `change` returns
624    /// whether it modified the record.
625    async fn modify(
626        &self,
627        run_id: &str,
628        mut change: impl FnMut(&mut RunRecord) -> Result<bool> + Send,
629    ) -> Result<RunRecord> {
630        for _ in 0..MAX_CAS_ATTEMPTS {
631            let Some((mut record, seq)) = self.read(run_id).await? else {
632                return Err(run_not_found_error(run_id));
633            };
634            let expected = record.revision;
635            if !change(&mut record)? {
636                return Ok(record);
637            }
638            if self.swap(&record, seq, expected).await? {
639                if record.state.is_terminal() {
640                    self.leave_key(&record).await?;
641                }
642                return Ok(record);
643            }
644        }
645        Err(storage(format!(
646            "run '{run_id}' lost {MAX_CAS_ATTEMPTS} compare-and-swap attempts to concurrent writes"
647        )))
648    }
649
650    /// Removes a finished run from its concurrency key's holders.
651    async fn leave_key(&self, record: &RunRecord) -> Result<()> {
652        if let Some(key) = &record.concurrency_key {
653            self.gates()
654                .update_one(
655                    doc! { "_id": gate_id(&record.queue, key) },
656                    doc! { "$pull": { "holders": &record.run_id } },
657                )
658                .await
659                .map_err(|e| storage(format!("concurrency key update failed: {e}")))?;
660        }
661        Ok(())
662    }
663
664    /// Cancels one run as part of an `Interrupt`; a run already gone is skipped.
665    async fn cancel_holder(&self, run_id: &str, now: DateTime<Utc>) -> Result<()> {
666        match self.modify(run_id, |record| Ok(apply_cancel(record, now))).await {
667            Err(error) if error.is_not_found() => Ok(()),
668            other => other.map(|_| ()),
669        }
670    }
671
672    /// Applies any pending `Interrupt`, drops finished runs from the head of the key's
673    /// holders, and returns the stored holders.
674    async fn settle_key(&self, queue: &str, key: &str) -> Result<Vec<String>> {
675        let id = gate_id(queue, key);
676        for _ in 0..MAX_CAS_ATTEMPTS {
677            let Some(gate) = self
678                .gates()
679                .find_one(doc! { "_id": &id })
680                .await
681                .map_err(|e| storage(format!("concurrency key read failed: {e}")))?
682            else {
683                return Ok(Vec::new());
684            };
685            if let Some(pending) = string_array(&gate, "pending_cancel") {
686                let now = self.now();
687                for run_id in &pending {
688                    self.cancel_holder(run_id, now).await?;
689                }
690                self.gates()
691                    .update_one(
692                        doc! { "_id": &id, "pending_cancel": &pending },
693                        doc! { "$unset": { "pending_cancel": "" } },
694                    )
695                    .await
696                    .map_err(|e| storage(format!("concurrency key update failed: {e}")))?;
697                continue;
698            }
699            let mut holders = string_array(&gate, "holders").unwrap_or_default();
700            while let Some(head) = holders.first().cloned() {
701                let finished = match self.read(&head).await? {
702                    Some((record, _)) => record.state.is_terminal(),
703                    // Pruned, so it finished.
704                    None => true,
705                };
706                if !finished {
707                    break;
708                }
709                self.gates()
710                    .update_one(doc! { "_id": &id }, doc! { "$pull": { "holders": &head } })
711                    .await
712                    .map_err(|e| storage(format!("concurrency key update failed: {e}")))?;
713                holders.remove(0);
714            }
715            return Ok(holders);
716        }
717        Err(storage(format!(
718            "concurrency key '{key}' kept changing under {MAX_CAS_ATTEMPTS} reads"
719        )))
720    }
721
722    /// Appends `run_id` to its key's holders unless it is there already.
723    async fn admit(&self, queue: &str, key: &str, run_id: &str) -> Result<()> {
724        match self
725            .gates()
726            .update_one(
727                doc! { "_id": gate_id(queue, key), "holders": { "$ne": run_id } },
728                doc! { "$push": { "holders": run_id } },
729            )
730            .upsert(true)
731            .await
732        {
733            Ok(_) => Ok(()),
734            // The gate exists and already lists the run.
735            Err(error) if is_duplicate_key(&error) => Ok(()),
736            Err(error) => Err(storage(format!("concurrency key update failed: {error}"))),
737        }
738    }
739
740    /// Admits `run_id` only while the key has no unfinished holder; returns whether it did.
741    async fn admit_if_free(&self, queue: &str, key: &str, run_id: &str) -> Result<bool> {
742        let result = self
743            .gates()
744            .update_one(
745                doc! {
746                    "_id": gate_id(queue, key),
747                    "holders": { "$size": 0 },
748                    "pending_cancel": { "$exists": false },
749                },
750                doc! { "$push": { "holders": run_id } },
751            )
752            .upsert(true)
753            .await;
754        match result {
755            Ok(result) => Ok(result.matched_count == 1 || result.upserted_id.is_some()),
756            Err(error) if is_duplicate_key(&error) => Ok(false),
757            Err(error) => Err(storage(format!("concurrency key update failed: {error}"))),
758        }
759    }
760
761    /// Admits `run_id` behind the key's current holders and cancels them.
762    async fn admit_interrupting(&self, queue: &str, key: &str, run_id: &str) -> Result<()> {
763        for _ in 0..MAX_CAS_ATTEMPTS {
764            let holders = self.settle_key(queue, key).await?;
765            if holders.is_empty() {
766                if self.admit_if_free(queue, key, run_id).await? {
767                    return Ok(());
768                }
769                continue;
770            }
771            let mut next = holders.clone();
772            next.push(run_id.to_string());
773            let id = gate_id(queue, key);
774            let swapped = self
775                .gates()
776                .update_one(
777                    doc! {
778                        "_id": &id,
779                        "holders": &holders,
780                        "pending_cancel": { "$exists": false },
781                    },
782                    doc! { "$set": { "holders": &next, "pending_cancel": &holders } },
783                )
784                .await
785                .map_err(|e| storage(format!("concurrency key update failed: {e}")))?;
786            if swapped.matched_count == 1 {
787                let now = self.now();
788                for holder in &holders {
789                    self.cancel_holder(holder, now).await?;
790                }
791                self.gates()
792                    .update_one(
793                        doc! { "_id": &id, "pending_cancel": &holders },
794                        doc! { "$unset": { "pending_cancel": "" } },
795                    )
796                    .await
797                    .map_err(|e| storage(format!("concurrency key update failed: {e}")))?;
798                return Ok(());
799            }
800        }
801        Err(storage(format!(
802            "concurrency key '{key}' kept changing under {MAX_CAS_ATTEMPTS} swaps"
803        )))
804    }
805
806    /// Whether a queued keyed run is first among its key's unfinished holders.
807    async fn heads_its_key(
808        &self,
809        record: &RunRecord,
810        key: &str,
811        now: DateTime<Utc>,
812    ) -> Result<bool> {
813        let holders = self.settle_key(&record.queue, key).await?;
814        if holders.first() == Some(&record.run_id) {
815            return Ok(true);
816        }
817        if !holders.contains(&record.run_id) && record.created_at + ADMIT_GRACE <= now {
818            // Its enqueue stopped before admitting it.
819            self.admit(&record.queue, key, &record.run_id).await?;
820            let holders = self.settle_key(&record.queue, key).await?;
821            return Ok(holders.first() == Some(&record.run_id));
822        }
823        Ok(false)
824    }
825
826    async fn find_existing(&self, queue: &str, key: &str) -> Result<Option<RunRecord>> {
827        self.runs()
828            .find_one(doc! { "queue": queue, "idempotency_key": key })
829            .await
830            .map_err(|e| storage(format!("run read failed: {e}")))?
831            .as_ref()
832            .map(|document| parse_run(document).map(|(record, _)| record))
833            .transpose()
834    }
835
836    /// Enqueues in one multi-document transaction: the idempotency check, the key
837    /// holders' policy, the insert, and the run's admission to its key commit together,
838    /// so no caller sees a run that is later withdrawn and a key never admits a second
839    /// run under `Reject`.
840    async fn enqueue_in_transaction(&self, run: NewRun, now: DateTime<Utc>) -> Result<Enqueued> {
841        let record = RunRecord::queued(uuid::Uuid::new_v4().to_string(), run, now);
842        // Ordering only: taken outside the transaction so enqueues do not all conflict on
843        // the counter document.
844        let seq = self.next_seq().await?;
845        let mut session = self
846            .db
847            .client()
848            .start_session()
849            .await
850            .map_err(|e| storage(format!("mongodb session failed: {e}")))?;
851        for attempt in 0..MAX_CAS_ATTEMPTS {
852            if attempt > 0 {
853                tokio::time::sleep(crate::mongodb_stores::claim_backoff(attempt)).await;
854            }
855            session
856                .start_transaction()
857                .await
858                .map_err(|e| storage(format!("mongodb transaction failed: {e}")))?;
859            let (enqueued, writes) = match self.enqueue_body(&mut session, &record, seq, now).await
860            {
861                Ok(outcome) => outcome,
862                Err(failure) => {
863                    let _ = session.abort_transaction().await;
864                    match failure {
865                        TxFailure::Retry => continue,
866                        TxFailure::Store(error) => return Err(error),
867                        // A concurrent enqueue of the same key or holders won; the next
868                        // attempt reads its committed result.
869                        TxFailure::Mongo(error)
870                            if is_duplicate_key(&error)
871                                || error.contains_label(TRANSIENT_TRANSACTION_ERROR) =>
872                        {
873                            continue;
874                        }
875                        TxFailure::Mongo(error) => {
876                            return Err(storage(format!("run enqueue failed: {error}")));
877                        }
878                    }
879                }
880            };
881            if !writes {
882                let _ = session.abort_transaction().await;
883                return Ok(enqueued);
884            }
885            let mut unknown = 0;
886            loop {
887                match session.commit_transaction().await {
888                    Ok(()) => return Ok(enqueued),
889                    Err(error)
890                        if unknown < 3
891                            && error.contains_label(UNKNOWN_TRANSACTION_COMMIT_RESULT) =>
892                    {
893                        unknown += 1;
894                    }
895                    Err(error) if error.contains_label(TRANSIENT_TRANSACTION_ERROR) => break,
896                    Err(error) => {
897                        return Err(storage(format!("run enqueue commit failed: {error}")));
898                    }
899                }
900            }
901        }
902        Err(storage(format!(
903            "enqueue into queue '{}' lost {MAX_CAS_ATTEMPTS} transactions to concurrent writes",
904            record.queue
905        )))
906    }
907
908    /// One transactional enqueue attempt; returns the outcome and whether it wrote.
909    async fn enqueue_body(
910        &self,
911        session: &mut ClientSession,
912        record: &RunRecord,
913        seq: i64,
914        now: DateTime<Utc>,
915    ) -> std::result::Result<(Enqueued, bool), TxFailure> {
916        if let Some(key) = &record.idempotency_key
917            && let Some(existing) = self
918                .runs()
919                .find_one(doc! { "queue": &record.queue, "idempotency_key": key })
920                .session(&mut *session)
921                .await?
922        {
923            return Ok((Enqueued::Existing(parse_run(&existing)?.0), false));
924        }
925        let mut holders: Vec<String> = Vec::new();
926        if let Some(key) = &record.concurrency_key {
927            let gate = self
928                .gates()
929                .find_one(doc! { "_id": gate_id(&record.queue, key) })
930                .session(&mut *session)
931                .await?;
932            let listed = gate.as_ref().and_then(|gate| string_array(gate, "holders"));
933            // Runs a fallback-path `Interrupt` left to cancel are cancelled here too.
934            let pending = gate.as_ref().and_then(|gate| string_array(gate, "pending_cancel"));
935            let interrupt = record.on_conflict == OnConflict::Interrupt;
936            for run_id in listed.unwrap_or_default() {
937                let Some(document) =
938                    self.runs().find_one(doc! { "_id": &run_id }).session(&mut *session).await?
939                else {
940                    continue;
941                };
942                let (mut holder, holder_seq) = parse_run(&document)?;
943                if holder.state.is_terminal() {
944                    continue;
945                }
946                if record.on_conflict == OnConflict::Reject {
947                    return Ok((Enqueued::Rejected { blocking_run_id: run_id }, false));
948                }
949                let cancel = interrupt || pending.as_ref().is_some_and(|ids| ids.contains(&run_id));
950                if cancel {
951                    let expected = holder.revision;
952                    if apply_cancel(&mut holder, now) {
953                        let replaced = self
954                            .runs()
955                            .replace_one(
956                                doc! { "_id": &run_id, "revision": to_i64(expected, RUN_STORAGE)? },
957                                run_document(&holder, holder_seq)?,
958                            )
959                            .session(&mut *session)
960                            .await?;
961                        if replaced.matched_count == 0 {
962                            return Err(TxFailure::Retry);
963                        }
964                    }
965                    if holder.state.is_terminal() {
966                        continue;
967                    }
968                }
969                holders.push(run_id);
970            }
971        }
972        self.runs().insert_one(run_document(record, seq)?).session(&mut *session).await?;
973        if let Some(key) = &record.concurrency_key {
974            holders.push(record.run_id.clone());
975            self.gates()
976                .update_one(
977                    doc! { "_id": gate_id(&record.queue, key) },
978                    doc! { "$set": { "holders": holders }, "$unset": { "pending_cancel": "" } },
979                )
980                .upsert(true)
981                .session(&mut *session)
982                .await?;
983        }
984        Ok((Enqueued::Created(record.clone()), true))
985    }
986
987    /// Tries to claim one candidate; returns the claim, or `None` to move on.
988    async fn try_claim(
989        &self,
990        mut record: RunRecord,
991        mut seq: i64,
992        worker: &str,
993        now: DateTime<Utc>,
994        expires_at: DateTime<Utc>,
995    ) -> Result<Option<ClaimedRun>> {
996        // One re-read covers a write that landed between the query and the swap.
997        for _ in 0..2 {
998            let expected = record.revision;
999            match claim_step(&record, now) {
1000                ClaimStep::NotReady => return Ok(None),
1001                ClaimStep::Exhaust => {
1002                    apply_exhaust(&mut record, now);
1003                    if self.swap(&record, seq, expected).await? {
1004                        self.leave_key(&record).await?;
1005                        return Ok(None);
1006                    }
1007                }
1008                ClaimStep::Claim { started } => {
1009                    if record.state == RunState::Queued
1010                        && let Some(key) = record.concurrency_key.clone()
1011                        && !self.heads_its_key(&record, &key, now).await?
1012                    {
1013                        return Ok(None);
1014                    }
1015                    let epoch = apply_claim(&mut record, started, worker, now, expires_at);
1016                    if self.swap(&record, seq, expected).await? {
1017                        return Ok(Some(ClaimedRun { record, epoch }));
1018                    }
1019                }
1020            }
1021            match self.read(&record.run_id).await? {
1022                Some((fresh, fresh_seq)) => (record, seq) = (fresh, fresh_seq),
1023                None => return Ok(None),
1024            }
1025        }
1026        Ok(None)
1027    }
1028}
1029
1030#[async_trait]
1031impl DurableRunStore for MongoRunStore {
1032    async fn enqueue(&self, run: NewRun) -> Result<Enqueued> {
1033        run.validate()?;
1034        let now = self.now();
1035        if self.supports_transactions().await? {
1036            return self.enqueue_in_transaction(run, now).await;
1037        }
1038        if let Some(key) = &run.idempotency_key
1039            && let Some(existing) = self.find_existing(&run.queue, key).await?
1040        {
1041            return Ok(Enqueued::Existing(existing));
1042        }
1043        if let (Some(key), OnConflict::Reject) = (&run.concurrency_key, run.on_conflict)
1044            && let Some(blocking_run_id) = self.settle_key(&run.queue, key).await?.first()
1045        {
1046            return Ok(Enqueued::Rejected { blocking_run_id: blocking_run_id.clone() });
1047        }
1048
1049        let run_id = uuid::Uuid::new_v4().to_string();
1050        let seq = self.next_seq().await?;
1051        let record = RunRecord::queued(run_id.clone(), run, now);
1052        match self.runs().insert_one(run_document(&record, seq)?).await {
1053            Ok(_) => {}
1054            Err(error) if is_duplicate_key(&error) => {
1055                let key = record.idempotency_key.as_deref().unwrap_or_default();
1056                return match self.find_existing(&record.queue, key).await? {
1057                    Some(existing) => Ok(Enqueued::Existing(existing)),
1058                    None => Err(storage(format!(
1059                        "run with idempotency key '{key}' was pruned during enqueue; retry"
1060                    ))),
1061                };
1062            }
1063            Err(error) => return Err(storage(format!("run insert failed: {error}"))),
1064        }
1065
1066        let Some(key) = record.concurrency_key.clone() else {
1067            return Ok(Enqueued::Created(record));
1068        };
1069        match record.on_conflict {
1070            OnConflict::Reject => {
1071                for _ in 0..8 {
1072                    if self.admit_if_free(&record.queue, &key, &run_id).await? {
1073                        return Ok(Enqueued::Created(record));
1074                    }
1075                    if let Some(blocking_run_id) =
1076                        self.settle_key(&record.queue, &key).await?.first().cloned()
1077                    {
1078                        self.runs()
1079                            .delete_one(doc! { "_id": &run_id })
1080                            .await
1081                            .map_err(|e| storage(format!("run delete failed: {e}")))?;
1082                        return Ok(Enqueued::Rejected { blocking_run_id });
1083                    }
1084                }
1085                Err(storage(format!("concurrency key '{key}' kept changing during enqueue")))
1086            }
1087            OnConflict::Interrupt => {
1088                self.admit_interrupting(&record.queue, &key, &run_id).await?;
1089                Ok(Enqueued::Created(record))
1090            }
1091            _ => {
1092                self.admit(&record.queue, &key, &run_id).await?;
1093                Ok(Enqueued::Created(record))
1094            }
1095        }
1096    }
1097
1098    async fn claim(&self, queue: &str, worker: &str, ttl: Duration) -> Result<Option<ClaimedRun>> {
1099        let now = self.now();
1100        let expires_at = deadline(now, ttl, "run_store.invalid_ttl")?;
1101        let mut after = i64::MIN;
1102        loop {
1103            let page = collect(
1104                self.runs()
1105                    .find(doc! {
1106                        "queue": queue,
1107                        "ready_us": { "$lte": micros(now) },
1108                        "seq": { "$gt": after },
1109                    })
1110                    .sort(doc! { "seq": 1 })
1111                    .limit(CLAIM_PAGE)
1112                    .await
1113                    .map_err(|e| storage(format!("run query failed: {e}")))?,
1114                RUN_STORAGE,
1115            )
1116            .await?;
1117            if page.is_empty() {
1118                return Ok(None);
1119            }
1120            for document in &page {
1121                let (record, seq) = parse_run(document)?;
1122                after = seq;
1123                if let Some(claimed) = self.try_claim(record, seq, worker, now, expires_at).await? {
1124                    return Ok(Some(claimed));
1125                }
1126            }
1127        }
1128    }
1129
1130    async fn heartbeat(&self, run_id: &str, epoch: u64, ttl: Duration) -> Result<bool> {
1131        let now = self.now();
1132        let expires_at = deadline(now, ttl, "run_store.invalid_ttl")?;
1133        let record = self
1134            .modify(run_id, |record| {
1135                check_fence(record, epoch)?;
1136                apply_heartbeat(record, now, expires_at);
1137                Ok(true)
1138            })
1139            .await?;
1140        Ok(record.cancel_requested)
1141    }
1142
1143    async fn set_checkpoint(
1144        &self,
1145        run_id: &str,
1146        epoch: u64,
1147        checkpoint: RunCheckpointRef,
1148    ) -> Result<()> {
1149        let now = self.now();
1150        self.modify(run_id, |record| {
1151            check_fence(record, epoch)?;
1152            apply_checkpoint(record, now, checkpoint.clone());
1153            Ok(true)
1154        })
1155        .await
1156        .map(|_| ())
1157    }
1158
1159    async fn wait(&self, run_id: &str, epoch: u64, until: Option<DateTime<Utc>>) -> Result<()> {
1160        let now = self.now();
1161        self.modify(run_id, |record| {
1162            check_fence(record, epoch)?;
1163            apply_wait(record, now, until);
1164            Ok(true)
1165        })
1166        .await
1167        .map(|_| ())
1168    }
1169
1170    async fn wake(&self, run_id: &str) -> Result<()> {
1171        let now = self.now();
1172        self.modify(run_id, |record| Ok(apply_wake(record, now))).await.map(|_| ())
1173    }
1174
1175    async fn finish(&self, run_id: &str, epoch: u64, outcome: RunOutcome) -> Result<RunRecord> {
1176        let now = self.now();
1177        self.modify(run_id, |record| {
1178            check_fence(record, epoch)?;
1179            apply_finish(record, now, outcome.clone());
1180            Ok(true)
1181        })
1182        .await
1183    }
1184
1185    async fn request_cancel(&self, run_id: &str) -> Result<()> {
1186        let now = self.now();
1187        self.modify(run_id, |record| Ok(apply_cancel(record, now))).await.map(|_| ())
1188    }
1189
1190    async fn get(&self, run_id: &str) -> Result<Option<RunRecord>> {
1191        Ok(self.read(run_id).await?.map(|(record, _)| record))
1192    }
1193
1194    async fn list(&self, filter: RunFilter) -> Result<Vec<RunRecord>> {
1195        let mut query = Document::new();
1196        if let Some(queue) = &filter.queue {
1197            query.insert("queue", queue.as_str());
1198        }
1199        if !filter.states.is_empty() {
1200            let states: Vec<&str> = filter.states.iter().map(|state| state_name(*state)).collect();
1201            query.insert("state", doc! { "$in": states });
1202        }
1203        for (field, value) in [
1204            ("app_name", &filter.app_name),
1205            ("user_id", &filter.user_id),
1206            ("session_id", &filter.session_id),
1207            ("concurrency_key", &filter.concurrency_key),
1208        ] {
1209            if let Some(value) = value {
1210                query.insert(field, value.as_str());
1211            }
1212        }
1213        let limit = match filter.limit {
1214            Some(0) => return Ok(Vec::new()),
1215            Some(limit) => i64::try_from(limit).unwrap_or(i64::MAX),
1216            // A zero limit is unlimited.
1217            None => 0,
1218        };
1219        let runs = self.runs();
1220        let documents = collect(
1221            runs.find(query)
1222                .sort(doc! { "seq": 1 })
1223                .limit(limit)
1224                .await
1225                .map_err(|e| storage(format!("run query failed: {e}")))?,
1226            RUN_STORAGE,
1227        )
1228        .await?;
1229        documents.iter().map(|document| parse_run(document).map(|(record, _)| record)).collect()
1230    }
1231
1232    async fn prune(&self, finished_before: DateTime<Utc>) -> Result<u64> {
1233        let terminal = [RunState::Completed, RunState::Failed, RunState::Cancelled].map(state_name);
1234        let deleted = self
1235            .runs()
1236            .delete_many(doc! {
1237                "state": { "$in": terminal.to_vec() },
1238                "finished_us": { "$lt": ceil_micros(finished_before) },
1239            })
1240            .await
1241            .map_err(|e| storage(format!("run prune failed: {e}")))?;
1242        Ok(deleted.deleted_count)
1243    }
1244}
1245
1246// ---------------------------------------------------------------------------
1247// Schedules
1248// ---------------------------------------------------------------------------
1249
1250/// MongoDB-backed [`ScheduleStore`].
1251///
1252/// One `adk_schedules` document per schedule; `due` reads an index on `due_us`, the next
1253/// fire time of an unpaused schedule.
1254///
1255/// # Example
1256///
1257/// ```rust,no_run
1258/// use adk_core::ScheduleStore;
1259/// use adk_session::MongoScheduleStore;
1260///
1261/// # async fn demo() -> adk_core::Result<()> {
1262/// let store = MongoScheduleStore::new("mongodb://localhost:27017", "adk").await?;
1263/// store.migrate().await?;
1264/// let due = store.due(chrono::Utc::now(), 100).await?;
1265/// # let _ = due;
1266/// # Ok(())
1267/// # }
1268/// ```
1269#[derive(Debug, Clone)]
1270pub struct MongoScheduleStore {
1271    db: Database,
1272}
1273
1274fn schedule_document(schedule: &Schedule) -> Result<Document> {
1275    let due = match (schedule.paused, schedule.next_fire_at) {
1276        (false, Some(at)) => Bson::Int64(micros(at)),
1277        _ => Bson::Null,
1278    };
1279    Ok(doc! {
1280        "_id": &schedule.id,
1281        "schedule": encode(schedule, SCHEDULE_STORAGE)?,
1282        "paused": schedule.paused,
1283        "due_us": due,
1284        "revision": to_i64(schedule.revision, SCHEDULE_STORAGE)?,
1285    })
1286}
1287
1288impl MongoScheduleStore {
1289    /// Connects to `connection_string` and uses `database_name`.
1290    ///
1291    /// # Errors
1292    ///
1293    /// Returns `session.schedule_store.storage` when the connection string is invalid.
1294    pub async fn new(connection_string: &str, database_name: &str) -> Result<Self> {
1295        Ok(Self::from_database(open(connection_string, database_name, SCHEDULE_STORAGE).await?))
1296    }
1297
1298    /// Uses an existing database handle, such as one shared with other stores.
1299    pub fn from_database(db: Database) -> Self {
1300        Self { db }
1301    }
1302
1303    /// Creates the index `due` reads through.
1304    ///
1305    /// # Errors
1306    ///
1307    /// Returns `session.schedule_store.storage` when the index cannot be created.
1308    pub async fn migrate(&self) -> Result<()> {
1309        create_index(
1310            &self.collection(),
1311            doc! { "due_us": 1, "_id": 1 },
1312            named("adk_schedules_due"),
1313            SCHEDULE_STORAGE,
1314        )
1315        .await
1316    }
1317
1318    fn collection(&self) -> Collection<Document> {
1319        self.db.collection(SCHEDULES)
1320    }
1321
1322    async fn read(&self, id: &str) -> Result<Option<Schedule>> {
1323        self.collection()
1324            .find_one(doc! { "_id": id })
1325            .await
1326            .map_err(|e| storage_error(SCHEDULE_STORAGE, format!("schedule read failed: {e}")))?
1327            .as_ref()
1328            .map(|document| decode(document, "schedule", SCHEDULE_STORAGE))
1329            .transpose()
1330    }
1331
1332    /// Replaces the schedule when its stored revision is still `expected`.
1333    async fn swap(&self, schedule: &Schedule, expected: u64) -> Result<bool> {
1334        let replaced = self
1335            .collection()
1336            .replace_one(
1337                doc! { "_id": &schedule.id, "revision": to_i64(expected, SCHEDULE_STORAGE)? },
1338                schedule_document(schedule)?,
1339            )
1340            .await
1341            .map_err(|e| storage_error(SCHEDULE_STORAGE, format!("schedule write failed: {e}")))?;
1342        Ok(replaced.matched_count == 1)
1343    }
1344
1345    fn contended(id: &str) -> adk_core::AdkError {
1346        storage_error(
1347            SCHEDULE_STORAGE,
1348            format!("schedule '{id}' lost {MAX_CAS_ATTEMPTS} compare-and-swap attempts"),
1349        )
1350    }
1351}
1352
1353#[async_trait]
1354impl ScheduleStore for MongoScheduleStore {
1355    async fn upsert(&self, mut schedule: Schedule) -> Result<Schedule> {
1356        schedule.validate()?;
1357        for _ in 0..MAX_CAS_ATTEMPTS {
1358            match self.read(&schedule.id).await? {
1359                Some(stored) => {
1360                    if same_definition(&stored, &schedule) {
1361                        return Ok(stored);
1362                    }
1363                    schedule.revision = stored.revision + 1;
1364                    if self.swap(&schedule, stored.revision).await? {
1365                        return Ok(schedule);
1366                    }
1367                }
1368                None => {
1369                    schedule.revision = 1;
1370                    match self.collection().insert_one(schedule_document(&schedule)?).await {
1371                        Ok(_) => return Ok(schedule),
1372                        Err(error) if is_duplicate_key(&error) => {}
1373                        Err(error) => {
1374                            return Err(storage_error(
1375                                SCHEDULE_STORAGE,
1376                                format!("schedule insert failed: {error}"),
1377                            ));
1378                        }
1379                    }
1380                }
1381            }
1382        }
1383        Err(Self::contended(&schedule.id))
1384    }
1385
1386    async fn get(&self, id: &str) -> Result<Option<Schedule>> {
1387        self.read(id).await
1388    }
1389
1390    async fn list(&self) -> Result<Vec<Schedule>> {
1391        let documents = collect(
1392            self.collection().find(doc! {}).sort(doc! { "_id": 1 }).await.map_err(|e| {
1393                storage_error(SCHEDULE_STORAGE, format!("schedule query failed: {e}"))
1394            })?,
1395            SCHEDULE_STORAGE,
1396        )
1397        .await?;
1398        documents.iter().map(|document| decode(document, "schedule", SCHEDULE_STORAGE)).collect()
1399    }
1400
1401    async fn delete(&self, id: &str) -> Result<()> {
1402        let deleted =
1403            self.collection().delete_one(doc! { "_id": id }).await.map_err(|e| {
1404                storage_error(SCHEDULE_STORAGE, format!("schedule delete failed: {e}"))
1405            })?;
1406        if deleted.deleted_count == 0 {
1407            return Err(schedule_not_found_error(id));
1408        }
1409        Ok(())
1410    }
1411
1412    async fn set_paused(&self, id: &str, paused: bool) -> Result<Schedule> {
1413        for _ in 0..MAX_CAS_ATTEMPTS {
1414            let Some(stored) = self.read(id).await? else {
1415                return Err(schedule_not_found_error(id));
1416            };
1417            if stored.paused == paused {
1418                return Ok(stored);
1419            }
1420            let changed = Schedule { paused, revision: stored.revision + 1, ..stored.clone() };
1421            if self.swap(&changed, stored.revision).await? {
1422                return Ok(changed);
1423            }
1424        }
1425        Err(Self::contended(id))
1426    }
1427
1428    async fn due(&self, now: DateTime<Utc>, limit: usize) -> Result<Vec<Schedule>> {
1429        if limit == 0 {
1430            return Ok(Vec::new());
1431        }
1432        let documents = collect(
1433            self.collection()
1434                .find(doc! { "due_us": { "$lte": micros(now) } })
1435                .sort(doc! { "due_us": 1, "_id": 1 })
1436                .limit(i64::try_from(limit).unwrap_or(i64::MAX))
1437                .await
1438                .map_err(|e| {
1439                    storage_error(SCHEDULE_STORAGE, format!("schedule query failed: {e}"))
1440                })?,
1441            SCHEDULE_STORAGE,
1442        )
1443        .await?;
1444        documents.iter().map(|document| decode(document, "schedule", SCHEDULE_STORAGE)).collect()
1445    }
1446
1447    async fn advance(
1448        &self,
1449        id: &str,
1450        expected_revision: u64,
1451        next_fire_at: Option<DateTime<Utc>>,
1452    ) -> Result<bool> {
1453        let Some(stored) = self.read(id).await? else {
1454            return Err(schedule_not_found_error(id));
1455        };
1456        if stored.revision != expected_revision {
1457            return Ok(false);
1458        }
1459        let advanced = Schedule { next_fire_at, revision: expected_revision + 1, ..stored };
1460        if self.swap(&advanced, expected_revision).await? {
1461            return Ok(true);
1462        }
1463        match self.read(id).await? {
1464            Some(_) => Ok(false),
1465            None => Err(schedule_not_found_error(id)),
1466        }
1467    }
1468}
1469
1470// ---------------------------------------------------------------------------
1471// Governance state
1472// ---------------------------------------------------------------------------
1473
1474/// MongoDB-backed [`GovernanceStateStore`].
1475///
1476/// One `adk_governance` document per scope, keyed by [`GovernanceScope::key`].
1477///
1478/// # Example
1479///
1480/// ```rust,no_run
1481/// use adk_core::{GovernanceScope, GovernanceStateStore};
1482/// use adk_session::MongoGovernanceStateStore;
1483///
1484/// # async fn demo() -> adk_core::Result<()> {
1485/// let store = MongoGovernanceStateStore::new("mongodb://localhost:27017", "adk").await?;
1486/// store.migrate().await?;
1487/// store.set(GovernanceScope::Org, 0, true, Some("incident 42".into()), None).await?;
1488/// # Ok(())
1489/// # }
1490/// ```
1491#[derive(Debug, Clone)]
1492pub struct MongoGovernanceStateStore {
1493    db: Database,
1494    clock: Arc<dyn Clock>,
1495}
1496
1497impl MongoGovernanceStateStore {
1498    /// Connects to `connection_string` and uses `database_name`.
1499    ///
1500    /// # Errors
1501    ///
1502    /// Returns `session.governance_store.storage` when the connection string is invalid.
1503    pub async fn new(connection_string: &str, database_name: &str) -> Result<Self> {
1504        Ok(Self::from_database(open(connection_string, database_name, GOVERNANCE_STORAGE).await?))
1505    }
1506
1507    /// Uses an existing database handle, such as one shared with other stores.
1508    pub fn from_database(db: Database) -> Self {
1509        Self { db, clock: Arc::new(SystemClock) }
1510    }
1511
1512    /// Sets the clock that stamps `issued_at`.
1513    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
1514        self.clock = clock;
1515        self
1516    }
1517
1518    /// Checks that the server is reachable. States need no index beyond `_id`.
1519    ///
1520    /// # Errors
1521    ///
1522    /// Returns `session.governance_store.storage` when the server cannot be reached.
1523    pub async fn migrate(&self) -> Result<()> {
1524        ping(&self.db, GOVERNANCE_STORAGE).await
1525    }
1526
1527    fn collection(&self) -> Collection<Document> {
1528        self.db.collection(GOVERNANCE)
1529    }
1530
1531    async fn current_epoch(&self, scope: &GovernanceScope) -> Result<u64> {
1532        Ok(self.get(scope).await?.map_or(0, |state| state.epoch))
1533    }
1534}
1535
1536fn governance_failure(error: mongodb::error::Error) -> adk_core::AdkError {
1537    storage_error(GOVERNANCE_STORAGE, format!("governance write failed: {error}"))
1538}
1539
1540#[async_trait]
1541impl GovernanceStateStore for MongoGovernanceStateStore {
1542    async fn get(&self, scope: &GovernanceScope) -> Result<Option<GovernanceState>> {
1543        self.collection()
1544            .find_one(doc! { "_id": scope.key() })
1545            .await
1546            .map_err(|e| storage_error(GOVERNANCE_STORAGE, format!("governance read failed: {e}")))?
1547            .as_ref()
1548            .map(|document| decode(document, "state", GOVERNANCE_STORAGE))
1549            .transpose()
1550    }
1551
1552    async fn set(
1553        &self,
1554        scope: GovernanceScope,
1555        expected_epoch: u64,
1556        frozen: bool,
1557        reason: Option<String>,
1558        issued_by: Option<SubjectRef>,
1559    ) -> Result<GovernanceState> {
1560        let key = scope.key();
1561        let state = GovernanceState {
1562            scope,
1563            frozen,
1564            reason,
1565            issued_by,
1566            issued_at: stored_now(self.clock.now()),
1567            epoch: expected_epoch + 1,
1568        };
1569        let json = encode(&state, GOVERNANCE_STORAGE)?;
1570        let epoch = to_i64(state.epoch, GOVERNANCE_STORAGE)?;
1571        let landed = if expected_epoch == 0 {
1572            match self
1573                .collection()
1574                .insert_one(doc! { "_id": &key, "state": &json, "epoch": epoch })
1575                .await
1576            {
1577                Ok(_) => true,
1578                Err(error) if is_duplicate_key(&error) => false,
1579                Err(error) => return Err(governance_failure(error)),
1580            }
1581        } else {
1582            self.collection()
1583                .update_one(
1584                    doc! { "_id": &key, "epoch": to_i64(expected_epoch, GOVERNANCE_STORAGE)? },
1585                    doc! { "$set": { "state": &json, "epoch": epoch } },
1586                )
1587                .await
1588                .map_err(governance_failure)?
1589                .matched_count
1590                == 1
1591        };
1592        if landed {
1593            return Ok(state);
1594        }
1595        let current = self.current_epoch(&state.scope).await?;
1596        Err(governance_conflict_error(&state.scope, expected_epoch, current))
1597    }
1598
1599    async fn list(&self) -> Result<Vec<GovernanceState>> {
1600        let documents = collect(
1601            self.collection().find(doc! {}).sort(doc! { "_id": 1 }).await.map_err(|e| {
1602                storage_error(GOVERNANCE_STORAGE, format!("governance query failed: {e}"))
1603            })?,
1604            GOVERNANCE_STORAGE,
1605        )
1606        .await?;
1607        documents.iter().map(|document| decode(document, "state", GOVERNANCE_STORAGE)).collect()
1608    }
1609}
1610
1611#[cfg(test)]
1612mod tests {
1613    use super::*;
1614    use chrono::TimeZone;
1615
1616    #[test]
1617    fn prune_cutoffs_round_up_to_whole_microseconds() {
1618        let whole = Utc.timestamp_opt(1_800_000_000, 5_000).single().unwrap();
1619        assert_eq!(ceil_micros(whole), whole.timestamp_micros());
1620        let partial = Utc.timestamp_opt(1_800_000_000, 5_500).single().unwrap();
1621        assert_eq!(ceil_micros(partial), whole.timestamp_micros() + 1);
1622    }
1623
1624    #[test]
1625    fn gate_ids_cannot_collide_across_queue_and_key() {
1626        assert_ne!(gate_id("a:b", "c"), gate_id("a", "b:c"));
1627        assert_eq!(gate_id("q", "k"), "71:6b");
1628    }
1629
1630    #[test]
1631    fn run_documents_round_trip_and_index_their_state() {
1632        let mut record = RunRecord::queued(
1633            "r1",
1634            NewRun::new("q/ü", "app", "user", "agent", serde_json::json!({}))
1635                .with_idempotency_key("k"),
1636            Utc.timestamp_opt(1_800_000_000, 0).single().unwrap(),
1637        );
1638        let queued = run_document(&record, 7).unwrap();
1639        assert_eq!(queued.get_str("state").unwrap(), "queued");
1640        assert_eq!(queued.get_i64("ready_us").unwrap(), i64::MIN);
1641        assert_eq!(queued.get("finished_us"), Some(&Bson::Null));
1642        assert_eq!(parse_run(&queued).unwrap(), (record.clone(), 7));
1643
1644        record.state = RunState::Cancelled;
1645        record.idempotency_key = None;
1646        let finished = run_document(&record, 7).unwrap();
1647        assert_eq!(finished.get("ready_us"), Some(&Bson::Null));
1648        assert_eq!(finished.get_i64("finished_us").unwrap(), micros(record.updated_at));
1649        assert!(!finished.contains_key("idempotency_key"));
1650    }
1651
1652    #[test]
1653    fn paused_schedules_have_no_due_time() {
1654        let at = Utc.timestamp_opt(1_800_000_000, 0).single().unwrap();
1655        let schedule = Schedule::new(
1656            "s",
1657            adk_core::schedule::ScheduleSpec::At(at),
1658            NewRun::new("q", "a", "u", "t", serde_json::Value::Null),
1659            adk_core::schedule::MissedFirePolicy::FireOnce,
1660        )
1661        .with_next_fire_at(at);
1662        assert_eq!(schedule_document(&schedule).unwrap().get_i64("due_us").unwrap(), micros(at));
1663        let paused = schedule_document(&schedule.with_paused(true)).unwrap();
1664        assert_eq!(paused.get("due_us"), Some(&Bson::Null));
1665    }
1666}