Skip to main content

aidaemon_memory/sqlite/
mod.rs

1//! The SQLite implementation of the [`crate::stores`] contract: facts with
2//! privacy and channel provenance, episodes, the claim graph, structured
3//! personal memory, people and learned habits.
4//!
5//! [`SqliteMemory`] works on a pool the host opens, so memory can share one
6//! database file (and its encryption) with the host's other tables.
7
8use std::collections::VecDeque;
9use std::sync::Arc;
10
11use async_trait::async_trait;
12use chrono::{DateTime, Utc};
13use sqlx::{Row, SqlitePool};
14use tokio::sync::Mutex;
15
16use crate::LearningStore;
17use crate::embed::{Embedder, decode_embedding_with_dim, encode_embedding};
18use crate::records::*;
19use crate::stores::*;
20use crate::text::truncate_chars as truncate_str;
21use crate::{BehaviorPattern, ErrorSolution, Expertise, Procedure, UserProfile};
22use aidaemon_core::ChannelVisibility;
23
24mod claims;
25mod episodes;
26mod export;
27mod fact_folds;
28mod facts;
29mod learning;
30mod people;
31mod retention;
32mod rows;
33mod schema;
34#[cfg(test)]
35mod search_tests;
36mod structured;
37
38pub(crate) use claims::memory_visible;
39pub use claims::{MemoryClaimRecord, project_message_span};
40pub use export::ExportFile;
41pub use fact_folds::{
42    FoldCandidate, FoldRule, ONE_VALUE_MIN_SIMILARITY, ONE_WORD_VALUE_MIN_SIMILARITY, PlannedFold,
43    facts_hold_one_value, plan_folds,
44};
45pub(crate) use facts::{FACT_RESTATEMENT_MIN_SIMILARITY, facts_make_the_same_claim};
46pub use facts::{
47    OWNER_QUOTED_SOURCE, build_fact_embedding_text, fact_category_is_personal, fact_source_rank,
48    facts_are_restatements, is_owner_authored_fact_source, keys_name_same_attribute,
49};
50pub use retention::{MemoryRetention, MemoryRetentionPolicy, MemoryRetentionStats};
51pub use schema::{migrate, rebuild_memory_fts_projections};
52
53/// Dimension of the test embedders' vectors.
54#[cfg(test)]
55const EMBEDDING_DIM: usize = 384;
56
57fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
58    crate::cosine(a, b)
59}
60
61fn episode_search_score(similarity: f32, recall_count: i32) -> f32 {
62    similarity * crate::episode_recall_boost(recall_count.max(0) as u32)
63}
64
65/// How the host's channel identifiers relate. The defaults suit a host whose
66/// ids are stable and carry no channel in the session id.
67pub trait ChannelIds: Send + Sync {
68    /// Whether a row stored under `stored` belongs to the channel `current`.
69    fn same_channel(&self, stored: &str, current: &str) -> bool {
70        stored == current
71    }
72
73    /// The channel a session belongs to, when its id says.
74    fn channel_of_session(&self, _session_id: &str) -> Option<String> {
75        None
76    }
77}
78
79/// Exact channel-id comparison, no channel derived from session ids.
80#[derive(Debug, Default, Clone, Copy)]
81pub struct ExactChannelIds;
82
83impl ChannelIds for ExactChannelIds {}
84
85/// The store's embedding model.
86#[derive(Clone)]
87pub(crate) struct StoreModels {
88    embedder: Arc<dyn Embedder>,
89    /// Recent single-text embeddings, shared by every clone.
90    queries: Arc<QueryMemo>,
91}
92
93/// How many recent query texts keep their vectors.
94const QUERY_MEMO_CAPACITY: usize = 8;
95
96/// The last few single-text embeddings. One turn's recall searches facts,
97/// episodes, procedures and error solutions for the same message at once;
98/// with this they share one model run instead of queueing four behind the
99/// model's lock. A text
100/// always has the same vector, so an entry never goes stale; one being
101/// computed is awaited, not recomputed, and a failed run leaves its entry
102/// empty for the next caller to retry.
103#[derive(Default)]
104struct QueryMemo {
105    entries: std::sync::Mutex<std::collections::VecDeque<(String, VectorCell)>>,
106}
107
108/// One text's vector, filled by whichever caller runs the model first.
109type VectorCell = Arc<tokio::sync::OnceCell<Vec<f32>>>;
110
111impl QueryMemo {
112    fn cell(&self, text: &str) -> VectorCell {
113        let Ok(mut entries) = self.entries.lock() else {
114            return Arc::new(tokio::sync::OnceCell::new());
115        };
116        if let Some(position) = entries.iter().position(|(key, _)| key == text) {
117            let entry = entries.remove(position).expect("position is in range");
118            let cell = entry.1.clone();
119            entries.push_back(entry);
120            return cell;
121        }
122        let cell = Arc::new(tokio::sync::OnceCell::new());
123        entries.push_back((text.to_string(), cell.clone()));
124        while entries.len() > QUERY_MEMO_CAPACITY {
125            entries.pop_front();
126        }
127        cell
128    }
129}
130
131impl StoreModels {
132    fn model_id(&self) -> String {
133        self.embedder.model_id().to_string()
134    }
135
136    /// A stored vector of this model's dimension (binary, or the legacy
137    /// JSON form); anything else is an error, never a vector of another
138    /// length.
139    fn decode(&self, blob: &[u8]) -> anyhow::Result<Vec<f32>> {
140        decode_embedding_with_dim(blob, self.embedder.dimensions()).map_err(anyhow::Error::from)
141    }
142
143    async fn embed(&self, text: String) -> anyhow::Result<Vec<f32>> {
144        let cell = self.queries.cell(&text);
145        cell.get_or_try_init(|| async {
146            self.embedder
147                .embed(&[text])
148                .await?
149                .into_iter()
150                .next()
151                .ok_or_else(|| anyhow::anyhow!("embedder returned no vector"))
152        })
153        .await
154        .cloned()
155    }
156
157    /// One embedder call for many texts: one model hop instead of one per
158    /// text.
159    async fn embed_many(&self, texts: Vec<String>) -> anyhow::Result<Vec<Vec<f32>>> {
160        if texts.is_empty() {
161            return Ok(Vec::new());
162        }
163        let expected = texts.len();
164        let vectors = self.embedder.embed(&texts).await?;
165        anyhow::ensure!(
166            vectors.len() == expected,
167            "embedder returned {} vectors for {expected} texts",
168            vectors.len()
169        );
170        Ok(vectors)
171    }
172}
173
174/// Long-term memory in SQLite.
175#[derive(Clone)]
176pub struct SqliteMemory {
177    pool: SqlitePool,
178    /// One index for this database, so its vector cache is shared by every
179    /// search and clone.
180    embedding_index: crate::embedding_index::SqliteEmbeddingIndex,
181    embedding_service: StoreModels,
182    fact_upsert_lock: Arc<Mutex<()>>,
183    channels: Arc<dyn ChannelIds>,
184    clean_error_text: fn(&str) -> String,
185    messages: Option<Arc<dyn crate::history::MessageLog>>,
186}
187
188impl SqliteMemory {
189    /// Memory over `pool`, whose tables [`migrate`] has created.
190    pub fn new(pool: SqlitePool, embedder: Arc<dyn Embedder>) -> Self {
191        Self {
192            embedding_index: crate::embedding_index::SqliteEmbeddingIndex::new(pool.clone()),
193            pool,
194            embedding_service: StoreModels {
195                embedder,
196                queries: Arc::default(),
197            },
198            fact_upsert_lock: Arc::new(Mutex::new(())),
199            channels: Arc::new(ExactChannelIds),
200            clean_error_text: str::to_string,
201            messages: None,
202        }
203    }
204
205    /// Compares and derives channel ids the host's way.
206    pub fn with_channel_ids(mut self, channels: Arc<dyn ChannelIds>) -> Self {
207        self.channels = channels;
208        self
209    }
210
211    /// Strips host text (wrappers, notices) from an error before its
212    /// recurrence pattern is derived.
213    pub fn with_error_cleaner(mut self, clean: fn(&str) -> String) -> Self {
214        self.clean_error_text = clean;
215        self
216    }
217
218    /// Links episodes to the host's messages (see [`MessageLog`]).
219    ///
220    /// [`MessageLog`]: crate::history::MessageLog
221    pub fn with_message_log(mut self, messages: Arc<dyn crate::history::MessageLog>) -> Self {
222        self.messages = Some(messages);
223        self
224    }
225
226    /// The first and last messages a span of a session covers, when the host
227    /// gave a [`MessageLog`](crate::history::MessageLog). Without one an
228    /// episode simply has no bounds.
229    async fn message_event_bounds(
230        &self,
231        session_id: &str,
232        start: DateTime<Utc>,
233        end: DateTime<Utc>,
234    ) -> anyhow::Result<(Option<i64>, Option<i64>)> {
235        match &self.messages {
236            Some(messages) => messages.message_bounds(session_id, start, end).await,
237            None => Ok((None, None)),
238        }
239    }
240
241    /// The pool the store works on.
242    pub fn pool(&self) -> &SqlitePool {
243        &self.pool
244    }
245}
246
247fn parse_dt(s: String) -> DateTime<Utc> {
248    DateTime::parse_from_rfc3339(&s)
249        .map(|dt| dt.with_timezone(&Utc))
250        .unwrap_or_else(|_| Utc::now())
251}
252
253#[cfg(test)]
254mod query_memo_tests {
255    use std::sync::Arc;
256    use std::sync::atomic::{AtomicUsize, Ordering};
257
258    use async_trait::async_trait;
259
260    use super::{QUERY_MEMO_CAPACITY, StoreModels};
261    use crate::Embedder;
262
263    struct Counting {
264        runs: AtomicUsize,
265        fail_first: bool,
266    }
267
268    #[async_trait]
269    impl Embedder for Counting {
270        fn model_id(&self) -> &str {
271            "counting"
272        }
273        fn dimensions(&self) -> usize {
274            1
275        }
276        async fn embed(&self, texts: &[String]) -> crate::Result<Vec<Vec<f32>>> {
277            let run = self.runs.fetch_add(1, Ordering::SeqCst);
278            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
279            if self.fail_first && run == 0 {
280                return Err(crate::MemoryError::Embedding("model not loaded yet".into()));
281            }
282            Ok(texts.iter().map(|text| vec![text.len() as f32]).collect())
283        }
284    }
285
286    fn models(fail_first: bool) -> (StoreModels, Arc<Counting>) {
287        let embedder = Arc::new(Counting {
288            runs: AtomicUsize::new(0),
289            fail_first,
290        });
291        let models = StoreModels {
292            embedder: embedder.clone(),
293            queries: Arc::default(),
294        };
295        (models, embedder)
296    }
297
298    #[tokio::test]
299    async fn concurrent_searches_for_one_text_share_one_model_run() {
300        let (models, embedder) = models(false);
301        let text = "what is on my calendar".to_string();
302        let (a, b, c, d) = tokio::join!(
303            models.embed(text.clone()),
304            models.embed(text.clone()),
305            models.embed(text.clone()),
306            models.embed(text.clone()),
307        );
308        let results = [a.unwrap(), b.unwrap(), c.unwrap(), d.unwrap()];
309        assert!(results.iter().all(|vector| vector == &results[0]));
310        assert_eq!(embedder.runs.load(Ordering::SeqCst), 1);
311        // A different text runs the model again.
312        models.embed("another question".to_string()).await.unwrap();
313        assert_eq!(embedder.runs.load(Ordering::SeqCst), 2);
314    }
315
316    #[tokio::test]
317    async fn a_failed_run_is_retried_and_old_texts_are_evicted() {
318        let (models, embedder) = models(true);
319        assert!(models.embed("first".to_string()).await.is_err());
320        assert!(models.embed("first".to_string()).await.is_ok());
321        assert_eq!(embedder.runs.load(Ordering::SeqCst), 2);
322        for n in 0..QUERY_MEMO_CAPACITY {
323            models.embed(format!("text {n}")).await.unwrap();
324        }
325        let before = embedder.runs.load(Ordering::SeqCst);
326        models.embed("first".to_string()).await.unwrap();
327        assert_eq!(embedder.runs.load(Ordering::SeqCst), before + 1);
328    }
329}