codelens-engine 1.9.56

Pure Rust code intelligence engine for repository indexing, graph analysis, and local semantic retrieval
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
use super::*;
use std::fs;

#[test]
fn creates_schema_and_upserts_file() {
    let db = IndexDb::open_memory().unwrap();
    let id = db
        .upsert_file("src/main.py", 1000, "abc123", 256, Some("py"))
        .unwrap();
    assert!(id > 0);

    let file = db.get_file("src/main.py").unwrap().unwrap();
    assert_eq!(file.content_hash, "abc123");
    assert_eq!(file.size_bytes, 256);

    // Upsert same path with new hash
    let id2 = db
        .upsert_file("src/main.py", 2000, "def456", 512, Some("py"))
        .unwrap();
    assert_eq!(id, id2);
    let file = db.get_file("src/main.py").unwrap().unwrap();
    assert_eq!(file.content_hash, "def456");
}

#[test]
fn fresh_file_check() {
    let db = IndexDb::open_memory().unwrap();
    db.upsert_file("a.py", 100, "hash1", 10, Some("py"))
        .unwrap();

    assert!(db.get_fresh_file("a.py", 100, "hash1").unwrap().is_some());
    assert!(db.get_fresh_file("a.py", 200, "hash1").unwrap().is_none());
    assert!(db.get_fresh_file("a.py", 100, "hash2").unwrap().is_none());
}

#[test]
fn inserts_and_queries_symbols() {
    let db = IndexDb::open_memory().unwrap();
    let file_id = db.upsert_file("main.py", 100, "h", 10, Some("py")).unwrap();

    let syms = vec![
        NewSymbol {
            name: "Service",
            kind: "class",
            line: 1,
            column_num: 1,
            start_byte: 0,
            end_byte: 50,
            signature: "class Service:",
            name_path: "Service",
            parent_id: None,
            end_line: 0,
        },
        NewSymbol {
            name: "run",
            kind: "method",
            line: 2,
            column_num: 5,
            start_byte: 20,
            end_byte: 48,
            signature: "def run(self):",
            name_path: "Service/run",
            parent_id: None,
            end_line: 0,
        },
    ];
    let ids = db.insert_symbols(file_id, &syms).unwrap();
    assert_eq!(ids.len(), 2);

    let found = db.find_symbols_by_name("Service", None, true, 10).unwrap();
    assert_eq!(found.len(), 1);
    assert_eq!(found[0].kind, "class");

    let found = db
        .find_symbols_by_name("run", Some("main.py"), true, 10)
        .unwrap();
    assert_eq!(found.len(), 1);

    let found = db.find_symbols_by_name("erv", None, false, 10).unwrap();
    assert_eq!(found.len(), 1);
    assert_eq!(found[0].name, "Service");
}

#[test]
fn upsert_file_clears_old_symbols() {
    let db = IndexDb::open_memory().unwrap();
    let file_id = db.upsert_file("a.py", 100, "h1", 10, Some("py")).unwrap();
    db.insert_symbols(
        file_id,
        &[NewSymbol {
            name: "Old",
            kind: "class",
            line: 1,
            column_num: 1,
            start_byte: 0,
            end_byte: 10,
            signature: "class Old:",
            name_path: "Old",
            parent_id: None,
            end_line: 0,
        }],
    )
    .unwrap();

    // Re-upsert should clear old symbols
    let file_id2 = db.upsert_file("a.py", 200, "h2", 20, Some("py")).unwrap();
    assert_eq!(file_id, file_id2);
    let found = db.find_symbols_by_name("Old", None, true, 10).unwrap();
    assert!(found.is_empty());
}

#[test]
fn streams_symbols_grouped_by_file_in_path_order() {
    let db = IndexDb::open_memory().unwrap();
    let b_file_id = db.upsert_file("b.py", 100, "hb", 10, Some("py")).unwrap();
    let a_file_id = db.upsert_file("a.py", 100, "ha", 10, Some("py")).unwrap();

    db.insert_symbols(
        b_file_id,
        &[
            NewSymbol {
                name: "b_second",
                kind: "function",
                line: 2,
                column_num: 0,
                start_byte: 20,
                end_byte: 30,
                signature: "def b_second():",
                name_path: "b_second",
                parent_id: None,
                end_line: 0,
            },
            NewSymbol {
                name: "b_first",
                kind: "function",
                line: 1,
                column_num: 0,
                start_byte: 0,
                end_byte: 10,
                signature: "def b_first():",
                name_path: "b_first",
                parent_id: None,
                end_line: 0,
            },
        ],
    )
    .unwrap();
    db.insert_symbols(
        a_file_id,
        &[NewSymbol {
            name: "a_only",
            kind: "function",
            line: 1,
            column_num: 0,
            start_byte: 0,
            end_byte: 10,
            signature: "def a_only():",
            name_path: "a_only",
            parent_id: None,
            end_line: 0,
        }],
    )
    .unwrap();

    let mut groups = Vec::new();
    let count = db
        .for_each_file_symbols_with_bytes(|file_path, symbols| {
            groups.push((
                file_path,
                symbols
                    .into_iter()
                    .map(|symbol| symbol.name)
                    .collect::<Vec<_>>(),
            ));
            Ok(())
        })
        .unwrap();

    assert_eq!(count, 3);
    assert_eq!(
        groups,
        vec![
            ("a.py".to_string(), vec!["a_only".to_string()]),
            (
                "b.py".to_string(),
                vec!["b_first".to_string(), "b_second".to_string()]
            ),
        ]
    );
}

#[test]
fn import_graph_operations() {
    let db = IndexDb::open_memory().unwrap();
    let main_id = db
        .upsert_file("main.py", 100, "h1", 10, Some("py"))
        .unwrap();
    let utils_id = db
        .upsert_file("utils.py", 100, "h2", 10, Some("py"))
        .unwrap();
    let _models_id = db
        .upsert_file("models.py", 100, "h3", 10, Some("py"))
        .unwrap();

    db.insert_imports(
        main_id,
        &[NewImport {
            target_path: "utils.py".into(),
            raw_import: "utils".into(),
        }],
    )
    .unwrap();
    db.insert_imports(
        utils_id,
        &[NewImport {
            target_path: "models.py".into(),
            raw_import: "models".into(),
        }],
    )
    .unwrap();

    let importers = db.get_importers("utils.py").unwrap();
    assert_eq!(importers, vec!["main.py"]);

    let imports_of = db.get_imports_of("main.py").unwrap();
    assert_eq!(imports_of, vec!["utils.py"]);

    let graph = db.build_import_graph().unwrap();
    assert_eq!(graph.len(), 3);
    assert_eq!(graph["utils.py"].1, vec!["main.py"]); // imported_by
}

#[test]
fn content_hash_is_deterministic() {
    let h1 = content_hash(b"hello world");
    let h2 = content_hash(b"hello world");
    let h3 = content_hash(b"hello world!");
    assert_eq!(h1, h2);
    assert_ne!(h1, h3);
}

#[test]
fn with_transaction_auto_rollback_on_error() {
    let mut db = IndexDb::open_memory().unwrap();
    let result: anyhow::Result<()> = db.with_transaction(|conn| {
        ops::upsert_file(conn, "rollback_test.py", 100, "h1", 10, Some("py"))?;
        anyhow::bail!("simulated error");
    });
    assert!(result.is_err());
    // File should not exist — transaction was rolled back
    assert!(db.get_file("rollback_test.py").unwrap().is_none());
}

#[test]
fn open_recreates_corrupt_db_and_wal_sidecars() {
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("symbols.db");
    let wal_path = dir.path().join("symbols.db-wal");
    let shm_path = dir.path().join("symbols.db-shm");

    fs::write(&db_path, b"not a sqlite database").unwrap();
    fs::write(&wal_path, b"bad wal").unwrap();
    fs::write(&shm_path, b"bad shm").unwrap();

    let db = IndexDb::open(&db_path).unwrap();
    assert_eq!(db.file_count().unwrap(), 0);

    let file_id = db
        .upsert_file("src/lib.rs", 100, "hash", 12, Some("rs"))
        .unwrap();
    assert!(file_id > 0);
    assert!(db.get_file("src/lib.rs").unwrap().is_some());

    assert!(db_path.is_file());

    let backup_names: Vec<String> = fs::read_dir(dir.path())
        .unwrap()
        .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
        .filter(|name| name.contains(".corrupt-"))
        .collect();

    assert!(
        backup_names
            .iter()
            .any(|name| name.starts_with("symbols.db.corrupt-")),
        "expected quarantined primary db file, found {backup_names:?}"
    );
}

#[test]
fn quarantine_corrupt_sqlite_files_moves_sidecars_when_present() {
    let dir = tempfile::tempdir().unwrap();
    let db_path = dir.path().join("symbols.db");
    let wal_path = dir.path().join("symbols.db-wal");
    let shm_path = dir.path().join("symbols.db-shm");

    fs::write(&db_path, b"not a sqlite database").unwrap();
    fs::write(&wal_path, b"bad wal").unwrap();
    fs::write(&shm_path, b"bad shm").unwrap();

    let backups = quarantine_corrupt_sqlite_files(&db_path).unwrap();
    let backup_names: Vec<String> = backups
        .iter()
        .map(|path| path.file_name().unwrap().to_string_lossy().into_owned())
        .collect();

    assert!(
        backup_names
            .iter()
            .any(|name| name.starts_with("symbols.db.corrupt-")),
        "expected quarantined primary db file, found {backup_names:?}"
    );
    assert!(
        backup_names
            .iter()
            .any(|name| name.starts_with("symbols.db-wal.corrupt-")),
        "expected quarantined wal sidecar, found {backup_names:?}"
    );
    assert!(
        backup_names
            .iter()
            .any(|name| name.starts_with("symbols.db-shm.corrupt-")),
        "expected quarantined shm sidecar, found {backup_names:?}"
    );
}

/// Regression: when migration `N` is added but `SCHEMA_VERSION` is not
/// bumped to match, `migrate()`'s `current >= SCHEMA_VERSION` early-exit
/// silently skips the new migration on any pre-existing DB that was
/// already at version `SCHEMA_VERSION`. For P1-4 this left `end_line`
/// missing on every user project that had been indexed before the
/// migration landed; `find_symbol` then failed with
/// "no such column: end_line" forever. This test simulates a DB that
/// reports `schema_version=6` (the state right before migration 7 was
/// added) and asserts that opening it through `IndexDb::open` brings
/// it current to the highest migration in `MIGRATIONS`, not just to
/// `SCHEMA_VERSION`.
#[test]
fn opening_a_db_at_the_previous_schema_version_runs_every_subsequent_migration() {
    let temp = std::env::temp_dir().join(format!(
        "codelens-migrate-regression-{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    fs::create_dir_all(&temp).expect("create temp dir");
    let db_path = temp.join("symbols.db");

    // Build a v6 DB by hand: apply migrations 1..=6 and stamp
    // schema_version=6. This mirrors the on-disk state of every
    // project indexed before migration 7 landed.
    {
        let conn = rusqlite::Connection::open(&db_path).expect("open fresh db");
        conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS meta (
                key TEXT PRIMARY KEY,
                value TEXT NOT NULL
            );",
        )
        .expect("meta table");
        for &(ver, sql) in IndexDb::MIGRATIONS.iter().filter(|(v, _)| *v <= 6) {
            conn.execute_batch(sql).expect("run migration");
            conn.execute(
                "INSERT OR REPLACE INTO meta (key, value) VALUES ('schema_version', ?1)",
                rusqlite::params![ver.to_string()],
            )
            .expect("stamp version");
        }
    }

    // Sanity: at this point the manually-built DB is at version 6 and
    // does NOT have the end_line column.
    {
        let conn = rusqlite::Connection::open(&db_path).expect("reopen");
        let version: i64 = conn
            .query_row(
                "SELECT CAST(value AS INTEGER) FROM meta WHERE key = 'schema_version'",
                [],
                |row| row.get(0),
            )
            .expect("version");
        assert_eq!(version, 6);
        let has_end_line: bool = conn.prepare("SELECT end_line FROM symbols LIMIT 1").is_ok();
        assert!(
            !has_end_line,
            "precondition: v6 DB must not yet have end_line"
        );
    }

    // Open through the real path. This MUST apply migration 7 even
    // though the stamped version equals the (stale) SCHEMA_VERSION
    // constant.
    let _db = IndexDb::open(&db_path).expect("reopen through IndexDb::open");

    // Post-condition: the column is now present.
    let conn = rusqlite::Connection::open(&db_path).expect("reopen after migrate");
    let can_select_end_line = conn.prepare("SELECT end_line FROM symbols LIMIT 1").is_ok();
    assert!(
        can_select_end_line,
        "migration 7 must have added end_line; otherwise find_symbol \
         will fail on every pre-existing project DB"
    );
    let version: i64 = conn
        .query_row(
            "SELECT CAST(value AS INTEGER) FROM meta WHERE key = 'schema_version'",
            [],
            |row| row.get(0),
        )
        .expect("version");
    let max_version = IndexDb::MIGRATIONS
        .iter()
        .map(|(v, _)| *v)
        .max()
        .expect("at least one migration");
    assert_eq!(
        version, max_version,
        "schema_version must advance to the highest migration, not just SCHEMA_VERSION"
    );

    let _ = fs::remove_dir_all(&temp);
}