Skip to main content

paper/core/index/
connection.rs

1use anyhow::{Context, Result};
2use rusqlite::OptionalExtension;
3use std::path::Path;
4use std::sync::Once;
5
6static REGISTER_VEC: Once = Once::new();
7
8/// Register `sqlite-vec` as a SQLite auto-extension exactly once per process.
9///
10/// The C extension is compiled statically into the binary (no runtime `.dylib`
11/// download, no `load_extension` call), which keeps `paper` a single binary.
12#[allow(clippy::missing_transmute_annotations)]
13pub fn register_sqlite_vec() {
14    REGISTER_VEC.call_once(|| unsafe {
15        // SAFETY: `sqlite_vec::sqlite3_vec_init` has the SQLite extension entry
16        // point signature, `sqlite3_extension_init`:
17        //     int (*sqlite3_extension_init)(sqlite3 *db, char **pzErrMsg,
18        //                                   const sqlite3_api_routines *pThunk)
19        // `sqlite3_auto_extension` registers entry points of type
20        // `void (*)(void)`. The sqlite-vec crate documents transmuting
21        // `sqlite3_vec_init` to `void (*)(void)` as the supported way to register
22        // a statically-linked extension. Both are `extern "C"` fn pointers of the
23        // same width, so the transmute is sound: SQLite invokes the entry point
24        // with the extension-init argument layout that `sqlite3_vec_init`
25        // expects. Registration runs once per process via `REGISTER_VEC`.
26        rusqlite::ffi::sqlite3_auto_extension(Some(std::mem::transmute(
27            sqlite_vec::sqlite3_vec_init as *const (),
28        )));
29    });
30}
31
32/// Keep the index, a plaintext copy of every indexed document, owner-only.
33/// A new database is created 0600 (SQLite's -wal/-shm inherit its mode);
34/// existing files are tightened best-effort so a read-only or foreign-owned
35/// index still opens.
36#[cfg(unix)]
37fn restrict_to_owner(path: &Path) -> Result<()> {
38    use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
39    match std::fs::OpenOptions::new()
40        .write(true)
41        .create_new(true)
42        .mode(0o600)
43        .open(path)
44    {
45        Err(err) if err.kind() != std::io::ErrorKind::AlreadyExists => {
46            return Err(err).with_context(|| format!("creating {}", path.display()));
47        }
48        _ => {}
49    }
50    for suffix in ["", "-wal", "-shm"] {
51        let mut file = path.as_os_str().to_os_string();
52        file.push(suffix);
53        let file = Path::new(&file);
54        // symlink_metadata: never chmod whatever a symlink points at.
55        let Ok(meta) = std::fs::symlink_metadata(file) else {
56            continue;
57        };
58        let mode = meta.permissions().mode();
59        if !meta.is_file() || mode & 0o077 == 0 {
60            continue;
61        }
62        let owner_only = std::fs::Permissions::from_mode(mode & 0o700);
63        if let Err(err) = std::fs::set_permissions(file, owner_only) {
64            tracing::warn!("could not make {} owner-only: {err}", file.display());
65        }
66    }
67    Ok(())
68}
69
70/// Thin wrapper around `rusqlite::Connection` that guarantees the sqlite-vec
71/// extension is available and applies Paper's pragmas.
72pub struct Connection {
73    conn: rusqlite::Connection,
74}
75
76impl Connection {
77    /// Open an existing database file, running `PRAGMA quick_check` to verify
78    /// integrity before any work proceeds. If the file doesn't exist, it is
79    /// created with creation-time pragmas (page_size, etc.).
80    ///
81    /// `quick_check` is O(database size) and only runs on the first open after
82    /// creation; subsequent opens skip it since WAL mode guarantees crash
83    /// safety (I4: avoids per-search latency on large indexes).
84    pub fn open(path: &Path) -> Result<Self> {
85        register_sqlite_vec();
86        let existed = path.exists();
87        if let Some(parent) = path.parent() {
88            crate::core::paths::create_private_dir(parent)
89                .with_context(|| format!("creating db directory {}", parent.display()))?;
90        }
91        #[cfg(unix)]
92        restrict_to_owner(path)?;
93        let conn = rusqlite::Connection::open(path)
94            .with_context(|| format!("opening {}", path.display()))?;
95        if !existed {
96            // Fresh database: quick_check is instant on an empty file.
97            let quick_check: String = conn.query_row("PRAGMA quick_check", [], |row| row.get(0))?;
98            if quick_check != "ok" {
99                anyhow::bail!("database quick_check failed: {quick_check}");
100            }
101        }
102        Self::finish(conn, !existed) // set page_size only on fresh files
103    }
104
105    /// Open a database file that will be created if it doesn't exist. Runs
106    /// `PRAGMA quick_check` on the new/empty file (always "ok") and applies
107    /// creation-time pragmas like `page_size`.
108    ///
109    /// This is a convenience alias for `open`; both now handle fresh files.
110    pub fn open_or_create(path: &Path) -> Result<Self> {
111        Self::open(path)
112    }
113
114    pub fn open_in_memory() -> Result<Self> {
115        register_sqlite_vec();
116        let conn = rusqlite::Connection::open_in_memory()?;
117        Self::finish(conn, false) // in-memory DB cannot set page_size
118    }
119
120    /// Apply Paper's standard pragmas. `allow_page_size` controls whether
121    /// `PRAGMA page_size = 8192` is executed (only on fresh files, never on
122    /// existing databases — changing it requires VACUUM).
123    fn finish(conn: rusqlite::Connection, allow_page_size: bool) -> Result<Self> {
124        conn.busy_timeout(std::time::Duration::from_secs(5))?;
125        // WAL lets searches run while the indexer writes.
126        conn.execute_batch(
127            "PRAGMA journal_mode = WAL;
128             PRAGMA synchronous = NORMAL;
129             PRAGMA foreign_keys = ON;
130             PRAGMA mmap_size = 268435456;
131             PRAGMA wal_autocheckpoint = 1000;",
132        )?;
133        if allow_page_size {
134            // page_size must be set before any tables are created; it only takes
135            // effect on a fresh file. On an existing DB this is a no-op.
136            conn.execute_batch("PRAGMA page_size = 8192;")?;
137        }
138        Ok(Self { conn })
139    }
140
141    pub fn inner(&self) -> &rusqlite::Connection {
142        &self.conn
143    }
144
145    pub fn inner_mut(&mut self) -> &mut rusqlite::Connection {
146        &mut self.conn
147    }
148
149    pub fn execute_batch(&self, sql: &str) -> Result<()> {
150        self.conn.execute_batch(sql)?;
151        Ok(())
152    }
153
154    /// Convenience for scalar queries used by doctor/tests.
155    pub fn query_i64(&self, sql: &str) -> Result<i64> {
156        Ok(self.conn.query_row(sql, [], |row| row.get(0))?)
157    }
158
159    pub fn query_row<T, P: rusqlite::Params>(
160        &self,
161        sql: &str,
162        params: P,
163        f: impl FnOnce(&rusqlite::Row<'_>) -> rusqlite::Result<T>,
164    ) -> Result<T> {
165        Ok(self.conn.query_row(sql, params, f)?)
166    }
167
168    /// Get the embedding model ID stored in the index, if any.
169    pub fn stored_embedding_model(&self) -> Result<Option<String>> {
170        let model: Option<String> = self
171            .conn
172            .query_row(
173                "SELECT value FROM index_meta WHERE key = 'embedding_model'",
174                [],
175                |row| row.get(0),
176            )
177            .optional()?;
178        Ok(model)
179    }
180}
181
182#[cfg(all(test, target_os = "linux"))]
183mod tests {
184    /// procfs refuses chmod even for root: tightening an existing file must
185    /// warn and carry on, never stop the index from opening.
186    #[test]
187    fn a_file_that_cannot_be_chmodded_does_not_block_opening() {
188        super::restrict_to_owner(std::path::Path::new("/proc/self/stat")).unwrap();
189    }
190}