scryer-engine 0.3.0

Tree-sitter AST indexing and reference resolution engine for Scryer code intelligence
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
use std::collections::{BTreeMap, HashSet};
use std::fs;
use std::time::Duration;
use tempfile::tempdir;

use scryer_db::{
    CodeGraphEdge, Project, Scope, ScryerDb, SourceFile, Symbol, SymbolReference,
    UnresolvedReference,
};
use scryer_engine::EngineService;

#[tokio::test]
async fn test_scanner_gitignore_and_initial_indexing() -> anyhow::Result<()> {
    let temp = tempdir()?;
    let root = temp.path();

    // Set up project files
    fs::create_dir_all(root.join("src"))?;
    fs::create_dir_all(root.join("target"))?;

    fs::write(root.join(".gitignore"), "target/\nignored.rs\n")?;

    fs::write(
        root.join("src/lib.rs"),
        r#"
pub fn root_init() -> bool {
    true
}
"#,
    )?;

    fs::write(
        root.join("src/helper.rs"),
        r#"
pub struct Helper {
    pub id: u64,
}
"#,
    )?;

    // Files that should be ignored
    fs::write(root.join("ignored.rs"), "pub fn ignored_fn() {}")?;
    fs::write(root.join("target/build.rs"), "pub fn build_fn() {}")?;

    let db = ScryerDb::new_in_memory().await?;
    let mut conn = db.lock().await;
    let project = Project::create()
        .slug("test-incremental".to_string())
        .root_path(root.to_string_lossy().to_string())
        .default_branch("main".to_string())
        .is_active(true)
        .created_at("2026-10-06T00:00:00Z".to_string())
        .updated_at("2026-10-06T00:00:00Z".to_string())
        .exec(&mut *conn)
        .await?;
    drop(conn);

    let engine = EngineService::new(db.clone());

    // 1. Initial indexing
    let report1 = engine.index_project(project.id, root).await?;
    assert_eq!(report1.scanned_files, 2);
    assert_eq!(report1.added_files, 2);
    assert_eq!(report1.modified_files, 0);
    assert_eq!(report1.unchanged_files, 0);
    assert_eq!(report1.deleted_files, 0);

    // Verify stored files in DB
    {
        let mut conn = db.lock().await;
        let files = SourceFile::filter_by_project_id(project.id)
            .exec(&mut *conn)
            .await?;
        assert_eq!(files.len(), 2);
        let paths: Vec<String> = files.iter().map(|f| f.path.clone()).collect();
        assert!(paths.contains(&"src/lib.rs".to_string()));
        assert!(paths.contains(&"src/helper.rs".to_string()));

        // Verify symbols
        let symbols = Symbol::filter_by_project_id(project.id)
            .exec(&mut *conn)
            .await?;
        assert_eq!(symbols.len(), 2);
        let sym_names: Vec<String> = symbols.iter().map(|s| s.name.clone()).collect();
        assert!(sym_names.contains(&"root_init".to_string()));
        assert!(sym_names.contains(&"Helper".to_string()));
    }

    // 2. Second indexing pass without changes - verify unchanged skip
    let report2 = engine.index_project(project.id, root).await?;
    assert_eq!(report2.scanned_files, 2);
    assert_eq!(report2.added_files, 0);
    assert_eq!(report2.modified_files, 0);
    assert_eq!(report2.unchanged_files, 2);
    assert_eq!(report2.deleted_files, 0);

    // 3. Modify a file - verify clean replacement without orphans
    fs::write(
        root.join("src/helper.rs"),
        r#"
pub struct NewHelper {
    pub name: String,
}

pub fn new_helper_fn() {}
"#,
    )?;

    let report3 = engine.index_project(project.id, root).await?;
    assert_eq!(report3.scanned_files, 2);
    assert_eq!(report3.added_files, 0);
    assert_eq!(report3.modified_files, 1);
    assert_eq!(report3.unchanged_files, 1);
    assert_eq!(report3.deleted_files, 0);

    // Verify that old `Helper` symbol is gone and `NewHelper`, `new_helper_fn` exist
    {
        let mut conn = db.lock().await;
        let symbols = Symbol::filter_by_project_id(project.id)
            .exec(&mut *conn)
            .await?;
        let sym_names: Vec<String> = symbols.iter().map(|s| s.name.clone()).collect();
        assert!(!sym_names.contains(&"Helper".to_string()));
        assert!(sym_names.contains(&"NewHelper".to_string()));
        assert!(sym_names.contains(&"new_helper_fn".to_string()));
        assert!(sym_names.contains(&"root_init".to_string()));
    }

    // 4. Delete a file - verify clean deletion
    fs::remove_file(root.join("src/helper.rs"))?;

    let report4 = engine.index_project(project.id, root).await?;
    assert_eq!(report4.scanned_files, 1);
    assert_eq!(report4.added_files, 0);
    assert_eq!(report4.modified_files, 0);
    assert_eq!(report4.unchanged_files, 1);
    assert_eq!(report4.deleted_files, 1);

    // Verify database only contains src/lib.rs
    {
        let mut conn = db.lock().await;
        let files = SourceFile::filter_by_project_id(project.id)
            .exec(&mut *conn)
            .await?;
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "src/lib.rs");

        let symbols = Symbol::filter_by_project_id(project.id)
            .exec(&mut *conn)
            .await?;
        assert_eq!(symbols.len(), 1);
        assert_eq!(symbols[0].name, "root_init");

        let scopes = Scope::filter_by_project_id(project.id)
            .exec(&mut *conn)
            .await?;
        assert_eq!(scopes.len(), 1); // Only root_init scope remains
    }

    Ok(())
}

#[tokio::test]
async fn test_workspace_watcher_reactive_indexing() -> anyhow::Result<()> {
    let temp = tempdir()?;
    let root = temp.path();

    fs::create_dir_all(root.join("src"))?;
    fs::write(root.join("src/lib.rs"), "pub fn initial() {}")?;

    let db = ScryerDb::new_in_memory().await?;
    let mut conn = db.lock().await;
    let project = Project::create()
        .slug("test-watcher".to_string())
        .root_path(root.to_string_lossy().to_string())
        .default_branch("main".to_string())
        .is_active(true)
        .created_at("2026-10-06T00:00:00Z".to_string())
        .updated_at("2026-10-06T00:00:00Z".to_string())
        .exec(&mut *conn)
        .await?;
    drop(conn);

    let engine = EngineService::new(db.clone());
    engine.index_project(project.id, root).await?;

    // Start background watcher
    let watcher = engine.watch_project(project.id, root)?;

    // Add a new file on disk
    fs::write(
        root.join("src/dynamic.rs"),
        r#"
pub fn dynamically_added() -> i32 {
    100
}
"#,
    )?;

    // Wait for the 200ms debounce window + worker processing
    tokio::time::sleep(Duration::from_millis(500)).await;

    // Check that watcher picked up the new file and indexed it
    {
        let mut conn = db.lock().await;
        let files = SourceFile::filter_by_project_id(project.id)
            .exec(&mut *conn)
            .await?;
        let paths: Vec<String> = files.iter().map(|f| f.path.clone()).collect();
        assert!(paths.contains(&"src/dynamic.rs".to_string()));

        let symbols = Symbol::filter_by_project_id(project.id)
            .exec(&mut *conn)
            .await?;
        let names: Vec<String> = symbols.iter().map(|s| s.name.clone()).collect();
        assert!(names.contains(&"dynamically_added".to_string()));
    }

    watcher.stop().await;
    Ok(())
}

async fn test_project(db: &ScryerDb, root: &std::path::Path) -> anyhow::Result<Project> {
    let mut conn = db.lock().await;
    let project = Project::create()
        .slug("test-incremental-extra".to_string())
        .root_path(root.to_string_lossy().to_string())
        .default_branch("main".to_string())
        .is_active(true)
        .created_at("2026-10-06T00:00:00Z".to_string())
        .updated_at("2026-10-06T00:00:00Z".to_string())
        .exec(&mut *conn)
        .await?;
    Ok(project)
}

#[tokio::test]
async fn test_unparseable_file_does_not_abort_index() -> anyhow::Result<()> {
    let temp = tempdir()?;
    let root = temp.path();
    fs::create_dir_all(root.join("src"))?;
    fs::write(root.join("src/good.rs"), "pub fn good() {}\n")?;
    // Invalid UTF-8 makes the Rust parser fail.
    fs::write(root.join("src/bad.rs"), [0xff, 0xfe, 0xfd, b'\n'])?;

    let db = ScryerDb::new_in_memory().await?;
    let project = test_project(&db, root).await?;
    let service = EngineService::new(db.clone());

    service.index_project(project.id, root).await?;

    let mut conn = db.lock().await;
    let files = SourceFile::filter_by_project_id(project.id)
        .exec(&mut *conn)
        .await?;
    let paths: Vec<_> = files.iter().map(|f| f.path.as_str()).collect();
    assert_eq!(paths, ["src/good.rs"], "bad file skipped, good file kept");
    Ok(())
}

#[tokio::test]
async fn test_incremental_index_after_restart_links_into_unchanged_files() -> anyhow::Result<()> {
    let temp = tempdir()?;
    let root = temp.path();
    fs::create_dir_all(root.join("src"))?;
    fs::write(root.join("src/a.rs"), "pub fn helper() {}\n")?;
    fs::write(root.join("src/b.rs"), "pub fn caller() { helper(); }\n")?;

    let db = ScryerDb::new_in_memory().await?;
    let project = test_project(&db, root).await?;
    EngineService::new(db.clone())
        .index_project(project.id, root)
        .await?;

    // A new service stands in for a restarted process: same DB, nothing in memory.
    fs::write(
        root.join("src/b.rs"),
        "pub fn caller() { helper(); helper(); }\n",
    )?;
    let restarted = EngineService::new(db.clone());
    let report = restarted.index_project(project.id, root).await?;
    assert_eq!(report.modified_files, 1);
    assert_eq!(report.unchanged_files, 1);

    // The modified file's calls link to the definition in the file that did not change.
    let mut conn = db.lock().await;
    let helper = Symbol::filter_by_project_id(project.id)
        .exec(&mut *conn)
        .await?
        .into_iter()
        .find(|s| s.name == "helper")
        .expect("helper is indexed");
    let calls = SymbolReference::filter_by_project_id(project.id)
        .exec(&mut *conn)
        .await?
        .into_iter()
        .filter(|r| r.symbol_id == helper.id && r.role == "call")
        .count();
    assert_eq!(calls, 2, "both calls in the modified file link to helper");
    Ok(())
}

#[tokio::test]
async fn test_batched_rows_round_trip_scopes_and_symbols() -> anyhow::Result<()> {
    let temp = tempdir()?;
    let root = temp.path();
    fs::create_dir_all(root.join("src"))?;
    fs::write(
        root.join("src/lib.rs"),
        r#"
/// It's a "quoted" doc with a 'single' quote and a backslash \ too.
pub struct Widget {
    pub id: u64,
}

impl Widget {
    /// Builds a widget; mentions O'Reilly.
    pub fn build(id: u64) -> Widget {
        fn inner() -> u64 { 1 }
        Widget { id: id + inner() }
    }
}
"#,
    )?;
    fs::write(root.join("src/other.rs"), "pub fn other() {}\n")?;

    let db = ScryerDb::new_in_memory().await?;
    let project = test_project(&db, root).await?;
    EngineService::new(db.clone())
        .index_project(project.id, root)
        .await?;

    let mut conn = db.lock().await;
    let files = SourceFile::filter_by_project_id(project.id)
        .exec(&mut *conn)
        .await?;
    let lib_id = files.iter().find(|f| f.path == "src/lib.rs").unwrap().id;
    let other_id = files.iter().find(|f| f.path == "src/other.rs").unwrap().id;

    let scopes = Scope::filter_by_project_id(project.id)
        .exec(&mut *conn)
        .await?;
    let scope_ids: std::collections::HashSet<u64> = scopes.iter().map(|s| s.id).collect();
    assert_eq!(scope_ids.len(), scopes.len(), "scope ids are unique");
    for scope in &scopes {
        if let Some(parent) = scope.parent_scope_id {
            let parent_scope = scopes.iter().find(|s| s.id == parent).unwrap();
            assert_eq!(parent_scope.file_id, scope.file_id, "parent in same file");
            assert!(
                parent_scope.start_byte <= scope.start_byte
                    && scope.end_byte <= parent_scope.end_byte
            );
        }
    }
    assert!(
        scopes.iter().any(|s| s.parent_scope_id.is_some()),
        "nested scopes keep parents"
    );

    let symbols = Symbol::filter_by_project_id(project.id)
        .exec(&mut *conn)
        .await?;
    let symbol_ids: std::collections::HashSet<u64> = symbols.iter().map(|s| s.id).collect();
    assert_eq!(symbol_ids.len(), symbols.len(), "symbol ids are unique");
    let widget = symbols
        .iter()
        .find(|s| s.name == "Widget" && s.kind != "reexport")
        .unwrap();
    assert_eq!(widget.file_id, lib_id);
    let doc = widget.docstring.as_deref().unwrap_or_default();
    assert!(
        doc.contains("It's a \"quoted\" doc with a 'single' quote and a backslash \\ too."),
        "doc: {doc:?}"
    );
    let build = symbols.iter().find(|s| s.name == "build").unwrap();
    assert!(
        build
            .docstring
            .as_deref()
            .unwrap_or_default()
            .contains("O'Reilly")
    );
    if let Some(scope_id) = build.scope_id {
        assert!(scope_ids.contains(&scope_id), "symbol scope exists");
    }
    let other = symbols.iter().find(|s| s.name == "other").unwrap();
    assert_eq!(other.file_id, other_id);
    assert!(other.dependency_package_id.is_none());
    drop(conn);

    // Rows written through the ORM afterwards must not collide with the explicit ids.
    fs::write(
        root.join("src/other.rs"),
        "pub fn other() {}\npub fn another() {}\n",
    )?;
    EngineService::new(db.clone())
        .index_project(project.id, root)
        .await?;
    let mut conn = db.lock().await;
    let symbols = Symbol::filter_by_project_id(project.id)
        .exec(&mut *conn)
        .await?;
    let ids: std::collections::HashSet<u64> = symbols.iter().map(|s| s.id).collect();
    assert_eq!(ids.len(), symbols.len());
    assert!(symbols.iter().any(|s| s.name == "another"));
    Ok(())
}

#[tokio::test]
async fn test_oversized_source_files_are_not_indexed() -> anyhow::Result<()> {
    use scryer_engine::{WorkspaceScanner, scanner::MAX_SOURCE_FILE_BYTES};

    let temp = tempdir()?;
    let root = temp.path();
    fs::create_dir_all(root.join("src"))?;
    fs::write(root.join("src/small.rs"), "pub fn small() {}\n")?;
    // A generated-looking file just over the cap: one huge function.
    let mut big = String::from("pub fn big() {\n");
    while (big.len() as u64) <= MAX_SOURCE_FILE_BYTES {
        big.push_str("    let _x = 1;\n");
    }
    big.push_str("}\n");
    fs::write(root.join("src/big.rs"), &big)?;

    let scanned = WorkspaceScanner::new(root).scan();
    assert_eq!(scanned, vec![std::path::PathBuf::from("src/small.rs")]);
    Ok(())
}

/// Number of references and of call edges into the symbols named `name`.
async fn links_into(db: &ScryerDb, project: u64, name: &str) -> anyhow::Result<(usize, usize)> {
    let mut conn = db.lock().await;
    let ids: Vec<u64> = Symbol::filter_by_project_id(project)
        .exec(&mut *conn)
        .await?
        .into_iter()
        .filter(|s| s.name == name)
        .map(|s| s.id)
        .collect();
    let refs = SymbolReference::filter_by_project_id(project)
        .exec(&mut *conn)
        .await?
        .into_iter()
        .filter(|r| ids.contains(&r.symbol_id))
        .count();
    let edges = CodeGraphEdge::filter_by_project_id(project)
        .exec(&mut *conn)
        .await?
        .into_iter()
        .filter(|e| ids.contains(&e.target_symbol_id))
        .count();
    Ok((refs, edges))
}

/// The watcher path (`index_file`) must keep a file's references into other files, not only
/// the ones that stay inside the file.
#[tokio::test]
async fn test_index_file_keeps_cross_file_references() -> anyhow::Result<()> {
    let temp = tempdir()?;
    let root = temp.path();
    fs::create_dir_all(root.join("src"))?;
    fs::write(root.join("src/a.rs"), "pub fn helper() {}\n")?;
    fs::write(root.join("src/b.rs"), "pub fn caller() { helper(); }\n")?;

    let db = ScryerDb::new_in_memory().await?;
    let project = test_project(&db, root).await?;
    let service = EngineService::new(db.clone());
    service.index_project(project.id, root).await?;
    assert_eq!(links_into(&db, project.id, "helper").await?, (1, 1));

    fs::write(
        root.join("src/b.rs"),
        "pub fn caller() { helper(); }\npub fn other() { helper(); }\n",
    )?;
    service
        .index_file(project.id, root, std::path::Path::new("src/b.rs"))
        .await?;
    assert_eq!(
        links_into(&db, project.id, "helper").await?,
        (2, 2),
        "both callers of `helper` after the single-file re-index"
    );
    Ok(())
}

/// Persisted unresolved (references, edges) of a project.
async fn unresolved_count(db: &ScryerDb, project: u64) -> anyhow::Result<(usize, usize)> {
    let mut conn = db.lock().await;
    let rows = UnresolvedReference::filter(UnresolvedReference::fields().project_id().eq(project))
        .exec(&mut *conn)
        .await?;
    let edges = rows.iter().filter(|r| r.kind == "edge").count();
    Ok((rows.len() - edges, edges))
}

/// A reference to a function that does not exist yet is kept, and links when a later edit
/// (`index_file`, the watcher path) or a later run (`index_project`) adds the function, though
/// the file that makes the call is not touched again.
#[tokio::test]
async fn test_unresolved_reference_links_when_the_definition_is_added_later() -> anyhow::Result<()>
{
    for by_file in [true, false] {
        let temp = tempdir()?;
        let root = temp.path();
        fs::create_dir_all(root.join("src"))?;
        fs::write(root.join("src/a.rs"), "pub fn caller() { helper(); }\n")?;

        let db = ScryerDb::new_in_memory().await?;
        let project = test_project(&db, root).await?;
        let service = EngineService::new(db.clone());
        let report = service.index_project(project.id, root).await?;
        assert_eq!(report.unresolved_references, 1, "by_file={by_file}");
        assert_eq!(unresolved_count(&db, project.id).await?, (1, 1));

        fs::write(root.join("src/b.rs"), "pub fn helper() {}\n")?;
        if by_file {
            service
                .index_file(project.id, root, std::path::Path::new("src/b.rs"))
                .await?;
        } else {
            let report = service.index_project(project.id, root).await?;
            assert_eq!(report.added_files, 1);
            assert_eq!(report.unresolved_references, 0);
        }
        assert_eq!(
            links_into(&db, project.id, "helper").await?,
            (1, 1),
            "by_file={by_file}: the reference and the call edge"
        );
        assert_eq!(unresolved_count(&db, project.id).await?, (0, 0));
    }
    Ok(())
}

/// What stays unresolved is counted for the whole project, not only for the files of the last
/// run, and re-indexing a file replaces its rows instead of adding to them.
#[tokio::test]
async fn test_unresolved_references_are_counted_for_the_whole_project() -> anyhow::Result<()> {
    let temp = tempdir()?;
    let root = temp.path();
    fs::create_dir_all(root.join("src"))?;
    fs::write(root.join("src/a.rs"), "pub fn a() { missing_one(); }\n")?;
    fs::write(root.join("src/b.rs"), "pub fn b() { missing_two(); }\n")?;

    let db = ScryerDb::new_in_memory().await?;
    let project = test_project(&db, root).await?;
    let service = EngineService::new(db.clone());
    assert_eq!(
        service
            .index_project(project.id, root)
            .await?
            .unresolved_references,
        2
    );

    fs::write(
        root.join("src/b.rs"),
        "pub fn b() { missing_two(); missing_three(); }\n",
    )?;
    let report = service.index_project(project.id, root).await?;
    assert_eq!(report.modified_files, 1);
    assert_eq!(report.unresolved_references, 3, "a's one plus b's two");
    assert_eq!(unresolved_count(&db, project.id).await?, (3, 3));
    Ok(())
}

/// Stored symbols by qualified name, each with its ids in source order.
async fn symbol_ids(db: &ScryerDb, project: u64) -> anyhow::Result<BTreeMap<String, Vec<u64>>> {
    let mut conn = db.lock().await;
    let mut symbols = Symbol::filter_by_project_id(project)
        .exec(&mut *conn)
        .await?;
    symbols.sort_by_key(|s| (s.file_id, s.start_byte));
    let mut out: BTreeMap<String, Vec<u64>> = BTreeMap::new();
    for s in symbols {
        out.entry(s.qualified_name).or_default().push(s.id);
    }
    Ok(out)
}

/// Every reference and edge points at a stored symbol.
async fn assert_no_dangling_links(db: &ScryerDb, project: u64) -> anyhow::Result<()> {
    let mut conn = db.lock().await;
    let ids: HashSet<u64> = Symbol::filter_by_project_id(project)
        .exec(&mut *conn)
        .await?
        .into_iter()
        .map(|s| s.id)
        .collect();
    for r in SymbolReference::filter_by_project_id(project)
        .exec(&mut *conn)
        .await?
    {
        assert!(ids.contains(&r.symbol_id), "dangling reference {r:?}");
    }
    for e in CodeGraphEdge::filter_by_project_id(project)
        .exec(&mut *conn)
        .await?
    {
        assert!(
            ids.contains(&e.source_symbol_id) && ids.contains(&e.target_symbol_id),
            "dangling edge {e:?}"
        );
    }
    Ok(())
}

/// A symbol that is still in the file after an edit keeps its row and id, so nothing that
/// points at it is touched; the row itself follows the edit.
#[tokio::test]
async fn test_unchanged_symbols_keep_their_ids_across_a_re_index() -> anyhow::Result<()> {
    let temp = tempdir()?;
    let root = temp.path();
    fs::create_dir_all(root.join("src"))?;
    fs::write(
        root.join("src/a.rs"),
        "pub fn alpha() -> u32 { 1 }\npub fn beta() -> u32 { alpha() }\n",
    )?;
    fs::write(
        root.join("src/b.rs"),
        "pub fn user() { beta(); alpha(); }\n",
    )?;

    let db = ScryerDb::new_in_memory().await?;
    let project = test_project(&db, root).await?;
    let service = EngineService::new(db.clone());
    service.index_project(project.id, root).await?;
    let before = symbol_ids(&db, project.id).await?;
    assert_eq!(links_into(&db, project.id, "alpha").await?, (2, 2));

    // A header pushes both functions down; `alpha` also changes body and `gamma` is new.
    fs::write(
        root.join("src/a.rs"),
        "// header\n// more header\npub fn alpha() -> u32 { 2 }\npub fn beta() -> u32 { alpha() }\npub fn gamma() {}\n",
    )?;
    service
        .index_file(project.id, root, std::path::Path::new("src/a.rs"))
        .await?;

    let after = symbol_ids(&db, project.id).await?;
    for (name, ids) in &before {
        assert_eq!(after.get(name), Some(ids), "{name} kept its id");
    }
    assert_eq!(after.len(), before.len() + 1, "only `gamma` was inserted");
    {
        let mut conn = db.lock().await;
        let alpha = Symbol::filter_by_project_id(project.id)
            .exec(&mut *conn)
            .await?
            .into_iter()
            .find(|s| s.name == "alpha")
            .unwrap();
        assert_eq!(alpha.start_line, 3, "the row follows the edit");
    }
    assert_eq!(links_into(&db, project.id, "alpha").await?, (2, 2));
    assert_eq!(links_into(&db, project.id, "beta").await?, (1, 1));
    assert_no_dangling_links(&db, project.id).await?;
    Ok(())
}

/// Same-named symbols of one file (`cfg` variants) keep their pairing of rows and ids when
/// the file is edited above them.
#[tokio::test]
async fn test_duplicate_symbols_keep_a_stable_pairing() -> anyhow::Result<()> {
    let temp = tempdir()?;
    let root = temp.path();
    fs::create_dir_all(root.join("src"))?;
    let variants = |header: &str| {
        format!(
            "{header}#[cfg(unix)]\npub fn dup() -> u32 {{ 1 }}\n#[cfg(not(unix))]\npub fn dup() -> u32 {{ 2 }}\n"
        )
    };
    fs::write(root.join("src/a.rs"), variants(""))?;

    let db = ScryerDb::new_in_memory().await?;
    let project = test_project(&db, root).await?;
    let service = EngineService::new(db.clone());
    service.index_project(project.id, root).await?;
    let before = symbol_ids(&db, project.id).await?;
    assert_eq!(before.values().map(Vec::len).max(), Some(2), "{before:?}");

    fs::write(root.join("src/a.rs"), variants("// header\n"))?;
    service
        .index_file(project.id, root, std::path::Path::new("src/a.rs"))
        .await?;
    assert_eq!(symbol_ids(&db, project.id).await?, before);
    Ok(())
}

/// A symbol an edit removes takes its incoming links with it (they wait as unresolved
/// references, and an edge), and defining it again restores them.
#[tokio::test]
async fn test_links_into_a_removed_symbol_come_back_when_it_is_defined_again() -> anyhow::Result<()>
{
    let temp = tempdir()?;
    let root = temp.path();
    fs::create_dir_all(root.join("src"))?;
    let with_beta = "pub fn alpha() {}\npub fn beta() {}\n";
    fs::write(root.join("src/a.rs"), with_beta)?;
    fs::write(root.join("src/b.rs"), "pub fn user() { beta(); }\n")?;

    let db = ScryerDb::new_in_memory().await?;
    let project = test_project(&db, root).await?;
    let service = EngineService::new(db.clone());
    service.index_project(project.id, root).await?;
    assert_eq!(links_into(&db, project.id, "beta").await?, (1, 1));

    let a = std::path::Path::new("src/a.rs");
    fs::write(root.join("src/a.rs"), "pub fn alpha() {}\n")?;
    service.index_file(project.id, root, a).await?;
    assert_eq!(links_into(&db, project.id, "beta").await?, (0, 0));
    assert_eq!(unresolved_count(&db, project.id).await?, (1, 1));
    assert_no_dangling_links(&db, project.id).await?;

    fs::write(root.join("src/a.rs"), with_beta)?;
    service.index_file(project.id, root, a).await?;
    assert_eq!(links_into(&db, project.id, "beta").await?, (1, 1));
    assert_eq!(unresolved_count(&db, project.id).await?, (0, 0));
    assert_no_dangling_links(&db, project.id).await?;
    Ok(())
}

/// Deleting the file that defines a symbol does the same, through `remove_file`.
#[tokio::test]
async fn test_links_into_a_deleted_file_come_back_when_it_does() -> anyhow::Result<()> {
    let temp = tempdir()?;
    let root = temp.path();
    fs::create_dir_all(root.join("src"))?;
    fs::write(root.join("src/a.rs"), "pub fn beta() {}\n")?;
    fs::write(root.join("src/b.rs"), "pub fn user() { beta(); }\n")?;

    let db = ScryerDb::new_in_memory().await?;
    let project = test_project(&db, root).await?;
    let service = EngineService::new(db.clone());
    service.index_project(project.id, root).await?;

    let a = std::path::Path::new("src/a.rs");
    service.remove_file(project.id, a).await?;
    assert_eq!(unresolved_count(&db, project.id).await?, (1, 1));
    assert_no_dangling_links(&db, project.id).await?;

    service.index_file(project.id, root, a).await?;
    assert_eq!(links_into(&db, project.id, "beta").await?, (1, 1));
    assert_eq!(unresolved_count(&db, project.id).await?, (0, 0));
    Ok(())
}