cartog-db 0.29.2

SQLite persistence layer for cartog code graph
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! Metadata, file, symbol, and edge writes (the core CRUD surface).
//!
//! Part of the [`Database`](super::Database) impl, split out of `lib.rs` for navigability.

use super::*;

impl Database {
    // ── Metadata ──

    /// Retrieve a metadata value by key.
    pub fn get_metadata(&self, key: &str) -> Result<Option<String>> {
        self.conn
            .query_row(
                "SELECT value FROM metadata WHERE key = ?1",
                params![key],
                |row| row.get(0),
            )
            .optional()
            .context("Failed to query metadata")
    }

    /// Store a metadata key-value pair (upserts on conflict).
    ///
    /// tx-safe: single statement — see [`Self::begin_indexing_tx`].
    pub fn set_metadata(&self, key: &str, value: &str) -> Result<()> {
        self.conn.execute(
            "INSERT OR REPLACE INTO metadata (key, value) VALUES (?1, ?2)",
            params![key, value],
        )?;
        Ok(())
    }

    /// Reconcile the stored embedding fingerprint with the one currently in
    /// use. Call right after `Database::open` from any code path that owns
    /// an `EmbeddingProvider` (indexer, watcher, MCP serve, `rag index`).
    ///
    /// Behavior:
    /// - All three fields (provider, model, dimension) match stored → no-op,
    ///   zero writes.
    /// - Any field differs → drop `symbol_vec`, clear `symbol_embedding_map`,
    ///   recreate the vector table at the new dimension, update all three
    ///   metadata keys. The user must run `cartog rag index` to repopulate.
    /// - DB has dimension but no provider/model (older cartog versions) →
    ///   backfill provider+model without wiping. The stored vectors stay
    ///   valid against whatever stack produced them; we just record the
    ///   identity going forward.
    ///
    /// Writes use `retry_busy` so a concurrent writer on the same DB does
    /// not crash this caller with `SQLITE_BUSY`.
    pub fn reconcile_embedding_fingerprint(&self, fp: &EmbeddingFingerprint) -> Result<()> {
        let stored_provider: Option<String> = self.get_metadata(EMBED_PROVIDER_KEY)?;
        let stored_model: Option<String> = self.get_metadata(EMBED_MODEL_KEY)?;
        let stored_dim: Option<usize> = self
            .conn
            .query_row(
                "SELECT CAST(value AS INTEGER) FROM metadata WHERE key = 'embedding_dimension'",
                [],
                |row| row.get::<_, i64>(0).map(|v| v as usize),
            )
            .optional()
            .context("Failed to query embedding dimension")?;

        // Full match AND `symbol_vec` actually exists on disk: zero writes.
        // The dim+table pair is the real invariant; checking metadata
        // alone misses the case where a previous open crashed mid-
        // migration and left the DB without `symbol_vec` while metadata
        // still claims a fingerprint.
        if stored_provider.as_deref() == Some(fp.provider.as_str())
            && stored_model.as_deref() == Some(fp.model.as_str())
            && stored_dim == Some(fp.dimension)
            && symbol_vec_exists(&self.conn)?
        {
            return Ok(());
        }

        // Backwards-compat: stored has dim from an older cartog (no provider/model
        // recorded yet). Treat first-time-with-provider as a backfill, not an
        // invalidation. Embeddings produced by the previous run are still valid
        // against whatever stack the user had configured then.
        let dim_matches = stored_dim == Some(fp.dimension);
        let is_backfill = dim_matches && stored_provider.is_none() && stored_model.is_none();

        if !is_backfill {
            tracing::warn!(
                old_provider = ?stored_provider,
                old_model = ?stored_model,
                old_dim = ?stored_dim,
                new_provider = %fp.provider,
                new_model = %fp.model,
                new_dim = fp.dimension,
                "Embedding fingerprint changed — clearing vector index. Run `cartog rag index` to re-embed."
            );
        }

        // Wrap the whole sequence in a transaction so a mid-sequence
        // failure (e.g. busy-retry exhausted on the third metadata write)
        // rolls back atomically. Otherwise the next open could see
        // partial state — e.g. provider/model match but dimension stale,
        // or symbol_vec dropped but metadata still pointing at the old
        // dim — and either skip migration or silently re-wipe.
        let schema = rag_vec_schema(fp.dimension);
        let do_wipe = !is_backfill;
        retry_busy(|| {
            let tx = self.conn.unchecked_transaction()?;
            if do_wipe {
                tx.execute("DROP TABLE IF EXISTS symbol_vec", [])?;
                tx.execute("DELETE FROM symbol_embedding_map", [])?;
            }
            tx.execute_batch(&schema)?;
            tx.execute(
                "INSERT OR REPLACE INTO metadata (key, value) VALUES (?1, ?2)",
                params![EMBED_PROVIDER_KEY, fp.provider],
            )?;
            tx.execute(
                "INSERT OR REPLACE INTO metadata (key, value) VALUES (?1, ?2)",
                params![EMBED_MODEL_KEY, fp.model],
            )?;
            #[cfg(test)]
            if RECONCILE_FAIL_AFTER_MODEL
                .with(|b| b.swap(false, std::sync::atomic::Ordering::SeqCst))
            {
                return Err(rusqlite::Error::SqliteFailure(
                    rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_FULL),
                    Some("injected mid-sequence failure".into()),
                ));
            }
            tx.execute(
                "INSERT OR REPLACE INTO metadata (key, value) VALUES ('embedding_dimension', ?1)",
                params![fp.dimension.to_string()],
            )?;
            tx.commit()
        })
        .map_err(|e| anyhow::anyhow!("failed to reconcile embedding fingerprint: {e}"))?;

        Ok(())
    }

    // ── Files ──

    /// Insert or update file metadata.
    ///
    /// tx-safe: single statement — see [`Self::begin_indexing_tx`].
    pub fn upsert_file(&self, file: &FileInfo) -> Result<()> {
        self.conn.execute(
            "INSERT OR REPLACE INTO files (path, last_modified, hash, language, num_symbols)
             VALUES (?1, ?2, ?3, ?4, ?5)",
            params![
                file.path,
                file.last_modified,
                file.hash,
                file.language,
                file.num_symbols,
            ],
        )?;
        Ok(())
    }

    /// Look up stored metadata for a file.
    pub fn get_file(&self, path: &str) -> Result<Option<FileInfo>> {
        self.conn
            .query_row(
                "SELECT path, last_modified, hash, language, num_symbols FROM files WHERE path = ?1",
                params![path],
                |row| {
                    Ok(FileInfo {
                        path: row.get(0)?,
                        last_modified: row.get(1)?,
                        hash: row.get(2)?,
                        language: row.get(3)?,
                        num_symbols: row.get(4)?,
                    })
                },
            )
            .optional()
            .context("Failed to query file")
    }

    /// Remove edges only for a file (used by Merkle diff which updates symbols surgically).
    ///
    /// tx-safe: single statement — see [`Self::begin_indexing_tx`].
    pub fn clear_edges_for_file(&self, path: &str) -> Result<()> {
        self.conn
            .execute("DELETE FROM edges WHERE file_path = ?1", params![path])?;
        Ok(())
    }

    /// Remove all symbols, edges, and RAG data for a file (before re-indexing it).
    pub fn clear_file_data(&self, path: &str) -> Result<()> {
        let tx = self.conn.unchecked_transaction()?;
        self.clear_file_data_in_tx(path)?;
        tx.commit()?;
        Ok(())
    }

    /// Like [`Self::clear_file_data`] but assumes the caller already holds an
    /// open transaction. Used by `cartog-indexer` to wrap the entire Phase 3
    /// pipeline atomically.
    pub fn clear_file_data_in_tx(&self, path: &str) -> Result<()> {
        self.clear_rag_data_for_file(path)?;
        self.conn
            .execute("DELETE FROM edges WHERE file_path = ?1", params![path])?;
        self.conn
            .execute("DELETE FROM symbols WHERE file_path = ?1", params![path])?;
        Ok(())
    }

    /// Remove a file and all its symbols and edges from the index.
    pub fn remove_file(&self, path: &str) -> Result<()> {
        let tx = self.conn.unchecked_transaction()?;
        self.remove_file_in_tx(path)?;
        tx.commit()?;
        Ok(())
    }

    /// Like [`Self::remove_file`] but assumes the caller already holds an
    /// open transaction.
    pub fn remove_file_in_tx(&self, path: &str) -> Result<()> {
        self.clear_file_data_in_tx(path)?;
        self.conn
            .execute("DELETE FROM files WHERE path = ?1", params![path])?;
        Ok(())
    }

    // ── Symbols ──

    /// Insert or replace a single symbol.
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn insert_symbol(&self, sym: &Symbol) -> Result<()> {
        self.conn
            .prepare_cached(SQL_INSERT_SYMBOL)?
            .execute(params![
                sym.id,
                sym.name,
                sym.kind.as_str(),
                sym.file_path,
                sym.start_line,
                sym.end_line,
                sym.start_byte,
                sym.end_byte,
                sym.parent_id,
                sym.signature,
                sym.visibility.as_str(),
                sym.is_async,
                sym.docstring,
                sym.content_hash,
                sym.subtree_hash,
            ])?;
        Ok(())
    }

    /// Insert or replace multiple symbols in a single transaction.
    pub fn insert_symbols(&self, symbols: &[Symbol]) -> Result<()> {
        let tx = self.conn.unchecked_transaction()?;
        self.insert_symbols_in_tx(symbols)?;
        tx.commit()?;
        Ok(())
    }

    /// Like [`Self::insert_symbols`] but assumes the caller already holds an
    /// open transaction.
    pub fn insert_symbols_in_tx(&self, symbols: &[Symbol]) -> Result<()> {
        let mut stmt = self.conn.prepare_cached(SQL_INSERT_SYMBOL)?;
        for sym in symbols {
            stmt.execute(params![
                sym.id,
                sym.name,
                sym.kind.as_str(),
                sym.file_path,
                sym.start_line,
                sym.end_line,
                sym.start_byte,
                sym.end_byte,
                sym.parent_id,
                sym.signature,
                sym.visibility.as_str(),
                sym.is_async,
                sym.docstring,
                sym.content_hash,
                sym.subtree_hash,
            ])?;
        }
        Ok(())
    }

    /// Get stored symbol hashes for a file (for Merkle diff).
    /// Returns `(id, content_hash, subtree_hash)` tuples.
    #[allow(clippy::type_complexity)]
    pub fn get_symbol_hashes_for_file(
        &self,
        file_path: &str,
    ) -> Result<Vec<(String, Option<String>, Option<String>)>> {
        let mut stmt = self
            .conn
            .prepare("SELECT id, content_hash, subtree_hash FROM symbols WHERE file_path = ?1")?;
        let rows = stmt
            .query_map(params![file_path], |row| {
                Ok((row.get(0)?, row.get(1)?, row.get(2)?))
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;
        Ok(rows)
    }

    /// Update only the position fields of a symbol (for moved-but-unchanged symbols).
    pub fn update_symbol_position(
        &self,
        id: &str,
        start_line: u32,
        end_line: u32,
        start_byte: u32,
        end_byte: u32,
    ) -> Result<()> {
        self.conn.execute(
            "UPDATE symbols SET start_line = ?2, end_line = ?3,
                    start_byte = ?4, end_byte = ?5 WHERE id = ?1",
            params![id, start_line, end_line, start_byte, end_byte],
        )?;
        Ok(())
    }

    /// Delete multiple symbols and cascade (edges, content, embeddings) in a
    /// single transaction.
    pub fn delete_symbols(&self, ids: &[String]) -> Result<()> {
        if ids.is_empty() {
            return Ok(());
        }
        let tx = self.conn.unchecked_transaction()?;
        self.delete_symbols_in_tx(ids)?;
        tx.commit()?;
        Ok(())
    }

    /// Like [`Self::delete_symbols`] but assumes the caller already holds an
    /// open transaction.
    pub fn delete_symbols_in_tx(&self, ids: &[String]) -> Result<()> {
        if ids.is_empty() {
            return Ok(());
        }
        let mut del_out = self
            .conn
            .prepare_cached("DELETE FROM edges WHERE source_id = ?1")?;
        // Reset state alongside target_id so the orphaned edge re-enters
        // unresolved_edges() instead of becoming a (NULL, state=1) zombie.
        // Clear resolution_source too, else the edge keeps a stale provenance
        // tag that no longer reflects a real target until/unless it re-resolves.
        let mut null_in = self.conn.prepare_cached(
            "UPDATE edges SET target_id = NULL, resolution_state = 0, resolution_source = NULL
             WHERE target_id = ?1",
        )?;
        let mut del_content = self
            .conn
            .prepare_cached("DELETE FROM symbol_content WHERE symbol_id = ?1")?;
        let mut del_sym = self
            .conn
            .prepare_cached("DELETE FROM symbols WHERE id = ?1")?;
        for id in ids {
            del_out.execute(params![id])?;
            null_in.execute(params![id])?;
            // Embedding vec+map delete shared with clear_embeddings_for_symbols_in_tx.
            self.delete_embedding_rows_for_id_in_tx(id)?;
            del_content.execute(params![id])?;
            del_sym.execute(params![id])?;
        }
        Ok(())
    }

    /// Delete a single symbol and cascade to edges, content, and embeddings.
    pub fn delete_symbol(&self, id: &str) -> Result<()> {
        let tx = self.conn.unchecked_transaction()?;
        self.conn
            .execute("DELETE FROM edges WHERE source_id = ?1", params![id])?;
        self.conn.execute(
            "UPDATE edges SET target_id = NULL, resolution_state = 0, resolution_source = NULL
             WHERE target_id = ?1",
            params![id],
        )?;
        let _ = self.conn.execute(
            "DELETE FROM symbol_vec WHERE rowid IN \
             (SELECT id FROM symbol_embedding_map WHERE symbol_id = ?1)",
            params![id],
        );
        let _ = self.conn.execute(
            "DELETE FROM symbol_embedding_map WHERE symbol_id = ?1",
            params![id],
        );
        let _ = self.conn.execute(
            "DELETE FROM symbol_content WHERE symbol_id = ?1",
            params![id],
        );
        self.conn
            .execute("DELETE FROM symbols WHERE id = ?1", params![id])?;
        tx.commit()?;
        Ok(())
    }

    // ── Edges ──

    /// Insert a single edge.
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn insert_edge(&self, edge: &Edge) -> Result<()> {
        self.conn.prepare_cached(SQL_INSERT_EDGE)?.execute(params![
            edge.source_id,
            edge.target_name,
            edge.target_id,
            edge.kind.as_str(),
            edge.file_path,
            edge.line,
            i64::from(edge.target_id.is_some()),
            edge.provenance.map(|p| p.as_str()),
        ])?;
        Ok(())
    }

    /// Insert multiple edges in a single transaction.
    pub fn insert_edges(&self, edges: &[Edge]) -> Result<()> {
        let tx = self.conn.unchecked_transaction()?;
        self.insert_edges_in_tx(edges)?;
        tx.commit()?;
        Ok(())
    }

    /// Like [`Self::insert_edges`] but assumes the caller already holds an
    /// open transaction.
    pub fn insert_edges_in_tx(&self, edges: &[Edge]) -> Result<()> {
        let mut stmt = self.conn.prepare_cached(SQL_INSERT_EDGE)?;
        for edge in edges {
            stmt.execute(params![
                edge.source_id,
                edge.target_name,
                edge.target_id,
                edge.kind.as_str(),
                edge.file_path,
                edge.line,
                i64::from(edge.target_id.is_some()),
                edge.provenance.map(|p| p.as_str()),
            ])?;
        }
        Ok(())
    }
}