Skip to main content

adk_memory/
mongodb.rs

1//! MongoDB memory service backed by MongoDB Atlas Vector Search.
2//!
3//! Provides [`MongoMemoryService`], a [`MemoryService`] implementation
4//! that stores memory entries in MongoDB with optional Atlas Vector Search for
5//! cosine similarity ranking. When no embedding provider is configured, falls back
6//! to MongoDB text search on the content field.
7//!
8//! # Example
9//!
10//! ```rust,ignore
11//! use adk_memory::MongoMemoryService;
12//!
13//! let client = mongodb::Client::with_uri_str("mongodb://localhost:27017").await?;
14//! let service = MongoMemoryService::new(client, "my_db", None)?;
15//! service.migrate().await?;
16//! ```
17
18use crate::embedding::EmbeddingProvider;
19use crate::service::*;
20use adk_core::Result;
21use async_trait::async_trait;
22use chrono::Utc;
23use mongodb::bson::{DateTime as BsonDateTime, Document, doc};
24use mongodb::options::IndexOptions;
25use mongodb::{Client, Database, IndexModel};
26use std::sync::Arc;
27use std::time::Duration;
28use tracing::instrument;
29
30/// MongoDB-backed memory service with optional Atlas Vector Search support.
31///
32/// When an [`EmbeddingProvider`] is supplied, entries are stored with vector
33/// embeddings and searched via MongoDB Atlas `$vectorSearch` aggregation stage
34/// for cosine similarity ranking. Without a provider, search falls back to
35/// MongoDB `$text` search using a text index on the content field.
36///
37/// # Note
38///
39/// Atlas Vector Search indexes must be created separately via the Atlas UI or
40/// API — they cannot be created programmatically through the MongoDB driver.
41/// The [`migrate`](Self::migrate) method creates the text index for fallback
42/// search and the compound index on `(app_name, user_id)`.
43pub struct MongoMemoryService {
44    db: Database,
45    embedding_provider: Option<Arc<dyn EmbeddingProvider>>,
46    default_ttl: Option<Duration>,
47}
48
49impl MongoMemoryService {
50    /// Create a MongoDB memory service from an existing client.
51    ///
52    /// # Arguments
53    ///
54    /// * `client` - A connected `mongodb::Client`
55    /// * `database_name` - The target MongoDB database name
56    /// * `embedding_provider` - Optional embedding provider for vector search
57    pub fn new(
58        client: Client,
59        database_name: &str,
60        embedding_provider: Option<Arc<dyn EmbeddingProvider>>,
61    ) -> Result<Self> {
62        let db = client.database(database_name);
63        Ok(Self { db, embedding_provider, default_ttl: None })
64    }
65
66    /// Expires each entry written without an expiry `ttl` after it is written.
67    ///
68    /// The TTL index that [`migrate`](Self::migrate) creates on `expires_at` lets MongoDB
69    /// delete expired entries itself, on its TTL monitor's schedule (every 60 seconds by
70    /// default); reads skip them before then.
71    ///
72    /// # Example
73    ///
74    /// ```rust,ignore
75    /// use adk_memory::MongoMemoryService;
76    /// use std::time::Duration;
77    ///
78    /// let client = mongodb::Client::with_uri_str("mongodb://localhost:27017").await?;
79    /// let service = MongoMemoryService::new(client, "my_db", None)?
80    ///     .with_default_ttl(Duration::from_secs(30 * 24 * 3600));
81    /// ```
82    pub fn with_default_ttl(mut self, ttl: Duration) -> Self {
83        self.default_ttl = Some(ttl);
84        self
85    }
86
87    /// The document an entry is stored as: `scope` (app, user, session and project) plus
88    /// the entry, stamped with its id and expiry.
89    fn document(
90        &self,
91        scope: &Document,
92        entry: MemoryEntry,
93        embedding: Option<&[f32]>,
94        now: chrono::DateTime<Utc>,
95    ) -> Result<Document> {
96        let entry = crate::expiry::stamp(entry, self.default_ttl, now);
97        let content_json = serde_json::to_value(&entry.content)
98            .map_err(|e| adk_core::AdkError::memory(format!("serialization failed: {e}")))?;
99        let content_bson = mongodb::bson::to_bson(&content_json)
100            .map_err(|e| adk_core::AdkError::memory(format!("bson conversion failed: {e}")))?;
101        let mut document = scope.clone();
102        document.insert("memory_id", entry.id.unwrap_or_default());
103        document.insert("content", content_bson);
104        document.insert("content_text", crate::text::extract_text(&entry.content));
105        document.insert("author", entry.author);
106        document.insert("timestamp", BsonDateTime::from_millis(entry.timestamp.timestamp_millis()));
107        // A BSON date, so the TTL index deletes the entry once it passes.
108        if let Some(expires_at) = entry.expires_at {
109            document.insert("expires_at", BsonDateTime::from_millis(expires_at.timestamp_millis()));
110        }
111        if let Some(embedding) = embedding {
112            let embedding: Vec<mongodb::bson::Bson> =
113                embedding.iter().map(|&v| mongodb::bson::Bson::Double(v as f64)).collect();
114            document.insert("embedding", embedding);
115        }
116        Ok(document)
117    }
118
119    /// Registry collection name for tracking applied migration versions.
120    const REGISTRY_COLLECTION: &'static str = "_adk_memory_migrations";
121
122    /// Compiled-in MongoDB migration steps.
123    ///
124    /// Each entry is `(version, description)`. The actual migration logic is
125    /// dispatched by version number in [`run_mongo_memory_step`].
126    const MONGO_MEMORY_MIGRATIONS: &'static [(i64, &'static str)] = &[
127        (1, "create initial indexes"),
128        (2, "add project_id compound index"),
129        (3, "add memory_id index and expires_at TTL index"),
130    ];
131
132    /// Run versioned migrations for MongoDB memory storage.
133    ///
134    /// The runner:
135    /// 1. Creates the registry collection with a unique index on `version`.
136    /// 2. Detects baseline — if `memory_entries` collection exists but registry
137    ///    is empty, records v1 as already applied.
138    /// 3. Reads the maximum applied version from the registry.
139    /// 4. Returns an error if the database version exceeds the compiled-in max.
140    /// 5. Executes each unapplied step idempotently and records it.
141    ///
142    /// Several processes may migrate one database at once: every step creates its
143    /// indexes idempotently, and each version is recorded with an upsert, so a version
144    /// another process recorded first is not an error.
145    ///
146    /// **Note:** Atlas Vector Search index on the `embedding` field must be
147    /// created separately via the Atlas UI or API. The index should be named
148    /// `memory_embedding_index` with cosine similarity on the `embedding` path.
149    pub async fn migrate(&self) -> Result<()> {
150        // Step 1: Ensure registry collection has a unique index on `version`
151        self.db
152            .collection::<Document>(Self::REGISTRY_COLLECTION)
153            .create_index(
154                IndexModel::builder()
155                    .keys(doc! { "version": 1 })
156                    .options(
157                        IndexOptions::builder()
158                            .unique(true)
159                            .name("idx_migration_version_unique".to_string())
160                            .build(),
161                    )
162                    .build(),
163            )
164            .await
165            .map_err(|e| {
166                adk_core::AdkError::memory(format!("migration registry creation failed: {e}"))
167            })?;
168
169        // Step 2: Read current max applied version
170        let mut max_applied = self.read_max_applied_version().await?;
171
172        // Step 3: Baseline detection — if registry is empty but memory_entries
173        // collection already exists, record v1 as applied.
174        if max_applied == 0 {
175            let existing = self.detect_existing_tables().await?;
176            if existing && let Some(&(version, description)) = Self::MONGO_MEMORY_MIGRATIONS.first()
177            {
178                self.record_migration(version, description).await?;
179                max_applied = version;
180            }
181        }
182
183        // Step 4: Compiled-in max version
184        let max_compiled = Self::MONGO_MEMORY_MIGRATIONS.last().map(|s| s.0).unwrap_or(0);
185
186        // Step 5: Version mismatch check
187        if max_applied > max_compiled {
188            return Err(adk_core::AdkError::memory(format!(
189                "schema version mismatch: database is at v{max_applied} \
190                 but code only knows up to v{max_compiled}. \
191                 Upgrade your ADK version."
192            )));
193        }
194
195        // Step 6: Execute unapplied steps idempotently
196        for &(version, description) in Self::MONGO_MEMORY_MIGRATIONS {
197            if version <= max_applied {
198                continue;
199            }
200
201            run_mongo_memory_step(&self.db, version).await.map_err(|e| {
202                adk_core::AdkError::memory(format!(
203                    "{}",
204                    crate::migration::MigrationError {
205                        version,
206                        description: description.to_string(),
207                        cause: e.to_string(),
208                    }
209                ))
210            })?;
211
212            self.record_migration(version, description).await?;
213        }
214
215        Ok(())
216    }
217
218    /// Returns the highest applied migration version, or 0 if no registry
219    /// exists or the registry is empty.
220    pub async fn schema_version(&self) -> Result<i64> {
221        // Check if registry collection exists
222        let collections =
223            self.db.list_collection_names().await.map_err(|e| {
224                adk_core::AdkError::memory(format!("schema version query failed: {e}"))
225            })?;
226        if !collections.contains(&Self::REGISTRY_COLLECTION.to_string()) {
227            return Ok(0);
228        }
229
230        self.read_max_applied_version().await
231    }
232
233    /// Read the maximum applied version from the registry collection.
234    async fn read_max_applied_version(&self) -> Result<i64> {
235        use mongodb::options::FindOneOptions;
236
237        let registry = self.db.collection::<Document>(Self::REGISTRY_COLLECTION);
238        let opts = FindOneOptions::builder().sort(doc! { "version": -1 }).build();
239        let result = registry.find_one(doc! {}).with_options(opts).await.map_err(|e| {
240            adk_core::AdkError::memory(format!("migration registry read failed: {e}"))
241        })?;
242
243        match result {
244            Some(doc) => {
245                let version = doc.get_i64("version").unwrap_or(0);
246                Ok(version)
247            }
248            None => Ok(0),
249        }
250    }
251
252    /// Whether v1's last index exists (baseline). A first `migrate` running in another
253    /// process creates v1's indexes in order, so the collection or an earlier index
254    /// existing does not mean v1 is complete.
255    async fn detect_existing_tables(&self) -> Result<bool> {
256        let failed = |e: mongodb::error::Error| {
257            adk_core::AdkError::memory(format!("baseline detection failed: {e}"))
258        };
259        let collections = self.db.list_collection_names().await.map_err(failed)?;
260        if !collections.iter().any(|name| name == "memory_entries") {
261            return Ok(false);
262        }
263        let indexes = self
264            .db
265            .collection::<Document>("memory_entries")
266            .list_index_names()
267            .await
268            .map_err(failed)?;
269        Ok(indexes.iter().any(|name| name == "idx_memory_entries_text"))
270    }
271
272    /// Records an applied migration step unless another process recorded it first.
273    async fn record_migration(&self, version: i64, description: &str) -> Result<()> {
274        let registry = self.db.collection::<Document>(Self::REGISTRY_COLLECTION);
275        let now = BsonDateTime::from_millis(Utc::now().timestamp_millis());
276        let recorded = registry
277            .update_one(
278                doc! { "version": version },
279                doc! { "$setOnInsert": { "description": description, "applied_at": now } },
280            )
281            .upsert(true)
282            .await;
283        // The server retries an upsert that loses a race on the unique `version` index;
284        // a duplicate key that still surfaces means the version is recorded.
285        match recorded {
286            Ok(_) => Ok(()),
287            Err(e) if is_duplicate_key(&e) => Ok(()),
288            Err(e) => Err(e),
289        }
290        .map_err(|e| {
291            adk_core::AdkError::memory(format!(
292                "{}",
293                crate::migration::MigrationError {
294                    version,
295                    description: description.to_string(),
296                    cause: format!("registry record failed: {e}"),
297                }
298            ))
299        })?;
300        Ok(())
301    }
302}
303
304/// Whether `error` is a duplicate-key violation of a unique index.
305fn is_duplicate_key(error: &mongodb::error::Error) -> bool {
306    use mongodb::error::{ErrorKind, WriteFailure};
307    match &*error.kind {
308        ErrorKind::Write(WriteFailure::WriteError(write)) => write.code == 11000,
309        _ => false,
310    }
311}
312
313/// Execute a single MongoDB memory migration step by version number.
314///
315/// Each step is idempotent — re-running a step that has already been applied
316/// completes without error (MongoDB's `create_index` is a no-op if the index
317/// already exists with the same specification).
318async fn run_mongo_memory_step(db: &Database, version: i64) -> Result<()> {
319    match version {
320        1 => mongo_memory_v1(db).await,
321        2 => mongo_memory_v2(db).await,
322        3 => mongo_memory_v3(db).await,
323        _ => Err(adk_core::AdkError::memory(format!("unknown migration version: {version}"))),
324    }
325}
326
327/// V1: Create initial indexes on memory_entries collection.
328///
329/// This matches the original `migrate()` index creation logic:
330/// - Compound index on `(app_name, user_id)` for filtered queries
331/// - Text index on `content_text` field for fallback text search
332async fn mongo_memory_v1(db: &Database) -> Result<()> {
333    let collection = db.collection::<Document>("memory_entries");
334
335    // Compound index on (app_name, user_id)
336    collection
337        .create_index(
338            IndexModel::builder()
339                .keys(doc! { "app_name": 1, "user_id": 1 })
340                .options(
341                    IndexOptions::builder().name("idx_memory_entries_app_user".to_string()).build(),
342                )
343                .build(),
344        )
345        .await
346        .map_err(|e| adk_core::AdkError::memory(format!("index creation failed: {e}")))?;
347
348    // Text index on content_text for fallback search
349    collection
350        .create_index(
351            IndexModel::builder()
352                .keys(doc! { "content_text": "text" })
353                .options(
354                    IndexOptions::builder().name("idx_memory_entries_text".to_string()).build(),
355                )
356                .build(),
357        )
358        .await
359        .map_err(|e| adk_core::AdkError::memory(format!("text index creation failed: {e}")))?;
360
361    Ok(())
362}
363
364/// V2: Add compound index on `(app_name, user_id, project_id)` for project-scoped queries.
365///
366/// Existing documents without a `project_id` field are treated as `null` by
367/// MongoDB query semantics, which is the correct behavior for global entries.
368async fn mongo_memory_v2(db: &Database) -> Result<()> {
369    let collection = db.collection::<Document>("memory_entries");
370
371    collection
372        .create_index(
373            IndexModel::builder()
374                .keys(doc! { "app_name": 1, "user_id": 1, "project_id": 1 })
375                .options(
376                    IndexOptions::builder()
377                        .name("idx_memory_entries_app_user_project".to_string())
378                        .build(),
379                )
380                .build(),
381        )
382        .await
383        .map_err(|e| {
384            adk_core::AdkError::memory(format!("project_id compound index creation failed: {e}"))
385        })?;
386
387    Ok(())
388}
389
390/// V3: index `memory_id` per user, and expire entries through a TTL index on `expires_at`.
391///
392/// `expireAfterSeconds: 0` makes MongoDB delete a document once its `expires_at` date has
393/// passed; documents without the field never expire.
394async fn mongo_memory_v3(db: &Database) -> Result<()> {
395    let collection = db.collection::<Document>("memory_entries");
396    collection
397        .create_index(
398            IndexModel::builder()
399                .keys(doc! { "app_name": 1, "user_id": 1, "memory_id": 1 })
400                .options(
401                    IndexOptions::builder()
402                        .name("idx_memory_entries_memory_id".to_string())
403                        .build(),
404                )
405                .build(),
406        )
407        .await
408        .map_err(|e| adk_core::AdkError::memory(format!("memory_id index creation failed: {e}")))?;
409    collection
410        .create_index(
411            IndexModel::builder()
412                .keys(doc! { "expires_at": 1 })
413                .options(
414                    IndexOptions::builder()
415                        .name("idx_memory_entries_expires_at_ttl".to_string())
416                        .expire_after(std::time::Duration::ZERO)
417                        .build(),
418                )
419                .build(),
420        )
421        .await
422        .map_err(|e| adk_core::AdkError::memory(format!("TTL index creation failed: {e}")))?;
423    Ok(())
424}
425
426/// The filter that keeps entries live at `now`: no `expires_at`, or one after `now`.
427///
428/// Mirrors `expiry::is_expired`; `$not` also matches documents without the field.
429fn live_filter(now: chrono::DateTime<Utc>) -> Document {
430    doc! { "expires_at": { "$not": { "$lte": BsonDateTime::from_millis(now.timestamp_millis()) } } }
431}
432
433/// A stored document as a memory entry, or `None` when its content is malformed.
434fn document_entry(doc: &Document) -> Option<MemoryEntry> {
435    let content_json: serde_json::Value =
436        mongodb::bson::from_bson(doc.get("content")?.clone()).ok()?;
437    let content: adk_core::Content = serde_json::from_value(content_json).ok()?;
438    let author = doc.get_str("author").ok()?.to_string();
439    let millis = |field: &str| {
440        doc.get_datetime(field)
441            .ok()
442            .and_then(|dt| chrono::DateTime::from_timestamp_millis(dt.timestamp_millis()))
443    };
444    let mut entry = MemoryEntry::new(content, author).with_timestamp(millis("timestamp")?);
445    // Entries written before 3.0 have no memory id; their document id stands in.
446    entry.id = doc
447        .get_str("memory_id")
448        .ok()
449        .filter(|id| !id.is_empty())
450        .map(str::to_string)
451        .or_else(|| doc.get_object_id("_id").ok().map(|id| id.to_hex()));
452    entry.expires_at = millis("expires_at");
453    Some(entry)
454}
455
456#[async_trait]
457impl MemoryService for MongoMemoryService {
458    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, session_id = %session_id, entry_count = entries.len()))]
459    async fn add_session(
460        &self,
461        app_name: &str,
462        user_id: &str,
463        session_id: &str,
464        entries: Vec<MemoryEntry>,
465    ) -> Result<()> {
466        if entries.is_empty() {
467            return Ok(());
468        }
469
470        let collection = self.db.collection::<Document>("memory_entries");
471
472        // Collect texts for batch embedding
473        let texts: Vec<String> =
474            entries.iter().map(|e| crate::text::extract_text(&e.content)).collect();
475
476        let embeddings = if let Some(provider) = &self.embedding_provider {
477            let non_empty_texts: Vec<String> = texts
478                .iter()
479                .map(|t| if t.is_empty() { " ".to_string() } else { t.clone() })
480                .collect();
481            Some(provider.embed(&non_empty_texts).await.map_err(|e| {
482                adk_core::AdkError::memory(format!("embedding generation failed: {e}"))
483            })?)
484        } else {
485            None
486        };
487
488        let now = Utc::now();
489        let scope = doc! {
490            "app_name": app_name,
491            "user_id": user_id,
492            "session_id": session_id,
493            "project_id": mongodb::bson::Bson::Null,
494        };
495        let mut documents = Vec::with_capacity(entries.len());
496        for (i, entry) in entries.into_iter().enumerate() {
497            let embedding = embeddings.as_ref().map(|embs| embs[i].as_slice());
498            documents.push(self.document(&scope, entry, embedding, now)?);
499        }
500
501        collection
502            .insert_many(documents)
503            .await
504            .map_err(|e| adk_core::AdkError::memory(format!("add_session failed: {e}")))?;
505
506        Ok(())
507    }
508
509    fn supports_project_scoping(&self) -> bool {
510        true
511    }
512
513    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, session_id = %session_id, project_id = %project_id, entry_count = entries.len()))]
514    async fn add_session_to_project(
515        &self,
516        app_name: &str,
517        user_id: &str,
518        session_id: &str,
519        project_id: &str,
520        entries: Vec<MemoryEntry>,
521    ) -> Result<()> {
522        validate_project_id(project_id)?;
523
524        if entries.is_empty() {
525            return Ok(());
526        }
527
528        let collection = self.db.collection::<Document>("memory_entries");
529
530        // Collect texts for batch embedding
531        let texts: Vec<String> =
532            entries.iter().map(|e| crate::text::extract_text(&e.content)).collect();
533
534        let embeddings = if let Some(provider) = &self.embedding_provider {
535            let non_empty_texts: Vec<String> = texts
536                .iter()
537                .map(|t| if t.is_empty() { " ".to_string() } else { t.clone() })
538                .collect();
539            Some(provider.embed(&non_empty_texts).await.map_err(|e| {
540                adk_core::AdkError::memory(format!("embedding generation failed: {e}"))
541            })?)
542        } else {
543            None
544        };
545
546        let now = Utc::now();
547        let scope = doc! {
548            "app_name": app_name,
549            "user_id": user_id,
550            "session_id": session_id,
551            "project_id": project_id,
552        };
553        let mut documents = Vec::with_capacity(entries.len());
554        for (i, entry) in entries.into_iter().enumerate() {
555            let embedding = embeddings.as_ref().map(|embs| embs[i].as_slice());
556            documents.push(self.document(&scope, entry, embedding, now)?);
557        }
558
559        collection.insert_many(documents).await.map_err(|e| {
560            adk_core::AdkError::memory(format!("add_session_to_project failed: {e}"))
561        })?;
562
563        Ok(())
564    }
565
566    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, project_id = %project_id))]
567    async fn add_entry_to_project(
568        &self,
569        app_name: &str,
570        user_id: &str,
571        project_id: &str,
572        entry: MemoryEntry,
573    ) -> Result<()> {
574        validate_project_id(project_id)?;
575
576        let collection = self.db.collection::<Document>("memory_entries");
577
578        let content_text = crate::text::extract_text(&entry.content);
579        let embedding = match &self.embedding_provider {
580            Some(provider) => {
581                let text_for_embed =
582                    if content_text.is_empty() { " ".to_string() } else { content_text.clone() };
583                let mut embeddings = provider.embed(&[text_for_embed]).await.map_err(|e| {
584                    adk_core::AdkError::memory(format!("embedding generation failed: {e}"))
585                })?;
586                Some(embeddings.swap_remove(0))
587            }
588            None => None,
589        };
590        let scope = doc! { "app_name": app_name, "user_id": user_id, "project_id": project_id };
591        let document = self.document(&scope, entry, embedding.as_deref(), Utc::now())?;
592
593        collection
594            .insert_one(document)
595            .await
596            .map_err(|e| adk_core::AdkError::memory(format!("add_entry_to_project failed: {e}")))?;
597
598        Ok(())
599    }
600
601    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id))]
602    async fn search(&self, req: SearchRequest) -> Result<SearchResponse> {
603        let collection = self.db.collection::<Document>("memory_entries");
604        let limit = req.limit.unwrap_or(10) as i64;
605
606        let docs = if let Some(ref provider) = self.embedding_provider {
607            // Vector search via $vectorSearch aggregation stage
608            let query_embedding = provider
609                .embed(std::slice::from_ref(&req.query))
610                .await
611                .map_err(|e| adk_core::AdkError::memory(format!("query embedding failed: {e}")))?;
612            let query_vec: Vec<mongodb::bson::Bson> =
613                query_embedding[0].iter().map(|&v| mongodb::bson::Bson::Double(v as f64)).collect();
614
615            let mut match_filter = doc! {
616                "app_name": &req.app_name,
617                "user_id": &req.user_id,
618            };
619            match &req.project_id {
620                None => {
621                    match_filter.insert("project_id", mongodb::bson::Bson::Null);
622                }
623                Some(id) => {
624                    match_filter.insert(
625                        "$or",
626                        vec![
627                            doc! { "project_id": mongodb::bson::Bson::Null },
628                            doc! { "project_id": id },
629                        ],
630                    );
631                }
632            }
633
634            let match_filter = doc! { "$and": [match_filter, live_filter(Utc::now())] };
635            let pipeline = vec![
636                doc! {
637                    "$vectorSearch": {
638                        "index": "memory_embedding_index",
639                        "path": "embedding",
640                        "queryVector": &query_vec,
641                        "numCandidates": 100,
642                        "limit": limit,
643                    }
644                },
645                doc! {
646                    "$match": match_filter,
647                },
648            ];
649
650            let mut cursor = collection.aggregate(pipeline).await.map_err(|e| {
651                let msg = e.to_string();
652                if msg.contains("PlanExecutor") || msg.contains("$vectorSearch") {
653                    adk_core::AdkError::memory(
654                        "vector search index not available: Atlas Vector Search index \
655                         'memory_embedding_index' must be created via Atlas UI/API"
656                            .to_string(),
657                    )
658                } else {
659                    adk_core::AdkError::memory(format!("search failed: {e}"))
660                }
661            })?;
662
663            let mut results = Vec::new();
664            while cursor
665                .advance()
666                .await
667                .map_err(|e| adk_core::AdkError::memory(format!("search cursor failed: {e}")))?
668            {
669                let doc = cursor.deserialize_current().map_err(|e| {
670                    adk_core::AdkError::memory(format!("search deserialization failed: {e}"))
671                })?;
672                results.push(doc);
673            }
674            results
675        } else {
676            // Text search fallback
677            let mut filter = doc! {
678                "app_name": &req.app_name,
679                "user_id": &req.user_id,
680                "$text": { "$search": &req.query },
681            };
682            match &req.project_id {
683                None => {
684                    filter.insert("project_id", mongodb::bson::Bson::Null);
685                }
686                Some(id) => {
687                    filter.insert(
688                        "$or",
689                        vec![
690                            doc! { "project_id": mongodb::bson::Bson::Null },
691                            doc! { "project_id": id.as_str() },
692                        ],
693                    );
694                }
695            }
696
697            filter.insert(
698                "expires_at",
699                live_filter(Utc::now()).get("expires_at").cloned().unwrap_or_default(),
700            );
701            let mut cursor = collection
702                .find(filter)
703                .sort(doc! { "score": { "$meta": "textScore" } })
704                .limit(limit)
705                .await
706                .map_err(|e| adk_core::AdkError::memory(format!("search failed: {e}")))?;
707
708            let mut results = Vec::new();
709            while cursor
710                .advance()
711                .await
712                .map_err(|e| adk_core::AdkError::memory(format!("search cursor failed: {e}")))?
713            {
714                let doc = cursor.deserialize_current().map_err(|e| {
715                    adk_core::AdkError::memory(format!("search deserialization failed: {e}"))
716                })?;
717                results.push(doc);
718            }
719            results
720        };
721
722        let memories = docs.iter().filter_map(document_entry).collect();
723
724        Ok(SearchResponse { memories })
725    }
726
727    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, project_id = %project_id))]
728    async fn delete_entries_in_project(
729        &self,
730        app_name: &str,
731        user_id: &str,
732        project_id: &str,
733        query: &str,
734    ) -> Result<u64> {
735        validate_project_id(project_id)?;
736
737        let collection = self.db.collection::<Document>("memory_entries");
738        let filter = doc! {
739            "app_name": app_name,
740            "user_id": user_id,
741            "project_id": project_id,
742            "$text": { "$search": query },
743        };
744        let result = collection.delete_many(filter).await.map_err(|e| {
745            adk_core::AdkError::memory(format!("delete_entries_in_project failed: {e}"))
746        })?;
747        Ok(result.deleted_count)
748    }
749
750    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, project_id = %project_id))]
751    async fn delete_project(&self, app_name: &str, user_id: &str, project_id: &str) -> Result<u64> {
752        validate_project_id(project_id)?;
753
754        let collection = self.db.collection::<Document>("memory_entries");
755        let filter = doc! {
756            "app_name": app_name,
757            "user_id": user_id,
758            "project_id": project_id,
759        };
760        let result = collection
761            .delete_many(filter)
762            .await
763            .map_err(|e| adk_core::AdkError::memory(format!("delete_project failed: {e}")))?;
764        Ok(result.deleted_count)
765    }
766
767    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
768    async fn export_user(&self, app_name: &str, user_id: &str) -> Result<Vec<UserMemory>> {
769        let failed = |e: mongodb::error::Error| {
770            adk_core::AdkError::memory(format!("export_user failed: {e}"))
771        };
772        let mut cursor = self
773            .db
774            .collection::<Document>("memory_entries")
775            .find(doc! { "app_name": app_name, "user_id": user_id })
776            .sort(doc! { "timestamp": 1, "_id": 1 })
777            .await
778            .map_err(failed)?;
779        let mut documents = Vec::new();
780        while cursor.advance().await.map_err(failed)? {
781            documents.push(cursor.deserialize_current().map_err(failed)?);
782        }
783        documents
784            .iter()
785            .map(|document| {
786                let corrupt =
787                    |field: &str| adk_core::AdkError::memory(format!("stored {field} is corrupt"));
788                Ok(UserMemory {
789                    entry: document_entry(document).ok_or_else(|| corrupt("entry"))?,
790                    session_id: document.get_str("session_id").ok().map(str::to_string),
791                    project_id: document.get_str("project_id").ok().map(str::to_string),
792                })
793            })
794            .collect()
795    }
796
797    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
798    async fn delete_user(&self, app_name: &str, user_id: &str) -> Result<()> {
799        let collection = self.db.collection::<Document>("memory_entries");
800        collection
801            .delete_many(doc! { "app_name": app_name, "user_id": user_id })
802            .await
803            .map_err(|e| adk_core::AdkError::memory(format!("delete_user failed: {e}")))?;
804        Ok(())
805    }
806
807    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, session_id = %session_id))]
808    async fn delete_session(&self, app_name: &str, user_id: &str, session_id: &str) -> Result<()> {
809        let collection = self.db.collection::<Document>("memory_entries");
810        collection
811            .delete_many(doc! {
812                "app_name": app_name,
813                "user_id": user_id,
814                "session_id": session_id,
815            })
816            .await
817            .map_err(|e| adk_core::AdkError::memory(format!("delete_session failed: {e}")))?;
818        Ok(())
819    }
820
821    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
822    async fn delete_memory(&self, app_name: &str, user_id: &str, memory_id: &str) -> Result<u64> {
823        let collection = self.db.collection::<Document>("memory_entries");
824        let mut filter = doc! { "app_name": app_name, "user_id": user_id, "memory_id": memory_id };
825        // An entry written before 3.0 is addressed by its document id.
826        if let Ok(object_id) = mongodb::bson::oid::ObjectId::parse_str(memory_id) {
827            filter = doc! {
828                "app_name": app_name,
829                "user_id": user_id,
830                "$or": [{ "memory_id": memory_id }, { "_id": object_id, "memory_id": { "$exists": false } }],
831            };
832        }
833        let result = collection
834            .delete_many(filter)
835            .await
836            .map_err(|e| adk_core::AdkError::memory(format!("delete_memory failed: {e}")))?;
837        Ok(result.deleted_count)
838    }
839
840    #[instrument(skip_all)]
841    async fn purge_expired(&self) -> Result<u64> {
842        let now = BsonDateTime::from_millis(Utc::now().timestamp_millis());
843        let result = self
844            .db
845            .collection::<Document>("memory_entries")
846            .delete_many(doc! { "expires_at": { "$lte": now } })
847            .await
848            .map_err(|e| adk_core::AdkError::memory(format!("purge_expired failed: {e}")))?;
849        Ok(result.deleted_count)
850    }
851
852    #[instrument(skip_all)]
853    async fn health_check(&self) -> Result<()> {
854        self.db
855            .run_command(doc! { "ping": 1 })
856            .await
857            .map_err(|e| adk_core::AdkError::memory(format!("health check failed: {e}")))?;
858        Ok(())
859    }
860}