scryer-engine 0.2.0

Tree-sitter and stack-graphs AST indexing 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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use scryer_db::{CodeGraphEdge, Scope, ScryerDb, SourceFile, Symbol, SymbolReference};
use tokio::sync::mpsc;
use tokio::task::JoinHandle;

use crate::payload::{ParsedFilePayload, RawCodeGraphEdge, RawSymbolReference};

/// Known persistence status of a source file before ingestion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ExistingFileStatus {
    #[default]
    Unknown,
    New,
    Existing(u64),
}

/// Ingestion actions processed by the transactional writer task.
#[derive(Debug)]
pub enum IngestionMessage {
    UpsertFile {
        payload: ParsedFilePayload,
        status: ExistingFileStatus,
        dependency_package_id: Option<u64>,
    },
    DeleteFile(PathBuf),
}

/// Handle to a running ingestion background actor with a bounded channel.
pub struct IngestionHandle {
    sender: mpsc::Sender<IngestionMessage>,
    join_handle: JoinHandle<anyhow::Result<usize>>,
}

impl IngestionHandle {
    pub fn sender(&self) -> mpsc::Sender<IngestionMessage> {
        self.sender.clone()
    }

    /// Await the completion of the background ingestion writer task.
    pub async fn finish(self) -> anyhow::Result<usize> {
        drop(self.sender);
        self.join_handle.await?
    }
}

/// Transactional batch ingestion actor persisting parsed entities into Turso.
pub struct BatchIngestionActor {
    db: ScryerDb,
    project_id: u64,
}

impl BatchIngestionActor {
    pub fn new(db: ScryerDb, project_id: u64) -> Self {
        Self { db, project_id }
    }

    /// Spawn the writer actor as a Tokio background task with a bounded channel.
    pub fn spawn(db: ScryerDb, project_id: u64, buffer_capacity: usize) -> IngestionHandle {
        let (sender, mut receiver) = mpsc::channel::<IngestionMessage>(buffer_capacity);
        let actor = Self::new(db, project_id);

        let join_handle = tokio::spawn(async move {
            let mut processed = 0;
            let mut batch = Vec::new();
            while let Some(msg) = receiver.recv().await {
                batch.push(msg);
                while batch.len() < 500 {
                    match receiver.try_recv() {
                        Ok(m) => batch.push(m),
                        Err(_) => break,
                    }
                }
                let count = batch.len();
                actor.ingest_batch(std::mem::take(&mut batch)).await?;
                processed += count;
            }
            Ok(processed)
        });

        IngestionHandle {
            sender,
            join_handle,
        }
    }

    /// Transactionally process a batch of upsert and delete operations under a single commit.
    pub async fn ingest_batch(&self, messages: Vec<IngestionMessage>) -> anyhow::Result<()> {
        if messages.is_empty() {
            return Ok(());
        }
        let batch_timer = std::time::Instant::now();
        let n_messages = messages.len();
        let mut db_guard = self.db.lock().await;
        let mut tx = db_guard.transaction().await?;

        // Insert every file's symbols before linking any references, so references into
        // files later in the batch still resolve.
        let mut pending = Vec::new();
        for msg in messages {
            match msg {
                IngestionMessage::UpsertFile {
                    payload,
                    status,
                    dependency_package_id,
                } => {
                    pending.push(
                        self.insert_file_entities(&mut tx, payload, status, dependency_package_id)
                            .await?,
                    );
                }
                IngestionMessage::DeleteFile(rel_path) => {
                    self.delete_file_in_tx(&mut tx, &rel_path).await?;
                }
            }
        }

        let insert_ms = batch_timer.elapsed().as_millis();
        let mut cache = HashMap::new();
        self.prefetch_targets(&mut tx, &pending, &mut cache).await?;
        for links in pending {
            self.link_in_tx(&mut tx, links, &mut cache).await?;
        }
        let link_ms = batch_timer.elapsed().as_millis() - insert_ms;

        tx.commit().await?;
        tracing::info!(
            "ingest_batch project={} messages={n_messages}: entities={insert_ms}ms link={link_ms}ms commit={}ms",
            self.project_id,
            batch_timer.elapsed().as_millis() - insert_ms - link_ms
        );
        Ok(())
    }

    /// Ingest a single parsed file transactionally.
    pub async fn ingest_payload(&self, payload: ParsedFilePayload) -> anyhow::Result<()> {
        self.ingest_batch(vec![IngestionMessage::UpsertFile {
            payload,
            status: ExistingFileStatus::Unknown,
            dependency_package_id: None,
        }])
        .await
    }

    /// Ingest a single parsed file inside an active transaction.
    pub async fn ingest_payload_in_tx(
        &self,
        tx: &mut toasty::db::Transaction<'_>,
        payload: ParsedFilePayload,
        status: ExistingFileStatus,
    ) -> anyhow::Result<()> {
        let links = self.insert_file_entities(tx, payload, status, None).await?;
        self.link_in_tx(tx, links, &mut HashMap::new()).await
    }

    /// Upsert the file row and insert its scopes and symbols, re-pointing references and
    /// edges from other files at the new symbol IDs. Returns the file's references and
    /// edges for [`Self::link_in_tx`].
    async fn insert_file_entities(
        &self,
        tx: &mut toasty::db::Transaction<'_>,
        payload: ParsedFilePayload,
        status: ExistingFileStatus,
        dependency_package_id: Option<u64>,
    ) -> anyhow::Result<PendingLinks> {
        let rel_path_str = payload.relative_path.to_string_lossy().to_string();
        let effective_project_id = if dependency_package_id.is_some() {
            0
        } else {
            self.project_id
        };

        let existing = match status {
            ExistingFileStatus::New => None,
            ExistingFileStatus::Existing(existing_id) => SourceFile::filter(
                SourceFile::fields()
                    .project_id()
                    .eq(effective_project_id)
                    .and(SourceFile::fields().id().eq(existing_id)),
            )
            .first()
            .exec(&mut *tx)
            .await?
            .map(|f| (existing_id, Some(f)))
            // The row vanished but its children may not have: purge them anyway.
            .or(Some((existing_id, None))),
            ExistingFileStatus::Unknown => {
                if let Some(dep_pkg_id) = dependency_package_id {
                    SourceFile::filter(
                        SourceFile::fields()
                            .project_id()
                            .eq(0)
                            .and(
                                SourceFile::fields()
                                    .dependency_package_id()
                                    .eq(Some(dep_pkg_id)),
                            )
                            .and(SourceFile::fields().path().eq(&rel_path_str)),
                    )
                    .first()
                    .exec(&mut *tx)
                    .await?
                    .map(|f| (f.id, Some(f)))
                } else {
                    SourceFile::filter(
                        SourceFile::fields()
                            .project_id()
                            .eq(effective_project_id)
                            .and(SourceFile::fields().path().eq(&rel_path_str)),
                    )
                    .first()
                    .exec(&mut *tx)
                    .await?
                    .map(|f| (f.id, Some(f)))
                }
            }
        };

        let mut old_symbols = Vec::new();
        let file_id = match existing {
            Some((existing_id, file)) => {
                old_symbols = Symbol::filter(
                    Symbol::fields()
                        .project_id()
                        .eq(effective_project_id)
                        .and(Symbol::fields().file_id().eq(existing_id)),
                )
                .exec(&mut *tx)
                .await?;
                purge_file_records(
                    tx,
                    effective_project_id,
                    existing_id,
                    PurgeMode::KeepIncoming,
                )
                .await?;
                match file {
                    Some(mut file) => {
                        file.update()
                            .content_hash(payload.content_hash.clone())
                            .line_count(payload.line_count)
                            .byte_size(payload.byte_size)
                            .exec(&mut *tx)
                            .await?;
                        Some(file.id)
                    }
                    None => None,
                }
            }
            None => None,
        };
        let file_id = match file_id {
            Some(id) => id,
            None => {
                let mut builder = SourceFile::create();
                builder = builder
                    .project_id(effective_project_id)
                    .path(rel_path_str)
                    .content_hash(payload.content_hash.clone())
                    .language(payload.language.clone())
                    .line_count(payload.line_count)
                    .byte_size(payload.byte_size);

                if let Some(dep_pkg_id) = dependency_package_id {
                    builder = builder.dependency_package_id(dep_pkg_id);
                }

                builder.exec(&mut *tx).await?.id
            }
        };

        // 2. Insert Scope rows a depth level at a time, so each level can name the database
        // ids of its parents (parents always precede their children in the payload).
        let scopes = payload.scopes;
        let mut depth = Vec::with_capacity(scopes.len());
        let mut local_depth = HashMap::new();
        for raw_scope in &scopes {
            let d = raw_scope
                .parent_local_id
                .and_then(|p| local_depth.get(&p).copied())
                .map_or(0, |parent_depth| parent_depth + 1);
            local_depth.insert(raw_scope.local_id, d);
            depth.push(d);
        }
        let max_depth = depth.iter().copied().max().unwrap_or(0);
        let mut local_to_db_id: HashMap<_, u64> = HashMap::with_capacity(scopes.len());
        for level in 0..=max_depth {
            let level_scopes: Vec<_> = scopes
                .iter()
                .zip(&depth)
                .filter(|&(_, &d)| d == level)
                .map(|(scope, _)| scope)
                .collect();
            for chunk in level_scopes.chunks(INSERT_CHUNK) {
                let mut create = Scope::create_many();
                for raw_scope in chunk {
                    let mut builder = Scope::create()
                        .project_id(effective_project_id)
                        .file_id(file_id)
                        .scope_kind(raw_scope.scope_kind.clone())
                        .start_byte(raw_scope.start_byte)
                        .end_byte(raw_scope.end_byte)
                        .start_line(raw_scope.start_line)
                        .end_line(raw_scope.end_line);
                    if let Some(parent_id) = raw_scope
                        .parent_local_id
                        .and_then(|p| local_to_db_id.get(&p).copied())
                    {
                        builder = builder.parent_scope_id(parent_id);
                    }
                    create = create.item(builder);
                }
                let inserted = create.exec(&mut *tx).await?;
                anyhow::ensure!(
                    inserted.len() == chunk.len(),
                    "scope batch insert returned {} rows for {}",
                    inserted.len(),
                    chunk.len()
                );
                for (raw_scope, row) in chunk.iter().zip(inserted) {
                    anyhow::ensure!(
                        row.start_byte == raw_scope.start_byte
                            && row.end_byte == raw_scope.end_byte,
                        "scope batch insert returned rows out of order"
                    );
                    local_to_db_id.insert(raw_scope.local_id, row.id);
                }
            }
        }

        // 3. Insert Symbol rows referencing the mapped scope ids.
        let mut symbol_name_to_id = HashMap::new();
        for chunk in payload.symbols.chunks(INSERT_CHUNK) {
            let mut create = Symbol::create_many();
            for raw_symbol in chunk {
                let mut builder = Symbol::create()
                    .project_id(effective_project_id)
                    .file_id(file_id)
                    .name(raw_symbol.name.clone())
                    .qualified_name(raw_symbol.qualified_name.clone())
                    .kind(raw_symbol.kind.clone())
                    .visibility(raw_symbol.visibility.clone())
                    .signature(raw_symbol.signature.clone())
                    .start_byte(raw_symbol.start_byte)
                    .end_byte(raw_symbol.end_byte)
                    .start_line(raw_symbol.start_line)
                    .end_line(raw_symbol.end_line);
                if let Some(dep_pkg_id) = dependency_package_id {
                    builder = builder.dependency_package_id(dep_pkg_id);
                }
                if let Some(scope_id) = raw_symbol
                    .scope_local_id
                    .and_then(|s| local_to_db_id.get(&s).copied())
                {
                    builder = builder.scope_id(scope_id);
                }
                if let Some(doc) = &raw_symbol.docstring {
                    builder = builder.docstring(doc.clone());
                }
                create = create.item(builder);
            }
            let inserted = create.exec(&mut *tx).await?;
            anyhow::ensure!(
                inserted.len() == chunk.len(),
                "symbol batch insert returned {} rows for {}",
                inserted.len(),
                chunk.len()
            );
            for (raw_symbol, row) in chunk.iter().zip(inserted) {
                anyhow::ensure!(
                    row.qualified_name == raw_symbol.qualified_name
                        && row.start_byte == raw_symbol.start_byte,
                    "symbol batch insert returned rows out of order"
                );
                // Keep the first symbol for duplicate names, matching the database lookup order.
                symbol_name_to_id
                    .entry(raw_symbol.qualified_name.clone())
                    .or_insert(row.id);
                symbol_name_to_id
                    .entry(raw_symbol.name.clone())
                    .or_insert(row.id);
            }
        }

        // 4. Re-point references and edges from other files at the replacement symbols,
        // dropping those whose target no longer exists.
        let p = effective_project_id;
        for old in old_symbols {
            let stmts = match symbol_name_to_id.get(&old.qualified_name) {
                Some(&new_id) => [
                    format!(
                        "UPDATE symbol_reference SET symbol_id = {new_id} WHERE project_id = {p} AND symbol_id = {};",
                        old.id
                    ),
                    format!(
                        "UPDATE code_graph_edge SET target_symbol_id = {new_id} WHERE project_id = {p} AND target_symbol_id = {};",
                        old.id
                    ),
                ],
                None => [
                    format!(
                        "DELETE FROM symbol_reference WHERE project_id = {p} AND symbol_id = {};",
                        old.id
                    ),
                    format!(
                        "DELETE FROM code_graph_edge WHERE project_id = {p} AND target_symbol_id = {};",
                        old.id
                    ),
                ],
            };
            for stmt in &stmts {
                toasty::sql::statement(stmt).exec(&mut *tx).await?;
            }
        }

        Ok(PendingLinks {
            file_id,
            local_symbols: symbol_name_to_id,
            references: payload.references,
            edges: payload.edges,
        })
    }

    /// Insert a file's references and call edges, resolving target names against the
    /// file's own symbols first and then the whole project.
    async fn link_in_tx(
        &self,
        tx: &mut toasty::db::Transaction<'_>,
        links: PendingLinks,
        cache: &mut HashMap<String, Option<u64>>,
    ) -> anyhow::Result<()> {
        let PendingLinks {
            file_id,
            local_symbols,
            references,
            edges,
        } = links;

        let mut ref_rows = Vec::with_capacity(references.len());
        for raw_ref in references {
            let target = self
                .resolve_name(tx, &local_symbols, cache, &raw_ref.target_symbol_name)
                .await?;
            if let Some(sym_id) = target {
                ref_rows.push(
                    SymbolReference::create()
                        .project_id(self.project_id)
                        .symbol_id(sym_id)
                        .file_id(file_id)
                        .role(raw_ref.role)
                        .start_byte(raw_ref.start_byte)
                        .end_byte(raw_ref.end_byte)
                        .line_number(raw_ref.line_number),
                );
            }
        }
        insert_all(tx, ref_rows, SymbolReference::create_many).await?;

        let mut seen = HashSet::new();
        let mut edge_rows = Vec::with_capacity(edges.len());
        for raw_edge in edges {
            let source = local_symbols.get(&raw_edge.source_symbol_name).copied();
            let target = self
                .resolve_name(tx, &local_symbols, cache, &raw_edge.target_symbol_name)
                .await?;
            if let (Some(src), Some(tgt)) = (source, target) {
                if !seen.insert((src, tgt, raw_edge.edge_type.clone())) {
                    continue;
                }
                edge_rows.push(
                    CodeGraphEdge::create()
                        .project_id(self.project_id)
                        .source_symbol_id(src)
                        .target_symbol_id(tgt)
                        .edge_type(raw_edge.edge_type),
                );
            }
        }
        insert_all(tx, edge_rows, CodeGraphEdge::create_many).await?;

        Ok(())
    }

    async fn resolve_name(
        &self,
        tx: &mut toasty::db::Transaction<'_>,
        local_symbols: &HashMap<String, u64>,
        cache: &mut HashMap<String, Option<u64>>,
        target: &str,
    ) -> anyhow::Result<Option<u64>> {
        if let Some(&id) = local_symbols.get(target) {
            return Ok(Some(id));
        }
        if let Some(&cached) = cache.get(target) {
            return Ok(cached);
        }
        // Not prefetched (e.g. produced after the batch snapshot): fall back to a query.
        let found = find_symbol_for_target(&mut *tx, self.project_id, target, None)
            .await?
            .map(|s| s.id);
        cache.insert(target.to_string(), found);
        Ok(found)
    }

    /// Resolve every target name the batch references with a few `IN` queries, instead of
    /// one query (or two, with the dependency fallback) per distinct name.
    async fn prefetch_targets(
        &self,
        tx: &mut toasty::db::Transaction<'_>,
        pending: &[PendingLinks],
        cache: &mut HashMap<String, Option<u64>>,
    ) -> anyhow::Result<()> {
        let mut targets: HashSet<&str> = HashSet::new();
        for links in pending {
            let names = links
                .references
                .iter()
                .map(|r| r.target_symbol_name.as_str())
                .chain(links.edges.iter().map(|e| e.target_symbol_name.as_str()));
            for name in names {
                if !links.local_symbols.contains_key(name) {
                    targets.insert(name);
                }
            }
        }

        let bare = |t: &str| bare_name(t).to_string();
        let names: Vec<String> = targets
            .iter()
            .map(|t| bare(t))
            .filter(|n| !n.is_empty())
            .collect::<HashSet<_>>()
            .into_iter()
            .collect();

        let mut by_name = fetch_candidates(&mut *tx, self.project_id, &names).await?;
        if self.project_id != 0 {
            // Dependency symbols are only consulted for names the project does not define.
            let missing: Vec<String> = names
                .iter()
                .filter(|n| !by_name.contains_key(*n))
                .cloned()
                .collect();
            by_name.extend(fetch_candidates(&mut *tx, 0, &missing).await?);
        }

        for target in targets {
            let candidates = by_name.get(&bare(target)).cloned().unwrap_or_default();
            let found = pick_candidate(candidates, target, None).map(|s| s.id);
            cache.insert(target.to_string(), found);
        }
        Ok(())
    }

    /// Transactionally delete a file and all its cascaded entities inside an active transaction.
    pub async fn delete_file_in_tx(
        &self,
        tx: &mut toasty::db::Transaction<'_>,
        rel_path: &Path,
    ) -> anyhow::Result<()> {
        let rel_path_str = rel_path.to_string_lossy().to_string();

        let existing_file = SourceFile::filter(
            SourceFile::fields()
                .project_id()
                .eq(self.project_id)
                .and(SourceFile::fields().path().eq(&rel_path_str)),
        )
        .first()
        .exec(&mut *tx)
        .await?;

        if let Some(file) = existing_file {
            purge_file_records(tx, self.project_id, file.id, PurgeMode::All).await?;

            let del_source_file = format!(
                "DELETE FROM source_file WHERE project_id = {} AND id = {};",
                self.project_id, file.id
            );
            toasty::sql::statement(&del_source_file)
                .exec(&mut *tx)
                .await?;
        }

        Ok(())
    }

    /// Transactionally delete a file and all its cascaded entities.
    pub async fn delete_file(&self, rel_path: &Path) -> anyhow::Result<()> {
        self.ingest_batch(vec![IngestionMessage::DeleteFile(rel_path.to_path_buf())])
            .await
    }
}

/// Rows per batched `INSERT`. Bounds the statement's bind-parameter count.
const INSERT_CHUNK: usize = 500;

/// Insert records through the ORM with one multi-row `INSERT` per chunk, instead of one
/// statement per row.
async fn insert_all<M, C>(
    tx: &mut toasty::db::Transaction<'_>,
    items: Vec<C>,
    create_many: fn() -> toasty::stmt::CreateMany<M>,
) -> anyhow::Result<()>
where
    M: toasty::schema::Model,
    C: toasty::stmt::IntoInsert<Model = M>,
{
    let mut items = items.into_iter().peekable();
    while items.peek().is_some() {
        let mut create = create_many();
        for item in items.by_ref().take(INSERT_CHUNK) {
            create = create.item(item);
        }
        create.exec(&mut *tx).await?;
    }
    Ok(())
}

/// References and edges produced for a file, awaiting target resolution.
struct PendingLinks {
    file_id: u64,
    /// The file's own symbols by qualified and bare name.
    local_symbols: HashMap<String, u64>,
    references: Vec<RawSymbolReference>,
    edges: Vec<RawCodeGraphEdge>,
}

/// Whether purging a file also removes references and edges from other files into it.
#[derive(Clone, Copy, PartialEq, Eq)]
enum PurgeMode {
    /// The file is being deleted: drop everything pointing into it.
    All,
    /// The file is being re-indexed: keep incoming references and edges so they can be
    /// re-pointed at the replacement symbols.
    KeepIncoming,
}

/// Executes cascading SQL deletes to remove any existing child records for a file.
async fn purge_file_records(
    tx: &mut toasty::db::Transaction<'_>,
    project_id: u64,
    file_id: u64,
    mode: PurgeMode,
) -> anyhow::Result<()> {
    let file_symbols =
        format!("SELECT id FROM symbol WHERE project_id = {project_id} AND file_id = {file_id}");
    let mut statements = vec![
        format!(
            "DELETE FROM symbol_reference WHERE project_id = {project_id} AND file_id = {file_id};"
        ),
        format!(
            "DELETE FROM code_graph_edge WHERE project_id = {project_id} AND source_symbol_id IN ({file_symbols});"
        ),
    ];
    if mode == PurgeMode::All {
        statements.push(format!(
            "DELETE FROM symbol_reference WHERE project_id = {project_id} AND symbol_id IN ({file_symbols});"
        ));
        statements.push(format!(
            "DELETE FROM code_graph_edge WHERE project_id = {project_id} AND target_symbol_id IN ({file_symbols});"
        ));
    }
    statements.push(format!(
        "DELETE FROM symbol WHERE project_id = {project_id} AND file_id = {file_id};"
    ));
    statements.push(format!(
        "DELETE FROM scope WHERE project_id = {project_id} AND file_id = {file_id};"
    ));

    for stmt in &statements {
        toasty::sql::statement(stmt).exec(&mut *tx).await?;
    }

    Ok(())
}

/// Load candidate symbols for the given bare names, grouped by name and ordered by id.
async fn fetch_candidates(
    executor: &mut dyn toasty::Executor,
    project_id: u64,
    names: &[String],
) -> anyhow::Result<HashMap<String, Vec<Symbol>>> {
    let mut by_name: HashMap<String, Vec<Symbol>> = HashMap::new();
    for chunk in names.chunks(200) {
        let rows = Symbol::filter(
            Symbol::fields()
                .project_id()
                .eq(project_id)
                .and(Symbol::fields().name().in_list(chunk.to_vec())),
        )
        .exec(&mut *executor)
        .await?;
        for sym in rows {
            by_name.entry(sym.name.clone()).or_default().push(sym);
        }
    }
    for list in by_name.values_mut() {
        list.sort_by_key(|s| s.id);
    }
    Ok(by_name)
}

/// Choose the symbol a reference target names from same-name candidates (ordered by id).
///
/// Path targets (`a::b::f`) match a symbol whose qualified name equals the path or ends
/// with `::a::b::f`; bare names take the first candidate. Symbols in `prefer_file` win ties.
/// The last segment of a qualified name: `crate::a::f` (Rust) and `pkg.mod.f` (Python,
/// TypeScript) both give `f`.
fn bare_name(target: &str) -> &str {
    let last = target.rsplit("::").next().unwrap_or(target);
    last.rsplit('.').next().unwrap_or(last)
}

fn pick_candidate(
    mut candidates: Vec<Symbol>,
    target: &str,
    prefer_file: Option<u64>,
) -> Option<Symbol> {
    if target.contains("::") || target.contains('.') {
        let rust_suffix = format!("::{target}");
        let dotted_suffix = format!(".{target}");
        candidates.retain(|s| {
            s.qualified_name == target
                || s.qualified_name.ends_with(&rust_suffix)
                || s.qualified_name.ends_with(&dotted_suffix)
        });
        if let Some(pos) = candidates.iter().position(|s| s.qualified_name == target) {
            return Some(candidates.swap_remove(pos));
        }
    }

    let preferred = prefer_file.and_then(|f| candidates.iter().position(|s| s.file_id == f));
    match preferred {
        Some(pos) => Some(candidates.swap_remove(pos)),
        None => candidates.into_iter().next(),
    }
}

/// Find the project symbol a reference target names.
///
/// Falls back to external dependencies (project 0) when the project defines no symbol
/// with that name. See [`pick_candidate`] for the matching rules.
pub async fn find_symbol_for_target(
    executor: &mut dyn toasty::Executor,
    project_id: u64,
    target: &str,
    prefer_file: Option<u64>,
) -> anyhow::Result<Option<Symbol>> {
    let name = bare_name(target);
    if name.is_empty() {
        return Ok(None);
    }
    let names = [name.to_string()];
    let mut by_name = fetch_candidates(&mut *executor, project_id, &names).await?;
    if by_name.is_empty() && project_id != 0 {
        by_name = fetch_candidates(&mut *executor, 0, &names).await?;
    }
    let candidates = by_name.remove(name).unwrap_or_default();
    Ok(pick_candidate(candidates, target, prefer_file))
}