1use std::path::Path;
9use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
10use std::sync::Arc;
11
12use rusqlite::OptionalExtension;
13
14use crate::database_owner_identity::{DatabaseOwnerIdentity, DatabaseOwnerIdentityError};
15use crate::error::SqliteError;
16use crate::pool::{ConnectionPool, PoolConfig, WalCeilingPolicy};
17use crate::stores::{agents, attachment, blob, entity, event, graph, note, sparse, text, vectors};
18
19mod capability_factories;
20mod code_map;
21mod core_stores;
22#[path = "backend/schema_readiness.rs"]
23mod memory_visibility;
24mod pack_schema;
25mod policy_open;
26mod schema_barrier;
27pub use schema_barrier::ForcedIndexCheck;
28
29#[cfg(test)]
30#[path = "backend/filter_builder_tests.rs"]
31mod filter_builder_tests;
32
33mod namespace_listing;
34pub use namespace_listing::NamespaceLiveness;
35
36#[cfg(test)]
37#[path = "backend/memory_visibility_tests.rs"]
38mod memory_visibility_tests;
39
40#[cfg(any(unix, windows))]
41mod claimed_file_identity;
42
43fn sqlite_table_exists(conn: &rusqlite::Connection, table: &str) -> Result<bool, SqliteError> {
44 conn.query_row(
45 "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?1",
46 rusqlite::params![table],
47 |row| row.get::<_, i64>(0),
48 )
49 .optional()
50 .map(|row| row.is_some())
51 .map_err(SqliteError::Rusqlite)
52}
53
54fn ensure_fts_rowid_map_backfilled(
110 conn: &rusqlite::Connection,
111 table: &str,
112 admission: &crate::pool::WriteAdmission,
113) -> Result<(), SqliteError> {
114 let map = text::rowid_map_table(table);
115 let state = text::rowid_map_state_table(table);
116 let already_backfilled: bool = conn.query_row(
117 &format!("SELECT EXISTS(SELECT 1 FROM {state} WHERE key = 'backfill' AND value = ?1)"),
118 rusqlite::params![text::ROWID_MAP_BACKFILL_COMPLETE],
119 |row| row.get(0),
120 )?;
121 if already_backfilled {
122 return Ok(());
123 }
124
125 conn.execute_batch("BEGIN IMMEDIATE")?;
126 if let Err(error) = admission.check() {
127 return Err(crate::migrations::capacity_refusal_after_rollback(
128 conn,
129 conn.execute_batch("ROLLBACK"),
130 error,
131 "FTS rowid-map backfill",
132 ));
133 }
134 let result: Result<(), SqliteError> = (|| {
135 conn.execute_batch(&format!(
136 "DELETE FROM {map} WHERE NOT EXISTS ( \
137 SELECT 1 FROM {table} \
138 WHERE {table}.rowid = {map}.rowid \
139 AND {table}.namespace = {map}.namespace \
140 AND {table}.subject_id = {map}.subject_id \
141 )"
142 ))?;
143 conn.execute_batch(&format!(
144 "INSERT OR REPLACE INTO {map} (namespace, subject_id, rowid) \
145 SELECT namespace, subject_id, rowid FROM {table} \
146 WHERE namespace IS NOT NULL AND subject_id IS NOT NULL \
147 ORDER BY updated_at ASC, rowid ASC"
148 ))?;
149 conn.execute_batch(&format!(
150 "DELETE FROM {table} \
151 WHERE namespace IS NOT NULL AND subject_id IS NOT NULL \
152 AND rowid NOT IN (SELECT rowid FROM {map})"
153 ))?;
154 conn.execute(
155 &format!("INSERT OR REPLACE INTO {state} (key, value) VALUES ('backfill', ?1)"),
156 rusqlite::params![text::ROWID_MAP_BACKFILL_COMPLETE],
157 )?;
158 Ok(())
159 })();
160
161 match result {
162 Ok(()) => {
163 conn.execute_batch("COMMIT")?;
164 Ok(())
165 }
166 Err(e) => {
167 let _ = conn.execute_batch("ROLLBACK");
168 Err(e)
169 }
170 }
171}
172
173fn warn_scan_fallback_once(table: &str) {
179 static WARNED: std::sync::Once = std::sync::Once::new();
180 WARNED.call_once(|| {
181 tracing::warn!(
182 table,
183 "opened a read-only text-search table with no rowid-map sidecar, or with a sidecar \
184 that has never proven a completed backfill (no durable completion marker); a \
185 read-only connection cannot create, backfill, or reconcile the map itself, so this \
186 falls back to pre-map namespace/subject_id scan predicates for get/delete on this \
187 table rather than trusting a map that might be partial"
188 );
189 });
190}
191
192fn validate_vector_model_key(model_key: &str) -> Result<(), SqliteError> {
193 if model_key.is_empty()
194 || !model_key
195 .chars()
196 .all(|c| c.is_ascii_alphanumeric() || c == '_')
197 {
198 return Err(SqliteError::InvalidData(format!(
199 "invalid model_key '{}': must be non-empty and contain only \
200 alphanumeric/underscore characters",
201 model_key
202 )));
203 }
204 Ok(())
205}
206
207fn validate_vector_table_columns(
208 conn: &rusqlite::Connection,
209 table: &str,
210) -> Result<(), SqliteError> {
211 let pragma = format!("PRAGMA table_xinfo({table})");
212 let mut stmt = conn.prepare(&pragma)?;
213 let mut rows = stmt.query([])?;
214 let mut has_field = false;
215 let mut has_embedding_model = false;
216 while let Some(row) = rows.next()? {
217 let name: String = row.get(1)?;
218 if name == "field" {
219 has_field = true;
220 }
221 if name == "embedding_model" {
222 has_embedding_model = true;
223 }
224 }
225 if !has_field || !has_embedding_model {
226 return Err(SqliteError::InvalidData(format!(
227 "vec0 table '{table}' is missing required column(s) (field={has_field}, \
228 embedding_model={has_embedding_model}); this is a pre-v0.2.8 vector schema and is \
229 not supported — recreate the database"
230 )));
231 }
232 Ok(())
233}
234
235#[derive(Clone, Copy, Debug, PartialEq, Eq)]
236pub(crate) enum StoreSchemaKind {
237 Entities,
238 Graph,
239 Notes,
240 Events,
241 Agents,
242}
243
244impl StoreSchemaKind {
245 pub(crate) fn initializer(self) -> fn(&rusqlite::Connection) -> Result<(), rusqlite::Error> {
246 match self {
247 Self::Entities => entity::ensure_entities_schema,
248 Self::Graph => graph::ensure_graph_schema,
249 Self::Notes => note::ensure_notes_schema,
250 Self::Events => event::ensure_events_schema,
251 Self::Agents => agents::ensure_agents_schema,
252 }
253 }
254}
255
256#[derive(Default)]
257pub(crate) struct StoreSchemaGate {
258 pub(crate) ready: AtomicBool,
259 #[cfg(test)]
260 pub(crate) attempts: AtomicUsize,
261}
262
263impl StoreSchemaGate {
264 pub(crate) fn ensure(
265 &self,
266 conn: &rusqlite::Connection,
267 ensure: fn(&rusqlite::Connection) -> Result<(), rusqlite::Error>,
268 ) -> Result<(), rusqlite::Error> {
269 if self.ready.load(Ordering::Acquire) {
272 return Ok(());
273 }
274 #[cfg(test)]
275 self.attempts.fetch_add(1, Ordering::Relaxed);
276 ensure(conn)?;
277 self.ready.store(true, Ordering::Release);
278 Ok(())
279 }
280}
281
282pub struct StorageBackend {
288 pool: Arc<ConnectionPool>,
289 is_file_backed: bool,
290 path: Option<std::path::PathBuf>,
291 vector_tables_ready: parking_lot::Mutex<std::collections::HashSet<String>>,
299 text_tables_ready: parking_lot::Mutex<std::collections::HashSet<String>>,
307 sparse_tables_ready: parking_lot::Mutex<std::collections::HashSet<String>>,
313 notes_seq_repair_runs: AtomicUsize,
320 store_schemas: [Arc<StoreSchemaGate>; 5],
321}
322
323impl StorageBackend {
324 pub fn sqlite(path: impl AsRef<Path>) -> Result<Self, SqliteError> {
338 Self::sqlite_with_pool_config(path, PoolConfig::default(), None)
339 }
340
341 #[cfg(any(test, feature = "test-support"))]
343 pub fn sqlite_for_test(path: impl AsRef<Path>) -> Result<Self, SqliteError> {
344 Self::sqlite_with_pool_config(path, PoolConfig::for_test(), None)
345 }
346
347 #[cfg(any(test, feature = "test-support"))]
349 pub fn sqlite_for_test_with_journal_mode(
350 path: impl AsRef<Path>,
351 wal_mode: bool,
352 busy_timeout: std::time::Duration,
353 ) -> Result<Self, SqliteError> {
354 Self::sqlite_with_pool_config(
355 path,
356 PoolConfig {
357 wal_mode,
358 busy_timeout,
359 write_queue_enabled: Some(true),
360 ..PoolConfig::for_test()
361 },
362 None,
363 )
364 }
365
366 #[cfg(any(test, feature = "test-support"))]
371 pub fn sqlite_for_test_with_journal_mode_in(
372 path: impl AsRef<Path>,
373 wal_mode: bool,
374 busy_timeout: std::time::Duration,
375 volume_lock_dir: std::path::PathBuf,
376 ) -> Result<Self, SqliteError> {
377 Self::sqlite_with_pool_config(
378 path,
379 PoolConfig {
380 wal_mode,
381 busy_timeout,
382 write_queue_enabled: Some(true),
383 volume_lock_dir: Some(volume_lock_dir),
384 ..PoolConfig::for_test()
385 },
386 None,
387 )
388 }
389
390 pub fn sqlite_with_max_readers(
394 path: impl AsRef<Path>,
395 max_readers: Option<usize>,
396 ) -> Result<Self, SqliteError> {
397 Self::sqlite_with_pool_config(path, PoolConfig::default(), max_readers)
398 }
399
400 pub fn sqlite_with_max_readers_and_wal_ceiling(
404 path: impl AsRef<Path>,
405 max_readers: Option<usize>,
406 wal_ceiling: WalCeilingPolicy,
407 ) -> Result<Self, SqliteError> {
408 Self::sqlite_with_pool_config(
409 path,
410 PoolConfig {
411 wal_ceiling,
412 ..PoolConfig::default()
413 },
414 max_readers,
415 )
416 }
417
418 pub(crate) fn sqlite_with_pool_config(
419 path: impl AsRef<Path>,
420 pool_config: PoolConfig,
421 max_readers: Option<usize>,
422 ) -> Result<Self, SqliteError> {
423 crate::extension::ensure_extensions_loaded();
424 let resolved = path.as_ref().to_path_buf();
425 let read_only =
426 std::fs::metadata(&resolved).is_ok_and(|metadata| metadata.permissions().readonly());
427 let mut config = PoolConfig {
428 path: Some(resolved.clone()),
429 read_only,
430 ..pool_config
431 };
432 if let Some(max_readers) = max_readers {
433 config.max_readers = max_readers;
434 }
435 if read_only {
436 config.write_queue_enabled = Some(false);
437 }
438 let pool = ConnectionPool::new(config)?;
439 Ok(Self {
440 pool: Arc::new(pool),
441 is_file_backed: true,
442 path: Some(resolved),
443 vector_tables_ready: Default::default(),
444 text_tables_ready: Default::default(),
445 sparse_tables_ready: Default::default(),
446 notes_seq_repair_runs: AtomicUsize::new(0),
447 store_schemas: std::array::from_fn(|_| Arc::new(StoreSchemaGate::default())),
448 })
449 }
450
451 pub fn sqlite_read_only(path: impl AsRef<Path>) -> Result<Self, SqliteError> {
462 Self::sqlite_read_only_with_pool_config(path, PoolConfig::default(), None)
463 }
464
465 #[cfg(any(test, feature = "test-support"))]
467 pub fn sqlite_read_only_for_test(path: impl AsRef<Path>) -> Result<Self, SqliteError> {
468 Self::sqlite_read_only_with_pool_config(path, PoolConfig::for_test(), None)
469 }
470
471 pub fn sqlite_read_only_with_max_readers(
473 path: impl AsRef<Path>,
474 max_readers: Option<usize>,
475 ) -> Result<Self, SqliteError> {
476 Self::sqlite_read_only_with_pool_config(path, PoolConfig::default(), max_readers)
477 }
478
479 pub fn sqlite_read_only_with_max_readers_and_wal_ceiling(
482 path: impl AsRef<Path>,
483 max_readers: Option<usize>,
484 wal_ceiling: WalCeilingPolicy,
485 ) -> Result<Self, SqliteError> {
486 Self::sqlite_read_only_with_pool_config(
487 path,
488 PoolConfig {
489 wal_ceiling,
490 ..PoolConfig::default()
491 },
492 max_readers,
493 )
494 }
495
496 pub fn sqlite_read_only_live_with_max_readers_and_wal_ceiling(
501 path: impl AsRef<Path>,
502 max_readers: Option<usize>,
503 wal_ceiling: WalCeilingPolicy,
504 ) -> Result<Self, SqliteError> {
505 Self::sqlite_read_only_with_pool_constructor(
506 path,
507 PoolConfig {
508 wal_ceiling,
509 ..PoolConfig::default()
510 },
511 max_readers,
512 ConnectionPool::new_read_only_live,
513 )
514 }
515
516 fn sqlite_read_only_with_pool_config(
517 path: impl AsRef<Path>,
518 pool_config: PoolConfig,
519 max_readers: Option<usize>,
520 ) -> Result<Self, SqliteError> {
521 Self::sqlite_read_only_with_pool_constructor(
522 path,
523 pool_config,
524 max_readers,
525 ConnectionPool::new,
526 )
527 }
528
529 fn sqlite_read_only_with_pool_constructor(
530 path: impl AsRef<Path>,
531 pool_config: PoolConfig,
532 max_readers: Option<usize>,
533 open_pool: fn(PoolConfig) -> Result<ConnectionPool, SqliteError>,
534 ) -> Result<Self, SqliteError> {
535 crate::extension::ensure_extensions_loaded();
536 let resolved = path.as_ref().to_path_buf();
537 let mut config = PoolConfig {
538 path: Some(resolved.clone()),
539 read_only: true,
540 write_queue_enabled: Some(false),
541 ..pool_config
542 };
543 if let Some(max_readers) = max_readers {
544 config.max_readers = max_readers;
545 }
546 let pool = open_pool(config)?;
552 Ok(Self {
553 pool: Arc::new(pool),
554 is_file_backed: true,
555 path: Some(resolved),
556 vector_tables_ready: Default::default(),
557 text_tables_ready: Default::default(),
558 sparse_tables_ready: Default::default(),
559 notes_seq_repair_runs: AtomicUsize::new(0),
560 store_schemas: std::array::from_fn(|_| Arc::new(StoreSchemaGate::default())),
561 })
562 }
563
564 pub fn memory() -> Result<Self, SqliteError> {
570 crate::extension::ensure_extensions_loaded();
571 let config = PoolConfig {
572 path: None,
573 ..PoolConfig::default()
574 };
575 let pool = ConnectionPool::new(config)?;
576 Ok(Self {
577 pool: Arc::new(pool),
578 is_file_backed: false,
579 path: None,
580 vector_tables_ready: Default::default(),
581 text_tables_ready: Default::default(),
582 sparse_tables_ready: Default::default(),
583 notes_seq_repair_runs: AtomicUsize::new(0),
584 store_schemas: std::array::from_fn(|_| Arc::new(StoreSchemaGate::default())),
585 })
586 }
587
588 pub fn apply_schema(
595 &self,
596 plan: &crate::migrations::ServiceSchemaPlan,
597 ) -> Result<(), SqliteError> {
598 let admission = self.pool.write_admission();
599 crate::migrations::apply_schema_plan_with_admission(
600 &mut self.pool.migration_transactions(),
601 plan,
602 &admission,
603 )
604 }
605
606 pub fn apply_pack_ddl_statements(
622 &self,
623 statements: &[&'static str],
624 ) -> Result<(), SqliteError> {
625 self.apply_pack_ddl_statements_with_columns(statements, &[])
626 }
627
628 pub fn apply_pack_ddl_statements_with_columns(
635 &self,
636 statements: &[&'static str],
637 additions: &[khive_types::PackColumnAddition],
638 ) -> Result<(), SqliteError> {
639 let writer = self.pool.writer()?;
640 writer.transaction(|conn| {
641 pack_schema::add_missing_columns(conn, additions)?;
642 for &stmt in statements {
643 conn.execute_batch(stmt)?;
644 }
645 pack_schema::validate_columns(conn, additions)?;
646 Ok(())
647 })
648 }
649
650 pub fn validate_pack_schema_columns(
653 &self,
654 additions: &[khive_types::PackColumnAddition],
655 ) -> Result<(), SqliteError> {
656 if additions.is_empty() {
657 return Ok(());
658 }
659 let reader = self.pool.reader()?;
660 pack_schema::validate_columns(reader.conn(), additions)
661 }
662
663 pub fn prepare_core_schema(&self) -> Result<u32, SqliteError> {
673 if self.is_read_only() {
674 let reader = self.pool.reader()?;
675 crate::migrations::validate_schema_is_current(reader.conn())
676 } else {
677 let latest = crate::migrations::MIGRATIONS
678 .last()
679 .map(|migration| migration.version)
680 .unwrap_or(0);
681 {
682 let reader = self.pool.reader()?;
683 let current = crate::migrations::read_schema_version(reader.conn())?;
684 if current >= latest {
685 return crate::migrations::validate_schema_is_current(reader.conn());
686 }
687 }
688 let owner = crate::stores::blob::acquire_database_gc_owner_for_path_blocking(
689 self.pool.canonical_path().map(Path::to_path_buf),
690 )
691 .map_err(|error| {
692 SqliteError::InvalidData(format!(
693 "failed to acquire database GC owner before schema preparation: {error}"
694 ))
695 })?;
696 self.run_core_migrations(&owner)
697 }
698 }
699
700 pub fn attachment_cutover_status(
702 &self,
703 ) -> Result<crate::migrations::AttachmentCutoverStatus, SqliteError> {
704 let reader = self.pool.reader()?;
705 crate::migrations::attachment_cutover_status(reader.conn())
706 }
707
708 fn require_attachment_cutover_owner(
709 &self,
710 owner: &crate::stores::blob::DatabaseGcOwnerGuard,
711 ) -> Result<(), SqliteError> {
712 let sql = self.sql();
713 let backend_path = sql.database_path();
714 if owner.database_path() != backend_path.as_deref() {
715 return Err(SqliteError::InvalidData(format!(
716 "attachment cutover GC owner targets {:?}, but this backend is {:?}",
717 owner.database_path(),
718 backend_path.as_deref()
719 )));
720 }
721 Ok(())
722 }
723
724 pub fn stage_attachment_cutover(
728 &self,
729 owner: &crate::stores::blob::DatabaseGcOwnerGuard,
730 ) -> Result<(), SqliteError> {
731 self.require_attachment_cutover_owner(owner)?;
732 if self.is_read_only() {
733 return Err(SqliteError::InvalidData(
734 "cannot stage attachment cutover on a read-only backend".into(),
735 ));
736 }
737 let _class = crate::disk_guard::lease_class_scope(crate::disk_guard::LeaseClass::Migration);
739 let mut writer = self.pool.writer()?;
740 let admission = self.pool.write_admission();
741 writer.conn_mut().with_mut(|conn| {
742 crate::migrations::stage_attachment_cutover_with_admission(conn, &admission)
743 })
744 }
745
746 pub fn apply_verified_attachments(
748 &self,
749 owner: &crate::stores::blob::DatabaseGcOwnerGuard,
750 attachments: &[khive_storage::Attachment],
751 ) -> Result<(), SqliteError> {
752 self.require_attachment_cutover_owner(owner)?;
753 if self.is_read_only() {
754 return Err(SqliteError::InvalidData(
755 "cannot apply verified attachments on a read-only backend".into(),
756 ));
757 }
758 let _class = crate::disk_guard::lease_class_scope(crate::disk_guard::LeaseClass::Migration);
759 let mut writer = self.pool.writer()?;
760 let admission = self.pool.write_admission();
761 writer.conn_mut().with_mut(|conn| {
762 let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
763 if let Err(error) = admission.check() {
764 let rollback = tx.rollback();
765 return Err(crate::migrations::capacity_refusal_after_rollback(
766 conn,
767 rollback,
768 error,
769 "verified attachment publication",
770 ));
771 }
772 for attachment in attachments {
773 attachment
774 .validate()
775 .map_err(|error| SqliteError::InvalidData(error.to_string()))?;
776 crate::migrations::apply_generic_verified_attachment(
777 &tx,
778 &attachment.record_uuid.to_string(),
779 attachment.substrate.as_str(),
780 &attachment.role,
781 &attachment.content_ref,
782 attachment.media_type.as_deref(),
783 attachment.size_bytes,
784 attachment.created_at,
785 )?;
786 }
787 tx.commit()?;
788 Ok(())
789 })
790 }
791
792 pub fn finalize_attachment_cutover(
795 &self,
796 owner: &crate::stores::blob::DatabaseGcOwnerGuard,
797 ) -> Result<(), SqliteError> {
798 self.require_attachment_cutover_owner(owner)?;
799 if self.is_read_only() {
800 return Err(SqliteError::InvalidData(
801 "cannot finalize attachment cutover on a read-only backend".into(),
802 ));
803 }
804 let _class = crate::disk_guard::lease_class_scope(crate::disk_guard::LeaseClass::Migration);
805 let mut writer = self.pool.writer()?;
806 let admission = self.pool.write_admission();
807 writer.conn_mut().with_mut(|conn| {
808 crate::migrations::finalize_attachment_cutover_with_admission(conn, &admission)
809 })
810 }
811
812 pub fn entities(&self) -> Result<Arc<dyn khive_storage::EntityStore>, SqliteError> {
816 self.entities_for_namespace("local")
817 }
818
819 pub fn entities_for_namespace(
823 &self,
824 namespace: &str,
825 ) -> Result<Arc<dyn khive_storage::EntityStore>, SqliteError> {
826 if namespace.trim().is_empty() {
827 return Err(SqliteError::InvalidData(
828 "entities namespace must be non-empty".to_string(),
829 ));
830 }
831 self.ensure_store_schema(StoreSchemaKind::Entities)?;
832
833 Ok(Arc::new(entity::SqlEntityStore::new(
834 Arc::clone(&self.pool),
835 self.is_file_backed,
836 )))
837 }
838
839 pub fn attachments(&self) -> Result<Arc<dyn khive_storage::AttachmentStore>, SqliteError> {
846 Ok(Arc::new(attachment::SqlAttachmentStore::new(
847 Arc::clone(&self.pool),
848 self.is_file_backed,
849 )))
850 }
851
852 pub fn graph(&self) -> Result<Arc<dyn khive_storage::GraphStore>, SqliteError> {
857 self.graph_for_namespace("local")
858 }
859
860 pub fn graph_for_namespace(
862 &self,
863 namespace: &str,
864 ) -> Result<Arc<dyn khive_storage::GraphStore>, SqliteError> {
865 if namespace.trim().is_empty() {
866 return Err(SqliteError::InvalidData(
867 "graph namespace must be non-empty".to_string(),
868 ));
869 }
870 self.ensure_store_schema(StoreSchemaKind::Graph)?;
871
872 Ok(Arc::new(
873 graph::SqlGraphStore::new_scoped(
874 Arc::clone(&self.pool),
875 self.is_file_backed,
876 namespace.trim().to_string(),
877 )
878 .with_index_repair(crate::stores::index_repair::IndexRepairContext::new(
879 Arc::clone(&self.pool),
880 self.store_schemas.clone(),
881 crate::stores::index_repair::IndexReadKind::Graph,
882 )),
883 ))
884 }
885
886 fn ensure_store_schema(&self, kind: StoreSchemaKind) -> Result<(), SqliteError> {
887 if self.is_read_only()
888 || self.store_schemas[kind as usize]
889 .ready
890 .load(Ordering::Acquire)
891 {
892 return Ok(());
893 }
894 let writer = self.constructor_writer()?;
895 self.ensure_store_schema_with_writer(kind, writer.conn())
896 }
897
898 fn ensure_store_schema_with_writer(
899 &self,
900 kind: StoreSchemaKind,
901 conn: &rusqlite::Connection,
902 ) -> Result<(), SqliteError> {
903 self.store_schemas[kind as usize].ensure(conn, kind.initializer())?;
904 Ok(())
905 }
906
907 fn constructor_writer(
908 &self,
909 ) -> Result<crate::pool::PooledAutocommitWriteUnit<'_>, SqliteError> {
910 let context = khive_storage::capture_request_read_context();
911 let Some(operation) = context.store_acquisition_operation() else {
912 return self.pool.autocommit_write_unit();
913 };
914 let writer = self
915 .pool
916 .writer_until_for_admitted_operation(|| context.blocking_stop_reason().is_some())?
917 .ok_or_else(|| {
918 SqliteError::RequestReadStopped(khive_storage::StorageError::Timeout {
919 operation: operation.into(),
920 })
921 })?;
922 writer.admit_autocommit()
923 }
924
925 pub fn notes(&self) -> Result<Arc<dyn khive_storage::NoteStore>, SqliteError> {
929 self.notes_for_namespace("local")
930 }
931
932 pub fn notes_for_namespace(
936 &self,
937 namespace: &str,
938 ) -> Result<Arc<dyn khive_storage::NoteStore>, SqliteError> {
939 if namespace.trim().is_empty() {
940 return Err(SqliteError::InvalidData(
941 "notes namespace must be non-empty".to_string(),
942 ));
943 }
944 if !self.is_read_only()
945 && (!self.store_schemas[StoreSchemaKind::Notes as usize]
946 .ready
947 .load(Ordering::Acquire)
948 || self.notes_seq_repair_runs.load(Ordering::Relaxed) == 0)
949 {
950 let writer = self.constructor_writer()?;
951 self.ensure_store_schema_with_writer(StoreSchemaKind::Notes, writer.conn())?;
952
953 self.repair_notes_seq_with_writer(writer.conn())?;
960 }
961
962 Ok(Arc::new(
963 note::SqlNoteStore::new(Arc::clone(&self.pool), self.is_file_backed).with_index_repair(
964 crate::stores::index_repair::IndexRepairContext::new(
965 Arc::clone(&self.pool),
966 self.store_schemas.clone(),
967 crate::stores::index_repair::IndexReadKind::Notes,
968 ),
969 ),
970 ))
971 }
972
973 pub fn notes_seq_repair_run_count(&self) -> usize {
978 self.notes_seq_repair_runs.load(Ordering::Relaxed)
979 }
980
981 pub fn events(&self) -> Result<Arc<dyn khive_storage::EventStore>, SqliteError> {
986 self.events_for_namespace("local")
987 }
988
989 pub fn events_for_namespace(
991 &self,
992 namespace: &str,
993 ) -> Result<Arc<dyn khive_storage::EventStore>, SqliteError> {
994 if namespace.trim().is_empty() {
995 return Err(SqliteError::InvalidData(
996 "events namespace must be non-empty".to_string(),
997 ));
998 }
999 self.ensure_store_schema(StoreSchemaKind::Events)?;
1000
1001 Ok(Arc::new(event::SqlEventStore::new_scoped(
1002 Arc::clone(&self.pool),
1003 self.is_file_backed,
1004 namespace.trim().to_string(),
1005 )))
1006 }
1007
1008 pub fn agents(&self) -> Result<Arc<dyn khive_storage::AgentStore>, SqliteError> {
1013 self.ensure_store_schema(StoreSchemaKind::Agents)?;
1014
1015 Ok(Arc::new(agents::SqlAgentStore::new(
1016 Arc::clone(&self.pool),
1017 self.is_file_backed,
1018 )))
1019 }
1020
1021 pub fn vectors(
1027 &self,
1028 model_key: &str,
1029 embedding_model: &str,
1030 dimensions: usize,
1031 ) -> Result<Arc<dyn khive_storage::VectorStore>, SqliteError> {
1032 self.vectors_for_namespace(model_key, embedding_model, dimensions, "local")
1033 }
1034
1035 pub fn vectors_for_namespace(
1045 &self,
1046 model_key: &str,
1047 embedding_model: &str,
1048 dimensions: usize,
1049 namespace: &str,
1050 ) -> Result<Arc<dyn khive_storage::VectorStore>, SqliteError> {
1051 validate_vector_model_key(model_key)?;
1052 if namespace.trim().is_empty() {
1053 return Err(SqliteError::InvalidData(
1054 "vector store namespace must be non-empty".to_string(),
1055 ));
1056 }
1057 self.ensure_vector_tables(&[(model_key, dimensions)])?;
1058 Ok(Arc::new(vectors::SqliteVecStore::new(
1059 Arc::clone(&self.pool),
1060 self.is_file_backed,
1061 model_key.to_string(),
1062 embedding_model.to_string(),
1063 dimensions,
1064 namespace.trim().to_string(),
1065 )?))
1066 }
1067
1068 pub fn ensure_vector_tables(&self, models: &[(&str, usize)]) -> Result<(), SqliteError> {
1077 for (model_key, _) in models {
1078 validate_vector_model_key(model_key)?;
1079 }
1080 if models.is_empty() {
1081 return Ok(());
1082 }
1083
1084 crate::extension::ensure_extensions_loaded();
1086
1087 if self.is_read_only() {
1092 let reader = self.pool.reader()?;
1096 for (model_key, _) in models {
1097 let table = format!("vec_{model_key}");
1098 if !sqlite_table_exists(reader.conn(), &table)? {
1099 return Err(SqliteError::InvalidData(format!(
1100 "read-only database has no vector table '{table}'; create and populate it in \
1101 a writable copy before opening the snapshot"
1102 )));
1103 }
1104 validate_vector_table_columns(reader.conn(), &table)?;
1105 }
1106 return Ok(());
1107 }
1108
1109 let pending = self.unprepared_vector_tables(models);
1110 if pending.is_empty() {
1111 return Ok(());
1112 }
1113 let writer = self.constructor_writer()?;
1114 let pending = self.unprepared_vector_tables(&pending);
1117 if pending.is_empty() {
1118 return Ok(());
1119 }
1120
1121 for (model_key, _) in &pending {
1125 let table = format!("vec_{model_key}");
1126 if sqlite_table_exists(writer.conn(), &table)? {
1132 validate_vector_table_columns(writer.conn(), &table)?;
1133 }
1134 }
1135
1136 writer
1145 .conn()
1146 .execute_batch(crate::migrations::EMBEDDING_MODELS_DDL)?;
1147
1148 writer
1152 .conn()
1153 .execute_batch(crate::migrations::ANN_WRITE_LOG_DDL)?;
1154 writer
1155 .conn()
1156 .execute_batch(crate::migrations::ANN_WRITE_LOG_MODEL_SEQ_INDEX_DDL)?;
1157 writer
1158 .conn()
1159 .execute_batch(crate::migrations::ANN_CONSUMER_PENDING_DDL)?;
1160 for (model_key, dimensions) in &pending {
1162 let ddl = format!(
1163 "CREATE VIRTUAL TABLE IF NOT EXISTS vec_{} USING vec0(\
1164 subject_id TEXT PRIMARY KEY, \
1165 namespace TEXT NOT NULL, \
1166 kind TEXT NOT NULL, \
1167 field TEXT NOT NULL, \
1168 embedding_model TEXT NOT NULL, \
1169 embedding float[{}] distance_metric=cosine\
1170 )",
1171 model_key, dimensions
1172 );
1173 writer.conn().execute_batch(&ddl)?;
1174 }
1175 self.vector_tables_ready.lock().extend(
1178 pending
1179 .iter()
1180 .map(|(model_key, _)| (*model_key).to_string()),
1181 );
1182 Ok(())
1183 }
1184
1185 fn unprepared_vector_tables<'a>(&self, models: &[(&'a str, usize)]) -> Vec<(&'a str, usize)> {
1187 let ready = self.vector_tables_ready.lock();
1188 models
1189 .iter()
1190 .filter(|(model_key, _)| !ready.contains(*model_key))
1191 .copied()
1192 .collect()
1193 }
1194
1195 pub fn register_embedding_model(
1200 &self,
1201 engine_name: &str,
1202 model_id: &str,
1203 key_version: &str,
1204 dimensions: u32,
1205 ) -> Result<(), SqliteError> {
1206 let writer = self.pool.autocommit_write_unit()?;
1207 writer
1208 .conn()
1209 .execute_batch(crate::migrations::EMBEDDING_MODELS_DDL)
1210 .map_err(|error| {
1211 SqliteError::write(error, khive_storage::error::SqliteWriteStage::Statement)
1212 })?;
1213
1214 let now = chrono::Utc::now().timestamp_micros();
1215 let canonical_key =
1216 format!("{engine_name}:{model_id}:{key_version}:{dimensions}").into_bytes();
1217 let id = uuid::Uuid::new_v4();
1218 writer
1219 .conn()
1220 .execute(
1221 "INSERT INTO _embedding_models \
1222 (id, engine_name, model_id, key_version, dim, output_dim, status, \
1223 activated_at, superseded_at, superseded_by, canonical_key, created_at) \
1224 VALUES (?1, ?2, ?3, ?4, ?5, NULL, 'active', ?6, NULL, NULL, ?7, ?8) \
1225 ON CONFLICT(canonical_key) DO UPDATE SET \
1226 status = 'active', \
1227 activated_at = COALESCE(_embedding_models.activated_at, excluded.activated_at)",
1228 rusqlite::params![
1229 id.as_bytes().as_slice(),
1230 engine_name,
1231 model_id,
1232 key_version,
1233 dimensions as i64,
1234 now,
1235 canonical_key,
1236 now,
1237 ],
1238 )
1239 .map_err(|error| {
1240 SqliteError::write(error, khive_storage::error::SqliteWriteStage::Statement)
1241 })?;
1242 Ok(())
1243 }
1244
1245 pub fn sparse(
1249 &self,
1250 model_key: &str,
1251 ) -> Result<Arc<dyn khive_storage::SparseStore>, SqliteError> {
1252 self.sparse_for_namespace(model_key, "local")
1253 }
1254
1255 #[cfg(test)]
1259 pub(crate) fn forget_proven_text_tables_for_test(&self) {
1260 self.text_tables_ready.lock().clear();
1261 }
1262
1263 fn ensure_sparse_table(&self, model_key: &str) -> Result<(), SqliteError> {
1269 if self.sparse_tables_ready.lock().contains(model_key) {
1270 return Ok(());
1271 }
1272 let writer = self.pool.autocommit_write_unit()?;
1273 if !self.sparse_tables_ready.lock().contains(model_key) {
1274 sparse::ensure_sparse_schema(writer.conn(), model_key)
1275 .map_err(SqliteError::Rusqlite)?;
1276 self.sparse_tables_ready
1277 .lock()
1278 .insert(model_key.to_string());
1279 }
1280 Ok(())
1281 }
1282
1283 pub fn sparse_for_namespace(
1287 &self,
1288 model_key: &str,
1289 namespace: &str,
1290 ) -> Result<Arc<dyn khive_storage::SparseStore>, SqliteError> {
1291 if model_key.is_empty()
1292 || !model_key
1293 .chars()
1294 .all(|c| c.is_ascii_alphanumeric() || c == '_')
1295 {
1296 return Err(SqliteError::InvalidData(format!(
1297 "invalid model_key '{}': must be non-empty and contain only alphanumeric/underscore characters",
1298 model_key
1299 )));
1300 }
1301 if namespace.trim().is_empty() {
1302 return Err(SqliteError::InvalidData(
1303 "sparse store namespace must be non-empty".to_string(),
1304 ));
1305 }
1306
1307 if self.is_read_only() {
1308 let table = format!("sparse_{model_key}");
1309 let reader = self.pool.reader()?;
1310 if !sqlite_table_exists(reader.conn(), &table)? {
1311 return Err(SqliteError::InvalidData(format!(
1312 "read-only database has no sparse table '{table}'; create and populate it in \
1313 a writable copy before opening the snapshot"
1314 )));
1315 }
1316 } else {
1317 self.ensure_sparse_table(model_key)?;
1318 }
1319
1320 Ok(Arc::new(sparse::SqliteSparseStore::new(
1321 Arc::clone(&self.pool),
1322 self.is_file_backed,
1323 model_key.to_string(),
1324 namespace.trim().to_string(),
1325 )?))
1326 }
1327
1328 pub fn text(&self, table_key: &str) -> Result<Arc<dyn khive_storage::TextSearch>, SqliteError> {
1335 self.text_with_tokenizer(table_key, "trigram")
1336 }
1337
1338 pub fn text_with_tokenizer(
1346 &self,
1347 table_key: &str,
1348 tokenizer: &str,
1349 ) -> Result<Arc<dyn khive_storage::TextSearch>, SqliteError> {
1350 if table_key.is_empty()
1351 || !table_key
1352 .chars()
1353 .all(|c| c.is_ascii_alphanumeric() || c == '_')
1354 {
1355 return Err(SqliteError::InvalidData(format!(
1356 "invalid table_key '{}': must be non-empty and contain only \
1357 alphanumeric/underscore characters",
1358 table_key
1359 )));
1360 }
1361 if table_key.ends_with("_rowids") || table_key.ends_with("_rowids_state") {
1371 return Err(SqliteError::InvalidData(format!(
1372 "invalid table_key '{}': must not end in '_rowids' or '_rowids_state' — those \
1373 suffixes are reserved for a text table's own rowid-map sidecar and its \
1374 completion-marker state table (see text::rowid_map_table, \
1375 text::rowid_map_state_table)",
1376 table_key
1377 )));
1378 }
1379 if tokenizer.is_empty()
1380 || !tokenizer
1381 .chars()
1382 .all(|c| c.is_ascii_alphanumeric() || c == '_')
1383 {
1384 return Err(SqliteError::InvalidData(format!(
1385 "invalid tokenizer '{}': must be non-empty and contain only \
1386 alphanumeric/underscore characters",
1387 tokenizer
1388 )));
1389 }
1390
1391 let ddl = format!(
1392 "CREATE VIRTUAL TABLE IF NOT EXISTS fts_{} USING fts5(\
1393 subject_id UNINDEXED, \
1394 kind UNINDEXED, \
1395 title, \
1396 body, \
1397 tags UNINDEXED, \
1398 namespace UNINDEXED, \
1399 metadata UNINDEXED, \
1400 updated_at UNINDEXED, \
1401 record_kind, \
1402 tokenize = '{}'\
1403 )",
1404 table_key, tokenizer
1405 );
1406 let table = format!("fts_{table_key}");
1407 if self.is_read_only() {
1408 let reader = self.pool.reader()?;
1409 if !sqlite_table_exists(reader.conn(), &table)? {
1410 return Err(SqliteError::InvalidData(format!(
1411 "read-only database has no text-search table '{table}'; create and populate \
1412 it in a writable copy before opening the snapshot"
1413 )));
1414 }
1415 let map = text::rowid_map_table(&table);
1429 let map_exists = sqlite_table_exists(reader.conn(), &map)?;
1430 let marker_present = if map_exists {
1431 let state = text::rowid_map_state_table(&table);
1432 sqlite_table_exists(reader.conn(), &state)?
1433 && reader.conn().query_row(
1434 &format!(
1435 "SELECT EXISTS(SELECT 1 FROM {state} WHERE key = 'backfill' AND value = ?1)"
1436 ),
1437 rusqlite::params![text::ROWID_MAP_BACKFILL_COMPLETE],
1438 |row| row.get(0),
1439 )?
1440 } else {
1441 false
1442 };
1443 if !map_exists || !marker_present {
1444 warn_scan_fallback_once(&table);
1445 return Ok(Arc::new(text::Fts5TextSearch::new_scan_fallback(
1446 Arc::clone(&self.pool),
1447 self.is_file_backed,
1448 table_key.to_string(),
1449 )));
1450 }
1451 } else if !self.text_tables_ready.lock().contains(&table) {
1452 let writer = self.pool.autocommit_write_unit()?;
1453 if !self.text_tables_ready.lock().contains(&table) {
1456 writer.conn().execute_batch(&ddl)?;
1457 writer.conn().execute_batch(&text::rowid_map_ddl(&table))?;
1458 ensure_fts_rowid_map_backfilled(
1459 writer.conn(),
1460 &table,
1461 &self.pool.write_admission(),
1462 )?;
1463 self.text_tables_ready.lock().insert(table.clone());
1466 }
1467 }
1468
1469 Ok(Arc::new(text::Fts5TextSearch::new(
1470 Arc::clone(&self.pool),
1471 self.is_file_backed,
1472 table_key.to_string(),
1473 )))
1474 }
1475
1476 pub fn blob_store(
1485 &self,
1486 config_root: Option<&Path>,
1487 floor_bytes: Option<u64>,
1488 ) -> Result<Arc<dyn khive_storage::BlobStore>, SqliteError> {
1489 Ok(Arc::new(self.fs_blob_store(config_root, floor_bytes)?))
1490 }
1491
1492 pub(crate) fn fs_blob_store(
1495 &self,
1496 config_root: Option<&Path>,
1497 floor_bytes: Option<u64>,
1498 ) -> Result<blob::FsBlobStore, SqliteError> {
1499 let root = blob::resolve_blob_root(self.data_dir().as_deref(), config_root)?;
1500 let floor = blob::FsBlobStore::resolve_floor(&root, floor_bytes);
1501 blob::FsBlobStore::new(root, floor)
1502 }
1503
1504 pub fn blob_store_read_only(
1509 &self,
1510 config_root: Option<&Path>,
1511 floor_bytes: Option<u64>,
1512 ) -> Result<Arc<dyn khive_storage::BlobStore>, SqliteError> {
1513 let root = blob::resolve_blob_root(self.data_dir().as_deref(), config_root)?;
1514 let floor = blob::FsBlobStore::resolve_floor(&root, floor_bytes);
1515 Ok(Arc::new(blob::FsBlobStore::open_existing(root, floor)?))
1516 }
1517
1518 pub fn is_file_backed(&self) -> bool {
1520 self.is_file_backed
1521 }
1522
1523 pub fn is_read_only(&self) -> bool {
1526 self.pool.config().read_only
1527 }
1528
1529 pub fn data_dir(&self) -> Option<std::path::PathBuf> {
1532 self.path.as_ref()?.parent().map(|p| p.to_path_buf())
1533 }
1534
1535 pub fn ann_root(&self) -> Option<std::path::PathBuf> {
1543 ann_root_for(self.path.as_ref()?)
1544 }
1545
1546 pub fn pool(&self) -> &ConnectionPool {
1548 &self.pool
1549 }
1550
1551 pub fn database_owner_identity(
1554 &self,
1555 ) -> Result<DatabaseOwnerIdentity, DatabaseOwnerIdentityError> {
1556 self.pool.database_owner_identity()
1557 }
1558
1559 pub fn verify_database_owner(
1561 &self,
1562 expected: &DatabaseOwnerIdentity,
1563 ) -> Result<(), DatabaseOwnerIdentityError> {
1564 self.pool.verify_database_owner(expected)
1565 }
1566
1567 pub fn pool_arc(&self) -> Arc<ConnectionPool> {
1569 Arc::clone(&self.pool)
1570 }
1571}
1572
1573fn ann_root_for(path: &std::path::Path) -> Option<std::path::PathBuf> {
1578 let mut file = path.file_name()?.to_os_string();
1579 file.push(".ann");
1580 path.parent().map(|p| p.join(file))
1581}
1582
1583#[cfg(test)]
1584#[path = "backend/store_accessor_tests.rs"]
1585mod store_accessor_tests;
1586
1587#[cfg(test)]
1588#[path = "backend/store_accessor_index_tests.rs"]
1589mod store_accessor_index_tests;
1590
1591#[cfg(test)]
1592#[path = "backend/schema_barrier_tests.rs"]
1593mod schema_barrier_tests;
1594
1595#[cfg(test)]
1596#[path = "backend_tests.rs"]
1597mod tests;
1598
1599#[cfg(test)]
1600#[path = "backend_admission_tests.rs"]
1601mod admission_tests;
1602
1603#[cfg(test)]
1604mod live_readonly_tests;