geg 0.3.0

Geg Embeds Gemma: offline semantic grep with EmbeddingGemma 2 and persistent vector caching
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
use std::{
    collections::{BTreeMap, BTreeSet},
    fs,
    path::{Path, PathBuf},
    time::Duration,
};

use anyhow::{Context, Result, ensure};
use rusqlite::{Connection, OptionalExtension, params};

use crate::{
    cache::Cache,
    codegraph,
    hybrid::{self, reciprocal_rank_fusion},
    input,
    search::{Hit, Response, Searcher, Stats},
};

const INDEX_FORMAT: &str = "geg-index-v5-incremental-hybrid";

pub fn default_path() -> Result<PathBuf> {
    Ok(std::env::current_dir()?.join(".geg/index.sqlite3"))
}

fn open(path: &Path) -> Result<Connection> {
    crate::cache::prepare_database(path)?;
    let db = Connection::open(path)?;
    db.busy_timeout(Duration::from_secs(30))?;
    db.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA cache_size=-2048; PRAGMA mmap_size=0;
        CREATE TABLE IF NOT EXISTS meta_v1 (key TEXT PRIMARY KEY, value TEXT NOT NULL);
        CREATE TABLE IF NOT EXISTS files_v1 (path TEXT PRIMARY KEY, modified_ns INTEGER NOT NULL DEFAULT 0, size INTEGER NOT NULL DEFAULT 0);
        CREATE TABLE IF NOT EXISTS vectors_v1 (key BLOB PRIMARY KEY, vector BLOB NOT NULL) WITHOUT ROWID;
        CREATE TABLE IF NOT EXISTS chunks_v4 (id INTEGER PRIMARY KEY, path TEXT NOT NULL, line INTEGER NOT NULL, text TEXT NOT NULL, vector_key BLOB NOT NULL, symbol TEXT NOT NULL DEFAULT '');
        CREATE INDEX IF NOT EXISTS chunks_v4_vector_key ON chunks_v4(vector_key);
        CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts_v4 USING fts5(chunk_id UNINDEXED, text, tokenize='unicode61 remove_diacritics 2');")?;
    if !has_column(&db, "files_v1", "modified_ns")? {
        db.execute(
            "ALTER TABLE files_v1 ADD COLUMN modified_ns INTEGER NOT NULL DEFAULT 0",
            [],
        )?;
    }
    if !has_column(&db, "files_v1", "size")? {
        db.execute(
            "ALTER TABLE files_v1 ADD COLUMN size INTEGER NOT NULL DEFAULT 0",
            [],
        )?;
    }
    Ok(db)
}

fn delete_chunks(db: &Connection, path: &str) -> Result<()> {
    db.execute(
        "DELETE FROM chunks_fts_v4 WHERE chunk_id IN (SELECT id FROM chunks_v4 WHERE path=?1)",
        [path],
    )?;
    db.execute("DELETE FROM chunks_v4 WHERE path=?1", [path])?;
    Ok(())
}

fn has_column(db: &Connection, table: &str, column: &str) -> Result<bool> {
    let mut statement = db.prepare(&format!("PRAGMA table_info({table})"))?;
    let mut rows = statement.query([])?;
    while let Some(row) = rows.next()? {
        if row.get::<_, String>(1)? == column {
            return Ok(true);
        }
    }
    Ok(false)
}

fn file_signature(path: &Path) -> Result<(i64, i64)> {
    let metadata = fs::metadata(path)?;
    let modified = metadata
        .modified()?
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    Ok((
        i64::try_from(modified).unwrap_or(i64::MAX),
        i64::try_from(metadata.len()).unwrap_or(i64::MAX),
    ))
}

fn decode(bytes: &[u8], dimensions: usize) -> Result<Vec<f32>> {
    ensure!(
        bytes.len() == dimensions * 4,
        "invalid index vector length; rebuild the index"
    );
    let vector: Vec<f32> = bytes
        .as_chunks::<4>()
        .0
        .iter()
        .map(|v| f32::from_le_bytes(*v))
        .collect();
    ensure!(
        vector.iter().all(|v| v.is_finite()),
        "non-finite index vector; rebuild the index"
    );
    Ok(vector)
}

impl Searcher<'_> {
    pub fn build_index(&mut self, paths: &[PathBuf], output: &Path) -> Result<Stats> {
        ensure!(
            paths.iter().all(|p| p != Path::new("-")),
            "indexing requires files/directories, not stdin"
        );
        ensure!(
            !self.cache.shares_path(output)?,
            "index and global cache must use different database paths"
        );
        self.progress.begin("building repository index");
        let mut db = open(output)?;
        let output = fs::canonicalize(output)?;
        let mut wal = output.as_os_str().to_os_string();
        wal.push("-wal");
        let mut shm = output.as_os_str().to_os_string();
        shm.push("-shm");
        let transaction = db.transaction()?;
        let build_meta = [
            ("model", self.model_hash.to_hex().to_string()),
            ("dimensions", self.dimensions.to_string()),
            ("ignore_case", self.args.ignore_case.to_string()),
            ("chunk_lines", self.args.chunk_lines.to_string()),
            ("embedding_format", crate::cache::FORMAT.to_owned()),
            ("format", INDEX_FORMAT.to_owned()),
        ];
        let rebuild = build_meta.iter().try_fold(false, |rebuild, (key, value)| {
            let current: Option<String> = transaction
                .query_row("SELECT value FROM meta_v1 WHERE key=?1", [key], |row| {
                    row.get(0)
                })
                .optional()?;
            Ok::<_, anyhow::Error>(rebuild || current.as_deref() != Some(value))
        })?;
        if rebuild {
            transaction.execute("DELETE FROM chunks_fts_v4", [])?;
            transaction.execute("DELETE FROM chunks_v4", [])?;
            transaction.execute("DELETE FROM files_v1", [])?;
        }
        let mut stats = Stats::default();
        let mut seen = BTreeSet::new();
        input::visit_files(paths, self.args.no_ignore, self.args.hidden, |path| {
            let absolute = fs::canonicalize(path)?;
            if absolute == output || absolute.as_os_str() == wal || absolute.as_os_str() == shm {
                return Ok(());
            }
            let label = absolute.to_string_lossy().into_owned();
            if !seen.insert(label.clone()) {
                return Ok(());
            }
            let signature = file_signature(&absolute)?;
            let previous: Option<(i64, i64)> = transaction
                .query_row(
                    "SELECT modified_ns, size FROM files_v1 WHERE path=?1",
                    [&label],
                    |row| Ok((row.get(0)?, row.get(1)?)),
                )
                .optional()?;
            if previous == Some(signature) {
                let chunks = transaction.query_row(
                    "SELECT count(*) FROM chunks_v4 WHERE path=?1",
                    [&label],
                    |row| row.get::<_, i64>(0),
                )?;
                let chunks = u64::try_from(chunks)?;
                stats.files += 1;
                stats.chunks += chunks;
                stats.cache_hits += chunks;
                return Ok(());
            }
            delete_chunks(&transaction, &label)?;
            self.read_file(&absolute, |this, reader, label| {
                input::chunks(reader, this.args.chunk_lines, |line, text, symbol| {
                    if !input::searchable(text) {
                        return Ok(());
                    }
                    let prompt = input::prompt(symbol, text);
                    let prompt = if this.args.ignore_case {
                        prompt.to_lowercase()
                    } else {
                        prompt
                    };
                    let key = Cache::key(&this.model_hash, this.dimensions, &prompt);
                    let local: Option<Vec<u8>> = transaction
                        .prepare_cached("SELECT vector FROM vectors_v1 WHERE key=?1")?
                        .query_row([key.as_bytes().as_slice()], |row| row.get(0))
                        .optional()?;
                    if let Some(bytes) = local {
                        decode(&bytes, this.dimensions)?;
                        stats.cache_hits += 1;
                    } else {
                        let vector = if let Some(vector) = this.cached_vector(&key)? {
                            stats.cache_hits += 1;
                            vector
                        } else {
                            this.embed_uncached(&prompt, &mut stats)?
                        };
                        let bytes: Vec<u8> = vector.iter().flat_map(|v| v.to_le_bytes()).collect();
                        transaction
                            .prepare_cached("INSERT INTO vectors_v1 VALUES (?1, ?2)")?
                            .execute(params![key.as_bytes().as_slice(), bytes])?;
                    }
                    transaction
                        .prepare_cached("INSERT INTO chunks_v4(path, line, text, vector_key, symbol) VALUES (?1, ?2, ?3, ?4, ?5)")?
                        .execute(params![
                            label,
                            i64::try_from(line)?,
                            text,
                            key.as_bytes().as_slice(),
                            symbol
                        ])?;
                    let chunk_id = transaction.last_insert_rowid();
                    transaction
                        .prepare_cached("INSERT INTO chunks_fts_v4(chunk_id, text) VALUES (?1, ?2)")?
                        .execute(params![chunk_id, hybrid::tokenize(text).join(" ")])?;
                    stats.chunks += 1;
                    this.progress.update(&stats);
                    Ok(())
                })
            })?;
            transaction.execute(
                "INSERT OR REPLACE INTO files_v1(path, modified_ns, size) VALUES (?1, ?2, ?3)",
                params![label, signature.0, signature.1],
            )?;
            stats.files += 1;
            Ok(())
        })?;
        let indexed: Vec<String> = transaction
            .prepare("SELECT path FROM files_v1")?
            .query_map([], |row| row.get(0))?
            .collect::<rusqlite::Result<_>>()?;
        for path in indexed {
            if !seen.contains(&path) {
                delete_chunks(&transaction, &path)?;
                transaction.execute("DELETE FROM files_v1 WHERE path=?1", [&path])?;
            }
        }
        for (key, value) in build_meta {
            transaction.execute(
                "INSERT OR REPLACE INTO meta_v1 VALUES (?1, ?2)",
                params![key, value],
            )?;
        }
        // Prune removed/changed chunks, duplicate content shares one vector locally too.
        transaction.execute(
            "DELETE FROM vectors_v1 WHERE key NOT IN (SELECT vector_key FROM chunks_v4)",
            [],
        )?;
        transaction.execute_batch(
            "DROP TABLE IF EXISTS chunks_v1; DROP TABLE IF EXISTS chunks_v2; DROP TABLE IF EXISTS chunks_v3;",
        )?;
        transaction.commit()?;
        db.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
        // A failure before commit never removes the user's last cached generation.
        self.cache.remove_indexed(&output)?;
        self.progress.finish(&stats);
        Ok(stats)
    }

    pub fn search_index(&mut self, query: &str, path: &Path) -> Result<Response> {
        self.validate_query(query)?;
        self.progress
            .begin("reading index and matching semantic chunks");
        let db = Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
            .with_context(|| {
                format!(
                    "opening index {}; run `geg index <paths>` to build/rebuild it",
                    path.display()
                )
            })?;
        db.busy_timeout(Duration::from_secs(30))?;
        db.execute_batch("PRAGMA cache_size=-2048; PRAGMA mmap_size=0; BEGIN;")?;
        // Validate format first so legacy indexes get a clear rebuild message.
        for (key, expected) in [
            ("format", INDEX_FORMAT.to_owned()),
            ("model", self.model_hash.to_hex().to_string()),
            ("dimensions", self.dimensions.to_string()),
            ("ignore_case", self.args.ignore_case.to_string()),
            ("embedding_format", crate::cache::FORMAT.to_owned()),
        ] {
            let actual: Option<String> = db
                .query_row("SELECT value FROM meta_v1 WHERE key=?1", [key], |r| {
                    r.get(0)
                })
                .optional()?;
            ensure!(
                actual.as_deref() == Some(&expected),
                "index {key} mismatch; rebuild with `geg index <paths>` and the current model/settings"
            );
        }
        let mut stats = Stats::default();
        let query_vector = self.query_vector(query, &mut stats)?;
        let mut hits = Vec::new();
        let mut counts = BTreeMap::new();
        for path in db
            .prepare("SELECT path FROM files_v1")?
            .query_map([], |r| r.get::<_, String>(0))?
        {
            counts.insert(path?, 0u64);
        }
        stats.files = counts.len() as u64;
        let lexical_terms = hybrid::terms(query);
        let fts_query = lexical_terms
            .iter()
            .map(|term| format!("\"{}\"", term.replace('"', "\"\"")))
            .collect::<Vec<_>>()
            .join(" OR ");
        let mut lexical_ranks = BTreeMap::new();
        if !fts_query.is_empty() {
            let mut statement = db.prepare(
                "SELECT chunk_id FROM chunks_fts_v4 WHERE chunks_fts_v4 MATCH ?1 ORDER BY bm25(chunks_fts_v4), chunk_id",
            )?;
            for (rank, row) in statement
                .query_map([fts_query], |row| row.get::<_, i64>(0))?
                .enumerate()
            {
                lexical_ranks.insert(row?, rank + 1);
            }
        }
        let mut statement = db.prepare("SELECT c.id, c.path, c.line, c.text, v.vector, c.symbol FROM chunks_v4 c JOIN vectors_v1 v ON v.key=c.vector_key")?;
        let mut rows = statement.query([])?;
        let mut ranked = Vec::new();
        while let Some(row) = rows.next()? {
            let chunk_id: i64 = row.get(0)?;
            let text: String = row.get(3)?;
            if !input::searchable(&text) {
                continue;
            }
            let bytes: Vec<u8> = row.get(4)?;
            let vector = decode(&bytes, self.dimensions)?;
            let score = crate::search::best_score(&query_vector, &vector);
            stats.chunks += 1;
            self.progress.update(&stats);
            let path: String = row.get(1)?;
            let count = counts.entry(path.clone()).or_default();
            if self.accepts(score) && *count < self.args.max_count.unwrap_or(u64::MAX) {
                let text = crate::search::select_lines(
                    &text,
                    self.args.max_count.unwrap_or(u64::MAX) - *count,
                );
                *count += text.lines().count() as u64;
                ranked.push((
                    0.0,
                    chunk_id,
                    Hit {
                        path,
                        line: u64::try_from(row.get::<_, i64>(2)?)?,
                        text,
                        score,
                        symbol: row.get(5)?,
                    },
                ));
            }
        }
        ranked.sort_unstable_by(|(_, _, a), (_, _, b)| {
            b.score
                .total_cmp(&a.score)
                .then_with(|| a.path.cmp(&b.path))
                .then_with(|| a.line.cmp(&b.line))
        });
        let vector_ranks: BTreeMap<_, _> = ranked
            .iter()
            .enumerate()
            .map(|(rank, (_, id, _))| (*id, rank + 1))
            .collect();
        let mut lexical_order: Vec<_> = ranked
            .iter()
            .filter_map(|(_, id, _)| lexical_ranks.get(id).copied().map(|rank| (rank, *id)))
            .collect();
        lexical_order.sort_unstable();
        let lexical_ranks: BTreeMap<_, _> = lexical_order
            .into_iter()
            .enumerate()
            .map(|(rank, (_, id))| (id, rank + 1))
            .collect();
        for (fusion, id, _) in &mut ranked {
            *fusion = reciprocal_rank_fusion(
                vector_ranks.get(id).copied(),
                lexical_ranks.get(id).copied(),
            );
        }
        ranked.sort_unstable_by(|(a_rank, _, a), (b_rank, _, b)| {
            b_rank
                .total_cmp(a_rank)
                .then_with(|| b.score.total_cmp(&a.score))
                .then_with(|| a.path.cmp(&b.path))
                .then_with(|| a.line.cmp(&b.line))
        });
        hits.extend(ranked.into_iter().take(self.limit()).map(|(_, _, hit)| hit));
        if self.args.codegraph {
            let paths: Vec<_> = hits.iter().map(|hit| PathBuf::from(&hit.path)).collect();
            let symbols = codegraph::lookup(&paths, &crate::hybrid::terms(query));
            for hit in &mut hits {
                if let Some(symbol) = codegraph::symbol_at(&symbols, &hit.path, hit.line) {
                    hit.symbol = symbol.to_owned();
                }
            }
        }
        self.progress.finish(&stats);
        Ok(Response {
            query: query.to_owned(),
            hits,
            counts,
            stats,
        })
    }
}