Skip to main content

khive_db/backend/
schema_barrier.rs

1//! Store schema work a serving process runs before it reports ready (ADR-154 Amendment 3).
2
3use std::sync::atomic::Ordering;
4
5use super::{StorageBackend, StoreSchemaKind};
6use crate::error::SqliteError;
7use crate::stores::index_repair::FORCED_INDEXES;
8use crate::stores::note;
9
10const MAPPED_TEXT_TABLES: &str = include_str!("../../sql/mapped-text-tables.sql");
11const FORCED_INDEX_EXISTS: &str = include_str!("../../sql/forced-index-exists.sql");
12
13const SERVING_STORE_KINDS: [StoreSchemaKind; 5] = [
14    StoreSchemaKind::Entities,
15    StoreSchemaKind::Notes,
16    StoreSchemaKind::Graph,
17    StoreSchemaKind::Agents,
18    StoreSchemaKind::Events,
19];
20
21/// The result of [`StorageBackend::check_serving_forced_indexes`].
22#[derive(Clone, Debug, Default, PartialEq, Eq)]
23pub struct ForcedIndexCheck {
24    /// How many forced indexes were checked.
25    pub checked: usize,
26    /// The forced indexes that were missing and have been rebuilt, in check order.
27    pub rebuilt: Vec<&'static str>,
28}
29
30impl StorageBackend {
31    /// Run the schema ensure of every serving store kind (entities, notes,
32    /// graph, agents, events), each in its own write unit.
33    ///
34    /// An ensure that already succeeded on this backend is not run again, so
35    /// a store accessor called after this takes no writer for its schema. The
36    /// `notes_seq` repair is separate: [`Self::repair_notes_seq_once`]. A
37    /// read-only backend runs no schema work.
38    pub fn prepare_serving_store_schemas(&self) -> Result<(), SqliteError> {
39        for kind in SERVING_STORE_KINDS {
40            self.ensure_store_schema(kind)?;
41        }
42        Ok(())
43    }
44
45    /// Run the `notes_seq` anti-join repair, which scans `notes` in full, if it
46    /// has not yet run on this backend.
47    ///
48    /// Returns the number of `notes_seq` rows it inserted, or `None` when it
49    /// had already run (here or on a notes store acquisition) or the backend
50    /// is read-only. The notes schema ensure runs first under the same writer.
51    pub fn repair_notes_seq_once(&self) -> Result<Option<usize>, SqliteError> {
52        if self.is_read_only() || self.notes_seq_repair_runs.load(Ordering::Relaxed) != 0 {
53            return Ok(None);
54        }
55        let writer = self.constructor_writer()?;
56        self.ensure_store_schema_with_writer(StoreSchemaKind::Notes, writer.conn())?;
57        self.repair_notes_seq_with_writer(writer.conn())
58    }
59
60    /// Run the repair once per backend; the caller holds the writer, which
61    /// makes the check and the count update one step.
62    pub(super) fn repair_notes_seq_with_writer(
63        &self,
64        conn: &rusqlite::Connection,
65    ) -> Result<Option<usize>, SqliteError> {
66        if self.notes_seq_repair_runs.load(Ordering::Relaxed) != 0 {
67            return Ok(None);
68        }
69        let inserted = note::repair_notes_seq(conn)?;
70        self.notes_seq_repair_runs.fetch_add(1, Ordering::Relaxed);
71        Ok(Some(inserted))
72    }
73
74    /// The table keys of every FTS table in this store that has a rowid-map
75    /// sidecar, in name order (`fts_<key>` gives `<key>`).
76    ///
77    /// FTS tables kept in step by triggers have no sidecar and are not listed.
78    /// Passing each key to [`Self::text_with_tokenizer`] backfills its map, or
79    /// writes the completion marker on an empty table.
80    pub fn mapped_text_table_keys(&self) -> Result<Vec<String>, SqliteError> {
81        let reader = self.pool.reader()?;
82        let mut statement = reader.conn().prepare(MAPPED_TEXT_TABLES)?;
83        let keys = statement
84            .query_map([], |row| row.get::<_, String>(0))?
85            .collect::<Result<Vec<_>, _>>()?;
86        Ok(keys)
87    }
88
89    /// Check that every index a typed read forces with `INDEXED BY` exists,
90    /// and rebuild a missing one through its store's schema ensure.
91    ///
92    /// A read after readiness that has to repair a forced index then means the
93    /// index was dropped while serving. A read-only backend cannot rebuild,
94    /// so a missing index there is an error naming it, as is one still missing
95    /// after its ensure ran.
96    pub fn check_serving_forced_indexes(&self) -> Result<ForcedIndexCheck, SqliteError> {
97        let missing = self.missing_forced_indexes()?;
98        if missing.is_empty() {
99            return Ok(ForcedIndexCheck {
100                checked: FORCED_INDEXES.len(),
101                rebuilt: Vec::new(),
102            });
103        }
104        if self.is_read_only() {
105            return Err(SqliteError::InvalidData(format!(
106                "read-only database is missing forced index(es) {}; rebuild them in a \
107                 writable copy before opening the snapshot",
108                missing.join(", ")
109            )));
110        }
111        {
112            let writer = self.constructor_writer()?;
113            for kind in SERVING_STORE_KINDS {
114                if FORCED_INDEXES
115                    .iter()
116                    .any(|index| index.kind == kind && missing.contains(&index.name))
117                {
118                    self.store_schemas[kind as usize]
119                        .ready
120                        .store(false, Ordering::Release);
121                    self.ensure_store_schema_with_writer(kind, writer.conn())?;
122                }
123            }
124        }
125        let still_missing = self.missing_forced_indexes()?;
126        if !still_missing.is_empty() {
127            return Err(SqliteError::InvalidData(format!(
128                "forced index(es) {} still missing after their store schema ensure ran",
129                still_missing.join(", ")
130            )));
131        }
132        Ok(ForcedIndexCheck {
133            checked: FORCED_INDEXES.len(),
134            rebuilt: missing,
135        })
136    }
137
138    fn missing_forced_indexes(&self) -> Result<Vec<&'static str>, SqliteError> {
139        let reader = self.pool.reader()?;
140        let mut statement = reader.conn().prepare(FORCED_INDEX_EXISTS)?;
141        let mut missing = Vec::new();
142        for index in &FORCED_INDEXES {
143            let exists: bool = statement.query_row([index.name], |row| row.get(0))?;
144            if !exists {
145                missing.push(index.name);
146            }
147        }
148        Ok(missing)
149    }
150}