1use std::collections::{HashMap, HashSet};
16
17use crate::records::Fact;
18
19const KEY_FIELD_WEIGHT: f32 = 3.0;
22
23pub fn tokenize(text: &str) -> Vec<String> {
27 text.split(|c: char| !c.is_alphanumeric())
28 .filter(|t| t.chars().count() >= 2)
29 .map(str::to_lowercase)
30 .collect()
31}
32
33const MAX_PHRASE_PINS: usize = 5;
37
38fn word_sequence(text: &str) -> Vec<String> {
41 text.split(|c: char| !c.is_alphanumeric())
42 .filter(|t| !t.is_empty())
43 .map(str::to_lowercase)
44 .collect()
45}
46
47fn contains_word_run(words: &[String], phrase: &[String]) -> bool {
49 !phrase.is_empty() && words.windows(phrase.len()).any(|window| window == phrase)
50}
51
52fn fold_phrase(text: &str) -> String {
54 text.to_lowercase()
55 .replace(['_', '-'], " ")
56 .split_whitespace()
57 .collect::<Vec<_>>()
58 .join(" ")
59}
60
61struct IndexedFact {
62 key_tokens: HashSet<String>,
63 other_tokens: HashSet<String>,
64 folded_key: String,
65 key_words: Vec<String>,
66 value_words: Vec<String>,
67 updated_at: chrono::DateTime<chrono::Utc>,
68 id: i64,
69}
70
71#[derive(Debug, Clone, Copy, PartialEq)]
74pub struct LexicalHit {
75 pub index: usize,
76 pub score: f32,
77 pub pinned: bool,
78}
79
80pub struct LexicalIndex {
82 facts: Vec<IndexedFact>,
83 document_frequency: HashMap<String, usize>,
84}
85
86impl LexicalIndex {
87 pub fn build(facts: &[Fact]) -> Self {
88 let mut document_frequency: HashMap<String, usize> = HashMap::new();
89 let facts: Vec<IndexedFact> = facts
90 .iter()
91 .map(|fact| {
92 let key_tokens: HashSet<String> = tokenize(&fact.key).into_iter().collect();
93 let other_tokens: HashSet<String> = tokenize(&fact.value)
94 .into_iter()
95 .chain(tokenize(&fact.category))
96 .collect();
97 for token in key_tokens.union(&other_tokens) {
98 *document_frequency.entry(token.clone()).or_default() += 1;
99 }
100 IndexedFact {
101 key_tokens,
102 other_tokens,
103 folded_key: fold_phrase(&fact.key),
104 key_words: word_sequence(&fact.key),
105 value_words: word_sequence(&fact.value),
106 updated_at: fact.updated_at,
107 id: fact.id,
108 }
109 })
110 .collect();
111 Self {
112 facts,
113 document_frequency,
114 }
115 }
116
117 fn idf(&self, token: &str) -> f32 {
118 let n = self.facts.len() as f32;
119 let df = self.document_frequency.get(token).copied().unwrap_or(0) as f32;
120 (1.0 + (n - df + 0.5) / (df + 0.5)).ln()
121 }
122
123 pub fn score(&self, query: &str) -> Vec<LexicalHit> {
127 let mut seen = HashSet::new();
128 let terms: Vec<(String, f32)> = tokenize(query)
129 .into_iter()
130 .filter(|t| seen.insert(t.clone()))
131 .map(|t| {
132 let idf = self.idf(&t);
133 (t, idf)
134 })
135 .collect();
136 let phrase = fold_phrase(query);
137 let phrase_words = word_sequence(query);
138 let multi_word = phrase_words.len() >= 2;
139
140 let mut matches: Vec<(LexicalHit, bool)> = self
141 .facts
142 .iter()
143 .enumerate()
144 .filter_map(|(index, fact)| {
145 let score: f32 = terms
146 .iter()
147 .map(|(term, idf)| {
148 if fact.key_tokens.contains(term) {
149 idf * KEY_FIELD_WEIGHT
150 } else if fact.other_tokens.contains(term) {
151 *idf
152 } else {
153 0.0
154 }
155 })
156 .sum();
157 let exact_key = !phrase.is_empty() && fact.folded_key == phrase;
158 let phrase_pin = !exact_key
160 && multi_word
161 && (contains_word_run(&fact.key_words, &phrase_words)
162 || contains_word_run(&fact.value_words, &phrase_words));
163 (score > 0.0 || exact_key || phrase_pin).then_some((
164 LexicalHit {
165 index,
166 score,
167 pinned: exact_key || phrase_pin,
168 },
169 exact_key,
170 ))
171 })
172 .collect();
173 matches.sort_by(|(a, _), (b, _)| {
175 b.score
176 .total_cmp(&a.score)
177 .then_with(|| self.tie_order(a.index, b.index))
178 });
179 let mut phrase_pins = 0usize;
180 for (hit, exact_key) in &mut matches {
181 if hit.pinned && !*exact_key {
182 phrase_pins += 1;
183 if phrase_pins > MAX_PHRASE_PINS {
184 hit.pinned = false;
185 }
186 }
187 }
188 let mut hits: Vec<LexicalHit> = matches
189 .into_iter()
190 .map(|(hit, _)| hit)
191 .filter(|hit| hit.pinned || hit.score > 0.0)
192 .collect();
193 hits.sort_by(|a, b| {
194 b.pinned
195 .cmp(&a.pinned)
196 .then(b.score.total_cmp(&a.score))
197 .then_with(|| self.tie_order(a.index, b.index))
198 });
199 hits
200 }
201
202 fn tie_order(&self, a: usize, b: usize) -> std::cmp::Ordering {
204 let (a, b) = (&self.facts[a], &self.facts[b]);
205 b.updated_at.cmp(&a.updated_at).then(a.id.cmp(&b.id))
206 }
207}
208
209#[derive(Debug, Clone, PartialEq)]
211pub struct FactSearchConfig {
212 pub lexical_pool: usize,
214 pub semantic_pool: usize,
216 pub semantic_min_cosine: f32,
218 pub rrf_k: f32,
220 pub related_max: usize,
222 pub related_pool: usize,
224}
225
226impl Default for FactSearchConfig {
227 fn default() -> Self {
228 Self {
229 lexical_pool: 25,
230 semantic_pool: 25,
231 semantic_min_cosine: 0.22,
232 rrf_k: 60.0,
233 related_max: 5,
234 related_pool: 30,
235 }
236 }
237}
238
239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
241pub enum MatchKind {
242 Exact,
244 Lexical,
245 Semantic,
246 Both,
247}
248
249#[derive(Debug, Clone)]
250pub struct SearchHit {
251 pub fact: Fact,
252 pub score: f32,
254 pub kind: MatchKind,
255}
256
257#[derive(Debug, Clone, Default)]
259pub struct FactSearchReport {
260 pub hits: Vec<SearchHit>,
262 pub related: Vec<SearchHit>,
264 pub considered: usize,
266}
267
268#[derive(Debug, Clone, Copy, PartialEq, Eq)]
270pub struct Candidate {
271 pub index: usize,
273 pub lexical_rank: Option<usize>,
274 pub semantic_rank: Option<usize>,
275 pub pinned: bool,
276}
277
278pub fn candidates(
286 facts: &[Fact],
287 lexical: &[LexicalHit],
288 cosine: &[(usize, f32)],
289 cfg: &FactSearchConfig,
290) -> Vec<Candidate> {
291 let mut nominated: Vec<Candidate> = Vec::new();
292 let mut unpinned = 0usize;
293 for (rank, hit) in lexical.iter().enumerate() {
294 if !hit.pinned {
295 if unpinned >= cfg.lexical_pool {
296 continue;
297 }
298 unpinned += 1;
299 }
300 nominated.push(Candidate {
301 index: hit.index,
302 lexical_rank: Some(rank + 1),
303 semantic_rank: None,
304 pinned: hit.pinned,
305 });
306 }
307
308 let mut semantic: Vec<(usize, f32)> = cosine
309 .iter()
310 .copied()
311 .filter(|(_, score)| *score > cfg.semantic_min_cosine)
312 .collect();
313 semantic.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0)));
314 semantic.truncate(cfg.semantic_pool);
315 for (rank, (index, _)) in semantic.into_iter().enumerate() {
316 nominated.push(Candidate {
317 index,
318 lexical_rank: None,
319 semantic_rank: Some(rank + 1),
320 pinned: false,
321 });
322 }
323
324 type Identity<'a> = (&'a str, &'a str, &'a str);
326 let mut by_id: HashMap<i64, usize> = HashMap::new();
327 let mut by_content: HashMap<Identity, usize> = HashMap::new();
328 let mut pool: Vec<Candidate> = Vec::new();
329 for candidate in nominated {
330 let fact = &facts[candidate.index];
331 let content = (
332 fact.category.as_str(),
333 fact.key.as_str(),
334 fact.value.as_str(),
335 );
336 let existing = by_id
337 .get(&fact.id)
338 .or_else(|| by_content.get(&content))
339 .copied();
340 let slot = match existing {
341 Some(slot) => {
342 let kept = &mut pool[slot];
343 kept.lexical_rank = min_rank(kept.lexical_rank, candidate.lexical_rank);
344 kept.semantic_rank = min_rank(kept.semantic_rank, candidate.semantic_rank);
345 kept.pinned |= candidate.pinned;
346 if facts[kept.index].id <= 0 && fact.id > 0 {
347 kept.index = candidate.index;
348 }
349 slot
350 }
351 None => {
352 pool.push(candidate);
353 pool.len() - 1
354 }
355 };
356 by_id.insert(fact.id, slot);
357 by_content.insert(content, slot);
358 }
359 pool
360}
361
362fn min_rank(a: Option<usize>, b: Option<usize>) -> Option<usize> {
363 match (a, b) {
364 (Some(a), Some(b)) => Some(a.min(b)),
365 (a, b) => a.or(b),
366 }
367}
368
369pub fn rank(
372 facts: &[Fact],
373 candidates: &[Candidate],
374 limit: usize,
375 cfg: &FactSearchConfig,
376) -> FactSearchReport {
377 let mut scored: Vec<(&Candidate, f32)> = candidates
378 .iter()
379 .map(|candidate| (candidate, rrf_score(candidate, cfg.rrf_k)))
380 .collect();
381 scored.sort_by(|(a, a_score), (b, b_score)| {
382 b.pinned
383 .cmp(&a.pinned)
384 .then(b_score.total_cmp(a_score))
385 .then_with(|| newest_first(&facts[a.index], &facts[b.index]))
386 });
387 let hits = scored
388 .into_iter()
389 .take(limit)
390 .map(|(candidate, score)| SearchHit {
391 fact: facts[candidate.index].clone(),
392 score,
393 kind: match (
394 candidate.pinned,
395 candidate.lexical_rank,
396 candidate.semantic_rank,
397 ) {
398 (true, _, _) => MatchKind::Exact,
399 (false, Some(_), Some(_)) => MatchKind::Both,
400 (false, None, Some(_)) => MatchKind::Semantic,
401 (false, _, None) => MatchKind::Lexical,
402 },
403 })
404 .collect();
405 FactSearchReport {
406 hits,
407 related: Vec::new(),
408 considered: candidates.len(),
409 }
410}
411
412pub fn rank_related(
419 neighbors: &[&Fact],
420 scores: &[(usize, f32)],
421 cfg: &FactSearchConfig,
422) -> Vec<SearchHit> {
423 let mut seen = HashSet::new();
424 let mut scored: Vec<(&Fact, f32)> = scores
425 .iter()
426 .filter(|(position, _)| seen.insert(*position))
427 .filter_map(|(position, score)| neighbors.get(*position).map(|f| (*f, *score)))
428 .collect();
429 scored.sort_by(|(a, a_score), (b, b_score)| {
430 b_score
431 .total_cmp(a_score)
432 .then(b.recall_count.cmp(&a.recall_count))
433 .then(a.id.cmp(&b.id))
434 });
435 scored
436 .into_iter()
437 .take(cfg.related_max)
438 .map(|(fact, score)| SearchHit {
439 fact: fact.clone(),
440 score,
441 kind: MatchKind::Semantic,
442 })
443 .collect()
444}
445
446fn rrf_score(candidate: &Candidate, k: f32) -> f32 {
447 [candidate.lexical_rank, candidate.semantic_rank]
448 .into_iter()
449 .flatten()
450 .map(|rank| 1.0 / (k + rank as f32))
451 .sum()
452}
453
454fn newest_first(a: &Fact, b: &Fact) -> std::cmp::Ordering {
455 b.updated_at.cmp(&a.updated_at).then(a.id.cmp(&b.id))
456}
457
458#[cfg(test)]
459mod tests {
460 use super::*;
461 use crate::search_fixture::{self as fx, corpus};
462
463 fn ids(facts: &[Fact], hits: &[LexicalHit]) -> Vec<i64> {
464 hits.iter().map(|h| facts[h.index].id).collect()
465 }
466
467 #[test]
468 fn rare_term_outranks_common_terms() {
469 let facts = corpus();
470 let hits = LexicalIndex::build(&facts).score("staging deploy port");
471 assert!(hits.len() >= 61, "{} hits", hits.len());
472 assert_eq!(facts[hits[0].index].id, fx::STAGING_DEPLOY_PORT);
473 }
474
475 #[test]
476 fn ties_do_not_fall_back_to_category_order() {
477 let facts = corpus();
478 let hits = LexicalIndex::build(&facts).score("deploy staging");
479 let flood: Vec<&LexicalHit> = hits
480 .iter()
481 .filter(|h| fx::TIE_FLOOD.contains(&facts[h.index].id))
482 .collect();
483 assert_eq!(flood.len(), 60);
484 assert!(flood.windows(2).all(|w| w[0].score == w[1].score));
485 assert!(
486 flood
487 .windows(2)
488 .all(|w| facts[w[0].index].updated_at > facts[w[1].index].updated_at)
489 );
490 }
491
492 #[test]
493 fn synonym_list_keeps_single_word_answer() {
494 let facts = corpus();
495 let hits = LexicalIndex::build(&facts).score("spouse partner wife");
496 assert_eq!(ids(&facts, &hits).first(), Some(&fx::PARTNER_NAME));
497 }
498
499 #[test]
500 fn word_boundary_not_substring() {
501 let facts = vec![
502 fx::fact(1, "general", "monthly_report", "sent on Fridays", 0),
503 fx::fact(2, "general", "important_note", "support is closed", 0),
504 ];
505 assert!(LexicalIndex::build(&facts).score("port").is_empty());
506 }
507
508 #[test]
509 fn exact_key_is_pinned() {
510 let facts = corpus();
511 let index = LexicalIndex::build(&facts);
512 let hits = index.score("staging deploy port");
513 assert!(hits[0].pinned);
514 assert_eq!(facts[hits[0].index].id, fx::STAGING_DEPLOY_PORT);
515 assert!(hits[1..].iter().all(|h| !h.pinned));
516
517 let hits = index.score("partner name");
518 assert!(hits[0].pinned);
519 assert_eq!(facts[hits[0].index].id, fx::PARTNER_NAME);
520 }
521
522 fn lexical(index: usize, pinned: bool) -> LexicalHit {
523 LexicalHit {
524 index,
525 score: 1.0,
526 pinned,
527 }
528 }
529
530 fn filler(n: usize) -> Vec<Fact> {
531 (0..n as i64)
532 .map(|i| {
533 fx::fact(
534 i + 1,
535 "general",
536 &format!("item_{i}"),
537 &format!("value {i}"),
538 0,
539 )
540 })
541 .collect()
542 }
543
544 fn hit_ids(report: &FactSearchReport) -> Vec<i64> {
545 report.hits.iter().map(|h| h.fact.id).collect()
546 }
547
548 #[test]
549 fn lexical_flood_does_not_hide_semantic() {
550 let facts = filler(65);
551 let cfg = FactSearchConfig::default();
552 let lex: Vec<LexicalHit> = (0..60).map(|i| lexical(i, false)).collect();
553 let cosine: Vec<(usize, f32)> = (60..65).map(|i| (i, 0.5)).collect();
554 let pool = candidates(&facts, &lex, &cosine, &cfg);
555 assert_eq!(pool.len(), 30, "lexical capped at 25, plus 5 semantic");
556 let report = rank(&facts, &pool, 10, &cfg);
557 let ids = hit_ids(&report);
558 for i in 61..=65 {
559 assert!(ids.contains(&i), "semantic-only fact {i} hidden: {ids:?}");
560 }
561 assert_eq!(report.considered, 30);
562 }
563
564 #[test]
565 fn pinned_leads_whatever_its_fusion_score() {
566 let facts = filler(5);
567 let cfg = FactSearchConfig::default();
568 let lex = vec![lexical(0, false), lexical(1, false), lexical(3, true)];
569 let cosine = vec![(0, 0.9), (1, 0.8)];
570 let pool = candidates(&facts, &lex, &cosine, &cfg);
571 let report = rank(&facts, &pool, 10, &cfg);
572 assert_eq!(hit_ids(&report), vec![4, 1, 2]);
573 assert_eq!(report.hits[0].kind, MatchKind::Exact);
574 }
575
576 #[test]
577 fn fusion_orders_by_both_ranks() {
578 let facts = filler(3);
579 let cfg = FactSearchConfig::default();
580 let lex = vec![lexical(0, false), lexical(1, false)];
583 let cosine = vec![(1, 0.9), (2, 0.8)];
584 let pool = candidates(&facts, &lex, &cosine, &cfg);
585 let report = rank(&facts, &pool, 10, &cfg);
586 assert_eq!(hit_ids(&report), vec![2, 1, 3]);
587 assert_eq!(report.hits[0].kind, MatchKind::Both);
588 }
589
590 #[test]
591 fn no_vectors_is_lexical_only() {
592 let facts = corpus();
593 let cfg = FactSearchConfig::default();
594 let lex = LexicalIndex::build(&facts).score("deploy staging");
595 let pool = candidates(&facts, &lex, &[], &cfg);
596 let report = rank(&facts, &pool, 20, &cfg);
597 let expected: Vec<i64> = lex.iter().take(20).map(|h| facts[h.index].id).collect();
598 assert_eq!(hit_ids(&report), expected);
599 }
600
601 #[test]
602 fn duplicate_projection_collapses() {
603 let facts = corpus();
604 let cfg = FactSearchConfig::default();
605 let lex = LexicalIndex::build(&facts).score("home city");
606 let cosine: Vec<(usize, f32)> = facts
607 .iter()
608 .enumerate()
609 .map(|(i, f)| (i, fx::fake_cosine("home city", f)))
610 .collect();
611 let pool = candidates(&facts, &lex, &cosine, &cfg);
612 let report = rank(&facts, &pool, 10, &cfg);
613 let ids = hit_ids(&report);
614 assert!(ids.contains(&fx::HOME_CITY), "{ids:?}");
615 assert!(!ids.contains(&fx::HOME_CITY_PROJECTION), "{ids:?}");
616 }
617
618 #[test]
619 fn hot_cluster_does_not_win_on_recall_count() {
620 let facts = corpus();
621 let cfg = FactSearchConfig::default();
622 let neighbors: Vec<&Fact> = facts
623 .iter()
624 .filter(|f| fx::HOT_CLUSTER.contains(&f.id) || f.id == fx::FATHER_NAME)
625 .collect();
626 let scores: Vec<(usize, f32)> = neighbors
627 .iter()
628 .enumerate()
629 .map(|(p, f)| (p, if f.id == fx::FATHER_NAME { 0.4 } else { -1.0 }))
630 .collect();
631 let related = rank_related(&neighbors, &scores, &cfg);
632 assert_eq!(related[0].fact.id, fx::FATHER_NAME);
633 }
634
635 #[test]
636 fn related_is_capped() {
637 let facts = filler(30);
638 let cfg = FactSearchConfig::default();
639 let neighbors: Vec<&Fact> = facts.iter().collect();
640 let scores: Vec<(usize, f32)> = (0..30).map(|p| (p, 0.5 + p as f32 / 100.0)).collect();
641 let related = rank_related(&neighbors, &scores, &cfg);
642 assert_eq!(related.len(), 5);
643 assert_eq!(related[0].fact.id, 30, "best score first");
644 }
645
646 #[test]
647 fn related_ties_break_on_recall_count() {
648 let a = fx::fact(1, "user", "a", "x", 2);
649 let b = fx::fact(2, "user", "b", "x", 9);
650 let neighbors = vec![&a, &b];
651 let related = rank_related(
652 &neighbors,
653 &[(0, 0.5), (1, 0.5)],
654 &FactSearchConfig::default(),
655 );
656 assert_eq!(related[0].fact.id, 2);
657 }
658
659 #[test]
660 fn single_word_is_never_a_phrase_match() {
661 let facts = vec![fx::fact(1, "general", "notes", "the report is late", 0)];
662 let hits = LexicalIndex::build(&facts).score("report");
663 assert_eq!(hits.len(), 1);
664 assert!(!hits[0].pinned);
665 }
666
667 #[test]
668 fn phrase_pin_matches_whole_words_only() {
669 let facts = vec![
670 fx::fact(1, "notes", "schedule", "report 8080 daily", 0),
671 fx::fact(2, "project", "web_port", "port 80 is open", 0),
672 ];
673 let hits = LexicalIndex::build(&facts).score("port 80");
674 let pinned: Vec<usize> = hits.iter().filter(|h| h.pinned).map(|h| h.index).collect();
675 assert_eq!(pinned, vec![1]);
676 assert!(
677 hits.iter().all(|h| h.index != 0),
678 "`report 8080` shares no word with `port 80`"
679 );
680 }
681
682 #[test]
683 fn phrase_pins_are_capped_but_exact_keys_are_not() {
684 let mut facts: Vec<Fact> = (0..40)
685 .map(|i| {
686 fx::fact(
687 i,
688 "notes",
689 &format!("note_{i}"),
690 "a new blog post went out",
691 0,
692 )
693 })
694 .collect();
695 facts.push(fx::fact(100, "project", "blog_post", "weekly", 0));
696 let hits = LexicalIndex::build(&facts).score("blog post");
697 let pinned: Vec<&LexicalHit> = hits.iter().filter(|h| h.pinned).collect();
698 assert_eq!(pinned.len(), MAX_PHRASE_PINS + 1);
699 assert!(pinned.iter().any(|h| facts[h.index].id == 100));
700 assert_eq!(hits.len(), 41, "unpinned phrase matches still score");
701 }
702}