1use std::collections::{BTreeMap, BTreeSet, HashMap};
11use std::time::{Duration, Instant};
12
13use crate::core::call_graph::{
14 CallEdge, CallGraphInputs, ScopeMatch, StructuralTarget, callee_segment,
15};
16use crate::core::config::SemanticMode;
17use crate::core::property_graph::{CachedResolution, CodeGraph};
18use crate::lsp::router::{LiveIdentity, StartPolicy};
19
20use super::resolve::{Access, Resolution, ResolveError, live_backend_identity, resolve_definition};
21
22const OP_DEFINITION: &str = "definition";
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub struct EscalationBudget {
28 pub max_live_queries: usize,
29 pub wall: Duration,
31 pub per_request: Duration,
33}
34
35impl EscalationBudget {
36 pub const BACKGROUND: Self = Self {
41 max_live_queries: 1000,
42 wall: Duration::from_mins(1),
43 per_request: Duration::from_secs(5),
44 };
45 pub const INTERACTIVE: Self = Self {
47 max_live_queries: 20,
48 wall: Duration::from_secs(4),
49 per_request: Duration::from_secs(2),
50 };
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum SemanticVerdict {
56 Verified { file: String, backend: String },
58 NotInProject,
62}
63
64#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
66pub struct EscalationStats {
67 pub candidates: usize,
68 pub cache_hits: usize,
69 pub live_queries: usize,
70 pub verified: usize,
71 pub not_in_project: usize,
72 pub unresolved: usize,
74}
75
76#[derive(Debug, Clone, Default, PartialEq, Eq)]
78pub struct Escalation {
79 pub verdicts: Vec<Option<SemanticVerdict>>,
81 pub unsettled: Vec<bool>,
86 pub stats: EscalationStats,
87}
88
89fn needs_escalation(edge: &CallEdge, structural: &StructuralTarget) -> bool {
90 let uncertain = matches!(
91 structural,
92 StructuralTarget::Ambiguous
93 | StructuralTarget::Resolved {
94 via: ScopeMatch::UniqueInProject,
95 ..
96 }
97 );
98 uncertain
99 && edge.callee_pos.is_some()
100 && std::path::Path::new(&edge.caller_file)
101 .extension()
102 .and_then(|e| e.to_str())
103 .and_then(crate::lsp::config::language_for_extension)
104 .is_some()
105}
106
107fn definitions_fingerprint(
112 defs: &BTreeMap<&str, BTreeSet<&str>>,
113 name: &str,
114 file_hashes: &HashMap<String, String>,
115 dependency_revision: &str,
116) -> String {
117 let mut entries: Vec<String> = defs
118 .get(name)
119 .into_iter()
120 .flatten()
121 .map(|f| format!("{f}\t{}", file_hashes.get(*f).map_or("", String::as_str)))
122 .collect();
123 entries.push(dependency_revision.to_string());
124 crate::core::hasher::hash_str(&entries.join("\n"))
125}
126
127const DEPENDENCY_FILES: &[&str] = &[
131 "Cargo.toml",
132 "Cargo.lock",
133 "package.json",
134 "package-lock.json",
135 "pnpm-lock.yaml",
136 "yarn.lock",
137 "go.mod",
138 "go.sum",
139 "pyproject.toml",
140 "poetry.lock",
141 "uv.lock",
142 "requirements.txt",
143];
144
145fn dependency_revision(project_root: &str) -> String {
148 let entries: Vec<String> = DEPENDENCY_FILES
149 .iter()
150 .filter_map(|name| {
151 let content = std::fs::read(std::path::Path::new(project_root).join(name)).ok()?;
152 Some(format!("{name}\t{}", blake3::hash(&content).to_hex()))
153 })
154 .collect();
155 crate::core::hasher::hash_str(&entries.join("\n"))
156}
157
158#[derive(Debug, PartialEq, Eq)]
160enum CacheUse {
161 Reuse(Option<SemanticVerdict>),
163 Stale,
165 Defer,
168}
169
170fn verdict_from_cache(
174 hit: &CachedResolution,
175 inputs: &CallGraphInputs,
176 callee: &str,
177 context: &str,
178 live: &LiveIdentity,
179) -> CacheUse {
180 if hit.context != context {
181 return CacheUse::Stale;
182 }
183 match live {
184 LiveIdentity::Known(id) if *id != hit.backend => return CacheUse::Stale,
185 LiveIdentity::Busy => return CacheUse::Defer,
186 LiveIdentity::Known(_) | LiveIdentity::NotRunning => {}
187 }
188 match hit.outcome.as_str() {
189 "resolved" => {
190 let (Some(file), Some(line)) = (hit.target_file.clone(), hit.target_line) else {
191 return CacheUse::Stale;
192 };
193 let name = callee_segment(callee);
194 let still_there = inputs.symbols.iter().any(|s| {
195 s.file == file && s.name == name && s.start_line <= line && line <= s.end_line
196 });
197 if still_there {
198 CacheUse::Reuse(Some(SemanticVerdict::Verified {
199 file,
200 backend: hit.backend.clone(),
201 }))
202 } else {
203 CacheUse::Stale
204 }
205 }
206 "external" => CacheUse::Reuse(Some(SemanticVerdict::NotInProject)),
207 "ambiguous" => CacheUse::Reuse(None),
208 _ => CacheUse::Stale,
209 }
210}
211
212fn to_cache(resolution: &Resolution, backend: &str, context: &str) -> Option<CachedResolution> {
215 let (outcome, target_file, target_line, target_symbol) = match resolution {
216 Resolution::Resolved { file, line, symbol } => {
217 ("resolved", Some(file.clone()), Some(*line), symbol.clone())
218 }
219 Resolution::External => ("external", None, None, None),
220 Resolution::Ambiguous => ("ambiguous", None, None, None),
221 Resolution::NoResult => return None,
222 };
223 Some(CachedResolution {
224 backend: backend.to_string(),
225 outcome: outcome.to_string(),
226 target_file,
227 target_line,
228 target_symbol,
229 context: context.to_string(),
230 })
231}
232
233fn ext_of(file: &str) -> String {
234 std::path::Path::new(file)
235 .extension()
236 .and_then(|e| e.to_str())
237 .unwrap_or("")
238 .to_string()
239}
240
241fn escalation_order(
247 edges: &[CallEdge],
248 structural: &[StructuralTarget],
249 candidates: Vec<usize>,
250) -> Vec<usize> {
251 let group = |i: usize| match &structural[i] {
252 StructuralTarget::Resolved { file, .. } => (0u8, file.as_str()),
253 _ => (1u8, edges[i].callee_name.as_str()),
254 };
255 let mut by_site = candidates;
256 by_site.sort_by(|&a, &b| {
257 (&edges[a].caller_file, edges[a].callee_pos)
258 .cmp(&(&edges[b].caller_file, edges[b].callee_pos))
259 });
260 let mut seen: HashMap<(&str, (u8, &str)), usize> = HashMap::new();
261 let mut ranked: Vec<(usize, u8, usize)> = by_site
262 .iter()
263 .map(|&i| {
264 let (class, key) = group(i);
265 let rank = seen
266 .entry((edges[i].caller_file.as_str(), (class, key)))
267 .or_insert(0);
268 *rank += 1;
269 (*rank, class, i)
270 })
271 .collect();
272 ranked.sort_by_key(|&(rank, class, _)| (rank, class));
274 ranked.into_iter().map(|(_, _, i)| i).collect()
275}
276
277pub fn escalate_calls(
280 graph: &CodeGraph,
281 project_root: &str,
282 inputs: &CallGraphInputs,
283 edges: &[CallEdge],
284 structural: &[StructuralTarget],
285 file_hashes: &HashMap<String, String>,
286 mode: SemanticMode,
287 budget: EscalationBudget,
288) -> Escalation {
289 let mut out = Escalation {
290 verdicts: vec![None; edges.len()],
291 unsettled: vec![false; edges.len()],
292 stats: EscalationStats::default(),
293 };
294 let candidates: Vec<usize> = (0..edges.len())
295 .filter(|&i| needs_escalation(&edges[i], &structural[i]))
296 .collect();
297 out.stats.candidates = candidates.len();
298 if mode == SemanticMode::Off {
299 return out;
301 }
302 let order = escalation_order(edges, structural, candidates);
303
304 let access = Access {
305 policy: if mode == SemanticMode::Eager {
306 StartPolicy::Lazy
307 } else {
308 StartPolicy::ReuseOnly
309 },
310 wait: false,
311 timeout: Some(budget.per_request),
312 deadline: None,
313 };
314 let mut defs: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
315 for s in &inputs.symbols {
316 defs.entry(s.name.as_str())
317 .or_default()
318 .insert(s.file.as_str());
319 }
320
321 let deps = dependency_revision(project_root);
325 let admission = crate::core::context_admission::stores::StoreAdmission::current();
327 let started = Instant::now();
328 let mut live_identity: HashMap<String, LiveIdentity> = HashMap::new();
332 let mut unavailable: BTreeSet<String> = BTreeSet::new();
333
334 for i in order {
335 let edge = &edges[i];
336 out.unsettled[i] = true;
337 let (Some((line, col)), Some(hash)) = (edge.callee_pos, file_hashes.get(&edge.caller_file))
338 else {
339 continue;
340 };
341 let site = (edge.caller_file.as_str(), line, col, OP_DEFINITION);
342 let context =
343 definitions_fingerprint(&defs, callee_segment(&edge.callee_name), file_hashes, &deps);
344 let ext = ext_of(&edge.caller_file);
345
346 if let Ok(Some(hit)) = graph.semantic_lookup(site, hash) {
347 if live_identity
348 .get(&ext)
349 .is_none_or(|l| *l == LiveIdentity::Busy)
350 {
351 live_identity.insert(
352 ext.clone(),
353 live_backend_identity(project_root, &edge.caller_file),
354 );
355 }
356 let live = live_identity.get(&ext).unwrap_or(&LiveIdentity::NotRunning);
357 match verdict_from_cache(&hit, inputs, &edge.callee_name, &context, live) {
358 CacheUse::Reuse(v) => {
359 out.stats.cache_hits += 1;
360 out.verdicts[i] = v;
361 out.unsettled[i] = false;
362 continue;
363 }
364 CacheUse::Defer => continue,
365 CacheUse::Stale => {}
366 }
367 }
368
369 let remaining = budget.wall.saturating_sub(started.elapsed());
370 if unavailable.contains(&ext)
371 || out.stats.live_queries >= budget.max_live_queries
372 || remaining.is_zero()
373 {
374 continue;
375 }
376
377 out.stats.live_queries += 1;
378 let access = Access {
379 deadline: Some(started + budget.wall),
380 ..access
381 };
382 match resolve_definition(project_root, &edge.caller_file, (line, col), access, inputs) {
383 Ok(answer) => {
384 if let Some(record) = to_cache(&answer.resolution, &answer.backend, &context) {
385 let _ = graph.semantic_store(site, hash, &record, &admission);
386 }
387 live_identity.insert(ext, LiveIdentity::Known(answer.backend.clone()));
388 (out.verdicts[i], out.unsettled[i]) = match answer.resolution {
389 Resolution::Resolved { file, .. } => (
390 Some(SemanticVerdict::Verified {
391 file,
392 backend: answer.backend,
393 }),
394 false,
395 ),
396 Resolution::External => (Some(SemanticVerdict::NotInProject), false),
397 Resolution::Ambiguous => (None, false),
398 Resolution::NoResult => (None, true),
399 };
400 }
401 Err(ResolveError::Unavailable(_)) => {
404 unavailable.insert(ext);
405 }
406 Err(ResolveError::Site(_)) => {}
407 }
408 }
409
410 for v in out.verdicts.iter().flatten() {
411 match v {
412 SemanticVerdict::Verified { .. } => out.stats.verified += 1,
413 SemanticVerdict::NotInProject => out.stats.not_in_project += 1,
414 }
415 }
416 out.stats.unresolved = out.stats.candidates - out.stats.verified - out.stats.not_in_project;
417 tracing::debug!(
418 target: "lean_ctx::semantic",
419 "escalate: {} candidates, {} cached, {} live, {} verified, {} external in {} ms",
420 out.stats.candidates,
421 out.stats.cache_hits,
422 out.stats.live_queries,
423 out.stats.verified,
424 out.stats.not_in_project,
425 started.elapsed().as_millis()
426 );
427 out
428}
429
430#[cfg(test)]
431mod tests {
432 use super::*;
433 use crate::core::call_graph::SymbolSpan;
434
435 fn edge(file: &str, callee: &str, pos: Option<(usize, usize)>) -> CallEdge {
436 CallEdge {
437 caller_file: file.into(),
438 caller_symbol: "f".into(),
439 caller_line: 1,
440 callee_name: callee.into(),
441 callee_pos: pos,
442 ..Default::default()
443 }
444 }
445
446 #[test]
447 fn only_scope_unbound_edges_with_a_position_are_escalated() {
448 let resolved = |via| StructuralTarget::Resolved {
449 file: "b.rs".into(),
450 via,
451 };
452 let e = edge("a.rs", "save", Some((1, 4)));
453 assert!(needs_escalation(&e, &StructuralTarget::Ambiguous));
454 assert!(needs_escalation(&e, &resolved(ScopeMatch::UniqueInProject)));
455 assert!(!needs_escalation(&e, &resolved(ScopeMatch::SameFile)));
456 assert!(!needs_escalation(&e, &resolved(ScopeMatch::UniqueImport)));
457 assert!(!needs_escalation(&e, &StructuralTarget::Unknown));
458 assert!(!needs_escalation(
459 &edge("a.rs", "save", None),
460 &StructuralTarget::Ambiguous
461 ));
462 assert!(
463 !needs_escalation(
464 &edge("a.md", "save", Some((1, 0))),
465 &StructuralTarget::Ambiguous
466 ),
467 "no semantic backend for the language"
468 );
469 }
470
471 #[test]
472 fn cached_answers_are_reused_only_while_their_context_holds() {
473 let inputs = CallGraphInputs {
474 symbols: vec![SymbolSpan {
475 file: "repo.rs".into(),
476 name: "save".into(),
477 start_line: 5,
478 end_line: 9,
479 ..Default::default()
480 }],
481 ..Default::default()
482 };
483 let hit = |file: &str, line: usize| CachedResolution {
484 backend: "lsp:ra@1".into(),
485 outcome: "resolved".into(),
486 target_file: Some(file.into()),
487 target_line: Some(line),
488 target_symbol: None,
489 context: "ctx".into(),
490 };
491 let verified = CacheUse::Reuse(Some(SemanticVerdict::Verified {
492 file: "repo.rs".into(),
493 backend: "lsp:ra@1".into(),
494 }));
495 let none = LiveIdentity::NotRunning;
496 let check = |h: &CachedResolution, ctx: &str, live: &LiveIdentity| {
497 verdict_from_cache(h, &inputs, "save", ctx, live)
498 };
499
500 assert_eq!(check(&hit("repo.rs", 6), "ctx", &none), verified);
501 assert_eq!(
502 check(
503 &hit("repo.rs", 6),
504 "ctx",
505 &LiveIdentity::Known("lsp:ra@1".into())
506 ),
507 verified
508 );
509 assert_eq!(
510 check(
511 &hit("repo.rs", 6),
512 "ctx",
513 &LiveIdentity::Known("lsp:ra@2".into())
514 ),
515 CacheUse::Stale,
516 "another server version answers anew"
517 );
518 assert_eq!(
519 check(&hit("repo.rs", 6), "ctx", &LiveIdentity::Busy),
520 CacheUse::Defer,
521 "a busy backend cannot vouch for the old answer"
522 );
523 assert_eq!(
524 check(&hit("repo.rs", 6), "other-ctx", &none),
525 CacheUse::Stale,
526 "the `save` definitions (set or content) changed"
527 );
528 assert_eq!(
529 check(&hit("repo.rs", 2), "ctx", &none),
530 CacheUse::Stale,
531 "the recorded definition line no longer holds a `save`"
532 );
533 assert_eq!(check(&hit("moved.rs", 6), "ctx", &none), CacheUse::Stale);
534 let ambiguous = CachedResolution {
535 outcome: "ambiguous".into(),
536 target_file: None,
537 ..hit("repo.rs", 6)
538 };
539 assert_eq!(
540 check(&ambiguous, "ctx", &none),
541 CacheUse::Reuse(None),
542 "a definitive ambiguous answer is reused, not re-asked"
543 );
544 }
545
546 #[test]
547 fn unanswered_candidates_are_reported_unsettled_but_off_mode_is_settled() {
548 let g = CodeGraph::open_in_memory().unwrap();
549 let edges = [edge("a.rs", "save", Some((1, 4)))];
550 let hashes = HashMap::from([("a.rs".to_string(), "h".to_string())]);
551 let run = |mode| {
552 escalate_calls(
553 &g,
554 "/nonexistent/leanctx-escalation",
555 &CallGraphInputs::default(),
556 &edges,
557 &[StructuralTarget::Ambiguous],
558 &hashes,
559 mode,
560 EscalationBudget::INTERACTIVE,
561 )
562 };
563
564 let off = run(SemanticMode::Off);
565 assert_eq!((off.verdicts, off.unsettled), (vec![None], vec![false]));
566
567 let auto = run(SemanticMode::Auto);
570 assert_eq!((auto.verdicts, auto.unsettled), (vec![None], vec![true]));
571 }
572}