1use crate::graph::NodeId;
18use crate::lexicon::{stem, tokenize_identifier, Lexicon};
19use std::collections::{HashMap, HashSet};
20
21const MIN_NGRAM_LEN: usize = 2;
23
24const MAX_NGRAM_LEN: usize = 4;
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
29pub enum MatchKind {
30 Exact,
32 Substring,
34 AllTokens,
36 SomeTokens,
38 Concept,
40 Documentation,
42}
43
44impl MatchKind {
45 pub fn score(self) -> f32 {
47 match self {
48 MatchKind::Exact => 1.0,
49 MatchKind::Substring => 0.85,
50 MatchKind::AllTokens => 0.80,
51 MatchKind::SomeTokens => 0.55,
52 MatchKind::Concept => 0.45,
53 MatchKind::Documentation => 0.30,
54 }
55 }
56
57 pub fn label(self) -> &'static str {
59 match self {
60 MatchKind::Exact => "exact name",
61 MatchKind::Substring => "name contains query",
62 MatchKind::AllTokens => "all query words in name",
63 MatchKind::SomeTokens => "some query words in name",
64 MatchKind::Concept => "related concept",
65 MatchKind::Documentation => "mentioned in docs or path",
66 }
67 }
68
69 pub fn is_literal(self) -> bool {
71 matches!(self, MatchKind::Exact | MatchKind::Substring)
72 }
73}
74
75#[derive(Debug, Clone, PartialEq)]
77pub struct SearchHit {
78 pub id: NodeId,
79 pub kind: MatchKind,
80 pub score: f32,
81}
82
83#[derive(Debug, Default, Clone)]
85pub struct SearchIndex {
86 exact_index: HashMap<String, Vec<NodeId>>,
88 ngram_index: HashMap<String, HashSet<NodeId>>,
90 token_index: HashMap<String, HashSet<NodeId>>,
92 doc_token_index: HashMap<String, HashSet<NodeId>>,
94 name_by_id: HashMap<NodeId, String>,
101 lexicon: Lexicon,
102}
103
104impl SearchIndex {
105 pub fn new() -> Self {
106 Self::default()
107 }
108
109 pub fn insert(&mut self, name: &str, id: NodeId) {
111 let lower = name.to_lowercase();
112
113 self.exact_index.entry(lower.clone()).or_default().push(id);
114 self.name_by_id.insert(id, lower.clone());
115
116 for ngram in generate_ngrams(&lower) {
117 self.ngram_index.entry(ngram).or_default().insert(id);
118 }
119
120 for token in tokenize_identifier(name) {
121 self.token_index.entry(stem(&token)).or_default().insert(id);
122 }
123 }
124
125 pub fn insert_documentation(&mut self, text: &str, id: NodeId) {
132 for token in tokenize_identifier(text) {
133 self.doc_token_index
134 .entry(stem(&token))
135 .or_default()
136 .insert(id);
137 }
138 }
139
140 pub fn remove(&mut self, name: &str, id: NodeId) {
142 let lower = name.to_lowercase();
143
144 if let Some(ids) = self.exact_index.get_mut(&lower) {
145 ids.retain(|&x| x != id);
146 if ids.is_empty() {
147 self.exact_index.remove(&lower);
148 }
149 }
150 self.name_by_id.remove(&id);
151
152 for ngram in generate_ngrams(&lower) {
153 if let Some(ids) = self.ngram_index.get_mut(&ngram) {
154 ids.remove(&id);
155 if ids.is_empty() {
156 self.ngram_index.remove(&ngram);
157 }
158 }
159 }
160
161 for token in tokenize_identifier(name) {
162 let key = stem(&token);
163 if let Some(ids) = self.token_index.get_mut(&key) {
164 ids.remove(&id);
165 if ids.is_empty() {
166 self.token_index.remove(&key);
167 }
168 }
169 }
170
171 self.doc_token_index.retain(|_, ids| {
174 ids.remove(&id);
175 !ids.is_empty()
176 });
177 }
178
179 pub fn search(&self, query: &str) -> Vec<NodeId> {
183 let mut ids: Vec<NodeId> = self
184 .search_ranked(query)
185 .into_iter()
186 .filter(|hit| hit.kind.is_literal())
187 .map(|hit| hit.id)
188 .collect();
189 ids.sort();
190 ids.dedup();
191 ids
192 }
193
194 pub fn search_ranked(&self, query: &str) -> Vec<SearchHit> {
199 let query_lower = query.trim().to_lowercase();
200 if query_lower.is_empty() {
201 return Vec::new();
202 }
203
204 let mut best: HashMap<NodeId, MatchKind> = HashMap::new();
206 let record = |id: NodeId, kind: MatchKind, best: &mut HashMap<NodeId, MatchKind>| {
207 best.entry(id)
208 .and_modify(|existing| {
209 if kind < *existing {
210 *existing = kind;
211 }
212 })
213 .or_insert(kind);
214 };
215
216 if let Some(ids) = self.exact_index.get(&query_lower) {
218 for &id in ids {
219 record(id, MatchKind::Exact, &mut best);
220 }
221 }
222
223 for id in self.substring_candidates(&query_lower) {
224 record(id, MatchKind::Substring, &mut best);
225 }
226
227 let query_tokens: Vec<String> = tokenize_identifier(&query_lower);
229
230 if !query_tokens.is_empty() {
231 let stems: Vec<String> = query_tokens.iter().map(|t| stem(t)).collect();
232
233 let mut token_hits: HashMap<NodeId, usize> = HashMap::new();
235 for s in &stems {
236 if let Some(ids) = self.token_index.get(s) {
237 for &id in ids {
238 *token_hits.entry(id).or_insert(0) += 1;
239 }
240 }
241 }
242 for (id, hits) in token_hits {
243 let kind = if hits == stems.len() {
244 MatchKind::AllTokens
245 } else {
246 MatchKind::SomeTokens
247 };
248 record(id, kind, &mut best);
249 }
250
251 for token in &query_tokens {
254 for related in self.lexicon.expand(token) {
255 if &related == token {
256 continue;
257 }
258 if let Some(ids) = self.token_index.get(&stem(&related)) {
259 for &id in ids {
260 record(id, MatchKind::Concept, &mut best);
261 }
262 }
263 }
264 }
265
266 for s in &stems {
268 if let Some(ids) = self.doc_token_index.get(s) {
269 for &id in ids {
270 record(id, MatchKind::Documentation, &mut best);
271 }
272 }
273 }
274 }
275
276 let mut hits: Vec<SearchHit> = best
277 .into_iter()
278 .map(|(id, kind)| SearchHit {
279 id,
280 kind,
281 score: kind.score(),
282 })
283 .collect();
284
285 hits.sort_by(|a, b| {
286 b.score
287 .partial_cmp(&a.score)
288 .unwrap_or(std::cmp::Ordering::Equal)
289 .then_with(|| a.id.index().cmp(&b.id.index()))
290 });
291
292 hits
293 }
294
295 fn substring_candidates(&self, query_lower: &str) -> Vec<NodeId> {
297 if query_lower.len() < MIN_NGRAM_LEN {
298 let mut out: Vec<NodeId> = self
300 .exact_index
301 .iter()
302 .filter(|(name, _)| name.starts_with(query_lower))
303 .flat_map(|(_, ids)| ids.iter().copied())
304 .collect();
305 out.sort();
306 out.dedup();
307 return out;
308 }
309
310 let query_ngrams = generate_ngrams(query_lower);
311 if query_ngrams.is_empty() {
312 return Vec::new();
313 }
314
315 let mut candidates: Option<HashSet<NodeId>> = None;
316 for ngram in &query_ngrams {
317 let Some(ids) = self.ngram_index.get(ngram) else {
318 return Vec::new();
320 };
321 match &mut candidates {
322 None => candidates = Some(ids.clone()),
323 Some(c) => c.retain(|id| ids.contains(id)),
324 }
325 }
326
327 let mut out: Vec<NodeId> = candidates
330 .unwrap_or_default()
331 .into_iter()
332 .filter(|id| {
333 self.name_by_id
334 .get(id)
335 .is_some_and(|name| name.contains(query_lower))
336 })
337 .collect();
338 out.sort();
339 out
340 }
341
342 pub fn len(&self) -> usize {
344 self.exact_index.len()
345 }
346
347 pub fn is_empty(&self) -> bool {
348 self.exact_index.is_empty()
349 }
350}
351
352fn generate_ngrams(s: &str) -> Vec<String> {
354 let chars: Vec<char> = s.chars().collect();
355 let mut ngrams = Vec::new();
356
357 for n in MIN_NGRAM_LEN..=MAX_NGRAM_LEN {
358 if chars.len() >= n {
359 for i in 0..=(chars.len() - n) {
360 ngrams.push(chars[i..i + n].iter().collect());
361 }
362 }
363 }
364
365 ngrams
366}
367
368#[cfg(test)]
369mod tests {
370 use super::*;
371 use petgraph::graph::NodeIndex;
372
373 fn node_id(n: u32) -> NodeId {
374 NodeIndex::new(n as usize)
375 }
376
377 fn kind_of(hits: &[SearchHit], id: NodeId) -> Option<MatchKind> {
378 hits.iter().find(|h| h.id == id).map(|h| h.kind)
379 }
380
381 #[test]
384 fn test_insert_and_search_exact() {
385 let mut index = SearchIndex::new();
386 index.insert("validate_user", node_id(0));
387 index.insert("validate_email", node_id(1));
388 index.insert("send_email", node_id(2));
389
390 assert_eq!(index.search("validate_user"), vec![node_id(0)]);
391 }
392
393 #[test]
394 fn test_search_substring() {
395 let mut index = SearchIndex::new();
396 index.insert("validate_user", node_id(0));
397 index.insert("validate_email", node_id(1));
398 index.insert("send_email", node_id(2));
399
400 let results = index.search("validate");
401 assert!(results.contains(&node_id(0)));
402 assert!(results.contains(&node_id(1)));
403 assert!(!results.contains(&node_id(2)));
404 }
405
406 #[test]
407 fn test_search_case_insensitive() {
408 let mut index = SearchIndex::new();
409 index.insert("ValidateUser", node_id(0));
410
411 assert_eq!(index.search("validateuser"), vec![node_id(0)]);
412 assert_eq!(index.search("VALIDATEUSER"), vec![node_id(0)]);
413 }
414
415 #[test]
416 fn test_search_middle_substring() {
417 let mut index = SearchIndex::new();
418 index.insert("get_user_profile", node_id(0));
419
420 assert_eq!(index.search("user"), vec![node_id(0)]);
421 assert_eq!(index.search("_user_"), vec![node_id(0)]);
422 }
423
424 #[test]
425 fn test_remove_from_index() {
426 let mut index = SearchIndex::new();
427 index.insert("foo", node_id(0));
428 index.insert("foobar", node_id(1));
429
430 index.remove("foo", node_id(0));
431
432 let results = index.search("foo");
433 assert!(!results.contains(&node_id(0)));
434 assert!(results.contains(&node_id(1)));
435 }
436
437 #[test]
438 fn test_search_no_match() {
439 let mut index = SearchIndex::new();
440 index.insert("hello", node_id(0));
441 assert!(index.search("world").is_empty());
442 }
443
444 #[test]
445 fn test_short_query() {
446 let mut index = SearchIndex::new();
447 index.insert("ab", node_id(0));
448 index.insert("abc", node_id(1));
449 index.insert("xyz", node_id(2));
450
451 let results = index.search("a");
452 assert!(results.contains(&node_id(0)));
453 assert!(results.contains(&node_id(1)));
454 assert!(!results.contains(&node_id(2)));
455 }
456
457 #[test]
458 fn test_index_len_and_is_empty() {
459 let mut index = SearchIndex::new();
460 assert!(index.is_empty());
461 index.insert("foo", node_id(0));
462 index.insert("bar", node_id(1));
463 assert_eq!(index.len(), 2);
464 }
465
466 #[test]
467 fn test_duplicate_name_different_ids() {
468 let mut index = SearchIndex::new();
469 index.insert("process", node_id(0));
470 index.insert("process", node_id(1));
471
472 let results = index.search("process");
473 assert!(results.contains(&node_id(0)));
474 assert!(results.contains(&node_id(1)));
475 assert_eq!(index.len(), 1);
476 }
477
478 #[test]
479 fn test_remove_nonexistent_does_not_panic() {
480 let mut index = SearchIndex::new();
481 index.remove("nonexistent", node_id(99));
482 assert!(index.is_empty());
483 }
484
485 #[test]
486 fn test_search_empty_query() {
487 let mut index = SearchIndex::new();
488 index.insert("hello", node_id(0));
489 assert!(index.search("").is_empty());
490 }
491
492 #[test]
495 fn login_finds_get_authenticated() {
496 let mut index = SearchIndex::new();
499 index.insert("get_authenticated", node_id(0));
500 index.insert("render_chart", node_id(1));
501
502 assert!(
503 index.search("login").is_empty(),
504 "literal search genuinely cannot find this"
505 );
506
507 let hits = index.search_ranked("login");
508 assert_eq!(kind_of(&hits, node_id(0)), Some(MatchKind::Concept));
509 assert_eq!(kind_of(&hits, node_id(1)), None);
510 }
511
512 #[test]
513 fn security_query_reaches_the_auth_surface() {
514 let mut index = SearchIndex::new();
515 index.insert("verifyJwt", node_id(0));
516 index.insert("hashPassword", node_id(1));
517 index.insert("renderFooter", node_id(2));
518
519 let hits = index.search_ranked("credentials");
520 let found: Vec<NodeId> = hits.iter().map(|h| h.id).collect();
521
522 assert!(found.contains(&node_id(0)));
523 assert!(found.contains(&node_id(1)));
524 assert!(!found.contains(&node_id(2)));
525 }
526
527 #[test]
528 fn token_match_beats_concept_match() {
529 let mut index = SearchIndex::new();
530 index.insert("getUserProfile", node_id(0)); index.insert("get_authenticated", node_id(1)); let hits = index.search_ranked("user");
534 assert_eq!(hits.first().map(|h| h.id), Some(node_id(0)));
535 assert!(kind_of(&hits, node_id(0)).unwrap() < MatchKind::Concept);
536 }
537
538 #[test]
539 fn multi_word_query_prefers_full_coverage() {
540 let mut index = SearchIndex::new();
541 index.insert("getUserProfile", node_id(0));
542 index.insert("getUserSettings", node_id(1));
543 index.insert("deleteProfile", node_id(2));
544
545 let hits = index.search_ranked("user profile");
546 assert_eq!(kind_of(&hits, node_id(0)), Some(MatchKind::AllTokens));
547 assert_eq!(kind_of(&hits, node_id(1)), Some(MatchKind::SomeTokens));
548 assert_eq!(hits.first().map(|h| h.id), Some(node_id(0)));
549 }
550
551 #[test]
552 fn documentation_is_searchable() {
553 let mut index = SearchIndex::new();
554 index.insert("checkAccess", node_id(0));
555 index.insert_documentation(
556 "Validates the user's login credentials before granting access.",
557 node_id(0),
558 );
559 index.insert("renderChart", node_id(1));
560
561 let hits = index.search_ranked("login");
563 assert!(hits.iter().any(|h| h.id == node_id(0)));
564 assert!(!hits.iter().any(|h| h.id == node_id(1)));
565 }
566
567 #[test]
568 fn results_are_deterministic_and_ranked() {
569 let mut index = SearchIndex::new();
570 for i in 0..20u32 {
571 index.insert(&format!("authHandler{i}"), node_id(i));
572 }
573
574 let a = index.search_ranked("auth");
575 let b = index.search_ranked("auth");
576 assert_eq!(a, b, "repeat queries must return identical order");
577
578 for pair in a.windows(2) {
579 assert!(pair[0].score >= pair[1].score, "hits must be score-ordered");
580 }
581 }
582
583 #[test]
584 fn each_node_appears_once_under_its_best_kind() {
585 let mut index = SearchIndex::new();
586 index.insert("auth", node_id(0));
588 index.insert_documentation("auth auth auth", node_id(0));
589
590 let hits = index.search_ranked("auth");
591 assert_eq!(hits.iter().filter(|h| h.id == node_id(0)).count(), 1);
592 assert_eq!(hits[0].kind, MatchKind::Exact);
593 }
594
595 #[test]
596 fn unrelated_query_returns_nothing() {
597 let mut index = SearchIndex::new();
598 index.insert("renderChart", node_id(0));
599 assert!(index.search_ranked("payment").is_empty());
600 }
601
602 #[test]
603 fn match_kind_scores_are_ordered() {
604 assert!(MatchKind::Exact.score() > MatchKind::Substring.score());
605 assert!(MatchKind::Substring.score() > MatchKind::AllTokens.score());
606 assert!(MatchKind::AllTokens.score() > MatchKind::SomeTokens.score());
607 assert!(MatchKind::SomeTokens.score() > MatchKind::Concept.score());
608 assert!(MatchKind::Concept.score() > MatchKind::Documentation.score());
609 assert!(MatchKind::Exact.is_literal() && !MatchKind::Concept.is_literal());
610 }
611}