Skip to main content

adk_memory/
postgres.rs

1//! PostgreSQL memory service implementation with pgvector.
2//!
3//! Provides [`PostgresMemoryService`], a `MemoryService` backed by PostgreSQL
4//! with pgvector cosine similarity search and tsvector keyword fallback.
5//!
6//! ## High-dimensional embeddings (>2000 dims)
7//!
8//! pgvector limits both HNSW and IVFFlat indexes to 2000 dimensions on
9//! the `vector` type. When the embedding provider reports more than 2000
10//! dimensions (e.g. Gemini `embedding-001` at 3072), the service
11//! automatically uses `halfvec` expression indexing — storing full-precision
12//! `vector(N)` data but indexing and querying via `halfvec(N)` casts.
13//! `halfvec` supports HNSW up to 4000 dimensions with negligible recall
14//! loss and 50% storage savings on the index.
15
16use crate::embedding::EmbeddingProvider;
17use crate::migration::pg_runner;
18use crate::service::*;
19use adk_core::Result;
20use async_trait::async_trait;
21use chrono::Utc;
22use sqlx::{PgPool, Row};
23use std::sync::Arc;
24use std::time::Duration;
25use tracing::instrument;
26
27/// Maximum dimensions for a direct `vector` index in pgvector.
28/// Beyond this, we use `halfvec` expression indexing.
29const PGVECTOR_MAX_DIRECT_INDEX_DIMS: usize = 2000;
30
31/// Maximum dimensions for a `halfvec` index in pgvector.
32const PGVECTOR_MAX_HALFVEC_INDEX_DIMS: usize = 4000;
33
34/// pgvector index algorithm for the embedding column.
35///
36/// Defaults to [`Hnsw`](VectorIndexType::Hnsw). When the embedding
37/// dimension exceeds 2000, the index is automatically built using
38/// `halfvec` expression indexing (supports up to 4000 dimensions).
39///
40/// # Example
41///
42/// ```rust,ignore
43/// use adk_memory::{PostgresMemoryService, VectorIndexType};
44///
45/// let service = PostgresMemoryService::builder("postgres://...", None)
46///     .vector_index(VectorIndexType::IvfFlat { lists: 100 })
47///     .build()
48///     .await?;
49/// ```
50#[derive(Debug, Clone)]
51pub enum VectorIndexType {
52    /// HNSW (Hierarchical Navigable Small World) index.
53    ///
54    /// Supports up to 2000 dimensions directly, or up to 4000 dimensions
55    /// via automatic `halfvec` expression indexing. Recommended default.
56    Hnsw {
57        /// Maximum number of connections per node (default: 16).
58        m: u32,
59        /// Size of the dynamic candidate list during construction (default: 64).
60        ef_construction: u32,
61    },
62    /// IVFFlat (Inverted File with Flat compression) index.
63    ///
64    /// Supports up to 2000 dimensions directly, or up to 4000 dimensions
65    /// via automatic `halfvec` expression indexing. Faster index builds
66    /// than HNSW but lower recall.
67    IvfFlat {
68        /// Number of inverted lists (default: 100).
69        lists: u32,
70    },
71    /// Skip vector index creation entirely.
72    ///
73    /// Queries use exact sequential scan. Fine for small datasets
74    /// (<100k rows) or when you manage indexes manually.
75    None,
76}
77
78impl Default for VectorIndexType {
79    fn default() -> Self {
80        Self::Hnsw { m: 16, ef_construction: 64 }
81    }
82}
83
84/// PostgreSQL-backed memory service with optional vector search.
85///
86/// When an [`EmbeddingProvider`] is supplied, entries are stored with
87/// vector embeddings and searched via pgvector cosine similarity.
88/// Without a provider, search falls back to PostgreSQL full-text
89/// search (`tsvector`/`tsquery`).
90///
91/// For embeddings with more than 2000 dimensions, the service
92/// automatically uses `halfvec` expression indexing and query casts.
93///
94/// # Example
95///
96/// ```rust,ignore
97/// use adk_memory::PostgresMemoryService;
98///
99/// let service = PostgresMemoryService::new(
100///     "postgres://user:pass@localhost/mydb",
101///     None,
102/// ).await?;
103/// service.migrate().await?;
104/// ```
105pub struct PostgresMemoryService {
106    pool: PgPool,
107    embedding_provider: Option<Arc<dyn EmbeddingProvider>>,
108    vector_index: VectorIndexType,
109    /// True when dims > 2000 and we use halfvec expression indexing.
110    use_halfvec: bool,
111    default_ttl: Option<Duration>,
112}
113
114/// Builder for [`PostgresMemoryService`] with configurable vector index.
115///
116/// # Example
117///
118/// ```rust,ignore
119/// use adk_memory::{PostgresMemoryService, VectorIndexType};
120///
121/// // HNSW (default) — auto-uses halfvec for >2000 dims
122/// let service = PostgresMemoryService::builder("postgres://...", None)
123///     .build()
124///     .await?;
125///
126/// // IVFFlat with custom lists
127/// let service = PostgresMemoryService::builder("postgres://...", None)
128///     .vector_index(VectorIndexType::IvfFlat { lists: 200 })
129///     .build()
130///     .await?;
131/// ```
132pub struct PostgresMemoryServiceBuilder {
133    database_url: String,
134    embedding_provider: Option<Arc<dyn EmbeddingProvider>>,
135    vector_index: VectorIndexType,
136}
137
138impl PostgresMemoryServiceBuilder {
139    /// Set the vector index algorithm used during migration.
140    pub fn vector_index(mut self, index: VectorIndexType) -> Self {
141        self.vector_index = index;
142        self
143    }
144
145    /// Connect and build the service.
146    pub async fn build(self) -> Result<PostgresMemoryService> {
147        let pool = PgPool::connect(&self.database_url).await.map_err(|e| {
148            adk_core::AdkError::memory(format!("memory database connection failed: {e}"))
149        })?;
150        let use_halfvec = needs_halfvec(&self.embedding_provider);
151        Ok(PostgresMemoryService {
152            pool,
153            embedding_provider: self.embedding_provider,
154            vector_index: self.vector_index,
155            use_halfvec,
156            default_ttl: None,
157        })
158    }
159}
160
161/// Returns true when the provider's dimensions exceed the direct index limit.
162fn needs_halfvec(provider: &Option<Arc<dyn EmbeddingProvider>>) -> bool {
163    provider.as_ref().is_some_and(|p| p.dimensions() > PGVECTOR_MAX_DIRECT_INDEX_DIMS)
164}
165
166impl PostgresMemoryService {
167    /// Connect to PostgreSQL for memory storage.
168    ///
169    /// Uses HNSW vector indexing by default. Automatically switches to
170    /// `halfvec` expression indexing when the embedding provider reports
171    /// more than 2000 dimensions.
172    pub async fn new(
173        database_url: &str,
174        embedding_provider: Option<Arc<dyn EmbeddingProvider>>,
175    ) -> Result<Self> {
176        let pool = PgPool::connect(database_url).await.map_err(|e| {
177            adk_core::AdkError::memory(format!("memory database connection failed: {e}"))
178        })?;
179        let use_halfvec = needs_halfvec(&embedding_provider);
180        Ok(Self {
181            pool,
182            embedding_provider,
183            vector_index: VectorIndexType::default(),
184            use_halfvec,
185            default_ttl: None,
186        })
187    }
188
189    /// Create a builder for fine-grained configuration.
190    ///
191    /// # Example
192    ///
193    /// ```rust,ignore
194    /// let service = PostgresMemoryService::builder("postgres://...", Some(provider))
195    ///     .vector_index(VectorIndexType::Hnsw { m: 32, ef_construction: 128 })
196    ///     .build()
197    ///     .await?;
198    /// ```
199    pub fn builder(
200        database_url: impl Into<String>,
201        embedding_provider: Option<Arc<dyn EmbeddingProvider>>,
202    ) -> PostgresMemoryServiceBuilder {
203        PostgresMemoryServiceBuilder {
204            database_url: database_url.into(),
205            embedding_provider,
206            vector_index: VectorIndexType::default(),
207        }
208    }
209
210    /// Create a memory service from an existing connection pool.
211    pub fn from_pool(pool: PgPool, embedding_provider: Option<Arc<dyn EmbeddingProvider>>) -> Self {
212        let use_halfvec = needs_halfvec(&embedding_provider);
213        Self {
214            pool,
215            embedding_provider,
216            vector_index: VectorIndexType::default(),
217            use_halfvec,
218            default_ttl: None,
219        }
220    }
221
222    /// Create a memory service from an existing pool with a specific index type.
223    pub fn from_pool_with_index(
224        pool: PgPool,
225        embedding_provider: Option<Arc<dyn EmbeddingProvider>>,
226        vector_index: VectorIndexType,
227    ) -> Self {
228        let use_halfvec = needs_halfvec(&embedding_provider);
229        Self { pool, embedding_provider, vector_index, use_halfvec, default_ttl: None }
230    }
231
232    /// Expires each entry written without an expiry `ttl` after it is written.
233    ///
234    /// # Example
235    ///
236    /// ```rust,ignore
237    /// use adk_memory::PostgresMemoryService;
238    /// use std::time::Duration;
239    ///
240    /// let service = PostgresMemoryService::new("postgres://...", None)
241    ///     .await?
242    ///     .with_default_ttl(Duration::from_secs(30 * 24 * 3600));
243    /// ```
244    pub fn with_default_ttl(mut self, ttl: Duration) -> Self {
245        self.default_ttl = Some(ttl);
246        self
247    }
248
249    /// Embeds `entries` in one batch when a provider is set, then inserts them in one
250    /// transaction, each stamped with its id and expiry.
251    async fn insert(
252        &self,
253        app_name: &str,
254        user_id: &str,
255        session_id: &str,
256        project_id: Option<&str>,
257        entries: Vec<MemoryEntry>,
258    ) -> Result<()> {
259        if entries.is_empty() {
260            return Ok(());
261        }
262        let now = Utc::now();
263        let texts: Vec<String> =
264            entries.iter().map(|e| crate::text::extract_text(&e.content)).collect();
265        let mut embeddings = match &self.embedding_provider {
266            Some(provider) => {
267                let non_empty: Vec<String> = texts
268                    .iter()
269                    .map(|t| if t.is_empty() { " ".to_string() } else { t.clone() })
270                    .collect();
271                let embeddings = provider.embed(&non_empty).await.map_err(|e| {
272                    adk_core::AdkError::memory(format!("embedding generation failed: {e}"))
273                })?;
274                if embeddings.len() != entries.len() {
275                    return Err(adk_core::AdkError::memory(format!(
276                        "embedding provider returned {} embeddings for {} entries",
277                        embeddings.len(),
278                        entries.len()
279                    )));
280                }
281                embeddings.into_iter().map(|e| Some(pgvector::Vector::from(e))).collect()
282            }
283            None => vec![None; entries.len()],
284        }
285        .into_iter();
286        let mut tx = self
287            .pool
288            .begin()
289            .await
290            .map_err(|e| adk_core::AdkError::memory(format!("insert failed: {e}")))?;
291        for (entry, text) in entries.into_iter().zip(&texts) {
292            let entry = crate::expiry::stamp(entry, self.default_ttl, now);
293            let content_json = serde_json::to_value(&entry.content)
294                .map_err(|e| adk_core::AdkError::memory(format!("serialization failed: {e}")))?;
295            sqlx::query(
296                r#"
297                INSERT INTO memory_entries
298                    (app_name, user_id, session_id, content, author, timestamp, embedding,
299                     search_text, project_id, memory_id, expires_at)
300                VALUES
301                    ($1, $2, $3, $4, $5, $6, $7, to_tsvector('simple', $8), $9, $10, $11)
302                "#,
303            )
304            .bind(app_name)
305            .bind(user_id)
306            .bind(session_id)
307            .bind(&content_json)
308            .bind(&entry.author)
309            .bind(entry.timestamp)
310            .bind(embeddings.next().flatten())
311            .bind(text)
312            .bind(project_id)
313            .bind(&entry.id)
314            .bind(entry.expires_at)
315            .execute(&mut *tx)
316            .await
317            .map_err(|e| adk_core::AdkError::memory(format!("insert failed: {e}")))?;
318        }
319        tx.commit().await.map_err(|e| adk_core::AdkError::memory(format!("insert failed: {e}")))
320    }
321
322    /// The registry table used to track applied migration versions.
323    const REGISTRY_TABLE: &'static str = "_adk_memory_migrations";
324
325    /// V2 migration: add project_id column and composite index.
326    const V2_MIGRATION_SQL: &'static str = "\
327        ALTER TABLE memory_entries ADD COLUMN IF NOT EXISTS project_id TEXT;\
328        CREATE INDEX IF NOT EXISTS idx_memory_app_user_project \
329            ON memory_entries(app_name, user_id, project_id);";
330
331    /// V3 migration: memory ids and expiry, with ids backfilled from the row id.
332    const V3_MIGRATION_SQL: &'static str = "\
333        ALTER TABLE memory_entries ADD COLUMN IF NOT EXISTS memory_id TEXT;\
334        ALTER TABLE memory_entries ADD COLUMN IF NOT EXISTS expires_at TIMESTAMPTZ;\
335        UPDATE memory_entries SET memory_id = id::text WHERE memory_id IS NULL;\
336        CREATE INDEX IF NOT EXISTS idx_memory_app_user_memory_id \
337            ON memory_entries(app_name, user_id, memory_id);\
338        CREATE INDEX IF NOT EXISTS idx_memory_expires_at \
339            ON memory_entries(expires_at) WHERE expires_at IS NOT NULL;";
340
341    /// Advisory lock key that [`migrate`](Self::migrate) holds while it runs.
342    ///
343    /// Concurrent instances take this `pg_advisory_lock` key so only one migrates at a
344    /// time. The value is an FNV-1a hash of the registry table name, and `pg_locks` shows
345    /// it with the high 32 bits in `classid` and the low 32 bits in `objid`.
346    pub const ADVISORY_LOCK_KEY: i64 = {
347        let bytes = Self::REGISTRY_TABLE.as_bytes();
348        let mut hash: u64 = 0xcbf29ce484222325;
349        let mut i = 0;
350        while i < bytes.len() {
351            hash ^= bytes[i] as u64;
352            hash = hash.wrapping_mul(0x100000001b3);
353            i += 1;
354        }
355        hash as i64
356    };
357
358    /// Build the v1 migration SQL dynamically based on embedding dimensions
359    /// and vector index configuration.
360    ///
361    /// The SQL creates the pgvector extension, `memory_entries` table with
362    /// vector and tsvector columns, and all required indexes.
363    fn build_v1_migration_sql(&self) -> Result<String> {
364        let dims = self.embedding_provider.as_ref().map(|p| p.dimensions()).unwrap_or(1536);
365
366        if self.use_halfvec && dims > PGVECTOR_MAX_HALFVEC_INDEX_DIMS {
367            return Err(adk_core::AdkError::memory(format!(
368                "embedding dimension {dims} exceeds pgvector halfvec index limit of \
369                 {PGVECTOR_MAX_HALFVEC_INDEX_DIMS}. Reduce dimensions in your embedding provider \
370                 or use VectorIndexType::None for exact search."
371            )));
372        }
373
374        let mut sql = String::new();
375
376        // pgvector extension
377        sql.push_str("CREATE EXTENSION IF NOT EXISTS vector;\n");
378
379        // Main table
380        sql.push_str(&format!(
381            "CREATE TABLE IF NOT EXISTS memory_entries (\
382                id UUID PRIMARY KEY DEFAULT gen_random_uuid(), \
383                app_name TEXT NOT NULL, \
384                user_id TEXT NOT NULL, \
385                session_id TEXT NOT NULL, \
386                content JSONB NOT NULL, \
387                author TEXT NOT NULL, \
388                timestamp TIMESTAMPTZ NOT NULL, \
389                embedding vector({dims}), \
390                search_text TSVECTOR\
391            );\n"
392        ));
393
394        // Composite index on app_name + user_id
395        sql.push_str(
396            "CREATE INDEX IF NOT EXISTS idx_memory_app_user \
397             ON memory_entries(app_name, user_id);\n",
398        );
399
400        // Vector index (depends on index type and halfvec)
401        match &self.vector_index {
402            VectorIndexType::Hnsw { m, ef_construction } => {
403                if self.use_halfvec {
404                    sql.push_str(&format!(
405                        "CREATE INDEX IF NOT EXISTS idx_memory_embedding \
406                         ON memory_entries USING hnsw ((embedding::halfvec({dims})) halfvec_cosine_ops) \
407                         WITH (m = {m}, ef_construction = {ef_construction});\n"
408                    ));
409                } else {
410                    sql.push_str(&format!(
411                        "CREATE INDEX IF NOT EXISTS idx_memory_embedding \
412                         ON memory_entries USING hnsw (embedding vector_cosine_ops) \
413                         WITH (m = {m}, ef_construction = {ef_construction});\n"
414                    ));
415                }
416            }
417            VectorIndexType::IvfFlat { lists } => {
418                if self.use_halfvec {
419                    sql.push_str(&format!(
420                        "CREATE INDEX IF NOT EXISTS idx_memory_embedding \
421                         ON memory_entries USING ivfflat ((embedding::halfvec({dims})) halfvec_cosine_ops) \
422                         WITH (lists = {lists});\n"
423                    ));
424                } else {
425                    sql.push_str(&format!(
426                        "CREATE INDEX IF NOT EXISTS idx_memory_embedding \
427                         ON memory_entries USING ivfflat (embedding vector_cosine_ops) \
428                         WITH (lists = {lists});\n"
429                    ));
430                }
431            }
432            VectorIndexType::None => {}
433        }
434
435        // GIN index on tsvector for full-text search
436        sql.push_str(
437            "CREATE INDEX IF NOT EXISTS idx_memory_search_text \
438             ON memory_entries USING gin(search_text);\n",
439        );
440
441        Ok(sql)
442    }
443
444    /// Create the pgvector extension, `memory_entries` table, and indexes.
445    ///
446    /// The vector column uses the embedding provider's `dimensions()` value.
447    /// If no provider is configured, defaults to `vector(1536)`.
448    ///
449    /// When dimensions exceed 2000, the index is built using `halfvec`
450    /// expression indexing (`(embedding::halfvec(N))`) which supports
451    /// up to 4000 dimensions.
452    ///
453    /// Migrations are protected by a PostgreSQL advisory lock to prevent
454    /// concurrent migration races from multiple application instances. The
455    /// lock, every migration statement, and the unlock run on one connection,
456    /// which is closed afterwards instead of returning to the pool.
457    pub async fn migrate(&self) -> Result<()> {
458        // Build the v1 SQL dynamically (parameterized by dims + index type)
459        let v1_sql = self.build_v1_migration_sql()?;
460        let v2_sql = Self::V2_MIGRATION_SQL;
461
462        let steps: &[(i64, &str, &str)] = &[
463            (1, "create memory_entries table with vector and tsvector columns", &v1_sql),
464            (2, "add project_id column and composite index", v2_sql),
465            (3, "add memory_id and expires_at columns", Self::V3_MIGRATION_SQL),
466        ];
467
468        let mut conn =
469            self.pool.acquire().await.map_err(|e| {
470                adk_core::AdkError::memory(format!("database connection failed: {e}"))
471            })?;
472        // A session-level advisory lock belongs to this connection. Closing it on
473        // drop releases the lock even when this future is cancelled, rather than
474        // leaving it held by an idle pooled connection.
475        conn.close_on_drop();
476
477        sqlx::query("SELECT pg_advisory_lock($1)")
478            .bind(Self::ADVISORY_LOCK_KEY)
479            .execute(&mut *conn)
480            .await
481            .map_err(|e| {
482                adk_core::AdkError::memory(format!("advisory lock acquisition failed: {e}"))
483            })?;
484
485        let result = pg_runner::run_sql_migrations_on_connection(
486            &mut conn,
487            Self::REGISTRY_TABLE,
488            steps,
489            |conn| {
490                Box::pin(async move {
491                    let row = sqlx::query(
492                        "SELECT EXISTS(\
493                             SELECT 1 FROM information_schema.tables \
494                             WHERE table_schema = current_schema() \
495                               AND table_name = 'memory_entries'\
496                         ) AS exists_flag",
497                    )
498                    .fetch_one(conn)
499                    .await
500                    .map_err(|e| {
501                        adk_core::AdkError::memory(format!("baseline detection failed: {e}"))
502                    })?;
503                    let exists: bool = row.try_get("exists_flag").unwrap_or(false);
504                    Ok(exists)
505                })
506            },
507        )
508        .await;
509
510        // Released explicitly so the next instance proceeds without waiting for
511        // the connection to close; closing the connection releases it regardless.
512        let _ = sqlx::query("SELECT pg_advisory_unlock($1)")
513            .bind(Self::ADVISORY_LOCK_KEY)
514            .execute(&mut *conn)
515            .await;
516
517        result
518    }
519
520    /// Returns the highest applied migration version, or 0 if no registry
521    /// exists or the registry is empty.
522    ///
523    /// # Errors
524    ///
525    /// Returns an error when the registry cannot be read for any reason other
526    /// than the table being absent, such as a lost connection or a missing
527    /// privilege.
528    pub async fn schema_version(&self) -> Result<i64> {
529        pg_runner::sql_schema_version(&self.pool, Self::REGISTRY_TABLE).await
530    }
531}
532
533#[async_trait]
534impl MemoryService for PostgresMemoryService {
535    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, session_id = %session_id, entry_count = entries.len()))]
536    async fn add_session(
537        &self,
538        app_name: &str,
539        user_id: &str,
540        session_id: &str,
541        entries: Vec<MemoryEntry>,
542    ) -> Result<()> {
543        self.insert(app_name, user_id, session_id, None, entries).await
544    }
545
546    #[instrument(skip_all, fields(app_name = %req.app_name, user_id = %req.user_id))]
547    async fn search(&self, req: SearchRequest) -> Result<SearchResponse> {
548        let limit = req.limit.unwrap_or(10) as i64;
549        // Mirrors `expiry::is_expired`: an entry is live while `expires_at > now`.
550        let now = Utc::now();
551
552        let rows = if let Some(ref provider) = self.embedding_provider {
553            // Vector cosine similarity search
554            let query_embedding = provider
555                .embed(std::slice::from_ref(&req.query))
556                .await
557                .map_err(|e| adk_core::AdkError::memory(format!("query embedding failed: {e}")))?;
558            let query_vec =
559                pgvector::Vector::from(query_embedding.into_iter().next().ok_or_else(|| {
560                    adk_core::AdkError::memory(
561                        "embedding provider returned empty result".to_string(),
562                    )
563                })?);
564
565            if self.use_halfvec {
566                // Cast both sides to halfvec so the expression index is used
567                let dims = provider.dimensions();
568                match &req.project_id {
569                    None => {
570                        let sql = format!(
571                            r#"
572                            SELECT memory_id, content, author, timestamp, expires_at,
573                                   (embedding::halfvec({dims}) <=> $3::halfvec({dims})) AS distance
574                            FROM memory_entries
575                            WHERE app_name = $1 AND user_id = $2 AND embedding IS NOT NULL
576                              AND project_id IS NULL
577                              AND (expires_at IS NULL OR expires_at > $5)
578                            ORDER BY embedding::halfvec({dims}) <=> $3::halfvec({dims})
579                            LIMIT $4
580                            "#
581                        );
582                        // Only the validated numeric embedding dimension changes SQL structure.
583                        sqlx::query(sqlx::AssertSqlSafe(sql))
584                            .bind(&req.app_name)
585                            .bind(&req.user_id)
586                            .bind(&query_vec)
587                            .bind(limit)
588                            .bind(now)
589                            .fetch_all(&self.pool)
590                            .await
591                            .map_err(|e| {
592                                adk_core::AdkError::memory(format!("search failed: {e}"))
593                            })?
594                    }
595                    Some(pid) => {
596                        let sql = format!(
597                            r#"
598                            SELECT memory_id, content, author, timestamp, expires_at,
599                                   (embedding::halfvec({dims}) <=> $3::halfvec({dims})) AS distance
600                            FROM memory_entries
601                            WHERE app_name = $1 AND user_id = $2 AND embedding IS NOT NULL
602                              AND (project_id IS NULL OR project_id = $5)
603                              AND (expires_at IS NULL OR expires_at > $6)
604                            ORDER BY embedding::halfvec({dims}) <=> $3::halfvec({dims})
605                            LIMIT $4
606                            "#
607                        );
608                        // Only the validated numeric embedding dimension changes SQL structure.
609                        sqlx::query(sqlx::AssertSqlSafe(sql))
610                            .bind(&req.app_name)
611                            .bind(&req.user_id)
612                            .bind(&query_vec)
613                            .bind(limit)
614                            .bind(pid)
615                            .bind(now)
616                            .fetch_all(&self.pool)
617                            .await
618                            .map_err(|e| {
619                                adk_core::AdkError::memory(format!("search failed: {e}"))
620                            })?
621                    }
622                }
623            } else {
624                match &req.project_id {
625                    None => sqlx::query(
626                        r#"
627                            SELECT memory_id, content, author, timestamp, expires_at, (embedding <=> $3) AS distance
628                            FROM memory_entries
629                            WHERE app_name = $1 AND user_id = $2 AND embedding IS NOT NULL
630                              AND project_id IS NULL
631                              AND (expires_at IS NULL OR expires_at > $5)
632                            ORDER BY embedding <=> $3
633                            LIMIT $4
634                            "#,
635                    )
636                    .bind(&req.app_name)
637                    .bind(&req.user_id)
638                    .bind(&query_vec)
639                    .bind(limit)
640                    .bind(now)
641                    .fetch_all(&self.pool)
642                    .await
643                    .map_err(|e| adk_core::AdkError::memory(format!("search failed: {e}")))?,
644                    Some(pid) => sqlx::query(
645                        r#"
646                            SELECT memory_id, content, author, timestamp, expires_at, (embedding <=> $3) AS distance
647                            FROM memory_entries
648                            WHERE app_name = $1 AND user_id = $2 AND embedding IS NOT NULL
649                              AND (project_id IS NULL OR project_id = $5)
650                              AND (expires_at IS NULL OR expires_at > $6)
651                            ORDER BY embedding <=> $3
652                            LIMIT $4
653                            "#,
654                    )
655                    .bind(&req.app_name)
656                    .bind(&req.user_id)
657                    .bind(query_vec)
658                    .bind(limit)
659                    .bind(pid)
660                    .bind(now)
661                    .fetch_all(&self.pool)
662                    .await
663                    .map_err(|e| adk_core::AdkError::memory(format!("search failed: {e}")))?,
664                }
665            }
666        } else {
667            // Full-text search fallback
668            match &req.project_id {
669                None => {
670                    sqlx::query(
671                        r#"
672                        SELECT memory_id, content, author, timestamp, expires_at, ts_rank(search_text, plainto_tsquery('simple', $3)) AS rank_score
673                        FROM memory_entries
674                        WHERE app_name = $1 AND user_id = $2
675                          AND search_text @@ plainto_tsquery('simple', $3)
676                          AND project_id IS NULL
677                              AND (expires_at IS NULL OR expires_at > $5)
678                        ORDER BY rank_score DESC
679                        LIMIT $4
680                        "#,
681                    )
682                    .bind(&req.app_name)
683                    .bind(&req.user_id)
684                    .bind(&req.query)
685                    .bind(limit)
686                    .bind(now)
687                    .fetch_all(&self.pool)
688                    .await
689                    .map_err(|e| adk_core::AdkError::memory(format!("search failed: {e}")))?
690                }
691                Some(pid) => {
692                    sqlx::query(
693                        r#"
694                        SELECT memory_id, content, author, timestamp, expires_at, ts_rank(search_text, plainto_tsquery('simple', $3)) AS rank_score
695                        FROM memory_entries
696                        WHERE app_name = $1 AND user_id = $2
697                          AND search_text @@ plainto_tsquery('simple', $3)
698                          AND (project_id IS NULL OR project_id = $5)
699                              AND (expires_at IS NULL OR expires_at > $6)
700                        ORDER BY rank_score DESC
701                        LIMIT $4
702                        "#,
703                    )
704                    .bind(&req.app_name)
705                    .bind(&req.user_id)
706                    .bind(&req.query)
707                    .bind(limit)
708                    .bind(pid)
709                    .bind(now)
710                    .fetch_all(&self.pool)
711                    .await
712                    .map_err(|e| adk_core::AdkError::memory(format!("search failed: {e}")))?
713                }
714            }
715        };
716
717        let min_score = req.min_score;
718        let memories =
719            rows.iter()
720                .filter(|row| {
721                    if let Some(threshold) = min_score {
722                        // pgvector's distance operators return `float8` and `ts_rank`
723                        // returns `float4`; sqlx refuses to read either as the other.
724                        let score = row
725                            .try_get::<f64, _>("distance")
726                            .map(|distance| 1.0 - distance)
727                            .or_else(|_| row.try_get::<f32, _>("rank_score").map(f64::from))
728                            .unwrap_or(0.0);
729                        score >= f64::from(threshold)
730                    } else {
731                        true
732                    }
733                })
734                .map(|row| {
735                    let content_json: serde_json::Value = row.get("content");
736                    let content: adk_core::Content =
737                        serde_json::from_value(content_json).unwrap_or_else(|_| {
738                            adk_core::Content { role: "user".to_string(), parts: vec![] }
739                        });
740                    let author: String = row.get("author");
741                    let mut entry =
742                        MemoryEntry::new(content, author).with_timestamp(row.get("timestamp"));
743                    entry.id = row.get("memory_id");
744                    entry.expires_at = row.get("expires_at");
745                    entry
746                })
747                .collect();
748
749        Ok(SearchResponse { memories })
750    }
751
752    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, limit = %limit))]
753    async fn list_recent(
754        &self,
755        app_name: &str,
756        user_id: &str,
757        limit: usize,
758    ) -> Result<Vec<MemoryEntry>> {
759        let rows = sqlx::query(
760            r#"
761            SELECT memory_id, content, author, timestamp, expires_at
762            FROM memory_entries
763            WHERE app_name = $1 AND user_id = $2
764              AND (expires_at IS NULL OR expires_at > $4)
765            ORDER BY timestamp DESC
766            LIMIT $3
767            "#,
768        )
769        .bind(app_name)
770        .bind(user_id)
771        .bind(limit as i64)
772        .bind(Utc::now())
773        .fetch_all(&self.pool)
774        .await
775        .map_err(|e| adk_core::AdkError::memory(format!("list_recent failed: {e}")))?;
776
777        Ok(rows
778            .into_iter()
779            .map(|row| {
780                let content_json: serde_json::Value = row.get("content");
781                let content: adk_core::Content = serde_json::from_value(content_json)
782                    .unwrap_or_else(|_| adk_core::Content {
783                        role: "user".to_string(),
784                        parts: vec![],
785                    });
786                let mut entry = MemoryEntry::new(content, row.get::<String, _>("author"))
787                    .with_timestamp(row.get("timestamp"));
788                entry.id = row.get("memory_id");
789                entry.expires_at = row.get("expires_at");
790                entry
791            })
792            .collect())
793    }
794
795    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
796    async fn export_user(&self, app_name: &str, user_id: &str) -> Result<Vec<UserMemory>> {
797        let rows = sqlx::query(
798            "SELECT session_id, project_id, memory_id, content, author, timestamp, expires_at \
799             FROM memory_entries WHERE app_name = $1 AND user_id = $2 ORDER BY timestamp, id",
800        )
801        .bind(app_name)
802        .bind(user_id)
803        .fetch_all(&self.pool)
804        .await
805        .map_err(|e| adk_core::AdkError::memory(format!("export_user failed: {e}")))?;
806        rows.into_iter()
807            .map(|row| {
808                let content: serde_json::Value = row.get("content");
809                // Entries added without a session are stored with an empty session id.
810                let session_id: String = row.get("session_id");
811                let content = serde_json::from_value(content).map_err(|e| {
812                    adk_core::AdkError::memory(format!("stored content is corrupt: {e}"))
813                })?;
814                let mut entry = MemoryEntry::new(content, row.get::<String, _>("author"))
815                    .with_timestamp(row.get("timestamp"));
816                entry.id = row.get("memory_id");
817                entry.expires_at = row.get("expires_at");
818                Ok(UserMemory {
819                    entry,
820                    session_id: (!session_id.is_empty()).then_some(session_id),
821                    project_id: row.get("project_id"),
822                })
823            })
824            .collect()
825    }
826
827    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
828    async fn delete_user(&self, app_name: &str, user_id: &str) -> Result<()> {
829        sqlx::query("DELETE FROM memory_entries WHERE app_name = $1 AND user_id = $2")
830            .bind(app_name)
831            .bind(user_id)
832            .execute(&self.pool)
833            .await
834            .map_err(|e| adk_core::AdkError::memory(format!("delete_user failed: {e}")))?;
835        Ok(())
836    }
837
838    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, session_id = %session_id))]
839    async fn delete_session(&self, app_name: &str, user_id: &str, session_id: &str) -> Result<()> {
840        sqlx::query(
841            "DELETE FROM memory_entries WHERE app_name = $1 AND user_id = $2 AND session_id = $3",
842        )
843        .bind(app_name)
844        .bind(user_id)
845        .bind(session_id)
846        .execute(&self.pool)
847        .await
848        .map_err(|e| adk_core::AdkError::memory(format!("delete_session failed: {e}")))?;
849        Ok(())
850    }
851
852    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, query = %query))]
853    async fn delete_entries(&self, app_name: &str, user_id: &str, query: &str) -> Result<u64> {
854        let result = sqlx::query(
855            r#"
856            DELETE FROM memory_entries
857            WHERE app_name = $1 AND user_id = $2
858              AND search_text @@ plainto_tsquery('simple', $3)
859              AND project_id IS NULL
860            "#,
861        )
862        .bind(app_name)
863        .bind(user_id)
864        .bind(query)
865        .execute(&self.pool)
866        .await
867        .map_err(|e| adk_core::AdkError::memory(format!("delete_entries failed: {e}")))?;
868        Ok(result.rows_affected())
869    }
870
871    fn supports_project_scoping(&self) -> bool {
872        true
873    }
874
875    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, session_id = %session_id, project_id = %project_id))]
876    async fn add_session_to_project(
877        &self,
878        app_name: &str,
879        user_id: &str,
880        session_id: &str,
881        project_id: &str,
882        entries: Vec<MemoryEntry>,
883    ) -> Result<()> {
884        validate_project_id(project_id)?;
885        self.insert(app_name, user_id, session_id, Some(project_id), entries).await
886    }
887
888    /// Add a single global entry (`project_id = NULL`).
889    ///
890    /// Without this override the trait default returns "not implemented",
891    /// making direct global writes impossible on the Postgres backend even
892    /// though project-scoped writes work.
893    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
894    async fn add_entry(&self, app_name: &str, user_id: &str, entry: MemoryEntry) -> Result<()> {
895        // Entries added without a session are stored with an empty session id.
896        self.insert(app_name, user_id, "", None, vec![entry]).await
897    }
898
899    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, project_id = %project_id))]
900    async fn add_entry_to_project(
901        &self,
902        app_name: &str,
903        user_id: &str,
904        project_id: &str,
905        entry: MemoryEntry,
906    ) -> Result<()> {
907        validate_project_id(project_id)?;
908        self.insert(app_name, user_id, "", Some(project_id), vec![entry]).await
909    }
910
911    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, project_id = %project_id, query = %query))]
912    async fn delete_entries_in_project(
913        &self,
914        app_name: &str,
915        user_id: &str,
916        project_id: &str,
917        query: &str,
918    ) -> Result<u64> {
919        validate_project_id(project_id)?;
920
921        let result = sqlx::query(
922            r#"
923            DELETE FROM memory_entries
924            WHERE app_name = $1 AND user_id = $2
925              AND search_text @@ plainto_tsquery('simple', $3)
926              AND project_id = $4
927            "#,
928        )
929        .bind(app_name)
930        .bind(user_id)
931        .bind(query)
932        .bind(project_id)
933        .execute(&self.pool)
934        .await
935        .map_err(|e| {
936            adk_core::AdkError::memory(format!("delete_entries_in_project failed: {e}"))
937        })?;
938        Ok(result.rows_affected())
939    }
940
941    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id, project_id = %project_id))]
942    async fn delete_project(&self, app_name: &str, user_id: &str, project_id: &str) -> Result<u64> {
943        validate_project_id(project_id)?;
944
945        let result = sqlx::query(
946            "DELETE FROM memory_entries WHERE app_name = $1 AND user_id = $2 AND project_id = $3",
947        )
948        .bind(app_name)
949        .bind(user_id)
950        .bind(project_id)
951        .execute(&self.pool)
952        .await
953        .map_err(|e| adk_core::AdkError::memory(format!("delete_project failed: {e}")))?;
954        Ok(result.rows_affected())
955    }
956
957    #[instrument(skip_all, fields(app_name = %app_name, user_id = %user_id))]
958    async fn delete_memory(&self, app_name: &str, user_id: &str, memory_id: &str) -> Result<u64> {
959        let result = sqlx::query(
960            "DELETE FROM memory_entries WHERE app_name = $1 AND user_id = $2 AND memory_id = $3",
961        )
962        .bind(app_name)
963        .bind(user_id)
964        .bind(memory_id)
965        .execute(&self.pool)
966        .await
967        .map_err(|e| adk_core::AdkError::memory(format!("delete_memory failed: {e}")))?;
968        Ok(result.rows_affected())
969    }
970
971    #[instrument(skip_all)]
972    async fn purge_expired(&self) -> Result<u64> {
973        let result = sqlx::query("DELETE FROM memory_entries WHERE expires_at <= $1")
974            .bind(Utc::now())
975            .execute(&self.pool)
976            .await
977            .map_err(|e| adk_core::AdkError::memory(format!("purge_expired failed: {e}")))?;
978        Ok(result.rows_affected())
979    }
980
981    #[instrument(skip_all)]
982    async fn health_check(&self) -> Result<()> {
983        sqlx::query("SELECT 1")
984            .execute(&self.pool)
985            .await
986            .map_err(|e| adk_core::AdkError::memory(format!("health check failed: {e}")))?;
987        Ok(())
988    }
989}