Skip to content

Commit 36f756e

Browse files
committed
fix(resolution): candidate picks are insertion-order independent
- `SymbolLookupCache.by_name` candidate lists sort by `(file_path, start_line, id)` via `NameCandidate`, not insertion order - `insert` binary-searches for the sorted position instead of appending; `lookup_candidates` returns candidates in that identity order - Identity order is stable across runs, while parse-completion interleaving and collect-arrival id assignment both vary run to run, so first-match resolution ties break deterministically
1 parent af247f5 commit 36f756e

2 files changed

Lines changed: 155 additions & 9 deletions

File tree

‎src/indexing/pipeline/stages/resolve.rs‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -943,6 +943,112 @@ mod tests {
943943
assert_eq!(batch.relationships[0].to_id, SymbolId::new(2).unwrap());
944944
}
945945

946+
#[test]
947+
fn resolution_pick_is_insertion_order_independent() {
948+
// Candidate vectors fill in parse-completion order (thread
949+
// interleaving); the pick among equal-tier candidates must not
950+
// depend on it.
951+
let rust = LanguageId::new("rust");
952+
let build = |ids: &[u32]| {
953+
let cache = Arc::new(SymbolLookupCache::new());
954+
cache.insert(make_symbol(1, "caller", 1, rust));
955+
for &id in ids {
956+
// id N lives in file N (files 2 and 3, both cross-file)
957+
cache.insert(make_symbol(id, "format", id, rust));
958+
}
959+
let stage = make_stage(cache);
960+
let context = make_context(
961+
1,
962+
rust,
963+
vec![SymbolId::new(1).unwrap()],
964+
vec![make_unresolved(1, "format", 1, RelationKind::Calls)],
965+
);
966+
let (batch, _) = stage.resolve(&context);
967+
batch.relationships.first().map(|r| r.to_id)
968+
};
969+
970+
assert_eq!(
971+
build(&[2, 3]),
972+
build(&[3, 2]),
973+
"pick must not depend on candidate insertion order"
974+
);
975+
}
976+
977+
#[test]
978+
fn import_path_first_match_is_insertion_order_independent() {
979+
// Tier 2 scans candidates for a bidirectional module-path match;
980+
// two symbols can both match one import path. The winner must not
981+
// depend on insertion order.
982+
let rust = LanguageId::new("rust");
983+
let build = |order: &[(u32, &str)]| {
984+
let cache = Arc::new(SymbolLookupCache::new());
985+
cache.insert(make_symbol(1, "caller", 1, rust));
986+
for &(id, module_path) in order {
987+
let mut sym = make_symbol(id, "helper", id, rust);
988+
sym.module_path = Some(module_path.into());
989+
sym.file_path = format!("src/f{id}.rs").into();
990+
cache.insert(sym);
991+
}
992+
let stage = make_stage(cache);
993+
let mut context = make_context(
994+
1,
995+
rust,
996+
vec![SymbolId::new(1).unwrap()],
997+
vec![make_unresolved(1, "helper", 1, RelationKind::Calls)],
998+
);
999+
context.imports = vec![Import {
1000+
path: "app::util::helper".to_string(),
1001+
alias: None,
1002+
file_id: FileId::new(1).unwrap(),
1003+
is_glob: false,
1004+
is_type_only: false,
1005+
}];
1006+
let (batch, _) = stage.resolve(&context);
1007+
batch.relationships.first().map(|r| r.to_id)
1008+
};
1009+
1010+
let a = build(&[(2, "app::util"), (3, "util")]);
1011+
let b = build(&[(3, "util"), (2, "app::util")]);
1012+
assert!(a.is_some(), "import-path match must resolve");
1013+
assert_eq!(
1014+
a, b,
1015+
"import-path winner must not depend on insertion order"
1016+
);
1017+
}
1018+
1019+
#[test]
1020+
fn resolution_pick_is_id_assignment_independent() {
1021+
// Ids are session-scoped, assigned in collect-arrival order — the
1022+
// same tree hands the same symbol different ids across runs. The
1023+
// pick must land on the same symbol IDENTITY either way.
1024+
let rust = LanguageId::new("rust");
1025+
let winner_path = |id_for_alpha: u32, id_for_beta: u32| {
1026+
let cache = Arc::new(SymbolLookupCache::new());
1027+
cache.insert(make_symbol(1, "caller", 1, rust));
1028+
for (id, path) in [(id_for_alpha, "src/alpha.rs"), (id_for_beta, "src/beta.rs")] {
1029+
let mut sym = make_symbol(id, "format", id, rust);
1030+
sym.file_path = path.into();
1031+
cache.insert(sym);
1032+
}
1033+
let stage = make_stage(Arc::clone(&cache));
1034+
let context = make_context(
1035+
1,
1036+
rust,
1037+
vec![SymbolId::new(1).unwrap()],
1038+
vec![make_unresolved(1, "format", 1, RelationKind::Calls)],
1039+
);
1040+
let (batch, _) = stage.resolve(&context);
1041+
let to_id = batch.relationships.first().map(|r| r.to_id)?;
1042+
cache.get(to_id).map(|s| s.file_path)
1043+
};
1044+
1045+
assert_eq!(
1046+
winner_path(2, 3),
1047+
winner_path(3, 2),
1048+
"pick must land on the same symbol identity regardless of id assignment"
1049+
);
1050+
}
1051+
9461052
#[test]
9471053
fn python_self_aliases_pass_untyped_locals_fail_closed() {
9481054
// cls.get() resolves through the python self vocabulary;

‎src/indexing/pipeline/types.rs‎

Lines changed: 49 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -373,11 +373,43 @@ pub use crate::parsing::CallerContext;
373373
/// - `by_name`: name → `Vec<SymbolId>` for candidate resolution
374374
/// - `by_file_id`: FileId → `Vec<SymbolId>` for local symbol lookup
375375
///
376+
/// Identity-ordered entry in the `by_name` candidate lists. Derived
377+
/// `Ord` compares file_path, then start_line, then id — the id arm only
378+
/// breaks ties within one run; the identity prefix is what holds across
379+
/// runs (ids are session-scoped).
380+
#[derive(Debug, PartialEq, Eq)]
381+
struct NameCandidate {
382+
file_path: Box<str>,
383+
start_line: u32,
384+
id: crate::types::SymbolId,
385+
}
386+
387+
impl Ord for NameCandidate {
388+
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
389+
self.file_path
390+
.cmp(&other.file_path)
391+
.then_with(|| self.start_line.cmp(&other.start_line))
392+
.then_with(|| self.id.value().cmp(&other.id.value()))
393+
}
394+
}
395+
396+
impl PartialOrd for NameCandidate {
397+
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
398+
Some(self.cmp(other))
399+
}
400+
}
401+
376402
/// Memory: ~500 bytes/symbol, 600K symbols ≈ 300MB
403+
///
404+
/// `by_name` candidates stay sorted by symbol identity
405+
/// (file_path, start_line, id): insertion order is parse-completion
406+
/// order and ids are assigned in collect-arrival order — both vary run
407+
/// to run — so first-match consumers need a tree-stable order to pick
408+
/// deterministically.
377409
#[derive(Debug)]
378410
pub struct SymbolLookupCache {
379411
by_id: dashmap::DashMap<crate::types::SymbolId, crate::Symbol>,
380-
by_name: dashmap::DashMap<Box<str>, Vec<crate::types::SymbolId>>,
412+
by_name: dashmap::DashMap<Box<str>, Vec<NameCandidate>>,
381413
by_file_id: dashmap::DashMap<crate::types::FileId, Vec<crate::types::SymbolId>>,
382414
/// Re-exported paths: "pkg.helper" -> the symbol defined at "pkg.a.helper"
383415
/// when pkg's namespace imports it. Populated by the Phase 2 pre-pass.
@@ -416,12 +448,23 @@ impl SymbolLookupCache {
416448
let id = symbol.id;
417449
let file_id = symbol.file_id;
418450
let name: Box<str> = symbol.name.as_ref().into();
451+
let candidate = NameCandidate {
452+
file_path: symbol.file_path.clone(),
453+
start_line: symbol.range.start_line,
454+
id,
455+
};
419456

420457
// Insert into by_id
421458
self.by_id.insert(id, symbol);
422459

423-
// Insert into by_name (append to candidates)
424-
self.by_name.entry(name).or_default().push(id);
460+
// Insert into by_name at the identity-sorted position
461+
{
462+
let mut entry = self.by_name.entry(name).or_default();
463+
let pos = entry
464+
.binary_search(&candidate)
465+
.unwrap_or_else(|insert_at| insert_at);
466+
entry.insert(pos, candidate);
467+
}
425468

426469
// Insert into by_file_id (append to file's symbols)
427470
self.by_file_id.entry(file_id).or_default().push(id);
@@ -440,11 +483,11 @@ impl SymbolLookupCache {
440483
self.by_id.get(&id)
441484
}
442485

443-
/// Get candidate symbol IDs by name (O(1)).
486+
/// Get candidate symbol IDs by name (O(1)), in identity order.
444487
pub fn lookup_candidates(&self, name: &str) -> Vec<crate::types::SymbolId> {
445488
self.by_name
446489
.get(name)
447-
.map(|r| r.value().clone())
490+
.map(|r| r.value().iter().map(|c| c.id).collect())
448491
.unwrap_or_default()
449492
}
450493

@@ -772,10 +815,7 @@ impl PipelineSymbolCache for SymbolLookupCache {
772815
}
773816

774817
fn lookup_candidates(&self, name: &str) -> Vec<SymbolId> {
775-
self.by_name
776-
.get(name)
777-
.map(|r| r.value().clone())
778-
.unwrap_or_default()
818+
SymbolLookupCache::lookup_candidates(self, name)
779819
}
780820
}
781821

0 commit comments

Comments
 (0)