sqlite-graphrag 1.2.5

Persistent GraphRAG memory for Claude Code, Codex, Cursor, and 27 AI agents — one self-contained ~19 MiB Rust binary, zero daemon. Never re-explain your codebase again. Hybrid retrieval (FTS5 BM25 + cosine similarity + multi-hop graph traversal) surfaces the right memory in milliseconds. Embedding and entity enrichment run as parallel REST calls against your cloud LLM — no fragile headless subprocesses, no ONNX runtime, no model downloads. Soft-delete with full version history, transactional atomic writes, BLAKE3-tracked mutations. OAuth-only: raw API keys ABORT the spawn.
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! GAP-SG-185 v1.2.4: page→enqueue streaming for high-volume enrich scans.
//!
//! Production enqueue walks keyset pages and never retains the full key list.
//! Dry-run and unit tests keep [`super::scan_operation`] (full `Vec`).

use super::super::args::{EnrichArgs, EnrichOperation, ReEmbedTarget};
use super::super::predicates::{
    entity_description_scan_predicate, is_low_quality_description, reembed_chunk_predicate,
    reembed_entity_predicate, reembed_memory_predicate, UNBOUND_MEMORY_PREDICATE,
};
use super::name_filter::resolve_name_filter;
use super::sql::{keyset_for_each, keyset_for_each_selected};
use crate::errors::AppError;
use rusqlite::Connection;

/// Walk candidate keys in pages, invoking `on_page` for each page.
///
/// Returns the total number of keys delivered. Peak key-buffer RSS is O(page_size)
/// for keyset-backed operations without a name filter; non-keyset ops (and name
/// filters) deliver via a single full collect page.
pub(in crate::commands::enrich) fn scan_operation_for_each<F>(
    conn: &Connection,
    namespace: &str,
    args: &EnrichArgs,
    mut on_page: F,
) -> Result<usize, AppError>
where
    F: FnMut(Vec<String>) -> Result<(), AppError>,
{
    let name_filter = resolve_name_filter(args)?;
    let page_size = args.scan_page_size().max(1);
    let limit = args.limit;

    // Name filters are small explicit subsets; reuse the full collect path so
    // keyset page fullness is not corrupted by post-fetch filtering.
    if !name_filter.is_empty() {
        return deliver_full(conn, namespace, args, &mut on_page);
    }

    match args.operation() {
        EnrichOperation::MemoryBindings => {
            for_each_unbound(conn, namespace, limit, page_size, &mut on_page)
        }
        EnrichOperation::BodyEnrich => for_each_short_body(
            conn,
            namespace,
            args.min_output_chars,
            limit,
            page_size,
            &mut on_page,
        ),
        EnrichOperation::ReEmbed => {
            for_each_reembed(conn, namespace, args, page_size, &mut on_page)
        }
        EnrichOperation::EntityDescriptions => for_each_entity_descriptions(
            conn,
            namespace,
            args.force_redescribe,
            limit,
            page_size,
            &mut on_page,
        ),
        EnrichOperation::DomainClassify
        | EnrichOperation::GraphAudit
        | EnrichOperation::DeepResearchSynth
        | EnrichOperation::BodyExtract => {
            for_each_all_memory_names(conn, namespace, limit, page_size, &mut on_page)
        }
        _ => deliver_full(conn, namespace, args, &mut on_page),
    }
}

fn deliver_full<F>(
    conn: &Connection,
    namespace: &str,
    args: &EnrichArgs,
    on_page: &mut F,
) -> Result<usize, AppError>
where
    F: FnMut(Vec<String>) -> Result<(), AppError>,
{
    let keys = super::scan_operation(conn, namespace, args)?;
    let n = keys.len();
    if n > 0 {
        on_page(keys)?;
    }
    Ok(n)
}

fn for_each_unbound<F>(
    conn: &Connection,
    namespace: &str,
    limit: Option<usize>,
    page_size: usize,
    on_page: &mut F,
) -> Result<usize, AppError>
where
    F: FnMut(Vec<String>) -> Result<(), AppError>,
{
    keyset_for_each(
        limit,
        page_size,
        &mut |after, want| {
            let limit_v = i64::try_from(want).unwrap_or(i64::MAX);
            let sql = format!(
                "SELECT m.id, m.name FROM memories m
                 WHERE m.namespace = ?1 AND m.deleted_at IS NULL AND m.id > ?2
                   AND {UNBOUND_MEMORY_PREDICATE}
                 ORDER BY m.id LIMIT ?3"
            );
            let mut stmt = conn.prepare(&sql)?;
            let rows = stmt
                .query_map(rusqlite::params![namespace, after, limit_v], |r| {
                    Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?))
                })?
                .collect::<Result<Vec<_>, _>>()?;
            Ok(rows)
        },
        // `&mut F` implements `FnMut` whenever `F` does, so the reborrow is
        // handed straight to `keyset_for_each` — wrapping it in a closure only
        // added a layer clippy rejects as redundant.
        &mut *on_page,
    )
}

fn for_each_short_body<F>(
    conn: &Connection,
    namespace: &str,
    min_chars: usize,
    limit: Option<usize>,
    page_size: usize,
    on_page: &mut F,
) -> Result<usize, AppError>
where
    F: FnMut(Vec<String>) -> Result<(), AppError>,
{
    let min_chars_i64 = min_chars as i64;
    keyset_for_each(
        limit,
        page_size,
        &mut |after, want| {
            let limit_v = i64::try_from(want).unwrap_or(i64::MAX);
            let sql = "SELECT m.id, m.name FROM memories m
             WHERE m.namespace = ?1 AND m.deleted_at IS NULL AND m.id > ?2
               AND LENGTH(COALESCE(m.body,'')) < ?3
             ORDER BY m.id LIMIT ?4";
            let mut stmt = conn.prepare(sql)?;
            let rows = stmt
                .query_map(
                    rusqlite::params![namespace, after, min_chars_i64, limit_v],
                    |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)),
                )?
                .collect::<Result<Vec<_>, _>>()?;
            Ok(rows)
        },
        // `&mut F` implements `FnMut` whenever `F` does, so the reborrow is
        // handed straight to `keyset_for_each` — wrapping it in a closure only
        // added a layer clippy rejects as redundant.
        &mut *on_page,
    )
}

fn for_each_all_memory_names<F>(
    conn: &Connection,
    namespace: &str,
    limit: Option<usize>,
    page_size: usize,
    on_page: &mut F,
) -> Result<usize, AppError>
where
    F: FnMut(Vec<String>) -> Result<(), AppError>,
{
    keyset_for_each(
        limit,
        page_size,
        &mut |after, want| {
            let limit_v = i64::try_from(want).unwrap_or(i64::MAX);
            let sql = "SELECT id, name FROM memories
                   WHERE namespace=?1 AND deleted_at IS NULL AND id > ?2
                   ORDER BY id LIMIT ?3";
            let mut stmt = conn.prepare(sql)?;
            let rows = stmt
                .query_map(rusqlite::params![namespace, after, limit_v], |r| {
                    Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?))
                })?
                .collect::<Result<Vec<_>, _>>()?;
            Ok(rows)
        },
        // `&mut F` implements `FnMut` whenever `F` does, so the reborrow is
        // handed straight to `keyset_for_each` — wrapping it in a closure only
        // added a layer clippy rejects as redundant.
        &mut *on_page,
    )
}

/// Streams entities whose description is missing or, under `--force-redescribe`,
/// too low-quality to keep.
///
/// The quality test lives in Rust, not in SQL, so a fetched row can still be
/// rejected — which is exactly the case
/// [`super::sql::keyset_for_each_selected`] exists for. Judging page fullness on
/// rows scanned rather than rows kept is what stops a page thinned by rejections
/// from being read as the end of the table.
fn for_each_entity_descriptions<F>(
    conn: &Connection,
    namespace: &str,
    force_redescribe: bool,
    limit: Option<usize>,
    page_size: usize,
    on_page: &mut F,
) -> Result<usize, AppError>
where
    F: FnMut(Vec<String>) -> Result<(), AppError>,
{
    let desc_pred = entity_description_scan_predicate(force_redescribe);
    keyset_for_each_selected(
        limit,
        page_size,
        &mut |after, want| {
            let limit_v = i64::try_from(want).unwrap_or(i64::MAX);
            let sql = format!(
                "SELECT id, name, COALESCE(description, '') FROM entities
                 WHERE namespace = ?1 AND id > ?2 AND {desc_pred}
                 ORDER BY id LIMIT ?3"
            );
            let mut stmt = conn.prepare(&sql)?;
            let rows = stmt
                .query_map(rusqlite::params![namespace, after, limit_v], |r| {
                    Ok((
                        r.get::<_, i64>(0)?,
                        r.get::<_, String>(1)?,
                        r.get::<_, String>(2)?,
                    ))
                })?
                .collect::<Result<Vec<_>, _>>()?;
            Ok(rows
                .into_iter()
                .map(|(id, name, desc)| {
                    let keep = !force_redescribe
                        || desc.trim().is_empty()
                        || is_low_quality_description(&desc);
                    (id, keep.then_some(name))
                })
                .collect())
        },
        &mut *on_page,
    )
}

fn for_each_reembed<F>(
    conn: &Connection,
    namespace: &str,
    args: &EnrichArgs,
    page_size: usize,
    on_page: &mut F,
) -> Result<usize, AppError>
where
    F: FnMut(Vec<String>) -> Result<(), AppError>,
{
    let mut total = 0usize;
    let limit = args.limit;
    if matches!(args.target, ReEmbedTarget::Memories | ReEmbedTarget::All) {
        let pred = reembed_memory_predicate(crate::constants::embedding_dim());
        let n = keyset_for_each(
            limit,
            page_size,
            &mut |after, want| {
                let limit_v = i64::try_from(want).unwrap_or(i64::MAX);
                let sql = format!(
                    "SELECT m.id, m.name FROM memories m
                 WHERE m.namespace = ?1 AND m.deleted_at IS NULL AND m.id > ?2
                   AND {pred}
                 ORDER BY m.id LIMIT ?3"
                );
                let mut stmt = conn.prepare(&sql)?;
                let rows = stmt
                    .query_map(rusqlite::params![namespace, after, limit_v], |r| {
                        Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?))
                    })?
                    .collect::<Result<Vec<_>, _>>()?;
                Ok(rows)
            },
            &mut *on_page,
        )?;
        total = total.saturating_add(n);
    }
    if matches!(args.target, ReEmbedTarget::Entities | ReEmbedTarget::All) {
        let pred = reembed_entity_predicate(crate::constants::embedding_dim());
        let n = keyset_for_each(
            limit,
            page_size,
            &mut |after, want| {
                let limit_v = i64::try_from(want).unwrap_or(i64::MAX);
                let sql = format!(
                    "SELECT e.id, e.name FROM entities e
                 WHERE e.namespace = ?1 AND e.id > ?2 AND {pred}
                 ORDER BY e.id LIMIT ?3"
                );
                let mut stmt = conn.prepare(&sql)?;
                let rows = stmt
                    .query_map(rusqlite::params![namespace, after, limit_v], |r| {
                        Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?))
                    })?
                    .collect::<Result<Vec<_>, _>>()?;
                Ok(rows)
            },
            |page| on_page(page.into_iter().map(|n| format!("entity:{n}")).collect()),
        )?;
        total = total.saturating_add(n);
    }
    if matches!(args.target, ReEmbedTarget::Chunks | ReEmbedTarget::All) {
        let pred = reembed_chunk_predicate(crate::constants::embedding_dim());
        let n = keyset_for_each(
            limit,
            page_size,
            &mut |after, want| {
                let limit_v = i64::try_from(want).unwrap_or(i64::MAX);
                let sql = format!(
                    "SELECT c.id FROM memory_chunks c
                 LEFT JOIN memories m ON m.id = c.memory_id
                 WHERE (m.namespace = ?1 OR m.id IS NULL) AND c.id > ?2 AND {pred}
                 ORDER BY c.id LIMIT ?3"
                );
                let mut stmt = conn.prepare(&sql)?;
                let rows = stmt
                    .query_map(rusqlite::params![namespace, after, limit_v], |r| {
                        let id = r.get::<_, i64>(0)?;
                        Ok((id, id))
                    })?
                    .collect::<Result<Vec<_>, _>>()?;
                Ok(rows)
            },
            |page| on_page(page.into_iter().map(|id| format!("chunk:{id}")).collect()),
        )?;
        total = total.saturating_add(n);
    }
    Ok(total)
}

#[cfg(test)]
mod entity_description_stream_tests {
    use super::*;

    /// Minimal `entities` shape the description scan touches.
    fn seeded_conn(rows: &[(&str, Option<&str>)]) -> Connection {
        let conn = Connection::open_in_memory().expect("in-memory db");
        conn.execute_batch(
            "CREATE TABLE entities (
                 id INTEGER PRIMARY KEY,
                 namespace TEXT NOT NULL,
                 name TEXT NOT NULL,
                 type TEXT NOT NULL DEFAULT 'concept',
                 description TEXT
             );",
        )
        .expect("schema");
        for (name, description) in rows {
            conn.execute(
                "INSERT INTO entities (namespace, name, description) VALUES ('global', ?1, ?2)",
                rusqlite::params![name, description],
            )
            .expect("seed row");
        }
        conn
    }

    fn streamed(conn: &Connection, force: bool, limit: Option<usize>, page: usize) -> Vec<String> {
        let mut seen = Vec::new();
        for_each_entity_descriptions(conn, "global", force, limit, page, &mut |names| {
            seen.extend(names);
            Ok(())
        })
        .expect("stream walk");
        seen
    }

    /// A page whose rows are all rejected must not be read as end-of-table.
    ///
    /// This is the failure the plain `keyset_for_each` would have produced: with
    /// `page_size = 2`, the middle page holds two acceptable descriptions, gets
    /// thinned to zero, and `n < want` ends the scan — losing every entity
    /// behind it. The tail here sits behind exactly such a page.
    #[test]
    fn a_fully_rejected_page_does_not_end_the_scan() {
        let conn = seeded_conn(&[
            ("alpha", None),
            ("beta", Some("")),
            (
                "gamma",
                Some("a genuinely specific description of the parser"),
            ),
            ("delta", Some("another honest sentence about the scheduler")),
            ("epsilon", None),
        ]);

        let names = streamed(&conn, true, None, 2);

        assert!(
            names.contains(&"epsilon".to_string()),
            "the tail behind a fully rejected page was lost: {names:?}"
        );
        assert_eq!(names, vec!["alpha", "beta", "epsilon"]);
    }

    /// Streaming must deliver exactly what the full collect delivers, at every
    /// page width — including one narrower than the number of rejections.
    #[test]
    fn streaming_matches_the_full_scan_at_every_page_width() {
        let rows: Vec<(String, Option<String>)> = (0..40)
            .map(|i| {
                let name = format!("entity-{i:02}");
                let description = match i % 3 {
                    0 => None,
                    1 => Some(String::new()),
                    _ => Some(format!("a specific description number {i} of real prose")),
                };
                (name, description)
            })
            .collect();
        let borrowed: Vec<(&str, Option<&str>)> = rows
            .iter()
            .map(|(n, d)| (n.as_str(), d.as_deref()))
            .collect();
        let conn = seeded_conn(&borrowed);

        let reference = streamed(&conn, true, None, 4096);
        for page in [1usize, 2, 3, 7, 40, 100] {
            assert_eq!(
                streamed(&conn, true, None, page),
                reference,
                "page width {page} diverged from the single-page walk"
            );
        }
    }

    /// `--limit N` counts items DELIVERED, not rows scanned.
    ///
    /// Decrementing the budget by rows looked at would return fewer than N
    /// usable entities whenever the post-filter rejected any of them.
    #[test]
    fn limit_counts_delivered_items_not_scanned_rows() {
        let conn = seeded_conn(&[
            ("a", None),
            (
                "b",
                Some("a real and sufficiently specific description here"),
            ),
            ("c", None),
            (
                "d",
                Some("another real description that must not be rewritten"),
            ),
            ("e", None),
        ]);

        assert_eq!(streamed(&conn, true, Some(2), 2), vec!["a", "c"]);
        assert_eq!(streamed(&conn, true, Some(3), 2), vec!["a", "c", "e"]);
    }
}