zeph_memory/store/mod.rs
1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! SQLite-backed relational store for all persistent agent data.
5//!
6//! [`SqliteStore`] wraps a [`zeph_db::DbPool`] and provides typed sub-store modules
7//! for every data domain:
8//!
9//! | Module | Contents |
10//! |--------|----------|
11//! | `messages` | Conversation messages, role strings, metadata |
12//! | `summaries` | Compression summaries per conversation |
13//! | `persona` | Long-lived user attributes ([`PersonaFactRow`]) |
14//! | `trajectory` | Goal trajectory entries ([`TrajectoryEntryRow`]) |
15//! | `memory_tree` | Hierarchical note consolidation tree ([`MemoryTreeRow`]) |
16//! | `session_digest` | Per-session digest records |
17//! | `experiments` | A/B experiment results and session summaries |
18//! | `corrections` | User-issued corrections stored for fine-tuning |
19//! | `graph_store` | Entity/edge adjacency tables for the knowledge graph |
20//! | `overflow` | Context-overflow handling metadata |
21//! | `preferences` | User preference key-value store |
22//! | `skills` | Skill metrics, usage, and version records |
23//! | `trust` | Skill trust scores by source |
24//! | `acp_sessions` | ACP protocol session events |
25//! | `mem_scenes` | Scene segmentation records |
26//! | `compression_guidelines` | LLM compression policy guidelines |
27//! | `admission_training` | A-MAC admission training data |
28//! | `channel_preferences` | Per-channel UX preferences (e.g. last active provider) |
29//! | `agent_sessions` | Fleet session lifecycle records ([`AgentSessionRow`]) |
30
31mod acp_sessions;
32pub mod admission_training;
33pub mod agent_sessions;
34pub mod channel_preferences;
35pub mod compression_guidelines;
36pub mod corrections;
37pub mod experiments;
38pub mod graph_store;
39mod history;
40mod mem_scenes;
41pub mod memory_tree;
42pub(crate) mod messages;
43pub mod overflow;
44pub mod persona;
45pub mod preferences;
46pub mod retrieval_failures;
47pub mod session_digest;
48mod skills;
49mod summaries;
50pub mod trajectory;
51mod trust;
52
53#[allow(unused_imports)]
54use zeph_db::sql;
55use zeph_db::{DbConfig, DbPool};
56
57use crate::error::MemoryError;
58
59pub use acp_sessions::{AcpSessionConfigSnapshot, AcpSessionEvent, AcpSessionInfo};
60pub use agent_sessions::{AgentSessionRow, SessionChannel, SessionKind, SessionStatus};
61pub use memory_tree::MemoryTreeRow;
62pub use messages::role_str;
63pub use persona::PersonaFactRow;
64pub use skills::{SkillMetricsRow, SkillUsageRow, SkillVersionRow};
65pub use trajectory::{NewTrajectoryEntry, TrajectoryEntryRow};
66pub use trust::{SkillTrustRow, SourceKind};
67
68/// Primary relational data store backed by a [`DbPool`].
69///
70/// Opening a `SqliteStore` runs all pending `SQLite` migrations automatically.
71///
72/// # Examples
73///
74/// ```rust,no_run
75/// # async fn example() -> Result<(), zeph_memory::MemoryError> {
76/// use zeph_memory::store::SqliteStore;
77///
78/// let store = SqliteStore::new(":memory:").await?;
79/// let cid = store.create_conversation().await?;
80/// # Ok(())
81/// # }
82/// ```
83#[derive(Debug, Clone)]
84pub struct SqliteStore {
85 pool: DbPool,
86 db_instance_id: String,
87}
88
89impl SqliteStore {
90 /// Open (or create) the database and run migrations.
91 ///
92 /// # Errors
93 ///
94 /// Returns an error if the database cannot be opened or migrations fail.
95 pub async fn new(path: &str) -> Result<Self, MemoryError> {
96 Self::with_pool_size(path, 5).await
97 }
98
99 /// Open (or create) the database with a configurable connection pool size.
100 ///
101 /// # Errors
102 ///
103 /// Returns an error if the database cannot be opened or migrations fail.
104 pub async fn with_pool_size(path: &str, pool_size: u32) -> Result<Self, MemoryError> {
105 let pool = DbConfig {
106 url: path.to_string(),
107 pool_size,
108 }
109 .connect()
110 .await?;
111 let db_instance_id = zeph_db::get_or_create_instance_id(&pool).await?;
112
113 Ok(Self {
114 pool,
115 db_instance_id,
116 })
117 }
118
119 /// Create a store from an already-open pool (no migrations run).
120 ///
121 /// Use this when the pool was obtained from an existing store (e.g. the main
122 /// agent memory store) to avoid redundant migration runs.
123 ///
124 /// # Errors
125 ///
126 /// Returns an error if this database's stable [`Self::db_instance_id`] cannot be
127 /// fetched or created (#5742).
128 pub async fn from_pool(pool: DbPool) -> Result<Self, MemoryError> {
129 let db_instance_id = zeph_db::get_or_create_instance_id(&pool).await?;
130 Ok(Self {
131 pool,
132 db_instance_id,
133 })
134 }
135
136 /// Expose the underlying pool for shared access by other stores.
137 #[must_use]
138 pub fn pool(&self) -> &DbPool {
139 &self.pool
140 }
141
142 /// Stable UUID identifying this physical database (#5742).
143 ///
144 /// Generated once and persisted in the `db_instance` table. Used to disambiguate
145 /// autoincrementing IDs (e.g. `conversation_id`) when multiple independent databases
146 /// share one Qdrant instance.
147 #[must_use]
148 pub fn db_instance_id(&self) -> &str {
149 &self.db_instance_id
150 }
151
152 /// Run all migrations on the given pool.
153 ///
154 /// # Errors
155 ///
156 /// Returns an error if any migration fails.
157 pub async fn run_migrations(pool: &DbPool) -> Result<(), MemoryError> {
158 zeph_db::run_migrations(pool).await?;
159 Ok(())
160 }
161}
162
163#[cfg(test)]
164mod tests {
165 use super::*;
166 use tempfile::NamedTempFile;
167
168 // Matches `DbConfig` busy_timeout default (5 seconds in ms)
169 const DEFAULT_BUSY_TIMEOUT_MS: i64 = 5_000;
170
171 #[tokio::test]
172 async fn wal_journal_mode_enabled_on_file_db() {
173 let file = NamedTempFile::new().expect("tempfile");
174 let path = file.path().to_str().expect("valid path");
175
176 let store = SqliteStore::new(path).await.expect("SqliteStore::new");
177
178 let mode: String = zeph_db::query_scalar(sql!("PRAGMA journal_mode"))
179 .fetch_one(store.pool())
180 .await
181 .expect("PRAGMA query");
182
183 assert_eq!(mode, "wal", "expected WAL journal mode, got: {mode}");
184 }
185
186 #[tokio::test]
187 async fn busy_timeout_enabled_on_file_db() {
188 let file = NamedTempFile::new().expect("tempfile");
189 let path = file.path().to_str().expect("valid path");
190
191 let store = SqliteStore::new(path).await.expect("SqliteStore::new");
192
193 let timeout_ms: i64 = zeph_db::query_scalar(sql!("PRAGMA busy_timeout"))
194 .fetch_one(store.pool())
195 .await
196 .expect("PRAGMA query");
197
198 assert_eq!(
199 timeout_ms, DEFAULT_BUSY_TIMEOUT_MS,
200 "expected busy_timeout pragma to match configured timeout"
201 );
202 }
203
204 #[tokio::test]
205 async fn creates_parent_dirs() {
206 let dir = tempfile::tempdir().expect("tempdir");
207 let deep = dir.path().join("a/b/c/zeph.db");
208 let path = deep.to_str().expect("valid path");
209 let _store = SqliteStore::new(path).await.expect("SqliteStore::new");
210 assert!(deep.exists(), "database file should exist");
211 }
212
213 #[tokio::test]
214 async fn with_pool_size_accepts_custom_size() {
215 let store = SqliteStore::with_pool_size(":memory:", 2)
216 .await
217 .expect("with_pool_size");
218 // Verify the store is operational with the custom pool size.
219 let _cid = store
220 .create_conversation()
221 .await
222 .expect("create_conversation");
223 }
224}