Skip to main content

second_brain_core/sqlite_store/
bootstrap.rs

1use anyhow::{Result, bail};
2use rusqlite::{OptionalExtension, params};
3
4use super::SqliteStore;
5
6const KEY: &str = "bootstrap";
7const PENDING: &str = "pending";
8const INGEST_DUE: &str = "ingest";
9
10/// Where a device paired into an identity stands before its first ingest.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum BootstrapState {
13    /// Waiting for the snapshot and follow-up pull from the pairing device;
14    /// nothing is ingested meanwhile.
15    Pending,
16    /// The bootstrap finished but the one full ingest pass that follows it
17    /// has not completed yet.
18    IngestDue,
19}
20
21impl BootstrapState {
22    fn as_meta(self) -> &'static str {
23        match self {
24            BootstrapState::Pending => PENDING,
25            BootstrapState::IngestDue => INGEST_DUE,
26        }
27    }
28
29    fn from_meta(value: &str) -> Result<Self> {
30        match value {
31            PENDING => Ok(BootstrapState::Pending),
32            INGEST_DUE => Ok(BootstrapState::IngestDue),
33            other => bail!("index_meta {KEY} = {other:?}: unknown bootstrap state"),
34        }
35    }
36}
37
38impl SqliteStore {
39    pub fn bootstrap_state(&self) -> Result<Option<BootstrapState>> {
40        let value: Option<String> = self
41            .reader()
42            .query_row(
43                "SELECT value FROM index_meta WHERE key = ?1",
44                params![KEY],
45                |r| r.get(0),
46            )
47            .optional()?;
48        value.as_deref().map(BootstrapState::from_meta).transpose()
49    }
50
51    /// `None` clears the state.
52    pub fn set_bootstrap_state(&self, state: Option<BootstrapState>) -> Result<()> {
53        let conn = self.conn();
54        match state {
55            Some(state) => conn.execute(
56                "INSERT OR REPLACE INTO index_meta (key, value) VALUES (?1, ?2)",
57                params![KEY, state.as_meta()],
58            )?,
59            None => conn.execute("DELETE FROM index_meta WHERE key = ?1", params![KEY])?,
60        };
61        Ok(())
62    }
63
64    /// True when any memory, entity, conversation or relation is stored.
65    pub fn holds_replicated_rows(&self) -> Result<bool> {
66        Ok(self.reader().query_row(
67            "SELECT EXISTS (SELECT 1 FROM memories) OR EXISTS (SELECT 1 FROM entities) \
68             OR EXISTS (SELECT 1 FROM conversations) OR EXISTS (SELECT 1 FROM relations)",
69            [],
70            |r| r.get(0),
71        )?)
72    }
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78
79    fn store() -> SqliteStore {
80        SqliteStore::in_memory("m".to_string()).unwrap()
81    }
82
83    #[test]
84    fn a_new_store_has_no_bootstrap_state() {
85        assert_eq!(store().bootstrap_state().unwrap(), None);
86    }
87
88    #[test]
89    fn each_bootstrap_state_reads_back_and_none_clears_it() {
90        let store = store();
91        for state in [BootstrapState::Pending, BootstrapState::IngestDue] {
92            store.set_bootstrap_state(Some(state)).unwrap();
93            assert_eq!(store.bootstrap_state().unwrap(), Some(state));
94        }
95        store.set_bootstrap_state(None).unwrap();
96        assert_eq!(store.bootstrap_state().unwrap(), None);
97    }
98
99    #[test]
100    fn a_pending_bootstrap_survives_a_reopen() {
101        let dir = tempfile::tempdir().unwrap();
102        let path = dir.path().join("brain.db");
103        SqliteStore::open(&path, "m".to_string())
104            .unwrap()
105            .set_bootstrap_state(Some(BootstrapState::Pending))
106            .unwrap();
107        let reopened = SqliteStore::open(&path, "m".to_string()).unwrap();
108        assert_eq!(
109            reopened.bootstrap_state().unwrap(),
110            Some(BootstrapState::Pending)
111        );
112    }
113
114    #[test]
115    fn an_unknown_bootstrap_value_is_an_error() {
116        let store = store();
117        store
118            .conn()
119            .execute(
120                "INSERT INTO index_meta (key, value) VALUES ('bootstrap', 'later')",
121                [],
122            )
123            .unwrap();
124        assert!(store.bootstrap_state().is_err());
125    }
126
127    #[test]
128    fn an_empty_store_holds_no_replicated_rows() {
129        assert!(!store().holds_replicated_rows().unwrap());
130    }
131
132    #[test]
133    fn a_row_in_any_replicated_table_counts() {
134        let inserts = [
135            "INSERT INTO memories (id, content, memory_type, confidence, created_at, \
136             updated_at, last_accessed, source, source_id, machine_id) \
137             VALUES ('m1', 'c', 'fact', 1.0, 't', 't', 't', 'remember', 's', 'm')",
138            "INSERT INTO entities (id, name, entity_type) VALUES ('e1', 'n', 'tool')",
139            "INSERT INTO conversations (id, source, machine_id, started_at) \
140             VALUES ('c1', 'claude', 'm', 't')",
141            "INSERT INTO relations (from_id, to_id, relation_type) VALUES ('a', 'b', 'uses')",
142        ];
143        for insert in inserts {
144            let store = store();
145            store.conn().execute(insert, []).unwrap();
146            assert!(store.holds_replicated_rows().unwrap(), "{insert}");
147        }
148    }
149
150    #[test]
151    fn non_replicated_tables_do_not_count() {
152        let store = store();
153        store
154            .set_bootstrap_state(Some(BootstrapState::Pending))
155            .unwrap();
156        store
157            .conn()
158            .execute(
159                "INSERT INTO ingest_log (file_path, file_hash, ingested_at, memory_count, source) \
160                 VALUES ('p', 'h', 't', 0, 'claude')",
161                [],
162            )
163            .unwrap();
164        assert!(!store.holds_replicated_rows().unwrap());
165    }
166}