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 ConflictCandidate, ConflictVerdict, FoldCandidate, FoldRule, FoldScope,
43 NUMERIC_CONFLICT_MIN_SIMILARITY, NumericConflict, ONE_VALUE_MIN_SIMILARITY,
44 ONE_WORD_VALUE_MIN_SIMILARITY, PlannedFold, detect_overlaps, detect_overlaps_excluding,
45 facts_hold_one_value, fold_scope_key, is_owner_app_channel, numeric_conflict_retirements,
46 overlap_pair, parse_fact_timestamp, plan_folds, plan_numeric_conflicts, value_numbers,
47};
48pub(crate) use facts::{FACT_RESTATEMENT_MIN_SIMILARITY, facts_make_the_same_claim};
49pub use facts::{
50 OWNER_QUOTED_SOURCE, build_fact_embedding_text, fact_category_is_personal, fact_source_rank,
51 facts_are_restatements, is_owner_authored_fact_source, keys_name_same_attribute,
52};
53pub use retention::{MemoryRetention, MemoryRetentionPolicy, MemoryRetentionStats};
54pub use schema::{migrate, rebuild_memory_fts_projections};
55
56#[cfg(test)]
58const EMBEDDING_DIM: usize = 384;
59
60fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
61 crate::cosine(a, b)
62}
63
64fn episode_search_score(similarity: f32, recall_count: i32) -> f32 {
65 similarity * crate::episode_recall_boost(recall_count.max(0) as u32)
66}
67
68pub trait ChannelIds: Send + Sync {
71 fn same_channel(&self, stored: &str, current: &str) -> bool {
73 stored == current
74 }
75
76 fn channel_of_session(&self, _session_id: &str) -> Option<String> {
78 None
79 }
80}
81
82#[derive(Debug, Default, Clone, Copy)]
84pub struct ExactChannelIds;
85
86impl ChannelIds for ExactChannelIds {}
87
88#[derive(Clone)]
90pub(crate) struct StoreModels {
91 embedder: Arc<dyn Embedder>,
92 queries: Arc<QueryMemo>,
94}
95
96const QUERY_MEMO_CAPACITY: usize = 8;
98
99#[derive(Default)]
107struct QueryMemo {
108 entries: std::sync::Mutex<std::collections::VecDeque<(String, VectorCell)>>,
109}
110
111type VectorCell = Arc<tokio::sync::OnceCell<Vec<f32>>>;
113
114impl QueryMemo {
115 fn cell(&self, text: &str) -> VectorCell {
116 let Ok(mut entries) = self.entries.lock() else {
117 return Arc::new(tokio::sync::OnceCell::new());
118 };
119 if let Some(position) = entries.iter().position(|(key, _)| key == text) {
120 let entry = entries.remove(position).expect("position is in range");
121 let cell = entry.1.clone();
122 entries.push_back(entry);
123 return cell;
124 }
125 let cell = Arc::new(tokio::sync::OnceCell::new());
126 entries.push_back((text.to_string(), cell.clone()));
127 while entries.len() > QUERY_MEMO_CAPACITY {
128 entries.pop_front();
129 }
130 cell
131 }
132}
133
134impl StoreModels {
135 fn model_id(&self) -> String {
136 self.embedder.model_id().to_string()
137 }
138
139 fn decode(&self, blob: &[u8]) -> anyhow::Result<Vec<f32>> {
143 decode_embedding_with_dim(blob, self.embedder.dimensions()).map_err(anyhow::Error::from)
144 }
145
146 async fn embed(&self, text: String) -> anyhow::Result<Vec<f32>> {
147 let cell = self.queries.cell(&text);
148 cell.get_or_try_init(|| async {
149 self.embedder
150 .embed(&[text])
151 .await?
152 .into_iter()
153 .next()
154 .ok_or_else(|| anyhow::anyhow!("embedder returned no vector"))
155 })
156 .await
157 .cloned()
158 }
159
160 async fn embed_many(&self, texts: Vec<String>) -> anyhow::Result<Vec<Vec<f32>>> {
163 if texts.is_empty() {
164 return Ok(Vec::new());
165 }
166 let expected = texts.len();
167 let vectors = self.embedder.embed(&texts).await?;
168 anyhow::ensure!(
169 vectors.len() == expected,
170 "embedder returned {} vectors for {expected} texts",
171 vectors.len()
172 );
173 Ok(vectors)
174 }
175}
176
177#[derive(Clone)]
179pub struct SqliteMemory {
180 pool: SqlitePool,
181 embedding_index: crate::embedding_index::SqliteEmbeddingIndex,
184 embedding_service: StoreModels,
185 fact_upsert_lock: Arc<Mutex<()>>,
186 channels: Arc<dyn ChannelIds>,
187 clean_error_text: fn(&str) -> String,
188 messages: Option<Arc<dyn crate::history::MessageLog>>,
189}
190
191impl SqliteMemory {
192 pub fn new(pool: SqlitePool, embedder: Arc<dyn Embedder>) -> Self {
194 Self {
195 embedding_index: crate::embedding_index::SqliteEmbeddingIndex::new(pool.clone()),
196 pool,
197 embedding_service: StoreModels {
198 embedder,
199 queries: Arc::default(),
200 },
201 fact_upsert_lock: Arc::new(Mutex::new(())),
202 channels: Arc::new(ExactChannelIds),
203 clean_error_text: str::to_string,
204 messages: None,
205 }
206 }
207
208 pub fn with_channel_ids(mut self, channels: Arc<dyn ChannelIds>) -> Self {
210 self.channels = channels;
211 self
212 }
213
214 pub fn with_error_cleaner(mut self, clean: fn(&str) -> String) -> Self {
217 self.clean_error_text = clean;
218 self
219 }
220
221 pub fn with_message_log(mut self, messages: Arc<dyn crate::history::MessageLog>) -> Self {
225 self.messages = Some(messages);
226 self
227 }
228
229 async fn message_event_bounds(
233 &self,
234 session_id: &str,
235 start: DateTime<Utc>,
236 end: DateTime<Utc>,
237 ) -> anyhow::Result<(Option<i64>, Option<i64>)> {
238 match &self.messages {
239 Some(messages) => messages.message_bounds(session_id, start, end).await,
240 None => Ok((None, None)),
241 }
242 }
243
244 pub fn pool(&self) -> &SqlitePool {
246 &self.pool
247 }
248}
249
250fn parse_dt(s: String) -> DateTime<Utc> {
251 crate::types::parse_ts(&s).unwrap_or_else(Utc::now)
252}
253
254#[cfg(test)]
255mod query_memo_tests {
256 use std::sync::Arc;
257 use std::sync::atomic::{AtomicUsize, Ordering};
258
259 use async_trait::async_trait;
260
261 use super::{QUERY_MEMO_CAPACITY, StoreModels};
262 use crate::Embedder;
263
264 struct Counting {
265 runs: AtomicUsize,
266 fail_first: bool,
267 }
268
269 #[async_trait]
270 impl Embedder for Counting {
271 fn model_id(&self) -> &str {
272 "counting"
273 }
274 fn dimensions(&self) -> usize {
275 1
276 }
277 async fn embed(&self, texts: &[String]) -> crate::Result<Vec<Vec<f32>>> {
278 let run = self.runs.fetch_add(1, Ordering::SeqCst);
279 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
280 if self.fail_first && run == 0 {
281 return Err(crate::MemoryError::Embedding("model not loaded yet".into()));
282 }
283 Ok(texts.iter().map(|text| vec![text.len() as f32]).collect())
284 }
285 }
286
287 fn models(fail_first: bool) -> (StoreModels, Arc<Counting>) {
288 let embedder = Arc::new(Counting {
289 runs: AtomicUsize::new(0),
290 fail_first,
291 });
292 let models = StoreModels {
293 embedder: embedder.clone(),
294 queries: Arc::default(),
295 };
296 (models, embedder)
297 }
298
299 #[tokio::test]
300 async fn concurrent_searches_for_one_text_share_one_model_run() {
301 let (models, embedder) = models(false);
302 let text = "what is on my calendar".to_string();
303 let (a, b, c, d) = tokio::join!(
304 models.embed(text.clone()),
305 models.embed(text.clone()),
306 models.embed(text.clone()),
307 models.embed(text.clone()),
308 );
309 let results = [a.unwrap(), b.unwrap(), c.unwrap(), d.unwrap()];
310 assert!(results.iter().all(|vector| vector == &results[0]));
311 assert_eq!(embedder.runs.load(Ordering::SeqCst), 1);
312 models.embed("another question".to_string()).await.unwrap();
314 assert_eq!(embedder.runs.load(Ordering::SeqCst), 2);
315 }
316
317 #[tokio::test]
318 async fn a_failed_run_is_retried_and_old_texts_are_evicted() {
319 let (models, embedder) = models(true);
320 assert!(models.embed("first".to_string()).await.is_err());
321 assert!(models.embed("first".to_string()).await.is_ok());
322 assert_eq!(embedder.runs.load(Ordering::SeqCst), 2);
323 for n in 0..QUERY_MEMO_CAPACITY {
324 models.embed(format!("text {n}")).await.unwrap();
325 }
326 let before = embedder.runs.load(Ordering::SeqCst);
327 models.embed("first".to_string()).await.unwrap();
328 assert_eq!(embedder.runs.load(Ordering::SeqCst), before + 1);
329 }
330}