Skip to main content

memory/
sqlite.rs

1//! The `sqlite` provider: one SQLite database per user holds every scope.
2//! Each memory is a row tagged with its scope and owner (the project root
3//! or the session id), so a query only ever sees the scopes its context
4//! reaches. SQLite is compiled into the program (`rusqlite`, `bundled`):
5//! no system library and no extension.
6//!
7//! The tables:
8//!
9//! ```text
10//! memories(key, scope, owner, name, kind, title, description, body,
11//!          links, created, updated)
12//! edges(memory, relation, target, valid_from, valid_to)
13//!     IN_PROJECT -> project root    IN_SESSION -> session id
14//!     ABOUT_FILE -> path            ABOUT_PANE -> pane (`%3`)
15//!     LINKS_TO   -> another memory's key
16//! vectors(memory, model, v)         one per memory, little-endian f32
17//! collector_rows(...)               rows the collectors keep
18//! summaries(session, text, updated) one per agent session
19//! imported(scope, owner, at, memories)
20//!                                   scope owners copied in from files
21//! ```
22//!
23//! Every edge has a valid time in microseconds: when a link is dropped its
24//! edge is closed (`valid_to` set), not deleted, so the database keeps what
25//! was true until when. Forgetting a memory deletes it, its edges, and the
26//! edges other memories had to it. Recall is the one the Kosmonaut
27//! provider gives ([`crate::graph::recall`]): words exactly as
28//! [`crate::search`] ranks them, then memories one edge away, then, with an
29//! embedder, memories whose vectors are near the query's.
30//!
31//! The database is opened on the first call and kept open; every call
32//! reads it again, so nothing cached goes stale. Each write is one
33//! transaction. `PRAGMA user_version` records the schema, so a later
34//! Dreamer can migrate it and an older one refuses a newer database.
35//!
36//! Made with [`Sqlite::importing`], the provider copies in what the
37//! `files` layout holds, once per scope owner: the user and host scopes on
38//! the first call, a project the first time a context reaches it, a
39//! session likewise. `imported` records each owner done (even one with no
40//! files), so nothing is copied twice, and a memory forgotten here does
41//! not come back. The copy keeps ids, kinds, text, links, and times, and
42//! leaves a memory this database already holds under the same id; the
43//! files are only read. A file that does not read is left where it is and
44//! reported once, in the problems of the next list or recall.
45
46use std::collections::BTreeMap;
47use std::path::{Path, PathBuf};
48use std::sync::{Arc, Mutex, MutexGuard};
49use std::time::Duration;
50
51use rusqlite::{Connection, OptionalExtension, Transaction, TransactionBehavior, params};
52
53use crate::embed::Embedder;
54use crate::graph::{self, CollectorRow, Recall, Summary, Vectors};
55use crate::{
56    Change, Context, Error, Files, Found, Kind, Memory, New, Problem, Provider, Scope, split_id,
57    time,
58};
59
60/// The schema this Dreamer writes, in `PRAGMA user_version`.
61const SCHEMA: i64 = 2;
62
63/// Each schema step, from the one before it: `STEPS[0]` makes version 1.
64const STEPS: &[&str] = &[
65    "
66CREATE TABLE memories(
67    key TEXT PRIMARY KEY,
68    scope TEXT NOT NULL,
69    owner TEXT NOT NULL,
70    name TEXT NOT NULL,
71    kind TEXT NOT NULL,
72    title TEXT NOT NULL,
73    description TEXT NOT NULL,
74    body TEXT NOT NULL,
75    links TEXT NOT NULL,
76    created INTEGER NOT NULL,
77    updated INTEGER NOT NULL
78);
79CREATE INDEX memories_owner ON memories(scope, owner);
80CREATE TABLE edges(
81    memory TEXT NOT NULL REFERENCES memories(key) ON DELETE CASCADE,
82    relation TEXT NOT NULL,
83    target TEXT NOT NULL,
84    valid_from INTEGER NOT NULL,
85    valid_to INTEGER
86);
87CREATE INDEX edges_memory ON edges(memory);
88CREATE INDEX edges_target ON edges(relation, target);
89CREATE TABLE vectors(
90    memory TEXT PRIMARY KEY REFERENCES memories(key) ON DELETE CASCADE,
91    model TEXT NOT NULL,
92    v BLOB NOT NULL
93);
94CREATE TABLE collector_rows(
95    id INTEGER PRIMARY KEY,
96    collector TEXT NOT NULL,
97    at INTEGER NOT NULL,
98    pane TEXT NOT NULL,
99    session TEXT,
100    cwd TEXT,
101    project TEXT,
102    command TEXT,
103    fields TEXT NOT NULL,
104    context TEXT NOT NULL
105);
106CREATE INDEX collector_rows_at ON collector_rows(collector, at);
107CREATE INDEX collector_rows_pane ON collector_rows(pane);
108CREATE INDEX collector_rows_session ON collector_rows(session);
109CREATE INDEX collector_rows_project ON collector_rows(project);
110CREATE TABLE summaries(
111    session TEXT PRIMARY KEY,
112    text TEXT NOT NULL,
113    updated INTEGER NOT NULL
114);
115",
116    "
117CREATE TABLE imported(
118    scope TEXT NOT NULL,
119    owner TEXT NOT NULL,
120    at INTEGER NOT NULL,
121    memories INTEGER NOT NULL,
122    PRIMARY KEY(scope, owner)
123);
124",
125];
126
127/// How long a call waits for another connection's write to finish.
128const BUSY: Duration = Duration::from_secs(5);
129
130pub struct Sqlite {
131    path: PathBuf,
132    embedder: Option<Arc<dyn Embedder>>,
133    /// Opened on first use and kept; tried again on the next call if
134    /// opening failed. One call at a time uses it.
135    conn: Mutex<Option<Connection>>,
136    /// Where memories are copied in from, once per scope owner.
137    files: Option<Arc<Files>>,
138    /// Files the copy could not read, until a list or recall reports them.
139    unread: Mutex<Vec<Problem>>,
140}
141
142impl std::fmt::Debug for Sqlite {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        f.debug_struct("Sqlite")
145            .field("path", &self.path)
146            .field("embedder", &self.embedder.as_ref().map(|e| e.model()))
147            .finish_non_exhaustive()
148    }
149}
150
151fn db_error(e: impl std::fmt::Display) -> Error {
152    Error::Io(format!("sqlite: {e}"))
153}
154
155fn json(v: &impl serde::Serialize) -> Result<String, Error> {
156    serde_json::to_string(v).map_err(|e| Error::Io(e.to_string()))
157}
158
159fn int(v: u64) -> i64 {
160    i64::try_from(v).unwrap_or(i64::MAX)
161}
162
163fn blob(v: &[f32]) -> Vec<u8> {
164    v.iter().flat_map(|x| x.to_le_bytes()).collect()
165}
166
167fn floats(b: &[u8]) -> Option<Vec<f32>> {
168    let (words, rest) = b.as_chunks::<4>();
169    rest.is_empty()
170        .then(|| words.iter().map(|w| f32::from_le_bytes(*w)).collect())
171}
172
173/// Columns every memory read returns, in this order.
174const COLUMNS: &str = "scope, name, kind, title, description, body, links, created, updated, key";
175
176fn memory(row: &rusqlite::Row<'_>) -> rusqlite::Result<Option<(String, Memory)>> {
177    let scope: String = row.get(0)?;
178    let name: String = row.get(1)?;
179    let kind: String = row.get(2)?;
180    let links: String = row.get(6)?;
181    let (Some(scope), Some(kind)) = (Scope::from_name(&scope), Kind::from_name(&kind)) else {
182        return Ok(None);
183    };
184    let ms = |i| row.get::<_, i64>(i).map(|v| u64::try_from(v).unwrap_or(0));
185    Ok(Some((
186        row.get(9)?,
187        Memory {
188            id: format!("{}/{name}", scope.name()),
189            scope,
190            kind,
191            title: row.get(3)?,
192            description: row.get(4)?,
193            text: row.get(5)?,
194            links: serde_json::from_str(&links).unwrap_or_default(),
195            created_unix_ms: ms(7)?,
196            updated_unix_ms: ms(8)?,
197            path: None,
198            score: None,
199        },
200    )))
201}
202
203fn find(c: &Connection, k: &str) -> Result<Option<Memory>, Error> {
204    c.query_row(
205        &format!("SELECT {COLUMNS} FROM memories WHERE key = ?1"),
206        [k],
207        memory,
208    )
209    .optional()
210    .map(|m| m.flatten().map(|(_, m)| m))
211    .map_err(db_error)
212}
213
214fn exists(c: &Connection, k: &str) -> Result<bool, Error> {
215    c.query_row("SELECT 1 FROM memories WHERE key = ?1", [k], |_| Ok(()))
216        .optional()
217        .map(|r| r.is_some())
218        .map_err(db_error)
219}
220
221/// Whether the scope owner was copied in from files already.
222fn done(c: &Connection, scope: Scope, owner: &str) -> Result<bool, Error> {
223    c.query_row(
224        "SELECT 1 FROM imported WHERE scope = ?1 AND owner = ?2",
225        params![scope.name(), owner],
226        |_| Ok(()),
227    )
228    .optional()
229    .map(|r| r.is_some())
230    .map_err(db_error)
231}
232
233/// Make the tables, or bring them up to [`SCHEMA`].
234fn migrate(c: &mut Connection, path: &Path) -> Result<(), Error> {
235    let tx = c
236        .transaction_with_behavior(TransactionBehavior::Immediate)
237        .map_err(db_error)?;
238    let version: i64 = tx
239        .query_row("PRAGMA user_version", [], |r| r.get(0))
240        .map_err(db_error)?;
241    if version > SCHEMA {
242        return Err(Error::Io(format!(
243            "sqlite: {} has schema {version}; this Dreamer reads {SCHEMA}",
244            path.display()
245        )));
246    }
247    for step in &STEPS[usize::try_from(version).unwrap_or(0)..] {
248        tx.execute_batch(step).map_err(db_error)?;
249    }
250    if version < SCHEMA {
251        tx.pragma_update(None, "user_version", SCHEMA)
252            .map_err(db_error)?;
253    }
254    tx.commit().map_err(db_error)
255}
256
257impl Sqlite {
258    /// The provider over the database at `path` (a file, made on first
259    /// use). With `embedder`, memories also get vectors and recall also
260    /// looks for memories near the query in meaning.
261    pub fn new(path: PathBuf, embedder: Option<Arc<dyn Embedder>>) -> Sqlite {
262        Sqlite {
263            path,
264            embedder,
265            conn: Mutex::new(None),
266            files: None,
267            unread: Mutex::new(Vec::new()),
268        }
269    }
270
271    /// Copy in what `files` holds, once for each scope owner a call
272    /// reaches (see the module documentation). The files are only read.
273    pub fn importing(mut self, files: Arc<Files>) -> Sqlite {
274        self.files = Some(files);
275        self
276    }
277
278    /// Copy in from `files` each scope owner `cx` reaches that has not
279    /// been copied yet.
280    fn adopt(&self, cx: &Context) -> Result<(), Error> {
281        let Some(files) = &self.files else {
282            return Ok(());
283        };
284        for scope in crate::reach(cx) {
285            // A scope the context cannot name, or the files layout has no
286            // place for (no configuration directory), has nothing to copy;
287            // the call itself says what is wrong.
288            let (Ok(owner), Ok(dir)) = (graph::owner(cx, scope), files.dir(cx, scope)) else {
289                continue;
290            };
291            if done(self.conn()?.get(), scope, &owner)? {
292                continue;
293            }
294            let found = match files.list(cx, Some(scope), None) {
295                Ok(f) => f,
296                Err(e) => {
297                    // Not recorded: tried again on the next call.
298                    self.unread(vec![Problem {
299                        path: dir,
300                        message: format!("not copied into sqlite: {e}"),
301                    }]);
302                    continue;
303                }
304            };
305            let mut problems = found.problems;
306            // Oldest first, so a later memory's links find the earlier.
307            let mut items = found.items;
308            items.reverse();
309            self.write(|tx| {
310                // Another call may have copied it meanwhile.
311                if done(tx, scope, &owner)? {
312                    return Ok(());
313                }
314                let mut copied = Vec::new();
315                for m in &items {
316                    let placed = graph::placed(cx, m);
317                    let (k, owner, m) = match placed {
318                        Ok(p) => p,
319                        Err(e) => {
320                            problems.push(Problem {
321                                path: m.path.clone().unwrap_or_else(|| dir.clone()),
322                                message: e.to_string(),
323                            });
324                            continue;
325                        }
326                    };
327                    if exists(tx, &k)? {
328                        continue;
329                    }
330                    Sqlite::row(tx, &k, &owner, &m)?;
331                    copied.push((k, owner, m));
332                }
333                // Edges once every memory is in, so links between them
334                // hold whatever their order.
335                for (k, owner, m) in &copied {
336                    let wanted = graph::wanted(cx, m.scope, owner, &m.links, |t| exists(tx, t))?;
337                    relate(tx, k, &wanted)?;
338                }
339                tx.execute(
340                    "INSERT INTO imported(scope, owner, at, memories) VALUES (?1, ?2, ?3, ?4)",
341                    params![
342                        scope.name(),
343                        owner,
344                        int(time::now_ms()),
345                        i64::try_from(copied.len()).unwrap_or(i64::MAX)
346                    ],
347                )
348                .map(drop)
349                .map_err(db_error)
350            })?;
351            self.unread(problems);
352        }
353        Ok(())
354    }
355
356    fn unread(&self, problems: Vec<Problem>) {
357        if !problems.is_empty() {
358            let mut u = self.unread.lock().unwrap_or_else(|e| e.into_inner());
359            u.extend(problems);
360        }
361    }
362
363    /// `found` with the files the copy could not read, reported once.
364    fn with_unread(&self, mut found: Found) -> Found {
365        let mut u = self.unread.lock().unwrap_or_else(|e| e.into_inner());
366        if !u.is_empty() {
367            let mut problems = std::mem::take(&mut *u);
368            problems.append(&mut found.problems);
369            found.problems = problems;
370        }
371        found
372    }
373
374    pub fn path(&self) -> &Path {
375        &self.path
376    }
377
378    fn open(&self) -> Result<Connection, Error> {
379        let at = |e: &dyn std::fmt::Display| Error::Io(format!("{}: {e}", self.path.display()));
380        if let Some(parent) = self.path.parent() {
381            std::fs::create_dir_all(parent).map_err(|e| at(&e))?;
382        }
383        let mut c = Connection::open(&self.path).map_err(|e| at(&e))?;
384        c.busy_timeout(BUSY).map_err(db_error)?;
385        c.pragma_update(None, "journal_mode", "WAL")
386            .map_err(db_error)?;
387        c.pragma_update(None, "synchronous", "NORMAL")
388            .map_err(db_error)?;
389        c.pragma_update(None, "foreign_keys", true)
390            .map_err(db_error)?;
391        migrate(&mut c, &self.path)?;
392        Ok(c)
393    }
394
395    /// The connection, opened on first use.
396    fn conn(&self) -> Result<Db<'_>, Error> {
397        let mut slot = self.conn.lock().unwrap_or_else(|e| e.into_inner());
398        if slot.is_none() {
399            *slot = Some(self.open()?);
400        }
401        Ok(Db(slot))
402    }
403
404    /// Run `f` in one write transaction: all of it commits, or none.
405    fn write<T>(&self, f: impl FnOnce(&Transaction<'_>) -> Result<T, Error>) -> Result<T, Error> {
406        let mut db = self.conn()?;
407        let tx = db
408            .get()
409            .transaction_with_behavior(TransactionBehavior::Immediate)
410            .map_err(db_error)?;
411        let out = f(&tx)?;
412        tx.commit().map_err(db_error)?;
413        Ok(out)
414    }
415
416    /// Memories in `scopes` for `cx`, newest first, with their keys.
417    fn load(&self, cx: &Context, scopes: &[Scope]) -> Result<Vec<(String, Memory)>, Error> {
418        let mut owners = Vec::new();
419        for &scope in scopes {
420            owners.push((scope, graph::owner(cx, scope)?));
421        }
422        let mut db = self.conn()?;
423        let c = db.get();
424        let mut q = c
425            .prepare_cached(&format!(
426                "SELECT {COLUMNS} FROM memories WHERE scope = ?1 AND owner = ?2"
427            ))
428            .map_err(db_error)?;
429        let mut out = Vec::new();
430        for (scope, owner) in owners {
431            let rows = q
432                .query_map(params![scope.name(), owner], memory)
433                .map_err(db_error)?;
434            for r in rows {
435                out.extend(r.map_err(db_error)?);
436            }
437        }
438        graph::newest_first(&mut out);
439        Ok(out)
440    }
441
442    fn existing(&self, cx: &Context, id: &str) -> Result<(String, Memory), Error> {
443        let (scope, name) = split_id(id)?;
444        let k = graph::key(scope, &graph::owner(cx, scope)?, name);
445        let m = find(self.conn()?.get(), &k)?.ok_or_else(|| Error::NotFound(id.to_owned()))?;
446        Ok((k, m))
447    }
448
449    /// A vector for `m` now, if there is an embedder. A failure is left
450    /// for recall, which embeds what has no vector yet.
451    fn embed_one(&self, m: &Memory) -> Option<(String, Vec<f32>)> {
452        let e = self.embedder.as_ref()?;
453        let mut v = e.embed(&[&graph::vector_text(m)]).ok()?;
454        Some((e.model().to_owned(), v.pop()?))
455    }
456
457    /// Keep `m` under key `k`, creating or replacing it, with its edges
458    /// brought up to date and its vector, all in `tx`.
459    fn store(
460        tx: &Transaction<'_>,
461        cx: &Context,
462        k: &str,
463        owner: &str,
464        m: &Memory,
465        vector: Option<(String, Vec<f32>)>,
466    ) -> Result<(), Error> {
467        let wanted = graph::wanted(cx, m.scope, owner, &m.links, |t| exists(tx, t))?;
468        Sqlite::row(tx, k, owner, m)?;
469        relate(tx, k, &wanted)?;
470        match vector {
471            Some((model, v)) => {
472                tx.execute(
473                    "INSERT OR REPLACE INTO vectors(memory, model, v) VALUES (?1, ?2, ?3)",
474                    params![k, model, blob(&v)],
475                )
476                .map_err(db_error)?;
477            }
478            // The text may have changed: an old vector would mislead.
479            None => {
480                tx.execute("DELETE FROM vectors WHERE memory = ?1", [k])
481                    .map_err(db_error)?;
482            }
483        }
484        Ok(())
485    }
486
487    /// The memory's row under key `k`, created or replaced; its edges and
488    /// vector are left as they are.
489    fn row(tx: &Transaction<'_>, k: &str, owner: &str, m: &Memory) -> Result<(), Error> {
490        let (_, name) = split_id(&m.id)?;
491        tx.execute(
492            "INSERT INTO memories(key, scope, owner, name, kind, title, description, body, \
493             links, created, updated) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11) \
494             ON CONFLICT(key) DO UPDATE SET kind = excluded.kind, title = excluded.title, \
495             description = excluded.description, body = excluded.body, links = excluded.links, \
496             created = excluded.created, updated = excluded.updated",
497            params![
498                k,
499                m.scope.name(),
500                owner,
501                name,
502                m.kind.name(),
503                m.title,
504                m.description,
505                m.text,
506                json(&m.links)?,
507                int(m.created_unix_ms),
508                int(m.updated_unix_ms),
509            ],
510        )
511        .map(drop)
512        .map_err(db_error)
513    }
514
515    /// Keep a collector's row, with its pane, session, and project.
516    pub fn add_row(&self, row: &CollectorRow) -> Result<(), Error> {
517        let fields = json(&row.fields)?;
518        let context = json(&row.context)?;
519        let cwd = row.cwd.as_ref().map(|c| c.display().to_string());
520        let project = row
521            .cwd
522            .as_deref()
523            .filter(|c| c.is_absolute())
524            .map(|c| crate::project_root(c).display().to_string());
525        self.write(|tx| {
526            tx.execute(
527                "INSERT INTO collector_rows(collector, at, pane, session, cwd, project, command, \
528                 fields, context) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
529                params![
530                    row.collector,
531                    int(row.at_unix_ms),
532                    row.pane,
533                    row.session,
534                    cwd,
535                    project,
536                    row.command,
537                    fields,
538                    context,
539                ],
540            )
541            .map(drop)
542            .map_err(db_error)
543        })
544    }
545
546    /// A collector's rows at or after `since_unix_ms`, oldest first, at
547    /// most `limit`.
548    pub fn rows(
549        &self,
550        collector: &str,
551        since_unix_ms: u64,
552        limit: usize,
553    ) -> Result<Vec<CollectorRow>, Error> {
554        let mut db = self.conn()?;
555        let mut q = db
556            .get()
557            .prepare_cached(
558                "SELECT collector, at, pane, session, cwd, command, fields, context \
559                 FROM collector_rows WHERE collector = ?1 AND at >= ?2 ORDER BY at, id LIMIT ?3",
560            )
561            .map_err(db_error)?;
562        let rows = q
563            .query_map(
564                params![
565                    collector,
566                    int(since_unix_ms),
567                    i64::try_from(limit).unwrap_or(i64::MAX)
568                ],
569                |r| {
570                    let opt = |i| {
571                        r.get::<_, Option<String>>(i)
572                            .map(|v| v.filter(|t| !t.is_empty()))
573                    };
574                    let fields: String = r.get(6)?;
575                    let context: String = r.get(7)?;
576                    Ok(CollectorRow {
577                        collector: r.get(0)?,
578                        at_unix_ms: u64::try_from(r.get::<_, i64>(1)?).unwrap_or(0),
579                        pane: r.get(2)?,
580                        session: opt(3)?,
581                        cwd: opt(4)?.map(PathBuf::from),
582                        command: opt(5)?,
583                        fields: serde_json::from_str(&fields).unwrap_or_default(),
584                        context: serde_json::from_str(&context).unwrap_or_default(),
585                    })
586                },
587            )
588            .map_err(db_error)?;
589        rows.collect::<rusqlite::Result<_>>().map_err(db_error)
590    }
591
592    /// Keep `text` as the summary of `session`, replacing the one there.
593    pub fn set_summary(&self, session: &str, text: &str) -> Result<Summary, Error> {
594        let cx = Context {
595            cwd: None,
596            session: Some(session.to_owned()),
597        };
598        let session = crate::session_of(&cx)?;
599        let now = time::now_ms();
600        self.write(|tx| {
601            tx.execute(
602                "INSERT OR REPLACE INTO summaries(session, text, updated) VALUES (?1, ?2, ?3)",
603                params![session, text, int(now)],
604            )
605            .map(drop)
606            .map_err(db_error)
607        })?;
608        Ok(Summary {
609            session: session.to_owned(),
610            text: text.to_owned(),
611            updated_unix_ms: now,
612        })
613    }
614
615    pub fn summary(&self, session: &str) -> Result<Option<Summary>, Error> {
616        self.conn()?
617            .get()
618            .query_row(
619                "SELECT session, text, updated FROM summaries WHERE session = ?1",
620                [session],
621                |r| {
622                    Ok(Summary {
623                        session: r.get(0)?,
624                        text: r.get(1)?,
625                        updated_unix_ms: u64::try_from(r.get::<_, i64>(2)?).unwrap_or(0),
626                    })
627                },
628            )
629            .optional()
630            .map_err(db_error)
631    }
632
633    /// The relations of a memory as they were at `at_unix_ms`: (relation,
634    /// target), from the valid times of its edges, current ones included.
635    pub fn relations_at(
636        &self,
637        cx: &Context,
638        id: &str,
639        at_unix_ms: u64,
640    ) -> Result<Vec<(String, String)>, Error> {
641        let (k, _) = self.existing(cx, id)?;
642        let at = graph::ms_to_us(at_unix_ms);
643        let mut db = self.conn()?;
644        let mut q = db
645            .get()
646            .prepare_cached(
647                "SELECT relation, target, valid_from, valid_to FROM edges WHERE memory = ?1",
648            )
649            .map_err(db_error)?;
650        let rows = q
651            .query_map([&k], |r| {
652                Ok((
653                    r.get::<_, String>(0)?,
654                    r.get::<_, String>(1)?,
655                    r.get::<_, i64>(2)?,
656                    r.get::<_, Option<i64>>(3)?,
657                ))
658            })
659            .map_err(db_error)?;
660        let mut out = Vec::new();
661        for r in rows {
662            let (rel, target, from, to) = r.map_err(db_error)?;
663            if graph::held(from, to, at) {
664                let shown = graph::shown(&rel, &target);
665                out.push((rel, shown));
666            }
667        }
668        out.sort();
669        Ok(out)
670    }
671}
672
673/// The connection, held for one call.
674struct Db<'a>(MutexGuard<'a, Option<Connection>>);
675
676impl Db<'_> {
677    fn get(&mut self) -> &mut Connection {
678        self.0.as_mut().expect("opened before use")
679    }
680}
681
682/// Close the current edges of memory `k` that are not `wanted`, and open
683/// the wanted ones it does not have.
684fn relate(
685    tx: &Transaction<'_>,
686    k: &str,
687    wanted: &std::collections::BTreeSet<(&'static str, String)>,
688) -> Result<(), Error> {
689    let now = graph::now_us();
690    let mut q = tx
691        .prepare_cached(
692            "SELECT rowid, relation, target, valid_from FROM edges \
693             WHERE memory = ?1 AND valid_to IS NULL",
694        )
695        .map_err(db_error)?;
696    let current: Vec<(i64, String, String, i64)> = q
697        .query_map([k], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))
698        .map_err(db_error)?
699        .collect::<rusqlite::Result<_>>()
700        .map_err(db_error)?;
701    for (rowid, rel, target, from) in &current {
702        if wanted.iter().any(|(r, t)| r == rel && t == target) {
703            continue;
704        }
705        // An interval must not be empty: an edge closed in the
706        // microsecond it opened ends one later.
707        tx.execute(
708            "UPDATE edges SET valid_to = ?1 WHERE rowid = ?2",
709            params![now.max(from + 1), rowid],
710        )
711        .map_err(db_error)?;
712    }
713    for (rel, target) in wanted {
714        if current.iter().any(|(_, r, t, _)| r == rel && t == target) {
715            continue;
716        }
717        tx.execute(
718            "INSERT INTO edges(memory, relation, target, valid_from) VALUES (?1, ?2, ?3, ?4)",
719            params![k, rel, target, now],
720        )
721        .map_err(db_error)?;
722    }
723    Ok(())
724}
725
726impl Recall for Sqlite {
727    fn neighbours(&self, keys: &[String]) -> Result<BTreeMap<String, u32>, Error> {
728        let mut out: BTreeMap<String, u32> = BTreeMap::new();
729        let seeds = json(&keys)?;
730        let queries = [
731            "SELECT target FROM edges WHERE relation = 'LINKS_TO' AND valid_to IS NULL \
732             AND memory IN (SELECT value FROM json_each(?1))",
733            "SELECT memory FROM edges WHERE relation = 'LINKS_TO' AND valid_to IS NULL \
734             AND target IN (SELECT value FROM json_each(?1))",
735            "SELECT b.memory FROM edges a JOIN edges b \
736             ON b.relation = a.relation AND b.target = a.target AND b.rowid != a.rowid \
737             WHERE a.relation IN ('ABOUT_FILE', 'ABOUT_PANE') \
738             AND a.memory IN (SELECT value FROM json_each(?1)) \
739             AND a.valid_to IS NULL AND b.valid_to IS NULL",
740        ];
741        let mut db = self.conn()?;
742        let c = db.get();
743        for sql in queries {
744            let mut q = c.prepare_cached(sql).map_err(db_error)?;
745            let rows = q
746                .query_map([&seeds], |r| r.get::<_, String>(0))
747                .map_err(db_error)?;
748            for k in rows {
749                *out.entry(k.map_err(db_error)?).or_default() += 1;
750            }
751        }
752        Ok(out)
753    }
754
755    fn vectors(
756        &self,
757        e: &dyn Embedder,
758        query: &str,
759        items: &[(String, Memory)],
760    ) -> Result<(Vec<f32>, Vectors), Error> {
761        let q = e.embed(&[query])?.pop().unwrap_or_default();
762        let keys: Vec<&str> = items.iter().map(|(k, _)| k.as_str()).collect();
763        let mut have = Vectors::new();
764        {
765            let mut db = self.conn()?;
766            let mut s = db
767                .get()
768                .prepare_cached(
769                    "SELECT memory, v FROM vectors WHERE model = ?1 \
770                     AND memory IN (SELECT value FROM json_each(?2))",
771                )
772                .map_err(db_error)?;
773            let rows = s
774                .query_map(params![e.model(), json(&keys)?], |r| {
775                    Ok((r.get::<_, String>(0)?, r.get::<_, Vec<u8>>(1)?))
776                })
777                .map_err(db_error)?;
778            for r in rows {
779                let (k, b) = r.map_err(db_error)?;
780                if let Some(v) = floats(&b).filter(|v| v.len() == e.dimension()) {
781                    have.insert(k, v);
782                }
783            }
784        }
785        let missing: Vec<&(String, Memory)> = items
786            .iter()
787            .filter(|(k, _)| !have.contains_key(k))
788            .collect();
789        if !missing.is_empty() {
790            let texts: Vec<String> = missing.iter().map(|(_, m)| graph::vector_text(m)).collect();
791            let refs: Vec<&str> = texts.iter().map(String::as_str).collect();
792            let got = e.embed(&refs)?;
793            let new: Vec<(String, Vec<f32>)> =
794                missing.iter().map(|(k, _)| k.clone()).zip(got).collect();
795            self.write(|tx| {
796                for (k, v) in &new {
797                    // Only for a memory still there: one forgotten since
798                    // the read keeps no vector.
799                    tx.execute(
800                        "INSERT OR REPLACE INTO vectors(memory, model, v) \
801                         SELECT ?1, ?2, ?3 WHERE EXISTS (SELECT 1 FROM memories WHERE key = ?1)",
802                        params![k, e.model(), blob(v)],
803                    )
804                    .map_err(db_error)?;
805                }
806                Ok(())
807            })?;
808            have.extend(new);
809        }
810        Ok((q, have))
811    }
812
813    fn place(&self) -> PathBuf {
814        self.path.clone()
815    }
816}
817
818impl Provider for Sqlite {
819    fn name(&self) -> &'static str {
820        "sqlite"
821    }
822
823    fn remember(&self, cx: &Context, new: New) -> Result<Memory, Error> {
824        // Checked before the embedder runs or the database opens.
825        if new.text.trim().is_empty() {
826            return Err(Error::Invalid("a memory needs text".into()));
827        }
828        graph::owner(cx, new.scope)?;
829        self.adopt(cx)?;
830        let mut vector = None;
831        if self.embedder.is_some() {
832            // The vector's text does not depend on the name picked.
833            let (_, _, draft) = graph::fresh(cx, new.clone(), |_| Ok(false))?;
834            vector = self.embed_one(&draft);
835        }
836        self.write(|tx| {
837            let (k, owner, m) = graph::fresh(cx, new, |k| exists(tx, k))?;
838            Sqlite::store(tx, cx, &k, &owner, &m, vector)?;
839            Ok(m)
840        })
841    }
842
843    fn list(&self, cx: &Context, scope: Option<Scope>, kind: Option<Kind>) -> Result<Found, Error> {
844        self.adopt(cx)?;
845        let items = self
846            .load(cx, &graph::scopes(cx, scope))?
847            .into_iter()
848            .map(|(_, m)| m)
849            .filter(|m| kind.is_none_or(|k| k == m.kind))
850            .collect();
851        Ok(self.with_unread(Found {
852            items,
853            problems: Vec::new(),
854        }))
855    }
856
857    fn get(&self, cx: &Context, id: &str) -> Result<Memory, Error> {
858        self.adopt(cx)?;
859        self.existing(cx, id).map(|(_, m)| m)
860    }
861
862    fn update(&self, cx: &Context, id: &str, change: Change) -> Result<Memory, Error> {
863        let (scope, name) = split_id(id)?;
864        let owner = graph::owner(cx, scope)?;
865        let k = graph::key(scope, &owner, name);
866        self.adopt(cx)?;
867        let (_, current) = self.existing(cx, id)?;
868        let draft = graph::changed(current, change.clone())?;
869        let vector = self.embed_one(&draft);
870        self.write(|tx| {
871            // Read again inside the transaction, so a change made in
872            // between is not lost.
873            let m = find(tx, &k)?.ok_or_else(|| Error::NotFound(id.to_owned()))?;
874            let m = graph::changed(m, change)?;
875            let vector = vector.filter(|_| graph::vector_text(&m) == graph::vector_text(&draft));
876            Sqlite::store(tx, cx, &k, &owner, &m, vector)?;
877            Ok(m)
878        })
879    }
880
881    fn forget(&self, cx: &Context, id: &str) -> Result<Memory, Error> {
882        let (scope, name) = split_id(id)?;
883        let k = graph::key(scope, &graph::owner(cx, scope)?, name);
884        self.adopt(cx)?;
885        self.write(|tx| {
886            let m = find(tx, &k)?.ok_or_else(|| Error::NotFound(id.to_owned()))?;
887            // Its own edges and vector go with it (ON DELETE CASCADE);
888            // the links other memories had to it go too.
889            tx.execute(
890                "DELETE FROM edges WHERE relation = 'LINKS_TO' AND target = ?1",
891                [&k],
892            )
893            .map_err(db_error)?;
894            tx.execute("DELETE FROM memories WHERE key = ?1", [&k])
895                .map_err(db_error)?;
896            Ok(m)
897        })
898    }
899
900    fn put(&self, cx: &Context, m: &Memory) -> Result<Memory, Error> {
901        let (k, owner, m) = graph::placed(cx, m)?;
902        self.adopt(cx)?;
903        let vector = self.embed_one(&m);
904        self.write(|tx| {
905            Sqlite::store(tx, cx, &k, &owner, &m, vector)?;
906            Ok(m)
907        })
908    }
909
910    fn recall(
911        &self,
912        cx: &Context,
913        query: &str,
914        scope: Option<Scope>,
915        limit: Option<usize>,
916    ) -> Result<Found, Error> {
917        self.adopt(cx)?;
918        let all = self.load(cx, &graph::scopes(cx, scope))?;
919        graph::recall(self, self.embedder.as_deref(), all, query, limit)
920            .map(|f| self.with_unread(f))
921    }
922}