Skip to main content

adk_session/
mongodb.rs

1//! MongoDB session service backend.
2//!
3//! Provides [`MongoSessionService`] for session persistence using MongoDB.
4//! Enabled via the `mongodb` feature flag.
5//!
6//! Supports both standalone and replica-set deployments. Transactions are
7//! used automatically when the deployment supports them (replica set / sharded
8//! cluster). On standalone deployments, operations execute sequentially
9//! without transactions — the upsert-based writes are idempotent, so partial
10//! failures leave state recoverable.
11//!
12//! # Example
13//!
14//! ```rust,ignore
15//! let service = MongoSessionService::new("mongodb://localhost:27017", "adk_sessions").await?;
16//! service.migrate().await?;
17//! ```
18
19use crate::history::{
20    HistoryOutcome, ImportSessionRequest, RewriteHistoryRequest, RewrittenHistory, SessionHistory,
21};
22use crate::service::{
23    identity_not_found, session_already_exists, session_id_not_found, session_not_found_for,
24    validate_scope, validate_session_id,
25};
26use crate::{
27    AppendEventRequest, CreateRequest, DeleteRequest, Event, Events, GetRequest, KEY_PREFIX_TEMP,
28    ListRequest, Session, SessionService, State, state_utils,
29};
30use adk_core::identity::AdkIdentity;
31use adk_core::{ErrorCategory, ErrorComponent, Result};
32use async_trait::async_trait;
33use chrono::{DateTime, Utc};
34use mongodb::bson::{self, Document, doc};
35use mongodb::options::{FindOptions, IndexOptions, ReturnDocument, UpdateOptions};
36use mongodb::{Client, Database, IndexModel};
37use serde_json::Value;
38use std::collections::HashMap;
39use tracing::instrument;
40use uuid::Uuid;
41
42/// Whether the deployment that sent `reply` to `hello` runs multi-document transactions.
43///
44/// A replica set member names its set (`setName`), and the `mongos` router of a sharded
45/// cluster answers `msg: "isdbgrid"`; a standalone `mongod` does neither.
46pub(crate) fn hello_supports_transactions(reply: &Document) -> bool {
47    reply.contains_key("setName") || reply.get_str("msg") == Ok("isdbgrid")
48}
49
50/// MongoDB-backed session service implementing [`SessionService`].
51///
52/// Uses four collections for the three-tier state model:
53/// - `sessions` — session documents with session-level state
54/// - `events` — event documents linked by `session_id`
55/// - `app_states` — application-level state keyed by `app_name`
56/// - `user_states` — user-level state keyed by `(app_name, user_id)`
57///
58/// Automatically detects whether the MongoDB deployment supports transactions
59/// (replica set or sharded cluster) and falls back to non-transactional
60/// sequential writes on standalone deployments.
61pub struct MongoSessionService {
62    db: Database,
63    supports_transactions: bool,
64}
65
66impl MongoSessionService {
67    /// Connect to MongoDB using a connection string and database name.
68    ///
69    /// Automatically detects whether the deployment supports transactions from the
70    /// `hello` command: a replica set member and a sharded cluster's `mongos` router do,
71    /// a standalone server does not. A failed `hello` is treated as standalone.
72    pub async fn new(connection_string: &str, database_name: &str) -> Result<Self> {
73        let client_options = mongodb::options::ClientOptions::parse(connection_string)
74            .await
75            .map_err(|e| adk_core::AdkError::session(format!("mongodb connection failed: {e}")))?;
76        let client = Client::with_options(client_options)
77            .map_err(|e| adk_core::AdkError::session(format!("mongodb connection failed: {e}")))?;
78        let db = client.database(database_name);
79
80        let supports_transactions = match db.run_command(doc! { "hello": 1 }).await {
81            Ok(reply) => hello_supports_transactions(&reply),
82            Err(error) => {
83                tracing::warn!(error = %error, "mongodb hello failed; writing without transactions");
84                false
85            }
86        };
87
88        if supports_transactions {
89            tracing::info!("mongodb replica set or sharded cluster detected; transactions enabled");
90        } else {
91            tracing::info!(
92                "mongodb standalone detected; writing sequentially without transactions"
93            );
94        }
95
96        Ok(Self { db, supports_transactions })
97    }
98
99    /// Returns whether this deployment supports multi-document transactions.
100    pub fn supports_transactions(&self) -> bool {
101        self.supports_transactions
102    }
103
104    const REGISTRY_COLLECTION: &'static str = "_adk_session_migrations";
105
106    const MONGO_SESSION_MIGRATIONS: &'static [(i64, &'static str)] =
107        &[(1, "create initial indexes"), (2, "index events in read order")];
108
109    /// Run versioned migrations for MongoDB session storage.
110    ///
111    /// Several processes may migrate one database at once: every step creates its
112    /// indexes idempotently, and each version is recorded with an upsert, so a version
113    /// another process recorded first is not an error.
114    pub async fn migrate(&self) -> Result<()> {
115        self.db
116            .collection::<Document>(Self::REGISTRY_COLLECTION)
117            .create_index(
118                IndexModel::builder()
119                    .keys(doc! { "version": 1 })
120                    .options(
121                        IndexOptions::builder()
122                            .unique(true)
123                            .name("idx_migration_version_unique".to_string())
124                            .build(),
125                    )
126                    .build(),
127            )
128            .await
129            .map_err(|e| {
130                adk_core::AdkError::session(format!("migration registry creation failed: {e}"))
131            })?;
132
133        let mut max_applied = self.read_max_applied_version().await?;
134
135        if max_applied == 0 {
136            let existing = self.detect_existing_tables().await?;
137            if existing
138                && let Some(&(version, description)) = Self::MONGO_SESSION_MIGRATIONS.first()
139            {
140                self.record_migration(version, description).await?;
141                max_applied = version;
142            }
143        }
144
145        let max_compiled = Self::MONGO_SESSION_MIGRATIONS.last().map(|s| s.0).unwrap_or(0);
146        if max_applied > max_compiled {
147            return Err(adk_core::AdkError::session(format!(
148                "schema version mismatch: database is at v{max_applied} but code only knows up to v{max_compiled}. Upgrade your ADK version."
149            )));
150        }
151
152        for &(version, description) in Self::MONGO_SESSION_MIGRATIONS {
153            if version <= max_applied {
154                continue;
155            }
156            run_mongo_session_step(&self.db, version).await.map_err(|e| {
157                adk_core::AdkError::session(format!(
158                    "{}",
159                    crate::migration::MigrationError {
160                        version,
161                        description: description.to_string(),
162                        cause: e.to_string(),
163                    }
164                ))
165            })?;
166            self.record_migration(version, description).await?;
167        }
168        Ok(())
169    }
170
171    /// Returns the highest applied migration version, or 0 if no migrations have been applied.
172    pub async fn schema_version(&self) -> Result<i64> {
173        let collections = self.db.list_collection_names().await.map_err(|e| {
174            adk_core::AdkError::session(format!("schema version query failed: {e}"))
175        })?;
176        if !collections.contains(&Self::REGISTRY_COLLECTION.to_string()) {
177            return Ok(0);
178        }
179        self.read_max_applied_version().await
180    }
181
182    async fn read_max_applied_version(&self) -> Result<i64> {
183        use mongodb::options::FindOneOptions;
184        let registry = self.db.collection::<Document>(Self::REGISTRY_COLLECTION);
185        let opts = FindOneOptions::builder().sort(doc! { "version": -1 }).build();
186        let result = registry.find_one(doc! {}).with_options(opts).await.map_err(|e| {
187            adk_core::AdkError::session(format!("migration registry read failed: {e}"))
188        })?;
189        match result {
190            Some(doc) => Ok(doc.get_i64("version").unwrap_or(0)),
191            None => Ok(0),
192        }
193    }
194
195    /// Whether v1's last index exists. A first `migrate` running in another process
196    /// creates v1's indexes in order, so an earlier one existing does not mean v1 is
197    /// complete.
198    async fn detect_existing_tables(&self) -> Result<bool> {
199        let failed = |e: mongodb::error::Error| {
200            adk_core::AdkError::session(format!("baseline detection failed: {e}"))
201        };
202        let collections = self.db.list_collection_names().await.map_err(failed)?;
203        if !collections.iter().any(|name| name == "user_states") {
204            return Ok(false);
205        }
206        let indexes = self
207            .db
208            .collection::<Document>("user_states")
209            .list_index_names()
210            .await
211            .map_err(failed)?;
212        Ok(indexes.iter().any(|name| name == "idx_user_states_unique"))
213    }
214
215    /// Records `version` unless another process recorded it first.
216    async fn record_migration(&self, version: i64, description: &str) -> Result<()> {
217        let registry = self.db.collection::<Document>(Self::REGISTRY_COLLECTION);
218        let now = chrono_to_bson_dt(Utc::now());
219        let recorded = registry
220            .update_one(
221                doc! { "version": version },
222                doc! { "$setOnInsert": { "description": description, "applied_at": now } },
223            )
224            .upsert(true)
225            .await;
226        // The server retries an upsert that loses a race on the unique `version` index;
227        // a duplicate key that still surfaces means the version is recorded.
228        match recorded {
229            Ok(_) => Ok(()),
230            Err(e) if is_duplicate_key(&e) => Ok(()),
231            Err(e) => Err(e),
232        }
233        .map_err(|e| {
234            adk_core::AdkError::session(format!(
235                "{}",
236                crate::migration::MigrationError {
237                    version,
238                    description: description.to_string(),
239                    cause: format!("registry record failed: {e}"),
240                }
241            ))
242        })?;
243        Ok(())
244    }
245
246    /// Start a transaction if supported, otherwise return None.
247    async fn maybe_start_transaction(&self) -> Result<Option<mongodb::ClientSession>> {
248        if self.supports_transactions {
249            let mut s =
250                self.db.client().start_session().await.map_err(|e| {
251                    adk_core::AdkError::session(format!("session start failed: {e}"))
252                })?;
253            s.start_transaction().await.map_err(|e| {
254                adk_core::AdkError::session(format!("transaction start failed: {e}"))
255            })?;
256            Ok(Some(s))
257        } else {
258            Ok(None)
259        }
260    }
261
262    /// Commit a transaction if one is active.
263    async fn maybe_commit(session: &mut Option<mongodb::ClientSession>) -> Result<()> {
264        if let Some(s) = session {
265            s.commit_transaction()
266                .await
267                .map_err(|e| adk_core::AdkError::session(format!("commit failed: {e}")))?;
268        }
269        Ok(())
270    }
271}
272
273// ── Migration steps ──
274
275async fn run_mongo_session_step(db: &Database, version: i64) -> Result<()> {
276    match version {
277        1 => mongo_session_v1(db).await,
278        2 => mongo_session_v2(db).await,
279        _ => Err(adk_core::AdkError::session(format!("unknown migration version: {version}"))),
280    }
281}
282
283async fn mongo_session_v1(db: &Database) -> Result<()> {
284    db.collection::<Document>("sessions")
285        .create_index(
286            IndexModel::builder()
287                .keys(doc! { "app_name": 1, "user_id": 1, "session_id": 1 })
288                .options(
289                    IndexOptions::builder()
290                        .unique(true)
291                        .name("idx_sessions_unique".to_string())
292                        .build(),
293                )
294                .build(),
295        )
296        .await
297        .map_err(|e| adk_core::AdkError::session(format!("index creation failed: {e}")))?;
298
299    db.collection::<Document>("events")
300        .create_index(
301            IndexModel::builder()
302                .keys(doc! { "session_id": 1, "timestamp": 1 })
303                .options(IndexOptions::builder().name("idx_events_session_ts".to_string()).build())
304                .build(),
305        )
306        .await
307        .map_err(|e| adk_core::AdkError::session(format!("index creation failed: {e}")))?;
308
309    db.collection::<Document>("app_states")
310        .create_index(
311            IndexModel::builder()
312                .keys(doc! { "app_name": 1 })
313                .options(
314                    IndexOptions::builder()
315                        .unique(true)
316                        .name("idx_app_states_unique".to_string())
317                        .build(),
318                )
319                .build(),
320        )
321        .await
322        .map_err(|e| adk_core::AdkError::session(format!("index creation failed: {e}")))?;
323
324    db.collection::<Document>("user_states")
325        .create_index(
326            IndexModel::builder()
327                .keys(doc! { "app_name": 1, "user_id": 1 })
328                .options(
329                    IndexOptions::builder()
330                        .unique(true)
331                        .name("idx_user_states_unique".to_string())
332                        .build(),
333                )
334                .build(),
335        )
336        .await
337        .map_err(|e| adk_core::AdkError::session(format!("index creation failed: {e}")))?;
338
339    Ok(())
340}
341
342/// Indexes events by session and read order: timestamp, then the append sequence `seq`.
343async fn mongo_session_v2(db: &Database) -> Result<()> {
344    db.collection::<Document>("events")
345        .create_index(
346            IndexModel::builder()
347                .keys(doc! {
348                    "app_name": 1, "user_id": 1, "session_id": 1, "timestamp": 1, "seq": 1,
349                })
350                .options(IndexOptions::builder().name("idx_events_read_order".to_string()).build())
351                .build(),
352        )
353        .await
354        .map_err(|e| adk_core::AdkError::session(format!("index creation failed: {e}")))?;
355    Ok(())
356}
357
358/// Whether `error` is a duplicate-key violation of a unique index.
359fn is_duplicate_key(error: &mongodb::error::Error) -> bool {
360    use mongodb::error::{ErrorKind, WriteFailure};
361    match &*error.kind {
362        ErrorKind::Write(WriteFailure::WriteError(write)) => write.code == 11000,
363        _ => false,
364    }
365}
366
367/// Attempts a history rewrite makes before giving up on a session that keeps changing between
368/// the read and the write.
369const MAX_REWRITE_ATTEMPTS: usize = 16;
370
371// ── BSON helpers ──
372
373fn state_to_bson(
374    state: &HashMap<String, Value>,
375) -> std::result::Result<Document, adk_core::AdkError> {
376    let json_value = serde_json::to_value(state)
377        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
378    let bson_value = bson::to_bson(&json_value)
379        .map_err(|e| adk_core::AdkError::session(format!("bson conversion failed: {e}")))?;
380    match bson_value {
381        bson::Bson::Document(doc) => Ok(doc),
382        _ => Ok(Document::new()),
383    }
384}
385
386fn bson_to_state(doc: &Document) -> HashMap<String, Value> {
387    let bson_value = bson::Bson::Document(doc.clone());
388    match bson::from_bson::<serde_json::Value>(bson_value) {
389        Ok(Value::Object(map)) => map.into_iter().collect(),
390        _ => HashMap::new(),
391    }
392}
393
394fn chrono_to_bson_dt(dt: DateTime<Utc>) -> bson::DateTime {
395    bson::DateTime::from_millis(dt.timestamp_millis())
396}
397
398fn bson_dt_to_chrono(dt: bson::DateTime) -> DateTime<Utc> {
399    let millis = dt.timestamp_millis();
400    DateTime::from_timestamp_millis(millis).unwrap_or_default()
401}
402
403/// Builds an update pipeline that merges `delta` into a document's `state` and sets
404/// `updated_at`.
405///
406/// `$mergeObjects` runs against the stored document while the write holds it, so
407/// concurrent writers of different keys never overwrite each other. `$literal` keeps
408/// keys and values that would otherwise parse as expressions (a leading `$`) as data.
409fn merge_state_pipeline(
410    delta: &HashMap<String, Value>,
411    updated_at: bson::DateTime,
412) -> std::result::Result<Vec<Document>, adk_core::AdkError> {
413    let delta = state_to_bson(delta)?;
414    Ok(vec![doc! { "$set": {
415        "state": { "$mergeObjects": [{ "$ifNull": ["$state", {}] }, { "$literal": delta }] },
416        "updated_at": updated_at,
417    } }])
418}
419
420// ── Session-optional DB operation helpers ──
421// Each helper accepts Option<&mut ClientSession>. When Some, the op runs
422// inside the transaction; when None, it runs standalone.
423
424macro_rules! with_optional_session {
425    ($action:expr, $session:expr) => {
426        match $session {
427            Some(s) => $action.session(s).await,
428            None => $action.await,
429        }
430    };
431}
432
433impl MongoSessionService {
434    /// Reads the current app and user state tiers.
435    async fn read_tiers(
436        &self,
437        txn: &mut Option<mongodb::ClientSession>,
438        app_name: &str,
439        user_id: &str,
440    ) -> Result<(HashMap<String, Value>, HashMap<String, Value>)> {
441        let app_coll = self.db.collection::<Document>("app_states");
442        let user_coll = self.db.collection::<Document>("user_states");
443
444        let app_state =
445            with_optional_session!(app_coll.find_one(doc! { "app_name": app_name }), txn.as_mut())
446                .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
447                .and_then(|d| d.get_document("state").ok().map(bson_to_state))
448                .unwrap_or_default();
449        let user_state = with_optional_session!(
450            user_coll.find_one(doc! { "app_name": app_name, "user_id": user_id }),
451            txn.as_mut()
452        )
453        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
454        .and_then(|d| d.get_document("state").ok().map(bson_to_state))
455        .unwrap_or_default();
456
457        Ok((app_state, user_state))
458    }
459
460    /// Merges each non-empty tier delta into the stored tier.
461    async fn apply_tier_deltas(
462        &self,
463        txn: &mut Option<mongodb::ClientSession>,
464        app_name: &str,
465        user_id: &str,
466        app_delta: &HashMap<String, Value>,
467        user_delta: &HashMap<String, Value>,
468        updated_at: bson::DateTime,
469    ) -> Result<()> {
470        let upsert = UpdateOptions::builder().upsert(true).build();
471        if !app_delta.is_empty() {
472            let app_coll = self.db.collection::<Document>("app_states");
473            with_optional_session!(
474                app_coll
475                    .update_one(
476                        doc! { "app_name": app_name },
477                        merge_state_pipeline(app_delta, updated_at)?
478                    )
479                    .with_options(upsert.clone()),
480                txn.as_mut()
481            )
482            .map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;
483        }
484        if !user_delta.is_empty() {
485            let user_coll = self.db.collection::<Document>("user_states");
486            with_optional_session!(
487                user_coll
488                    .update_one(
489                        doc! { "app_name": app_name, "user_id": user_id },
490                        merge_state_pipeline(user_delta, updated_at)?
491                    )
492                    .with_options(upsert),
493                txn.as_mut()
494            )
495            .map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;
496        }
497        Ok(())
498    }
499
500    /// Reads the history of `identity`, with the session document's `event_seq` and
501    /// `updated_at` as stored, which a rewrite requires to be unchanged when it writes.
502    async fn load_history(
503        &self,
504        txn: &mut Option<mongodb::ClientSession>,
505        identity: &AdkIdentity,
506    ) -> Result<(SessionHistory, bson::Bson, bson::Bson)> {
507        let filter = doc! {
508            "app_name": identity.app_name.as_ref(),
509            "user_id": identity.user_id.as_ref(),
510            "session_id": identity.session_id.as_ref(),
511        };
512        let session_doc = with_optional_session!(
513            self.db.collection::<Document>("sessions").find_one(filter.clone()),
514            txn.as_mut()
515        )
516        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
517        .ok_or_else(|| identity_not_found(identity))?;
518        let stored = session_doc.get_document("state").map(bson_to_state).unwrap_or_default();
519        // Documents written by earlier releases also hold a copy of the app and user tiers.
520        let (_, _, state) = state_utils::extract_state_deltas(&stored);
521        let initial_state = session_doc.get_document("initial_state").ok().map(bson_to_state);
522        let event_seq = session_doc.get("event_seq").cloned().unwrap_or(bson::Bson::Null);
523        let updated_at = session_doc.get("updated_at").cloned().unwrap_or(bson::Bson::Null);
524
525        let events_coll = self.db.collection::<Document>("events");
526        let options = FindOptions::builder().sort(doc! { "timestamp": 1, "seq": 1 }).build();
527        let query_error =
528            |e: mongodb::error::Error| adk_core::AdkError::session(format!("query failed: {e}"));
529        let mut docs = Vec::new();
530        match txn.as_mut() {
531            Some(session) => {
532                let mut cursor = events_coll
533                    .find(filter)
534                    .with_options(options)
535                    .session(&mut *session)
536                    .await
537                    .map_err(query_error)?;
538                while cursor.advance(&mut *session).await.map_err(query_error)? {
539                    docs.push(cursor.deserialize_current().map_err(query_error)?);
540                }
541            }
542            None => {
543                let mut cursor =
544                    events_coll.find(filter).with_options(options).await.map_err(query_error)?;
545                while cursor.advance().await.map_err(query_error)? {
546                    docs.push(cursor.deserialize_current().map_err(query_error)?);
547                }
548            }
549        }
550        let events = docs.iter().filter_map(doc_to_event).collect();
551        Ok((SessionHistory::new(events, state, initial_state), event_seq, updated_at))
552    }
553
554    /// One attempt at a rewrite: `None` when the session changed between the read and the
555    /// guarded write, so the caller reads it again.
556    async fn try_rewrite(
557        &self,
558        req: &RewriteHistoryRequest,
559    ) -> Result<Option<(RewrittenHistory, DateTime<Utc>)>> {
560        let identity = &req.identity;
561        let (app_name, user_id, session_id) =
562            (identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
563        let mut txn = self.maybe_start_transaction().await?;
564        let (history, event_seq, updated_at) = self.load_history(&mut txn, identity).await?;
565        let rewritten = history.rewrite(identity, &req.rewrite, req.expected_version.as_deref())?;
566
567        let now = Utc::now();
568        // The session document is written first and only while it still holds the append
569        // count and update time that were read, so without a transaction a concurrent append
570        // fails the guard instead of being overwritten.
571        let claimed = with_optional_session!(
572            self.db.collection::<Document>("sessions").update_one(
573                doc! {
574                    "app_name": app_name, "user_id": user_id, "session_id": session_id,
575                    "event_seq": event_seq, "updated_at": updated_at,
576                },
577                doc! { "$set": {
578                    "state": state_to_bson(&rewritten.state)?,
579                    "updated_at": chrono_to_bson_dt(now),
580                } }
581            ),
582            txn.as_mut()
583        )
584        .map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?;
585        if claimed.matched_count == 0 {
586            if let Some(session) = txn.as_mut() {
587                session.abort_transaction().await.ok();
588            }
589            return Ok(None);
590        }
591
592        let events_coll = self.db.collection::<Document>("events");
593        let change = &rewritten.change;
594        if !change.removed.is_empty() {
595            with_optional_session!(
596                events_coll.delete_many(doc! {
597                    "app_name": app_name, "user_id": user_id, "session_id": session_id,
598                    "id": { "$in": &change.removed },
599                }),
600                txn.as_mut()
601            )
602            .map_err(|e| adk_core::AdkError::session(format!("delete events failed: {e}")))?;
603        }
604        for event in rewritten.events.iter().filter(|e| change.replaced.contains(&e.id)) {
605            let replacement = event_doc(app_name, user_id, session_id, event, 0)?;
606            with_optional_session!(
607                events_coll.update_one(
608                    doc! {
609                        "app_name": app_name, "user_id": user_id, "session_id": session_id,
610                        "id": &event.id,
611                    },
612                    doc! { "$set": {
613                        "invocation_id": replacement.get("invocation_id").cloned(),
614                        "branch": replacement.get("branch").cloned(),
615                        "author": replacement.get("author").cloned(),
616                        "llm_response": replacement.get("llm_response").cloned(),
617                        "actions": replacement.get("actions").cloned(),
618                        "long_running_tool_ids": replacement.get("long_running_tool_ids").cloned(),
619                    } }
620                ),
621                txn.as_mut()
622            )
623            .map_err(|e| adk_core::AdkError::session(format!("update event failed: {e}")))?;
624        }
625        Self::maybe_commit(&mut txn).await?;
626        Ok(Some((rewritten, now)))
627    }
628
629    /// Applies `event` to the session `(app_name, user_id, session_id)`: merges each
630    /// tier's delta, bumps `updated_at`, and inserts the event.
631    async fn apply_event(
632        &self,
633        txn: &mut Option<mongodb::ClientSession>,
634        app_name: &str,
635        user_id: &str,
636        session_id: &str,
637        event: &Event,
638    ) -> Result<()> {
639        let sess_coll = self.db.collection::<Document>("sessions");
640        let ev_coll = self.db.collection::<Document>("events");
641
642        let (app_delta, user_delta, session_delta) =
643            state_utils::extract_state_deltas(&event.actions.state_delta);
644        let bson_ts = chrono_to_bson_dt(event.timestamp);
645
646        // `event_seq` counts the session's appends; it orders events with equal timestamps,
647        // which millisecond BSON dates make common.
648        let mut pipeline = merge_state_pipeline(&session_delta, bson_ts)?;
649        if let Some(set) =
650            pipeline.first_mut().and_then(|stage| stage.get_document_mut("$set").ok())
651        {
652            set.insert(
653                "event_seq",
654                doc! { "$add": [{ "$toLong": { "$ifNull": ["$event_seq", 0] } }, 1] },
655            );
656        }
657        let updated = with_optional_session!(
658            sess_coll
659                .find_one_and_update(
660                    doc! { "app_name": app_name, "user_id": user_id, "session_id": session_id },
661                    pipeline
662                )
663                .return_document(ReturnDocument::After)
664                .projection(doc! { "event_seq": 1 }),
665            txn.as_mut()
666        )
667        .map_err(|e| adk_core::AdkError::session(format!("update failed: {e}")))?
668        .ok_or_else(|| session_not_found_for(app_name, user_id, session_id))?;
669        let seq = updated
670            .get_i64("event_seq")
671            .or_else(|_| updated.get_i32("event_seq").map(i64::from))
672            .unwrap_or_default();
673
674        self.apply_tier_deltas(txn, app_name, user_id, &app_delta, &user_delta, bson_ts).await?;
675
676        with_optional_session!(
677            ev_coll.insert_one(event_doc(app_name, user_id, session_id, event, seq)?),
678            txn.as_mut()
679        )
680        .map_err(|e| adk_core::AdkError::session(format!("insert failed: {e}")))?;
681
682        Ok(())
683    }
684}
685
686// ── SessionService implementation ──
687
688#[async_trait]
689impl SessionService for MongoSessionService {
690    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id))]
691    async fn create(&self, req: CreateRequest) -> Result<Box<dyn Session>> {
692        req.try_identity()?;
693        let session_id = req.session_id.unwrap_or_else(|| Uuid::new_v4().to_string());
694        let now = Utc::now();
695        let bson_now = chrono_to_bson_dt(now);
696        let (app_delta, user_delta, session_state) = state_utils::extract_state_deltas(&req.state);
697
698        let sess_coll = self.db.collection::<Document>("sessions");
699
700        let conflict = || session_already_exists(&req.app_name, &req.user_id, &session_id);
701        let identity = doc! {
702            "app_name": &req.app_name, "user_id": &req.user_id, "session_id": &session_id,
703        };
704        let mut txn = self.maybe_start_transaction().await?;
705
706        // The session document is written before the tiers, so a create that conflicts writes
707        // nothing even without a transaction; the unique index catches a concurrent create.
708        let existing = with_optional_session!(sess_coll.find_one(identity.clone()), txn.as_mut())
709            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
710        if existing.is_some() {
711            return Err(conflict());
712        }
713        let session_bson = state_to_bson(&session_state)?;
714        let mut session_doc = identity;
715        session_doc.insert("initial_state", session_bson.clone());
716        session_doc.insert("state", session_bson);
717        session_doc.insert("created_at", bson_now);
718        session_doc.insert("updated_at", bson_now);
719        with_optional_session!(sess_coll.insert_one(session_doc), txn.as_mut()).map_err(|e| {
720            if is_duplicate_key(&e) {
721                conflict()
722            } else {
723                adk_core::AdkError::session(format!("insert failed: {e}"))
724            }
725        })?;
726
727        self.apply_tier_deltas(
728            &mut txn,
729            &req.app_name,
730            &req.user_id,
731            &app_delta,
732            &user_delta,
733            bson_now,
734        )
735        .await?;
736        let (app_state, user_state) =
737            self.read_tiers(&mut txn, &req.app_name, &req.user_id).await?;
738
739        MongoSessionService::maybe_commit(&mut txn).await?;
740
741        Ok(Box::new(MongoSession {
742            app_name: req.app_name,
743            user_id: req.user_id,
744            session_id,
745            state: state_utils::merge_states(&app_state, &user_state, &session_state),
746            events: Vec::new(),
747            updated_at: now,
748        }))
749    }
750
751    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id, session_id = %req.session_id))]
752    async fn get(&self, req: GetRequest) -> Result<Box<dyn Session>> {
753        req.try_identity()?;
754        let sess_coll = self.db.collection::<Document>("sessions");
755        let session_doc = sess_coll
756            .find_one(doc! { "app_name": &req.app_name, "user_id": &req.user_id, "session_id": &req.session_id })
757            .await.map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
758            .ok_or_else(|| crate::service::session_not_found(&req))?;
759
760        let stored = session_doc.get_document("state").map(bson_to_state).unwrap_or_default();
761        let (app_state, user_state) =
762            self.read_tiers(&mut None, &req.app_name, &req.user_id).await?;
763        let updated_at = session_doc
764            .get_datetime("updated_at")
765            .map(|dt| bson_dt_to_chrono(*dt))
766            .unwrap_or_else(|_| Utc::now());
767
768        let events_coll = self.db.collection::<Document>("events");
769        let mut cursor = events_coll
770            .find(doc! { "app_name": &req.app_name, "user_id": &req.user_id, "session_id": &req.session_id })
771            .with_options(FindOptions::builder().sort(doc! { "timestamp": 1, "seq": 1 }).build())
772            .await.map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
773
774        let mut events: Vec<Event> = Vec::new();
775        while cursor
776            .advance()
777            .await
778            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
779        {
780            let doc = cursor
781                .deserialize_current()
782                .map_err(|e| adk_core::AdkError::session(format!("deserialize failed: {e}")))?;
783            if let Some(event) = doc_to_event(&doc) {
784                events.push(event);
785            }
786        }
787        if let Some(num) = req.num_recent_events {
788            let start = events.len().saturating_sub(num);
789            events = events[start..].to_vec();
790        }
791        if let Some(after) = req.after {
792            events.retain(|e| e.timestamp >= after);
793        }
794
795        Ok(Box::new(MongoSession {
796            app_name: req.app_name,
797            user_id: req.user_id,
798            session_id: req.session_id,
799            state: state_utils::merge_current_tiers(&app_state, &user_state, &stored),
800            events,
801            updated_at,
802        }))
803    }
804
805    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id))]
806    async fn list(&self, req: ListRequest) -> Result<Vec<Box<dyn Session>>> {
807        validate_scope(&req.app_name, &req.user_id)?;
808        let sess_coll = self.db.collection::<Document>("sessions");
809        let opts = FindOptions::builder()
810            .sort(doc! { "updated_at": -1, "session_id": -1 })
811            .limit(req.limit.map(|l| l as i64))
812            .skip(req.offset.map(|o| o as u64))
813            .build();
814        let mut cursor = sess_coll
815            .find(doc! { "app_name": &req.app_name, "user_id": &req.user_id })
816            .with_options(opts)
817            .await
818            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?;
819
820        let (app_state, user_state) =
821            self.read_tiers(&mut None, &req.app_name, &req.user_id).await?;
822
823        let mut sessions: Vec<Box<dyn Session>> = Vec::new();
824        while cursor
825            .advance()
826            .await
827            .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
828        {
829            let doc = cursor
830                .deserialize_current()
831                .map_err(|e| adk_core::AdkError::session(format!("deserialize failed: {e}")))?;
832            let stored = doc.get_document("state").map(bson_to_state).unwrap_or_default();
833            sessions.push(Box::new(MongoSession {
834                app_name: req.app_name.clone(),
835                user_id: req.user_id.clone(),
836                session_id: doc.get_str("session_id").unwrap_or_default().to_string(),
837                state: state_utils::merge_current_tiers(&app_state, &user_state, &stored),
838                events: Vec::new(),
839                updated_at: doc
840                    .get_datetime("updated_at")
841                    .map(|dt| bson_dt_to_chrono(*dt))
842                    .unwrap_or_else(|_| Utc::now()),
843            }));
844        }
845        Ok(sessions)
846    }
847
848    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id, session_id = %req.session_id))]
849    async fn delete(&self, req: DeleteRequest) -> Result<()> {
850        req.try_identity()?;
851        let ev_coll = self.db.collection::<Document>("events");
852        let sess_coll = self.db.collection::<Document>("sessions");
853        let filter = doc! { "app_name": &req.app_name, "user_id": &req.user_id, "session_id": &req.session_id };
854
855        let mut txn = self.maybe_start_transaction().await?;
856        with_optional_session!(ev_coll.delete_many(filter.clone()), txn.as_mut())
857            .map_err(|e| adk_core::AdkError::session(format!("delete failed: {e}")))?;
858        with_optional_session!(sess_coll.delete_one(filter), txn.as_mut())
859            .map_err(|e| adk_core::AdkError::session(format!("delete failed: {e}")))?;
860        MongoSessionService::maybe_commit(&mut txn).await?;
861        Ok(())
862    }
863
864    #[instrument(skip_all, fields(session_id = %session_id))]
865    async fn append_event(&self, session_id: &str, mut event: Event) -> Result<()> {
866        validate_session_id(session_id)?;
867        event.actions.state_delta.retain(|k, _| !k.starts_with(KEY_PREFIX_TEMP));
868
869        let sess_coll = self.db.collection::<Document>("sessions");
870
871        let mut txn = self.maybe_start_transaction().await?;
872
873        let session_doc = with_optional_session!(
874            sess_coll.find_one(doc! { "session_id": session_id }),
875            txn.as_mut()
876        )
877        .map_err(|e| adk_core::AdkError::session(format!("query failed: {e}")))?
878        .ok_or_else(|| session_id_not_found(session_id))?;
879
880        let app_name = session_doc.get_str("app_name").unwrap_or_default().to_string();
881        let user_id = session_doc.get_str("user_id").unwrap_or_default().to_string();
882
883        self.apply_event(&mut txn, &app_name, &user_id, session_id, &event).await?;
884
885        MongoSessionService::maybe_commit(&mut txn).await?;
886        Ok(())
887    }
888
889    #[instrument(skip_all, fields(
890        app_name = %req.identity.app_name,
891        user_id = %req.identity.user_id,
892        session_id = %req.identity.session_id,
893    ))]
894    async fn append_event_for_identity(&self, req: AppendEventRequest) -> Result<()> {
895        let mut event = req.event;
896        event.actions.state_delta.retain(|k, _| !k.starts_with(KEY_PREFIX_TEMP));
897
898        let mut txn = self.maybe_start_transaction().await?;
899        self.apply_event(
900            &mut txn,
901            req.identity.app_name.as_ref(),
902            req.identity.user_id.as_ref(),
903            req.identity.session_id.as_ref(),
904            &event,
905        )
906        .await?;
907        MongoSessionService::maybe_commit(&mut txn).await?;
908        Ok(())
909    }
910
911    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
912    async fn delete_all_sessions(&self, app_name: &str, user_id: &str) -> Result<()> {
913        validate_scope(app_name, user_id)?;
914        let filter = doc! { "app_name": app_name, "user_id": user_id };
915        let ev_coll = self.db.collection::<Document>("events");
916        let sess_coll = self.db.collection::<Document>("sessions");
917        let user_coll = self.db.collection::<Document>("user_states");
918
919        let mut txn = self.maybe_start_transaction().await?;
920        with_optional_session!(ev_coll.delete_many(filter.clone()), txn.as_mut())
921            .map_err(|e| adk_core::AdkError::session(format!("delete_all_sessions failed: {e}")))?;
922        with_optional_session!(sess_coll.delete_many(filter.clone()), txn.as_mut())
923            .map_err(|e| adk_core::AdkError::session(format!("delete_all_sessions failed: {e}")))?;
924        with_optional_session!(user_coll.delete_many(filter), txn.as_mut())
925            .map_err(|e| adk_core::AdkError::session(format!("delete_all_sessions failed: {e}")))?;
926        MongoSessionService::maybe_commit(&mut txn).await?;
927        Ok(())
928    }
929
930    #[instrument(skip_all)]
931    async fn history(&self, identity: &AdkIdentity) -> Result<SessionHistory> {
932        Ok(self.load_history(&mut None, identity).await?.0)
933    }
934
935    async fn rewrite_history(&self, req: RewriteHistoryRequest) -> Result<HistoryOutcome> {
936        let identity = &req.identity;
937        for _ in 0..MAX_REWRITE_ATTEMPTS {
938            let Some((rewritten, updated_at)) = self.try_rewrite(&req).await? else {
939                continue;
940            };
941            let (app_state, user_state) = self
942                .read_tiers(&mut None, identity.app_name.as_ref(), identity.user_id.as_ref())
943                .await?;
944            let session = Box::new(MongoSession {
945                app_name: identity.app_name.as_ref().to_string(),
946                user_id: identity.user_id.as_ref().to_string(),
947                session_id: identity.session_id.as_ref().to_string(),
948                state: state_utils::merge_states(&app_state, &user_state, &rewritten.state),
949                events: rewritten.events,
950                updated_at,
951            });
952            return Ok(HistoryOutcome::new(session, rewritten.change));
953        }
954        Err(adk_core::AdkError::new(
955            ErrorComponent::Session,
956            ErrorCategory::Unavailable,
957            "session.mongodb.history_contention",
958            format!(
959                "session '{}' changed on each of {MAX_REWRITE_ATTEMPTS} rewrite attempts; retry \
960                 the rewrite",
961                identity.session_id
962            ),
963        ))
964    }
965
966    async fn import_session(&self, req: ImportSessionRequest) -> Result<Box<dyn Session>> {
967        let identity = &req.identity;
968        let (app_name, user_id, session_id) =
969            (identity.app_name.as_ref(), identity.user_id.as_ref(), identity.session_id.as_ref());
970        let (_, _, state) = state_utils::extract_state_deltas(&req.state);
971        let (_, _, initial_state) = state_utils::extract_state_deltas(&req.initial_state);
972        let updated_at = req.events.last().map_or_else(Utc::now, |event| event.timestamp);
973        let event_count = i64::try_from(req.events.len()).unwrap_or(i64::MAX);
974
975        let mut txn = self.maybe_start_transaction().await?;
976        // The session document goes first, so its unique index refuses an existing session
977        // before any event is written.
978        let session_doc = doc! {
979            "app_name": app_name, "user_id": user_id, "session_id": session_id,
980            "state": state_to_bson(&state)?,
981            "initial_state": state_to_bson(&initial_state)?,
982            "created_at": chrono_to_bson_dt(Utc::now()),
983            "updated_at": chrono_to_bson_dt(updated_at),
984            "event_seq": event_count,
985        };
986        with_optional_session!(
987            self.db.collection::<Document>("sessions").insert_one(session_doc),
988            txn.as_mut()
989        )
990        .map_err(|e| {
991            if is_duplicate_key(&e) {
992                session_already_exists(app_name, user_id, session_id)
993            } else {
994                adk_core::AdkError::session(format!("insert failed: {e}"))
995            }
996        })?;
997        if !req.events.is_empty() {
998            let docs = req
999                .events
1000                .iter()
1001                .zip(1_i64..)
1002                .map(|(event, seq)| event_doc(app_name, user_id, session_id, event, seq))
1003                .collect::<Result<Vec<_>>>()?;
1004            let inserted = with_optional_session!(
1005                self.db.collection::<Document>("events").insert_many(docs),
1006                txn.as_mut()
1007            );
1008            if let Err(error) = inserted {
1009                if txn.is_none() {
1010                    // Without a transaction, take back the session document so no partial
1011                    // import remains.
1012                    let _ = self
1013                        .db
1014                        .collection::<Document>("sessions")
1015                        .delete_one(doc! {
1016                            "app_name": app_name, "user_id": user_id, "session_id": session_id,
1017                        })
1018                        .await;
1019                }
1020                return Err(adk_core::AdkError::session(format!("insert events failed: {error}")));
1021            }
1022        }
1023        let (app_state, user_state) = self.read_tiers(&mut txn, app_name, user_id).await?;
1024        MongoSessionService::maybe_commit(&mut txn).await?;
1025
1026        Ok(Box::new(MongoSession {
1027            app_name: app_name.to_string(),
1028            user_id: user_id.to_string(),
1029            session_id: session_id.to_string(),
1030            state: state_utils::merge_states(&app_state, &user_state, &state),
1031            events: req.events,
1032            updated_at,
1033        }))
1034    }
1035
1036    async fn health_check(&self) -> Result<()> {
1037        self.db
1038            .run_command(doc! { "ping": 1 })
1039            .await
1040            .map_err(|e| adk_core::AdkError::session(format!("health check failed: {e}")))?;
1041        Ok(())
1042    }
1043}
1044
1045// ── Event deserialization ──
1046
1047/// The stored document of `event`, at append position `seq`.
1048fn event_doc(
1049    app_name: &str,
1050    user_id: &str,
1051    session_id: &str,
1052    event: &Event,
1053    seq: i64,
1054) -> Result<Document> {
1055    let llm_bson = bson::to_bson(&event.llm_response)
1056        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
1057    let act_bson = bson::to_bson(&event.actions)
1058        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
1059    let tid_bson = bson::to_bson(&event.long_running_tool_ids)
1060        .map_err(|e| adk_core::AdkError::session(format!("serialize failed: {e}")))?;
1061    Ok(doc! {
1062        "id": &event.id, "session_id": session_id, "app_name": app_name, "user_id": user_id,
1063        "invocation_id": &event.invocation_id, "branch": &event.branch, "author": &event.author,
1064        "timestamp": chrono_to_bson_dt(event.timestamp), "seq": seq, "llm_response": llm_bson,
1065        "actions": act_bson, "long_running_tool_ids": tid_bson,
1066    })
1067}
1068
1069fn doc_to_event(doc: &Document) -> Option<Event> {
1070    let llm_response_bson = doc.get("llm_response")?;
1071    let actions_bson = doc.get("actions")?;
1072    let tool_ids_bson = doc.get("long_running_tool_ids")?;
1073
1074    let llm_response = bson::from_bson(llm_response_bson.clone()).ok()?;
1075    let actions = bson::from_bson(actions_bson.clone()).ok()?;
1076    let long_running_tool_ids = bson::from_bson(tool_ids_bson.clone()).ok()?;
1077
1078    let timestamp = doc
1079        .get_datetime("timestamp")
1080        .map(|dt| bson_dt_to_chrono(*dt))
1081        .unwrap_or_else(|_| Utc::now());
1082
1083    Some(Event {
1084        id: doc.get_str("id").unwrap_or_default().to_string(),
1085        timestamp,
1086        invocation_id: doc.get_str("invocation_id").unwrap_or_default().to_string(),
1087        branch: doc.get_str("branch").unwrap_or_default().to_string(),
1088        author: doc.get_str("author").unwrap_or_default().to_string(),
1089        llm_request: None,
1090        llm_response,
1091        actions,
1092        long_running_tool_ids,
1093        provider_metadata: std::collections::HashMap::new(),
1094    })
1095}
1096
1097// ── MongoSession type ──
1098
1099struct MongoSession {
1100    app_name: String,
1101    user_id: String,
1102    session_id: String,
1103    state: HashMap<String, Value>,
1104    events: Vec<Event>,
1105    updated_at: DateTime<Utc>,
1106}
1107
1108impl Session for MongoSession {
1109    fn id(&self) -> &str {
1110        &self.session_id
1111    }
1112    fn app_name(&self) -> &str {
1113        &self.app_name
1114    }
1115    fn user_id(&self) -> &str {
1116        &self.user_id
1117    }
1118    fn state(&self) -> &dyn State {
1119        self
1120    }
1121    fn events(&self) -> &dyn Events {
1122        self
1123    }
1124    fn last_update_time(&self) -> DateTime<Utc> {
1125        self.updated_at
1126    }
1127
1128    fn take_events(&mut self) -> Vec<Event> {
1129        std::mem::take(&mut self.events)
1130    }
1131}
1132
1133impl State for MongoSession {
1134    fn get(&self, key: &str) -> Option<Value> {
1135        self.state.get(key).cloned()
1136    }
1137    fn set(&mut self, key: String, value: Value) {
1138        if let Err(msg) = adk_core::validate_state_key(&key) {
1139            tracing::warn!(key = %key, "rejecting invalid state key: {msg}");
1140            return;
1141        }
1142        self.state.insert(key, value);
1143    }
1144    fn all(&self) -> HashMap<String, Value> {
1145        self.state.clone()
1146    }
1147}
1148
1149impl Events for MongoSession {
1150    fn all(&self) -> Vec<Event> {
1151        self.events.clone()
1152    }
1153    fn len(&self) -> usize {
1154        self.events.len()
1155    }
1156    fn at(&self, index: usize) -> Option<&Event> {
1157        self.events.get(index)
1158    }
1159}
1160
1161#[cfg(test)]
1162mod tests {
1163    use super::*;
1164
1165    #[test]
1166    fn replica_set_members_support_transactions() {
1167        let primary = doc! { "isWritablePrimary": true, "setName": "rs0", "hosts": ["a:27017"] };
1168        assert!(hello_supports_transactions(&primary));
1169        let secondary = doc! { "isWritablePrimary": false, "secondary": true, "setName": "rs0" };
1170        assert!(hello_supports_transactions(&secondary));
1171    }
1172
1173    #[test]
1174    fn mongos_routers_support_transactions() {
1175        let mongos = doc! { "isWritablePrimary": true, "msg": "isdbgrid", "maxWireVersion": 21 };
1176        assert!(hello_supports_transactions(&mongos));
1177    }
1178
1179    #[test]
1180    fn standalone_servers_do_not_support_transactions() {
1181        let standalone = doc! { "isWritablePrimary": true, "maxWireVersion": 21 };
1182        assert!(!hello_supports_transactions(&standalone));
1183        assert!(!hello_supports_transactions(&doc! { "msg": "not a router" }));
1184    }
1185}