1mod score;
9
10pub use score::{Boosts, Feature, Scored, confidence, match_positions, match_quality, path_stem};
11
12use std::collections::{HashMap, HashSet};
13use std::path::Path;
14use std::time::{Instant, SystemTime, UNIX_EPOCH};
15
16use crate::store::{Store, SymbolRow};
17
18const CANDIDATE_LIMIT: usize = 8000;
23
24const LIVE_REPO_ID: i64 = -1;
27
28const BRANCH_FILE_BOOST: f64 = 180.0;
30const BRANCH_DIR_BOOST: f64 = 60.0;
32
33#[derive(Debug, Default, Clone)]
37pub struct ActiveFiles {
38 files: HashSet<String>,
39 dirs: HashSet<String>,
40}
41
42impl ActiveFiles {
43 pub fn new<I: IntoIterator<Item = String>>(paths: I) -> Self {
45 let files: HashSet<String> = paths.into_iter().collect();
46 let dirs = files
47 .iter()
48 .filter_map(|f| parent_dir(f))
49 .map(str::to_string)
50 .collect();
51 ActiveFiles { files, dirs }
52 }
53
54 fn is_empty(&self) -> bool {
55 self.files.is_empty()
56 }
57
58 fn boost(&self, path: &str) -> f64 {
61 if self.files.contains(path) {
62 BRANCH_FILE_BOOST
63 } else if parent_dir(path).is_some_and(|d| self.dirs.contains(d)) {
64 BRANCH_DIR_BOOST
65 } else {
66 0.0
67 }
68 }
69}
70
71fn parent_dir(path: &str) -> Option<&str> {
74 path.rfind('/').map(|i| &path[..i])
75}
76
77#[derive(Debug, Clone, PartialEq, serde::Serialize)]
79pub struct Hit {
80 pub name: String,
81 pub kind: String,
82 pub language: String,
83 pub file: String,
84 pub line: i64,
85 #[serde(skip_serializing_if = "Option::is_none")]
88 pub end_line: Option<i64>,
89 #[serde(skip_serializing_if = "Option::is_none")]
90 pub parent: Option<String>,
91 #[serde(skip_serializing_if = "Option::is_none")]
94 pub visibility: Option<String>,
95 #[serde(rename = "repo")]
96 pub repo_identity: String,
97 #[serde(skip)]
100 pub score: f64,
101 pub confidence: f64,
104 #[serde(serialize_with = "serialize_feature_names")]
107 pub features: Vec<Feature>,
108 #[serde(skip_serializing_if = "Option::is_none")]
111 pub signature: Option<String>,
112 #[serde(skip_serializing_if = "Option::is_none")]
114 pub body: Option<String>,
115}
116
117fn serialize_feature_names<S: serde::Serializer>(
120 features: &[Feature],
121 s: S,
122) -> Result<S::Ok, S::Error> {
123 use serde::Serialize;
124 let mut sorted: Vec<&Feature> = features.iter().collect();
125 sorted.sort_by(|a, b| b.value.total_cmp(&a.value));
126 let names: Vec<&str> = sorted.iter().map(|f| f.name).collect();
127 names.serialize(s)
128}
129
130pub fn search(
136 store: &Store,
137 query: &str,
138 current_repo_id: Option<i64>,
139 only_repo: Option<i64>,
140 active: &ActiveFiles,
141 limit: usize,
142) -> crate::store::Result<Vec<Hit>> {
143 let (leaf, _) = score::parse_qualified(query);
148 let stripped;
149 let recall = if score::has_wildcard(leaf) {
150 stripped = score::strip_wildcards(leaf);
151 stripped.as_str()
152 } else {
153 leaf
154 };
155 let trace_on = crate::trace::enabled();
156 let t = std::time::Instant::now();
157 let candidates = store.search_candidates(recall, CANDIDATE_LIMIT, score::has_wildcard(leaf))?;
158 let n_candidates = candidates.len();
159 let t_recall = t.elapsed();
160 let t = std::time::Instant::now();
161 let now = now_unix();
162 let learned = learned_boosts(store, query, now)?;
163
164 let mut hits: Vec<Hit> = candidates
165 .into_iter()
166 .filter_map(|c| {
167 if only_repo.is_some_and(|r| r != c.repository_id) {
170 return None;
171 }
172 let learned_boost = if learned.is_empty() {
175 0.0
176 } else {
177 let key = (c.repository_id, c.file.clone(), c.name.clone());
178 learned.get(&key).copied().unwrap_or(0.0)
179 };
180 let boosts = Boosts {
181 learned: learned_boost,
182 recency: recency_boost(c.git_ts.max(c.mtime.map(|n| n / 1_000_000_000)), now),
186 branch: if active.is_empty() {
187 0.0
188 } else {
189 active.boost(&c.file)
190 },
191 };
192 rank_one(query, c, current_repo_id, boosts)
193 })
194 .collect();
195 let n_hits = hits.len();
196 let t_score = t.elapsed();
197
198 let t = std::time::Instant::now();
199 sort_and_truncate(&mut hits, limit);
200 if trace_on {
201 crate::trace!(
202 "search {query:?}: recall {n_candidates} cand in {} ms, score→{n_hits} hits in {} ms, sort {} ms",
203 t_recall.as_millis(),
204 t_score.as_millis(),
205 t.elapsed().as_millis(),
206 );
207 }
208 Ok(hits)
209}
210
211fn recency_boost(mtime: Option<i64>, now: i64) -> f64 {
214 let Some(mtime) = mtime else {
215 return 0.0;
216 };
217 let age_days = (now - mtime).max(0) as f64 / 86_400.0;
218 let boost = 120.0 * 0.5_f64.powf(age_days / 14.0);
219 if boost < 1.0 { 0.0 } else { boost }
220}
221
222fn learned_boosts(
224 store: &Store,
225 query: &str,
226 now: i64,
227) -> crate::store::Result<HashMap<(i64, String, String), f64>> {
228 let q = query.to_ascii_lowercase();
229 let mut map: HashMap<(i64, String, String), f64> = HashMap::new();
230 for s in store.selections_for(&q)? {
231 let boost = learned_boost(s.selections, s.last_selected_at, now);
234 let entry = map.entry((s.repository_id, s.file, s.name)).or_insert(0.0);
235 *entry = entry.max(boost);
236 }
237 Ok(map)
238}
239
240fn learned_boost(selections: i64, last_selected_at: i64, now: i64) -> f64 {
244 if selections <= 0 {
245 return 0.0;
246 }
247 let strength = (selections.min(5) as f64) / 5.0;
248 let age_days = (now - last_selected_at).max(0) as f64 / 86_400.0;
249 let recency = 0.5_f64.powf(age_days / 30.0).max(0.25);
250 260.0 * strength * recency
251}
252
253fn now_unix() -> i64 {
254 SystemTime::now()
255 .duration_since(UNIX_EPOCH)
256 .map(|d| d.as_secs() as i64)
257 .unwrap_or(0)
258}
259
260pub fn live_search(
268 root: &Path,
269 query: &str,
270 limit: usize,
271 skip: &HashSet<String>,
272 deadline: Option<Instant>,
273 prefilter: bool,
274) -> Vec<Hit> {
275 let needle = prefilter.then_some(query.as_bytes());
276 let identity = crate::index::detect_identity(root).to_string();
277 let mut hits: Vec<Hit> = crate::index::scan(root, skip, deadline, needle)
278 .into_iter()
279 .flat_map(|fs| fs.symbols)
280 .filter_map(|s| {
281 let row = SymbolRow {
282 name: s.name,
283 kind: s.kind.as_str().to_string(),
284 language: s.language,
285 file: s.file,
286 line: s.line as i64,
287 end_line: Some(s.end_line as i64),
288 parent: s.parent,
289 repository_id: LIVE_REPO_ID,
290 repo_identity: identity.clone(),
291 mtime: None,
292 git_ts: None,
293 visibility: s.visibility.map(str::to_string),
294 };
295 rank_one(query, row, Some(LIVE_REPO_ID), Boosts::default())
296 })
297 .collect();
298 sort_and_truncate(&mut hits, limit);
299 hits
300}
301
302pub fn merge(a: Vec<Hit>, b: Vec<Hit>, limit: usize) -> Vec<Hit> {
306 use std::collections::HashMap;
307 let mut by_key: HashMap<(String, i64, String), Hit> = HashMap::new();
308 for hit in a.into_iter().chain(b) {
309 let key = (hit.file.clone(), hit.line, hit.name.clone());
310 match by_key.get(&key) {
311 Some(existing) if existing.score >= hit.score => {}
312 _ => {
313 by_key.insert(key, hit);
314 }
315 }
316 }
317 let mut hits: Vec<Hit> = by_key.into_values().collect();
318 sort_and_truncate(&mut hits, limit);
319 hits
320}
321
322pub fn apply_scope_gate(query: &str, hits: &mut Vec<Hit>) {
333 if score::parse_qualified(query).1.is_none() {
334 return; }
336 let in_scope = |h: &Hit| h.features.iter().any(|f| f.name == "parent");
337 if hits.iter().any(in_scope) {
338 hits.retain(in_scope);
339 }
340}
341
342fn sort_and_truncate(hits: &mut Vec<Hit>, limit: usize) {
344 hits.sort_by(|a, b| {
345 b.score
346 .partial_cmp(&a.score)
347 .unwrap_or(std::cmp::Ordering::Equal)
348 .then_with(|| a.name.len().cmp(&b.name.len()))
349 .then_with(|| a.name.cmp(&b.name))
350 });
351 hits.truncate(limit);
352}
353
354fn rank_one(
355 query: &str,
356 c: SymbolRow,
357 current_repo_id: Option<i64>,
358 boosts: Boosts,
359) -> Option<Hit> {
360 let scored = score::score(query, &c, current_repo_id, boosts)?;
361 Some(Hit {
362 name: c.name,
363 kind: c.kind,
364 language: c.language,
365 file: c.file,
366 line: c.line,
367 end_line: c.end_line,
368 parent: c.parent,
369 visibility: c.visibility,
370 repo_identity: c.repo_identity,
371 score: scored.total,
372 confidence: 0.0, features: scored.features,
374 signature: None,
375 body: None,
376 })
377}
378
379#[cfg(test)]
380mod tests {
381 use super::*;
382 use crate::core::{Kind, Symbol};
383
384 fn sym(name: &str, kind: Kind) -> Symbol {
385 Symbol {
386 name: name.into(),
387 kind,
388 language: "ruby".into(),
389 file: "app/x.rb".into(),
390 line: 1,
391 end_line: 1,
392 parent: None,
393 visibility: None,
394 }
395 }
396
397 fn store_with(symbols: &[Symbol]) -> Store {
398 let mut store = Store::open_in_memory().unwrap();
399 let repo = store
400 .upsert_repository(&crate::core::RepoIdentity::local("/tmp/x"), None)
401 .unwrap();
402 store
403 .replace_file_symbols(repo, "app/x.rb", "ruby", None, "h", symbols)
404 .unwrap();
405 store
406 }
407
408 fn names(hits: &[Hit]) -> Vec<&str> {
409 hits.iter().map(|h| h.name.as_str()).collect()
410 }
411
412 fn store_two_repos() -> (Store, i64, i64) {
414 let mut store = Store::open_in_memory().unwrap();
415 let a = store
416 .upsert_repository(&crate::core::RepoIdentity::local("/tmp/a"), None)
417 .unwrap();
418 let b = store
419 .upsert_repository(&crate::core::RepoIdentity::local("/tmp/b"), None)
420 .unwrap();
421 store
422 .replace_file_symbols(a, "a.rb", "ruby", None, "h", &[sym("Widget", Kind::Class)])
423 .unwrap();
424 store
425 .replace_file_symbols(b, "b.rb", "ruby", None, "h", &[sym("Widget", Kind::Class)])
426 .unwrap();
427 (store, a, b)
428 }
429
430 #[test]
431 fn only_repo_scopes_results_to_that_repo() {
432 let (store, a, b) = store_two_repos();
433 let hits = search(
435 &store,
436 "Widget",
437 Some(a),
438 Some(a),
439 &ActiveFiles::default(),
440 10,
441 )
442 .unwrap();
443 assert_eq!(hits.len(), 1);
444 assert_eq!(hits[0].repo_identity, "local:/tmp/a");
445 let all = search(&store, "Widget", Some(a), None, &ActiveFiles::default(), 10).unwrap();
447 assert_eq!(all.len(), 2);
448 let _ = b;
449 }
450
451 #[test]
452 fn scoped_search_reports_no_match_rather_than_leaking_another_repo() {
453 let (store, a, _b) = store_two_repos();
454 let hits = search(
456 &store,
457 "Gadget",
458 Some(a),
459 Some(a),
460 &ActiveFiles::default(),
461 10,
462 )
463 .unwrap();
464 assert!(hits.is_empty());
465 }
466
467 #[test]
468 fn ranks_exact_match_first() {
469 let store = store_with(&[
470 sym("Users", Kind::Class),
471 sym("User", Kind::Class),
472 sym("UserMailer", Kind::Class),
473 ]);
474 let hits = search(&store, "user", None, None, &ActiveFiles::default(), 10).unwrap();
475 assert_eq!(hits[0].name, "User");
476 }
477
478 #[test]
479 fn abbreviation_finds_the_intended_symbol() {
480 let store = store_with(&[
481 sym("RefundProcessor", Kind::Class),
482 sym("Refund", Kind::Class),
483 sym("Payment", Kind::Class),
484 ]);
485 let hits = search(
486 &store,
487 "refundproc",
488 None,
489 None,
490 &ActiveFiles::default(),
491 10,
492 )
493 .unwrap();
494 assert_eq!(hits[0].name, "RefundProcessor");
495 assert!(!names(&hits).contains(&"Payment"));
496 }
497
498 #[test]
499 fn short_fuzzy_query_still_resolves() {
500 let store = store_with(&[sym("User", Kind::Class), sym("Account", Kind::Class)]);
501 let hits = search(&store, "usr", None, None, &ActiveFiles::default(), 10).unwrap();
502 assert_eq!(hits[0].name, "User");
503 }
504
505 #[test]
506 fn no_match_returns_empty() {
507 let store = store_with(&[sym("User", Kind::Class)]);
508 let hits = search(&store, "zzzzz", None, None, &ActiveFiles::default(), 10).unwrap();
509 assert!(hits.is_empty());
510 }
511
512 #[test]
513 fn merge_dedups_by_location_keeping_higher_score() {
514 let mk = |name: &str, score: f64| Hit {
515 name: name.into(),
516 kind: "class".into(),
517 language: "ruby".into(),
518 file: "a.rb".into(),
519 line: 1,
520 end_line: Some(1),
521 parent: None,
522 visibility: None,
523 repo_identity: "r".into(),
524 score,
525 confidence: 0.0,
526 features: vec![],
527 signature: None,
528 body: None,
529 };
530 let from_index = vec![mk("User", 100.0)];
531 let from_live = vec![mk("User", 500.0), mk("Account", 200.0)];
532 let merged = merge(from_index, from_live, 10);
533 assert_eq!(merged.len(), 2, "the duplicate User is collapsed");
534 assert_eq!(merged[0].name, "User");
535 assert_eq!(merged[0].score, 500.0, "the higher-scored duplicate wins");
536 }
537
538 #[test]
539 fn active_files_boosts_the_file_and_its_neighbors() {
540 let active = ActiveFiles::new(["app/services/refund.rb".to_string()]);
541 assert_eq!(active.boost("app/services/refund.rb"), BRANCH_FILE_BOOST);
543 assert_eq!(active.boost("app/services/charge.rb"), BRANCH_DIR_BOOST);
545 assert_eq!(active.boost("app/models/user.rb"), 0.0);
547 }
548
549 fn nested(name: &str, kind: Kind, parent: &str) -> Symbol {
550 Symbol {
551 parent: Some(parent.into()),
552 ..sym(name, kind)
553 }
554 }
555
556 #[test]
557 fn qualified_query_ranks_the_definition_in_the_named_scope() {
558 let store = store_with(&[
559 nested("Config", Kind::Class, "Baz"),
560 nested("Config", Kind::Class, "Foo"),
561 nested("Config", Kind::Class, "Qux"),
562 ]);
563 let hits = search(
565 &store,
566 "Foo::Config",
567 None,
568 None,
569 &ActiveFiles::default(),
570 10,
571 )
572 .unwrap();
573 assert_eq!(hits[0].parent.as_deref(), Some("Foo"));
574 assert!(hits[0].features.iter().any(|f| f.name == "parent"));
575 }
576
577 #[test]
578 fn qualifier_resolves_modules_and_methods_too() {
579 let store = store_with(&[
580 nested("perform", Kind::Method, "Bar::Worker"),
581 nested("perform", Kind::Method, "Other::Worker"),
582 nested("Worker", Kind::Module, "Bar"),
583 ]);
584 let m = search(
586 &store,
587 "Bar::Worker#perform",
588 None,
589 None,
590 &ActiveFiles::default(),
591 10,
592 )
593 .unwrap();
594 assert_eq!(m[0].kind, "method");
595 assert_eq!(m[0].parent.as_deref(), Some("Bar::Worker"));
596 let w = search(
598 &store,
599 "Bar::Worker",
600 None,
601 None,
602 &ActiveFiles::default(),
603 10,
604 )
605 .unwrap();
606 assert_eq!(w[0].name, "Worker");
607 assert_eq!(w[0].parent.as_deref(), Some("Bar"));
608 }
609
610 fn hit(name: &str, in_scope: bool) -> Hit {
611 Hit {
612 name: name.into(),
613 kind: "method".into(),
614 language: "ruby".into(),
615 file: "a.rb".into(),
616 line: 1,
617 end_line: Some(1),
618 parent: None,
619 visibility: None,
620 repo_identity: "r".into(),
621 score: 1.0,
622 confidence: 0.0,
623 features: if in_scope {
624 vec![Feature {
625 name: "parent",
626 value: 180.0,
627 }]
628 } else {
629 vec![]
630 },
631 signature: None,
632 body: None,
633 }
634 }
635
636 #[test]
637 fn scope_gate_keeps_only_in_scope_results_when_some_match() {
638 let mut hits = vec![hit("baz", true), hit("baz", false), hit("baz", false)];
639 apply_scope_gate("Foo::Bar#baz", &mut hits);
640 assert_eq!(hits.len(), 1, "out-of-scope baz methods are dropped");
641 assert!(hits[0].features.iter().any(|f| f.name == "parent"));
642 }
643
644 #[test]
645 fn scope_gate_falls_back_when_nothing_matches_the_scope() {
646 let mut hits = vec![hit("baz", false), hit("baz", false)];
648 apply_scope_gate("Foo::Bar#baz", &mut hits);
649 assert_eq!(hits.len(), 2, "fall back rather than return empty");
650 }
651
652 #[test]
653 fn scope_gate_is_a_noop_for_an_unqualified_query() {
654 let mut hits = vec![hit("baz", true), hit("baz", false)];
655 apply_scope_gate("baz", &mut hits);
656 assert_eq!(hits.len(), 2, "no qualifier — nothing to gate on");
657 }
658
659 #[test]
660 fn branch_boost_lifts_an_active_file() {
661 let store = store_with(&[sym("User", Kind::Class)]); let active = ActiveFiles::new(["app/x.rb".to_string()]);
663 let hits = search(&store, "user", None, None, &active, 10).unwrap();
664 assert!(hits[0].features.iter().any(|f| f.name == "branch"));
665 }
666}