klieo-memory-sqlite 0.39.0

SQLite-backed implementations of klieo-core's memory traits.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! `SqliteLongTerm` — `LongTermMemory` over a SQLite table with
//! linear-scan cosine recall (default) or sqlite-vec k-NN MATCH
//! (under feature `sqlite-vec`).
//!
//! Embeddings are stored as `BLOB` (little-endian f32 array). On
//! `recall`, all rows matching the scope are loaded, the query is
//! embedded, cosine similarity is computed in Rust, results are sorted
//! and the top `k` returned. Acceptable for under ~10k facts; when the
//! `sqlite-vec` feature is enabled, a virtual shadow table is used for
//! k-NN via the MATCH operator instead.

use crate::connection::DbHandle;
use crate::embedder::Embedder;
use async_trait::async_trait;
use klieo_core::error::MemoryError;
use klieo_core::ids::FactId;
use klieo_core::memory::{Fact, LongTermMemory, Scope};
use std::sync::Arc;

/// SQLite-backed long-term semantic memory.
pub struct SqliteLongTerm {
    db: DbHandle,
    embedder: Arc<dyn Embedder>,
}

impl SqliteLongTerm {
    pub(crate) fn new(db: DbHandle, embedder: Arc<dyn Embedder>) -> Self {
        Self { db, embedder }
    }
}

fn scope_to_kv(scope: &Scope) -> (&'static str, String) {
    match scope {
        Scope::Workspace(s) => ("workspace", s.clone()),
        Scope::Agent(s) => ("agent", s.clone()),
        Scope::Global => ("global", String::new()),
    }
}

fn embedding_to_blob(v: &[f32]) -> Vec<u8> {
    let mut out = Vec::with_capacity(v.len() * 4);
    for x in v {
        out.extend_from_slice(&x.to_le_bytes());
    }
    out
}

#[cfg(not(feature = "sqlite-vec"))]
fn blob_to_embedding(b: &[u8]) -> Result<Vec<f32>, MemoryError> {
    if !b.len().is_multiple_of(4) {
        return Err(MemoryError::Serialization(format!(
            "embedding blob length not multiple of 4: {}",
            b.len()
        )));
    }
    Ok(b.chunks_exact(4)
        .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
        .collect())
}

#[cfg(not(feature = "sqlite-vec"))]
fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
    if a.len() != b.len() {
        return 0.0;
    }
    let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
    let na: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
    let nb: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
    if na == 0.0 || nb == 0.0 {
        // Zero-vector → undefined direction; treat as max similarity so
        // DummyEmbedder behaves predictably (FIFO-ish recall).
        return 1.0;
    }
    dot / (na * nb)
}

#[async_trait]
impl LongTermMemory for SqliteLongTerm {
    async fn remember(&self, scope: Scope, fact: Fact) -> Result<FactId, MemoryError> {
        let id = FactId(format!(
            "fact-{}-{}",
            ulid::Ulid::new(),
            chrono::Utc::now().timestamp_nanos_opt().unwrap_or(0)
        ));
        let id_inner = id.0.clone();
        let (kind, value) = scope_to_kv(&scope);
        let metadata_json = serde_json::to_string(&fact.metadata)
            .map_err(|e| MemoryError::Serialization(e.to_string()))?;
        let embeds = self
            .embedder
            .embed(std::slice::from_ref(&fact.text))
            .await?;
        let embedding = embeds
            .into_iter()
            .next()
            .ok_or_else(|| MemoryError::Embedding("embedder returned empty vec".into()))?;
        let dim = self.embedder.dimension();
        if embedding.len() != dim {
            return Err(MemoryError::Embedding(format!(
                "embedder produced {}-dim vector, expected {dim}",
                embedding.len()
            )));
        }
        let blob = embedding_to_blob(&embedding);
        let text = fact.text;
        self.db
            .execute(move |conn| {
                let tx = conn.transaction()?;
                tx.execute(
                    "INSERT INTO long_term_facts (id, scope_kind, scope_value, text, metadata, embedding) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                    rusqlite::params![&id_inner, kind, &value, &text, &metadata_json, &blob],
                )?;
                #[cfg(feature = "sqlite-vec")]
                {
                    tx.execute(
                        "INSERT INTO long_term_facts_vec (fact_id, embedding) VALUES (?1, ?2)",
                        rusqlite::params![&id_inner, &blob],
                    )?;
                }
                tx.commit()?;
                Ok(())
            })
            .await?;
        Ok(id)
    }

    #[allow(unreachable_code)]
    async fn recall(&self, scope: Scope, query: &str, k: usize) -> Result<Vec<Fact>, MemoryError> {
        if k == 0 {
            return Ok(Vec::new());
        }
        let (kind, value) = scope_to_kv(&scope);
        let query_embeds = self.embedder.embed(&[query.to_string()]).await?;
        let query_vec = query_embeds
            .into_iter()
            .next()
            .ok_or_else(|| MemoryError::Embedding("embedder returned empty vec".into()))?;
        let kind_owned = kind.to_string();
        let value_owned = value;

        #[cfg(feature = "sqlite-vec")]
        {
            // Fast path: k-NN via sqlite-vec MATCH operator. Filters
            // post-MATCH by scope.
            let query_blob = embedding_to_blob(&query_vec);
            let k_i64 = k as i64;
            let rows: Vec<(String, String)> = self
                .db
                .execute(move |conn| {
                    let mut stmt = conn.prepare(
                        r#"
                        SELECT f.text, f.metadata
                        FROM long_term_facts_vec v
                        JOIN long_term_facts f ON f.id = v.fact_id
                        WHERE v.embedding MATCH ?1 AND k = ?2
                          AND f.scope_kind = ?3 AND f.scope_value = ?4
                        ORDER BY v.distance ASC
                        "#,
                    )?;
                    let iter = stmt.query_map(
                        rusqlite::params![&query_blob, k_i64, &kind_owned, &value_owned],
                        |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)),
                    )?;
                    iter.collect::<Result<Vec<_>, _>>()
                })
                .await?;
            return rows
                .into_iter()
                .map(|(text, metadata_json)| {
                    let metadata: serde_json::Value = serde_json::from_str(&metadata_json)
                        .map_err(|e| MemoryError::Serialization(e.to_string()))?;
                    Ok(Fact { text, metadata })
                })
                .collect();
        }

        // Slow path (no sqlite-vec feature): linear scan + cosine.
        //
        // W5.A26 / round-1 perf MED: this path is O(N) in facts per
        // scope. For scopes above ~10 000 facts the per-call cost
        // dominates agent recall latency; the `sqlite-vec` feature
        // routes through a virtual-table MATCH that uses a real k-NN
        // index. We cap the row stream at MAX_SLOW_PATH_FACTS to
        // protect the agent from a runaway scope — callers hitting
        // the cap get a hint to enable the fast feature.
        #[cfg(not(feature = "sqlite-vec"))]
        {
            const MAX_SLOW_PATH_FACTS: usize = 10_000;
            let row_cap = MAX_SLOW_PATH_FACTS as i64;
            let rows: Vec<(String, String, Vec<u8>)> = self
                .db
                .execute(move |conn| {
                    let mut stmt = conn.prepare(
                        "SELECT text, metadata, embedding FROM long_term_facts \
                         WHERE scope_kind = ?1 AND scope_value = ?2 \
                         LIMIT ?3",
                    )?;
                    let iter = stmt.query_map(
                        rusqlite::params![&kind_owned, &value_owned, row_cap],
                        |row| {
                            Ok((
                                row.get::<_, String>(0)?,
                                row.get::<_, String>(1)?,
                                row.get::<_, Vec<u8>>(2)?,
                            ))
                        },
                    )?;
                    iter.collect::<Result<Vec<_>, _>>()
                })
                .await?;
            if rows.len() == MAX_SLOW_PATH_FACTS {
                tracing::warn!(
                    target: "klieo.memory.sqlite",
                    scope_kind = ?kind,
                    cap = MAX_SLOW_PATH_FACTS,
                    "long-term recall hit slow-path row cap — enable the \
                     `sqlite-vec` feature for O(log N) k-NN recall"
                );
            }
            let mut scored: Vec<(f32, Fact)> = Vec::with_capacity(rows.len());
            for (text, metadata_json, blob) in rows {
                let emb = blob_to_embedding(&blob)?;
                let score = cosine_similarity(&query_vec, &emb);
                let metadata: serde_json::Value = serde_json::from_str(&metadata_json)
                    .map_err(|e| MemoryError::Serialization(e.to_string()))?;
                scored.push((score, Fact { text, metadata }));
            }
            scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
            return Ok(scored.into_iter().take(k).map(|(_, f)| f).collect());
        }
    }

    async fn forget(&self, id: FactId) -> Result<(), MemoryError> {
        let id_inner = id.0;
        self.db
            .execute(move |conn| {
                let tx = conn.transaction()?;
                tx.execute(
                    "DELETE FROM long_term_facts WHERE id = ?1",
                    rusqlite::params![&id_inner],
                )?;
                #[cfg(feature = "sqlite-vec")]
                {
                    tx.execute(
                        "DELETE FROM long_term_facts_vec WHERE fact_id = ?1",
                        rusqlite::params![&id_inner],
                    )?;
                }
                tx.commit()?;
                Ok(())
            })
            .await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::embedder::FakeEmbedder;
    use std::sync::Arc;

    async fn fresh() -> SqliteLongTerm {
        let db = DbHandle::open(":memory:").await.unwrap();
        let e: Arc<dyn Embedder> = Arc::new(FakeEmbedder::new(8));
        #[cfg(feature = "sqlite-vec")]
        {
            db.create_vec_table(e.dimension()).await.unwrap();
        }
        SqliteLongTerm::new(db, e)
    }

    fn fact(text: &str) -> Fact {
        Fact {
            text: text.into(),
            metadata: serde_json::Value::Null,
        }
    }

    #[tokio::test]
    async fn remember_then_recall_finds_exact_match() {
        let m = fresh().await;
        m.remember(
            Scope::Workspace("w1".into()),
            fact("the cat sat on the mat"),
        )
        .await
        .unwrap();
        m.remember(Scope::Workspace("w1".into()), fact("rust async runtimes"))
            .await
            .unwrap();
        let hits = m
            .recall(Scope::Workspace("w1".into()), "the cat sat on the mat", 1)
            .await
            .unwrap();
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].text, "the cat sat on the mat");
    }

    #[tokio::test]
    async fn recall_isolates_by_scope() {
        let m = fresh().await;
        m.remember(Scope::Workspace("w1".into()), fact("workspace one fact"))
            .await
            .unwrap();
        m.remember(Scope::Workspace("w2".into()), fact("workspace two fact"))
            .await
            .unwrap();
        let hits = m
            .recall(Scope::Workspace("w1".into()), "any query", 10)
            .await
            .unwrap();
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].text, "workspace one fact");
    }

    #[tokio::test]
    async fn recall_respects_k() {
        let m = fresh().await;
        for i in 0..5 {
            m.remember(Scope::Global, fact(&format!("fact-{i}")))
                .await
                .unwrap();
        }
        let hits = m.recall(Scope::Global, "any", 2).await.unwrap();
        assert_eq!(hits.len(), 2);
    }

    #[tokio::test]
    async fn forget_removes_fact() {
        let m = fresh().await;
        let id = m.remember(Scope::Global, fact("fleeting")).await.unwrap();
        m.forget(id).await.unwrap();
        let hits = m.recall(Scope::Global, "any", 10).await.unwrap();
        assert!(hits.is_empty());
    }

    #[cfg(feature = "sqlite-vec")]
    #[tokio::test]
    async fn forget_removes_fact_from_vec_index_too() {
        // After forget, MATCH-based recall must not return the deleted fact.
        let m = fresh().await;
        let id_keep = m
            .remember(
                Scope::Global,
                Fact {
                    text: "keeper".into(),
                    metadata: serde_json::Value::Null,
                },
            )
            .await
            .unwrap();
        let id_drop = m
            .remember(
                Scope::Global,
                Fact {
                    text: "to be forgotten".into(),
                    metadata: serde_json::Value::Null,
                },
            )
            .await
            .unwrap();
        m.forget(id_drop).await.unwrap();
        let _ = id_keep; // suppress unused-binding warning
        let hits = m.recall(Scope::Global, "to be forgotten", 5).await.unwrap();
        // Recall MATCH-fast-path must not return the forgotten fact.
        assert!(
            !hits.iter().any(|f| f.text == "to be forgotten"),
            "forget did not remove fact from vec0 index; got: {hits:?}"
        );
    }

    #[tokio::test]
    async fn metadata_round_trips() {
        let m = fresh().await;
        m.remember(
            Scope::Global,
            Fact {
                text: "with metadata".into(),
                metadata: serde_json::json!({"k": "v", "n": 7}),
            },
        )
        .await
        .unwrap();
        let hits = m.recall(Scope::Global, "with metadata", 1).await.unwrap();
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].metadata, serde_json::json!({"k": "v", "n": 7}));
    }

    #[cfg(not(feature = "sqlite-vec"))]
    #[test]
    fn cosine_similarity_identical_vectors_returns_one() {
        let v = vec![1.0_f32, 0.0, 0.0];
        let score = cosine_similarity(&v, &v);
        assert!(
            (score - 1.0).abs() < 1e-6,
            "identical vectors must have similarity 1.0, got {score}"
        );
    }

    #[cfg(not(feature = "sqlite-vec"))]
    #[test]
    fn cosine_similarity_orthogonal_vectors_returns_zero() {
        let a = vec![1.0_f32, 0.0, 0.0];
        let b = vec![0.0_f32, 1.0, 0.0];
        let score = cosine_similarity(&a, &b);
        assert!(
            score.abs() < 1e-6,
            "orthogonal vectors must have similarity 0.0, got {score}"
        );
    }
}