1use 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#[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
65pub trait ChannelIds: Send + Sync {
68 fn same_channel(&self, stored: &str, current: &str) -> bool {
70 stored == current
71 }
72
73 fn channel_of_session(&self, _session_id: &str) -> Option<String> {
75 None
76 }
77}
78
79#[derive(Debug, Default, Clone, Copy)]
81pub struct ExactChannelIds;
82
83impl ChannelIds for ExactChannelIds {}
84
85#[derive(Clone)]
87pub(crate) struct StoreModels {
88 embedder: Arc<dyn Embedder>,
89 queries: Arc<QueryMemo>,
91}
92
93const QUERY_MEMO_CAPACITY: usize = 8;
95
96#[derive(Default)]
104struct QueryMemo {
105 entries: std::sync::Mutex<std::collections::VecDeque<(String, VectorCell)>>,
106}
107
108type 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 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 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#[derive(Clone)]
176pub struct SqliteMemory {
177 pool: SqlitePool,
178 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 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 pub fn with_channel_ids(mut self, channels: Arc<dyn ChannelIds>) -> Self {
207 self.channels = channels;
208 self
209 }
210
211 pub fn with_error_cleaner(mut self, clean: fn(&str) -> String) -> Self {
214 self.clean_error_text = clean;
215 self
216 }
217
218 pub fn with_message_log(mut self, messages: Arc<dyn crate::history::MessageLog>) -> Self {
222 self.messages = Some(messages);
223 self
224 }
225
226 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 pub fn pool(&self) -> &SqlitePool {
243 &self.pool
244 }
245}
246
247fn parse_dt(s: String) -> DateTime<Utc> {
248 crate::types::parse_ts(&s).unwrap_or_else(Utc::now)
249}
250
251#[cfg(test)]
252mod query_memo_tests {
253 use std::sync::Arc;
254 use std::sync::atomic::{AtomicUsize, Ordering};
255
256 use async_trait::async_trait;
257
258 use super::{QUERY_MEMO_CAPACITY, StoreModels};
259 use crate::Embedder;
260
261 struct Counting {
262 runs: AtomicUsize,
263 fail_first: bool,
264 }
265
266 #[async_trait]
267 impl Embedder for Counting {
268 fn model_id(&self) -> &str {
269 "counting"
270 }
271 fn dimensions(&self) -> usize {
272 1
273 }
274 async fn embed(&self, texts: &[String]) -> crate::Result<Vec<Vec<f32>>> {
275 let run = self.runs.fetch_add(1, Ordering::SeqCst);
276 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
277 if self.fail_first && run == 0 {
278 return Err(crate::MemoryError::Embedding("model not loaded yet".into()));
279 }
280 Ok(texts.iter().map(|text| vec![text.len() as f32]).collect())
281 }
282 }
283
284 fn models(fail_first: bool) -> (StoreModels, Arc<Counting>) {
285 let embedder = Arc::new(Counting {
286 runs: AtomicUsize::new(0),
287 fail_first,
288 });
289 let models = StoreModels {
290 embedder: embedder.clone(),
291 queries: Arc::default(),
292 };
293 (models, embedder)
294 }
295
296 #[tokio::test]
297 async fn concurrent_searches_for_one_text_share_one_model_run() {
298 let (models, embedder) = models(false);
299 let text = "what is on my calendar".to_string();
300 let (a, b, c, d) = tokio::join!(
301 models.embed(text.clone()),
302 models.embed(text.clone()),
303 models.embed(text.clone()),
304 models.embed(text.clone()),
305 );
306 let results = [a.unwrap(), b.unwrap(), c.unwrap(), d.unwrap()];
307 assert!(results.iter().all(|vector| vector == &results[0]));
308 assert_eq!(embedder.runs.load(Ordering::SeqCst), 1);
309 models.embed("another question".to_string()).await.unwrap();
311 assert_eq!(embedder.runs.load(Ordering::SeqCst), 2);
312 }
313
314 #[tokio::test]
315 async fn a_failed_run_is_retried_and_old_texts_are_evicted() {
316 let (models, embedder) = models(true);
317 assert!(models.embed("first".to_string()).await.is_err());
318 assert!(models.embed("first".to_string()).await.is_ok());
319 assert_eq!(embedder.runs.load(Ordering::SeqCst), 2);
320 for n in 0..QUERY_MEMO_CAPACITY {
321 models.embed(format!("text {n}")).await.unwrap();
322 }
323 let before = embedder.runs.load(Ordering::SeqCst);
324 models.embed("first".to_string()).await.unwrap();
325 assert_eq!(embedder.runs.load(Ordering::SeqCst), before + 1);
326 }
327}