Skip to main content

aidaemon_memory/store/
sqlite.rs

1use std::collections::{HashMap, HashSet};
2use std::path::Path;
3use std::str::FromStr;
4use std::time::Duration;
5
6use async_trait::async_trait;
7use chrono::{DateTime, Utc};
8use sqlx::sqlite::{
9    SqliteConnectOptions, SqliteJournalMode, SqlitePool, SqlitePoolOptions, SqliteRow,
10    SqliteSynchronous,
11};
12use sqlx::{Row, Sqlite, Transaction};
13
14use super::{MemoryStore, migrations, related_fact_scores};
15use crate::embed::{decode_embedding, encode_embedding};
16use crate::error::{MemoryError, Result};
17use crate::scoring::{term_overlap, tokens};
18use crate::types::{
19    DecayReport, Episode, EpisodeRecord, Fact, FactAccess, FactRecord, MemoryStats, NewEpisode,
20    NewFact, Provenance, RecordKind, RetentionConfig, StaleEmbedding, StoredEmbedding,
21    UpsertOutcome, episode_search_text, fact_search_text, new_id, normalize_category,
22    normalize_key, parse_ts, same_value, ts,
23};
24
25const FACT_COLUMNS: &str = "id, scope, category, key, value, confidence, source_run_id, \
26     source_session_id, source_excerpt, created_at, updated_at, superseded_at, recall_count, \
27     last_recalled_at, embedding, embedding_model";
28
29const EPISODE_COLUMNS: &str = "id, scope, session_id, summary, topics, importance, created_at, \
30     recall_count, last_recalled_at, embedding, embedding_model";
31
32/// SQLite-backed [`MemoryStore`]: versioned migrations, embeddings as
33/// little-endian f32 BLOBs, and FTS5 indexes (BM25) over active facts and
34/// episodes, kept in sync inside each write transaction. Cheap to clone.
35#[derive(Debug, Clone)]
36pub struct SqliteMemoryStore {
37    pool: SqlitePool,
38}
39
40impl SqliteMemoryStore {
41    /// Open (creating if needed) a database file with WAL and a busy
42    /// timeout, then migrate.
43    pub async fn open(path: impl AsRef<Path>) -> Result<Self> {
44        let options = SqliteConnectOptions::new()
45            .filename(path)
46            .create_if_missing(true)
47            .journal_mode(SqliteJournalMode::Wal)
48            .synchronous(SqliteSynchronous::Normal)
49            .busy_timeout(Duration::from_secs(10));
50        let pool = SqlitePoolOptions::new()
51            .max_connections(4)
52            .connect_with(options)
53            .await?;
54        Self::from_pool(pool).await
55    }
56
57    /// A private in-memory database, for tests.
58    pub async fn open_in_memory() -> Result<Self> {
59        let options = SqliteConnectOptions::from_str("sqlite::memory:")?;
60        let pool = SqlitePoolOptions::new()
61            .max_connections(1)
62            .min_connections(1)
63            .idle_timeout(None)
64            .max_lifetime(None)
65            .connect_with(options)
66            .await?;
67        Self::from_pool(pool).await
68    }
69
70    /// Use an existing pool (for example one shared with
71    /// `aidaemon-store-sqlite`) and apply this crate's migrations.
72    pub async fn from_pool(pool: SqlitePool) -> Result<Self> {
73        migrations::run(&pool).await?;
74        Ok(Self { pool })
75    }
76
77    pub fn pool(&self) -> &SqlitePool {
78        &self.pool
79    }
80
81    /// The schema version recorded in the database.
82    pub async fn schema_version(&self) -> Result<i64> {
83        migrations::current_version(&self.pool).await
84    }
85
86    /// Rows in the fact FTS index for `scope` (diagnostics and tests).
87    pub async fn fts_fact_ids(&self, scope: &str) -> Result<Vec<String>> {
88        let ids = sqlx::query_scalar("SELECT fact_id FROM memory_facts_fts WHERE scope = ?")
89            .bind(scope)
90            .fetch_all(&self.pool)
91            .await?;
92        Ok(ids)
93    }
94
95    async fn try_upsert(
96        &self,
97        fact: &NewFact,
98        embedding: &Option<StoredEmbedding>,
99        access: &FactAccess,
100        now: DateTime<Utc>,
101    ) -> std::result::Result<UpsertOutcome, sqlx::Error> {
102        let now_s = ts(now);
103        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
104        let existing = sqlx::query(
105            "SELECT id, value, source_excerpt, privacy, channel_id FROM memory_facts
106             WHERE scope = ? AND category = ? AND key = ? AND superseded_at IS NULL",
107        )
108        .bind(&fact.scope)
109        .bind(&fact.category)
110        .bind(&fact.key)
111        .fetch_optional(&mut *tx)
112        .await?;
113
114        let mut previous = None;
115        if let Some(row) = existing {
116            let id: String = row.get("id");
117            let value: String = row.get("value");
118            if same_value(&value, &fact.value) {
119                let (blob, model) = embedding_columns(embedding);
120                let narrowed = row_access(&row).narrowest(access);
121                sqlx::query(
122                    "UPDATE memory_facts SET updated_at = ?, confidence = MAX(confidence, ?),
123                        source_excerpt = COALESCE(source_excerpt, ?),
124                        embedding = COALESCE(?, embedding),
125                        embedding_model = COALESCE(?, embedding_model),
126                        privacy = ?, channel_id = ?
127                     WHERE id = ?",
128                )
129                .bind(&now_s)
130                .bind(fact.confidence)
131                .bind(&fact.source.excerpt)
132                .bind(blob)
133                .bind(model)
134                .bind(narrowed.privacy.to_string())
135                .bind(&narrowed.channel_id)
136                .bind(&id)
137                .execute(&mut *tx)
138                .await?;
139                tx.commit().await?;
140                return Ok(UpsertOutcome::Reinforced { id });
141            }
142            sqlx::query("UPDATE memory_facts SET superseded_at = ? WHERE id = ?")
143                .bind(&now_s)
144                .bind(&id)
145                .execute(&mut *tx)
146                .await?;
147            sqlx::query("DELETE FROM memory_facts_fts WHERE fact_id = ?")
148                .bind(&id)
149                .execute(&mut *tx)
150                .await?;
151            previous = Some((id, value));
152        }
153
154        let id = new_id();
155        let (blob, model) = embedding_columns(embedding);
156        sqlx::query(
157            "INSERT INTO memory_facts (id, scope, category, key, value, confidence,
158                source_run_id, source_session_id, source_excerpt, created_at, updated_at,
159                embedding, embedding_model, privacy, channel_id)
160             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
161        )
162        .bind(&id)
163        .bind(&fact.scope)
164        .bind(&fact.category)
165        .bind(&fact.key)
166        .bind(&fact.value)
167        .bind(fact.confidence)
168        .bind(&fact.source.run_id)
169        .bind(&fact.source.session_id)
170        .bind(&fact.source.excerpt)
171        .bind(&now_s)
172        .bind(&now_s)
173        .bind(blob)
174        .bind(model)
175        .bind(access.privacy.to_string())
176        .bind(&access.channel_id)
177        .execute(&mut *tx)
178        .await?;
179        sqlx::query("INSERT INTO memory_facts_fts (fact_id, scope, content) VALUES (?, ?, ?)")
180            .bind(&id)
181            .bind(&fact.scope)
182            .bind(fact_search_text(&fact.category, &fact.key, &fact.value))
183            .execute(&mut *tx)
184            .await?;
185        tx.commit().await?;
186        Ok(match previous {
187            None => UpsertOutcome::Inserted { id },
188            Some((previous_id, previous_value)) => UpsertOutcome::Superseded {
189                id,
190                previous_id,
191                previous_value,
192            },
193        })
194    }
195
196    /// Stored access of `scope`'s rows in `table`, for the ids asked about.
197    async fn access_of(
198        &self,
199        table: &str,
200        scope: &str,
201        ids: &[String],
202    ) -> Result<HashMap<String, FactAccess>> {
203        let wanted: HashSet<&String> = ids.iter().collect();
204        let sql = format!("SELECT id, privacy, channel_id FROM {table} WHERE scope = ?");
205        let rows = sqlx::query(sqlx::AssertSqlSafe(&*sql))
206            .bind(scope)
207            .fetch_all(&self.pool)
208            .await?;
209        Ok(rows
210            .iter()
211            .map(|row| (row.get::<String, _>("id"), row_access(row)))
212            .filter(|(id, _)| wanted.contains(id))
213            .collect())
214    }
215
216    /// BM25 over an FTS table, normalized to 0..=1: word coverage of the
217    /// query, weighted by BM25 relative to the best hit.
218    async fn fts_scores(
219        &self,
220        table: &str,
221        id_column: &str,
222        scope: &str,
223        query: &str,
224    ) -> Result<HashMap<String, f32>> {
225        let unique: HashSet<String> = tokens(query).into_iter().collect();
226        if unique.is_empty() {
227            return Ok(HashMap::new());
228        }
229        // Tokens are alphanumeric only, so quoting makes every term a literal.
230        let mut terms: Vec<String> = unique.into_iter().map(|t| format!("\"{t}\"")).collect();
231        terms.sort();
232        let sql = format!(
233            "SELECT {id_column} AS id, bm25({table}) AS rank, content FROM {table}
234             WHERE {table} MATCH ? AND scope = ?"
235        );
236        let rows = sqlx::query(sqlx::AssertSqlSafe(&*sql))
237            .bind(terms.join(" OR "))
238            .bind(scope)
239            .fetch_all(&self.pool)
240            .await?;
241        let hits: Vec<(String, f64, String)> = rows
242            .iter()
243            .map(|r| (r.get("id"), r.get::<f64, _>("rank").abs(), r.get("content")))
244            .collect();
245        let best = hits.iter().map(|h| h.1).fold(0.0f64, f64::max);
246        Ok(hits
247            .into_iter()
248            .map(|(id, rank, content)| {
249                let relative = if best > 0.0 {
250                    (rank / best) as f32
251                } else {
252                    1.0
253                };
254                let score = term_overlap(query, &content) * (0.5 + 0.5 * relative);
255                (id, score)
256            })
257            .filter(|(_, s)| *s > 0.0)
258            .collect())
259    }
260}
261
262fn embedding_columns(embedding: &Option<StoredEmbedding>) -> (Option<Vec<u8>>, Option<String>) {
263    match embedding {
264        Some(e) => (Some(encode_embedding(&e.vector)), Some(e.model.clone())),
265        None => (None, None),
266    }
267}
268
269fn row_embedding(row: &SqliteRow) -> Option<StoredEmbedding> {
270    let blob: Option<Vec<u8>> = row.get("embedding");
271    let model: Option<String> = row.get("embedding_model");
272    Some(StoredEmbedding {
273        vector: decode_embedding(&blob?)?,
274        model: model?,
275    })
276}
277
278fn row_access(row: &SqliteRow) -> FactAccess {
279    FactAccess::from_stored(row.get("privacy"), row.get("channel_id"))
280}
281
282fn row_time(row: &SqliteRow, column: &str) -> DateTime<Utc> {
283    row.get::<Option<String>, _>(column)
284        .and_then(|s| parse_ts(&s))
285        .unwrap_or_default()
286}
287
288fn row_opt_time(row: &SqliteRow, column: &str) -> Option<DateTime<Utc>> {
289    row.get::<Option<String>, _>(column)
290        .and_then(|s| parse_ts(&s))
291}
292
293fn row_to_fact(row: &SqliteRow) -> FactRecord {
294    FactRecord {
295        fact: Fact {
296            id: row.get("id"),
297            scope: row.get("scope"),
298            category: row.get("category"),
299            key: row.get("key"),
300            value: row.get("value"),
301            confidence: row.get::<f64, _>("confidence") as f32,
302            source: Provenance {
303                run_id: row.get("source_run_id"),
304                session_id: row.get("source_session_id"),
305                excerpt: row.get("source_excerpt"),
306            },
307            created_at: row_time(row, "created_at"),
308            updated_at: row_time(row, "updated_at"),
309            superseded_at: row_opt_time(row, "superseded_at"),
310            recall_count: row.get::<i64, _>("recall_count").max(0) as u32,
311            last_recalled_at: row_opt_time(row, "last_recalled_at"),
312        },
313        embedding: row_embedding(row),
314    }
315}
316
317fn row_to_episode(row: &SqliteRow) -> EpisodeRecord {
318    let topics: String = row.get("topics");
319    EpisodeRecord {
320        episode: Episode {
321            id: row.get("id"),
322            scope: row.get("scope"),
323            session_id: row.get("session_id"),
324            summary: row.get("summary"),
325            topics: serde_json::from_str(&topics).unwrap_or_default(),
326            importance: row.get::<f64, _>("importance") as f32,
327            created_at: row_time(row, "created_at"),
328            recall_count: row.get::<i64, _>("recall_count").max(0) as u32,
329            last_recalled_at: row_opt_time(row, "last_recalled_at"),
330        },
331        embedding: row_embedding(row),
332    }
333}
334
335fn is_unique_violation(err: &sqlx::Error) -> bool {
336    matches!(err, sqlx::Error::Database(db) if db.is_unique_violation())
337}
338
339async fn bump_recalls(
340    tx: &mut Transaction<'_, Sqlite>,
341    table: &str,
342    ids: &[String],
343    now: &str,
344) -> std::result::Result<(), sqlx::Error> {
345    let sql = format!(
346        "UPDATE {table} SET recall_count = recall_count + 1, last_recalled_at = ? WHERE id = ?"
347    );
348    for id in ids {
349        sqlx::query(sqlx::AssertSqlSafe(&*sql))
350            .bind(now)
351            .bind(id)
352            .execute(&mut **tx)
353            .await?;
354    }
355    Ok(())
356}
357
358#[async_trait]
359impl MemoryStore for SqliteMemoryStore {
360    async fn upsert_fact(
361        &self,
362        fact: NewFact,
363        embedding: Option<StoredEmbedding>,
364        now: DateTime<Utc>,
365    ) -> Result<UpsertOutcome> {
366        self.upsert_fact_with_access(fact, embedding, &FactAccess::default(), now)
367            .await
368    }
369
370    async fn upsert_fact_with_access(
371        &self,
372        fact: NewFact,
373        embedding: Option<StoredEmbedding>,
374        access: &FactAccess,
375        now: DateTime<Utc>,
376    ) -> Result<UpsertOutcome> {
377        match self.try_upsert(&fact, &embedding, access, now).await {
378            // A concurrent writer inserted the same key between our read and
379            // write; the retry sees its row and reinforces or supersedes it.
380            Err(err) if is_unique_violation(&err) => {
381                Ok(self.try_upsert(&fact, &embedding, access, now).await?)
382            }
383            other => Ok(other?),
384        }
385    }
386
387    async fn fact_access(
388        &self,
389        scope: &str,
390        ids: &[String],
391    ) -> Result<HashMap<String, FactAccess>> {
392        self.access_of("memory_facts", scope, ids).await
393    }
394
395    async fn supersede_fact(
396        &self,
397        scope: &str,
398        category: &str,
399        key: &str,
400        now: DateTime<Utc>,
401    ) -> Result<bool> {
402        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
403        let ids: Vec<String> = sqlx::query_scalar(
404            "SELECT id FROM memory_facts
405             WHERE scope = ? AND category = ? AND key = ? AND superseded_at IS NULL",
406        )
407        .bind(scope)
408        .bind(normalize_category(category))
409        .bind(normalize_key(key))
410        .fetch_all(&mut *tx)
411        .await?;
412        for id in &ids {
413            sqlx::query("UPDATE memory_facts SET superseded_at = ? WHERE id = ?")
414                .bind(ts(now))
415                .bind(id)
416                .execute(&mut *tx)
417                .await?;
418            sqlx::query("DELETE FROM memory_facts_fts WHERE fact_id = ?")
419                .bind(id)
420                .execute(&mut *tx)
421                .await?;
422        }
423        tx.commit().await?;
424        Ok(!ids.is_empty())
425    }
426
427    async fn active_facts(&self, scope: &str) -> Result<Vec<FactRecord>> {
428        let sql = format!(
429            "SELECT {FACT_COLUMNS} FROM memory_facts
430             WHERE scope = ? AND superseded_at IS NULL ORDER BY updated_at DESC"
431        );
432        let rows = sqlx::query(sqlx::AssertSqlSafe(&*sql))
433            .bind(scope)
434            .fetch_all(&self.pool)
435            .await?;
436        Ok(rows.iter().map(row_to_fact).collect())
437    }
438
439    async fn fact_graph_scores(
440        &self,
441        scope: &str,
442        seed_ids: &[String],
443    ) -> Result<HashMap<String, f32>> {
444        let active: Vec<Fact> = self
445            .active_facts(scope)
446            .await?
447            .into_iter()
448            .map(|r| r.fact)
449            .collect();
450        Ok(related_fact_scores(&active, seed_ids))
451    }
452
453    async fn fact_history(&self, scope: &str, category: &str, key: &str) -> Result<Vec<Fact>> {
454        let sql = format!(
455            "SELECT {FACT_COLUMNS} FROM memory_facts
456             WHERE scope = ? AND category = ? AND key = ? ORDER BY created_at, rowid"
457        );
458        let rows = sqlx::query(sqlx::AssertSqlSafe(&*sql))
459            .bind(scope)
460            .bind(normalize_category(category))
461            .bind(normalize_key(key))
462            .fetch_all(&self.pool)
463            .await?;
464        Ok(rows.iter().map(|r| row_to_fact(r).fact).collect())
465    }
466
467    async fn fact_lexical_scores(&self, scope: &str, query: &str) -> Result<HashMap<String, f32>> {
468        self.fts_scores("memory_facts_fts", "fact_id", scope, query)
469            .await
470    }
471
472    async fn record_fact_recalls(&self, ids: &[String], now: DateTime<Utc>) -> Result<()> {
473        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
474        bump_recalls(&mut tx, "memory_facts", ids, &ts(now)).await?;
475        tx.commit().await?;
476        Ok(())
477    }
478
479    async fn insert_episode(
480        &self,
481        episode: NewEpisode,
482        embedding: Option<StoredEmbedding>,
483        now: DateTime<Utc>,
484    ) -> Result<Episode> {
485        self.insert_episode_with_access(episode, embedding, &FactAccess::default(), now)
486            .await
487    }
488
489    async fn insert_episode_with_access(
490        &self,
491        episode: NewEpisode,
492        embedding: Option<StoredEmbedding>,
493        access: &FactAccess,
494        now: DateTime<Utc>,
495    ) -> Result<Episode> {
496        let episode = Episode {
497            id: new_id(),
498            scope: episode.scope,
499            session_id: episode.session_id,
500            summary: episode.summary,
501            topics: episode.topics,
502            importance: episode.importance,
503            created_at: now,
504            recall_count: 0,
505            last_recalled_at: None,
506        };
507        let topics = serde_json::to_string(&episode.topics)
508            .map_err(|e| MemoryError::Store(e.to_string()))?;
509        let (blob, model) = embedding_columns(&embedding);
510        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
511        sqlx::query(
512            "INSERT INTO memory_episodes (id, scope, session_id, summary, topics, importance,
513                created_at, embedding, embedding_model, privacy, channel_id)
514             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
515        )
516        .bind(&episode.id)
517        .bind(&episode.scope)
518        .bind(&episode.session_id)
519        .bind(&episode.summary)
520        .bind(topics)
521        .bind(episode.importance)
522        .bind(ts(now))
523        .bind(blob)
524        .bind(model)
525        .bind(access.privacy.to_string())
526        .bind(&access.channel_id)
527        .execute(&mut *tx)
528        .await?;
529        sqlx::query(
530            "INSERT INTO memory_episodes_fts (episode_id, scope, content) VALUES (?, ?, ?)",
531        )
532        .bind(&episode.id)
533        .bind(&episode.scope)
534        .bind(episode_search_text(&episode.summary, &episode.topics))
535        .execute(&mut *tx)
536        .await?;
537        tx.commit().await?;
538        Ok(episode)
539    }
540
541    async fn episode_access(
542        &self,
543        scope: &str,
544        ids: &[String],
545    ) -> Result<HashMap<String, FactAccess>> {
546        self.access_of("memory_episodes", scope, ids).await
547    }
548
549    async fn episodes(&self, scope: &str) -> Result<Vec<EpisodeRecord>> {
550        let sql = format!(
551            "SELECT {EPISODE_COLUMNS} FROM memory_episodes WHERE scope = ? ORDER BY created_at DESC"
552        );
553        let rows = sqlx::query(sqlx::AssertSqlSafe(&*sql))
554            .bind(scope)
555            .fetch_all(&self.pool)
556            .await?;
557        Ok(rows.iter().map(row_to_episode).collect())
558    }
559
560    async fn episode_lexical_scores(
561        &self,
562        scope: &str,
563        query: &str,
564    ) -> Result<HashMap<String, f32>> {
565        self.fts_scores("memory_episodes_fts", "episode_id", scope, query)
566            .await
567    }
568
569    async fn record_episode_recalls(&self, ids: &[String], now: DateTime<Utc>) -> Result<()> {
570        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
571        bump_recalls(&mut tx, "memory_episodes", ids, &ts(now)).await?;
572        tx.commit().await?;
573        Ok(())
574    }
575
576    async fn decay(&self, now: DateTime<Utc>, config: &RetentionConfig) -> Result<DecayReport> {
577        let mut report = DecayReport::default();
578        let mut tx = self.pool.begin_with("BEGIN IMMEDIATE").await?;
579        if let Some(window) = config.superseded_retention {
580            report.superseded_deleted = sqlx::query(
581                "DELETE FROM memory_facts WHERE superseded_at IS NOT NULL AND superseded_at < ?",
582            )
583            .bind(ts(now - window))
584            .execute(&mut *tx)
585            .await?
586            .rows_affected();
587        }
588        if let Some(window) = config.episode_retention {
589            let cutoff = ts(now - window);
590            sqlx::query(
591                "DELETE FROM memory_episodes_fts WHERE episode_id IN (
592                    SELECT id FROM memory_episodes WHERE recall_count = 0 AND created_at < ?)",
593            )
594            .bind(&cutoff)
595            .execute(&mut *tx)
596            .await?;
597            report.episodes_deleted = sqlx::query(
598                "DELETE FROM memory_episodes WHERE recall_count = 0 AND created_at < ?",
599            )
600            .bind(&cutoff)
601            .execute(&mut *tx)
602            .await?
603            .rows_affected();
604        }
605        if let Some(window) = config.fact_recall_decay_after {
606            report.facts_decayed = sqlx::query(
607                "UPDATE memory_facts
608                 SET recall_count = MAX(0, recall_count - MAX(1, recall_count / 10))
609                 WHERE superseded_at IS NULL AND recall_count > 0
610                   AND (last_recalled_at IS NULL OR last_recalled_at < ?)",
611            )
612            .bind(ts(now - window))
613            .execute(&mut *tx)
614            .await?
615            .rows_affected();
616        }
617        if let Some(window) = config.episode_recall_decay_after {
618            report.episodes_decayed = sqlx::query(
619                "UPDATE memory_episodes SET recall_count = MAX(0, recall_count - 1)
620                 WHERE recall_count > 0 AND (last_recalled_at IS NULL OR last_recalled_at < ?)",
621            )
622            .bind(ts(now - window))
623            .execute(&mut *tx)
624            .await?
625            .rows_affected();
626        }
627        tx.commit().await?;
628        Ok(report)
629    }
630
631    async fn stale_embeddings(
632        &self,
633        model: &str,
634        kind: RecordKind,
635        after_id: Option<&str>,
636        limit: usize,
637    ) -> Result<Vec<StaleEmbedding>> {
638        let (columns, table, active) = match kind {
639            RecordKind::Fact => (
640                "id, category, key, value, embedding_model",
641                "memory_facts",
642                "superseded_at IS NULL AND",
643            ),
644            RecordKind::Episode => (
645                "id, summary, topics, embedding_model",
646                "memory_episodes",
647                "",
648            ),
649        };
650        let sql = format!(
651            "SELECT {columns} FROM {table}
652             WHERE {active} (embedding_model IS NULL OR embedding_model != ?)
653               AND (? IS NULL OR id > ?)
654             ORDER BY id LIMIT ?"
655        );
656        let rows = sqlx::query(sqlx::AssertSqlSafe(&*sql))
657            .bind(model)
658            .bind(after_id)
659            .bind(after_id)
660            .bind(limit as i64)
661            .fetch_all(&self.pool)
662            .await?;
663        Ok(rows
664            .iter()
665            .map(|row| StaleEmbedding {
666                kind,
667                id: row.get("id"),
668                text: match kind {
669                    RecordKind::Fact => {
670                        fact_search_text(row.get("category"), row.get("key"), row.get("value"))
671                    }
672                    RecordKind::Episode => {
673                        let topics: String = row.get("topics");
674                        let topics: Vec<String> = serde_json::from_str(&topics).unwrap_or_default();
675                        episode_search_text(row.get("summary"), &topics)
676                    }
677                },
678                model: row.get("embedding_model"),
679            })
680            .collect())
681    }
682
683    async fn replace_embedding(
684        &self,
685        stale: &StaleEmbedding,
686        embedding: StoredEmbedding,
687    ) -> Result<bool> {
688        let (table, active) = match stale.kind {
689            RecordKind::Fact => ("memory_facts", "AND superseded_at IS NULL"),
690            RecordKind::Episode => ("memory_episodes", ""),
691        };
692        let sql = format!(
693            "UPDATE {table} SET embedding = ?, embedding_model = ?
694             WHERE id = ? AND embedding_model IS ? {active}"
695        );
696        let changed = sqlx::query(sqlx::AssertSqlSafe(&*sql))
697            .bind(encode_embedding(&embedding.vector))
698            .bind(&embedding.model)
699            .bind(&stale.id)
700            .bind(&stale.model)
701            .execute(&self.pool)
702            .await?
703            .rows_affected();
704        Ok(changed > 0)
705    }
706
707    async fn stats(&self) -> Result<MemoryStats> {
708        let row = sqlx::query(
709            "SELECT
710                (SELECT COUNT(*) FROM memory_facts WHERE superseded_at IS NULL) AS active,
711                (SELECT COUNT(*) FROM memory_facts WHERE superseded_at IS NOT NULL) AS superseded,
712                (SELECT COUNT(*) FROM memory_episodes) AS episodes,
713                (SELECT COUNT(*) FROM (SELECT scope FROM memory_facts
714                                       UNION SELECT scope FROM memory_episodes)) AS scopes",
715        )
716        .fetch_one(&self.pool)
717        .await?;
718        let count = |c: &str| row.get::<i64, _>(c).max(0) as u64;
719        Ok(MemoryStats {
720            active_facts: count("active"),
721            superseded_facts: count("superseded"),
722            episodes: count("episodes"),
723            scopes: count("scopes"),
724        })
725    }
726}