Skip to main content

subspace_core/
search.rs

1//! Item search over a dashboard's loaded documents (BM25F). Fields are
2//! scored separately and weighted;
3//! the last query word matches as a prefix while typing; documents that match
4//! more query words rank higher; a numeric query matches document numbers by
5//! prefix. No network and no dependency on the UI.
6
7use std::cmp::Ordering;
8use std::collections::{BTreeSet, HashMap};
9
10use unicode_normalization::UnicodeNormalization as _;
11
12const K1: f64 = 1.2;
13const B: f64 = 0.75;
14const FIELD_COUNT: usize = 3;
15const IDF_SMOOTHING: f64 = 0.5;
16const EXACT_NUMBER_BONUS: f64 = 100.0;
17const PREFIX_NUMBER_BONUS: f64 = 10.0;
18/// Weights of the `title`, `parent` and `meta` fields, in that order.
19const FIELD_WEIGHTS: [f64; FIELD_COUNT] = [1.0, 0.35, 0.5];
20const STOP_WORDS: &[&str] = &[
21    "a", "an", "and", "the", "of", "to", "in", "for", "with", "on", "or", "by", "is",
22];
23
24/// The number of results the palette shows (REQ-05).
25pub const MAX_RESULTS: usize = 8;
26
27/// Lower case with accents removed: NFKD, then combining marks dropped.
28pub fn fold(text: &str) -> String {
29    text.nfkd()
30        .filter(|c| !('\u{300}'..='\u{36f}').contains(c))
31        .flat_map(char::to_lowercase)
32        .collect()
33}
34
35/// Words of `text`: folded, split at anything but letters and digits, stop
36/// words removed.
37pub fn tokenize(text: &str) -> Vec<String> {
38    fold(text)
39        .split(|c: char| !c.is_alphanumeric())
40        .filter(|token| !token.is_empty() && !STOP_WORDS.contains(token))
41        .map(str::to_string)
42        .collect()
43}
44
45/// One searchable thing. Dashboards map their items to documents.
46#[derive(Debug, Clone, Default, PartialEq)]
47pub struct SearchDoc {
48    /// Unique within the index; ties rank by id, numbers compared as numbers.
49    pub id: String,
50    /// Matched by a numeric query (`1258950`, `#123`), such as a work item ID
51    /// or a pull request number.
52    pub number: Option<u64>,
53    pub title: String,
54    /// The parent's title: makes children findable, below the parent itself.
55    pub parent: String,
56    /// Type, state, people, labels.
57    pub meta: String,
58}
59
60// qual:allow(dry, boilerplate) reason: "Three small native setters preserve the public SearchDoc builder API; generating them would add a dependency without reducing meaningful complexity."
61impl SearchDoc {
62    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
63        Self {
64            id: id.into(),
65            title: title.into(),
66            ..Self::default()
67        }
68    }
69
70    pub fn number(mut self, number: u64) -> Self {
71        self.number = Some(number);
72        self
73    }
74
75    pub fn parent(mut self, parent: impl Into<String>) -> Self {
76        self.parent = parent.into();
77        self
78    }
79
80    pub fn meta(mut self, meta: impl Into<String>) -> Self {
81        self.meta = meta.into();
82        self
83    }
84
85    fn fields(&self) -> [&str; 3] {
86        [&self.title, &self.parent, &self.meta]
87    }
88}
89
90/// A match: the document's position in the index and its score.
91#[derive(Debug, Clone, Copy, PartialEq)]
92pub struct Hit {
93    pub index: usize,
94    pub score: f64,
95}
96
97struct Indexed {
98    terms: [HashMap<String, u32>; FIELD_COUNT],
99    lengths: [usize; FIELD_COUNT],
100}
101
102/// The index over a fixed set of documents. Build it again when they change.
103pub struct SearchIndex {
104    docs: Vec<SearchDoc>,
105    indexed: Vec<Indexed>,
106    average: [f64; FIELD_COUNT],
107    frequency: [HashMap<String, u32>; FIELD_COUNT],
108    vocabulary: BTreeSet<String>,
109}
110
111impl SearchIndex {
112    pub fn new(docs: Vec<SearchDoc>) -> Self {
113        let indexed: Vec<Indexed> = docs
114            .iter()
115            .map(|doc| {
116                let tokens = doc.fields().map(tokenize);
117                Indexed {
118                    lengths: [tokens[0].len(), tokens[1].len(), tokens[2].len()],
119                    terms: tokens.map(|tokens| {
120                        let mut counts = HashMap::new();
121                        for token in tokens {
122                            *counts.entry(token).or_insert(0) += 1;
123                        }
124                        counts
125                    }),
126                }
127            })
128            .collect();
129
130        let mut average = [1.0; FIELD_COUNT];
131        let mut frequency: [HashMap<String, u32>; FIELD_COUNT] = Default::default();
132        let mut vocabulary = BTreeSet::new();
133        for field in 0..FIELD_COUNT {
134            let total: usize = indexed.iter().map(|doc| doc.lengths[field]).sum();
135            let mean = total as f64 / indexed.len().max(1) as f64;
136            average[field] = if mean > 0.0 { mean } else { 1.0 };
137            for doc in &indexed {
138                for term in doc.terms[field].keys() {
139                    *frequency[field].entry(term.clone()).or_insert(0) += 1;
140                    vocabulary.insert(term.clone());
141                }
142            }
143        }
144        Self {
145            docs,
146            indexed,
147            average,
148            frequency,
149            vocabulary,
150        }
151    }
152
153    pub fn docs(&self) -> &[SearchDoc] {
154        &self.docs
155    }
156
157    pub fn is_empty(&self) -> bool {
158        self.docs.is_empty()
159    }
160
161    fn idf(&self, field: usize, term: &str) -> f64 {
162        let n = f64::from(self.frequency[field].get(term).copied().unwrap_or(0));
163        let count = self.docs.len() as f64;
164        (1.0 + (count - n + IDF_SMOOTHING) / (n + IDF_SMOOTHING)).ln()
165    }
166
167    fn term_score(&self, doc: &Indexed, term: &str) -> f64 {
168        let mut score = 0.0;
169        for (field, weight) in FIELD_WEIGHTS.iter().enumerate() {
170            let Some(&tf) = doc.terms[field].get(term) else {
171                continue;
172            };
173            let tf = f64::from(tf);
174            let norm = tf + K1 * (1.0 - B + B * doc.lengths[field] as f64 / self.average[field]);
175            score += weight * self.idf(field, term) * (tf * (K1 + 1.0)) / norm;
176        }
177        score
178    }
179
180    /// A query word stands for itself, or (the last word while typing, or a
181    /// word that is no term) for the terms it prefixes.
182    fn expand(&self, word: &str, is_last: bool) -> Vec<String> {
183        let exact = self.vocabulary.contains(word);
184        if exact && !is_last {
185            return vec![word.to_string()];
186        }
187        let prefixed: Vec<String> = self
188            .vocabulary
189            .range(word.to_string()..)
190            .take_while(|term| term.starts_with(word))
191            .cloned()
192            .collect();
193        match (prefixed.is_empty(), exact) {
194            (false, _) => prefixed,
195            (true, true) => vec![word.to_string()],
196            (true, false) => Vec::new(),
197        }
198    }
199
200    fn score_document(
201        &self,
202        index: usize,
203        expansions: &[Vec<String>],
204        word_count: usize,
205        id_query: Option<&str>,
206    ) -> Option<Hit> {
207        let doc = &self.indexed[index];
208        let mut score = 0.0;
209        let mut matched = 0usize;
210        for terms in expansions {
211            // The best expansion per word, so one prefix cannot add up many terms.
212            let best = terms
213                .iter()
214                .map(|term| self.term_score(doc, term))
215                .fold(0.0, f64::max);
216            matched += usize::from(best > 0.0);
217            score += best;
218        }
219        score *= (matched as f64 / word_count as f64).powi(2);
220        score += self.number_bonus(index, id_query);
221        (score > 0.0).then_some(Hit { index, score })
222    }
223
224    fn number_bonus(&self, index: usize, id_query: Option<&str>) -> f64 {
225        let Some(id) = id_query else {
226            return 0.0;
227        };
228        let Some(number) = self.docs[index].number else {
229            return 0.0;
230        };
231        let number = number.to_string();
232        if !number.starts_with(id) {
233            return 0.0;
234        }
235        if number == id {
236            EXACT_NUMBER_BONUS
237        } else {
238            PREFIX_NUMBER_BONUS
239        }
240    }
241
242    /// The best `limit` matches for `query`, best first.
243    pub fn search(&self, query: &str, limit: usize) -> Vec<Hit> {
244        let words = tokenize(query);
245        if words.is_empty() {
246            return Vec::new();
247        }
248        let last_is_prefix = !query.ends_with(char::is_whitespace);
249        let expansions: Vec<Vec<String>> = words
250            .iter()
251            .enumerate()
252            .map(|(i, word)| self.expand(word, last_is_prefix && i == words.len() - 1))
253            .collect();
254        let trimmed = query.trim();
255        let digits = trimmed.strip_prefix('#').unwrap_or(trimmed);
256        let id_query =
257            (!digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())).then_some(digits);
258
259        let mut hits: Vec<Hit> = self
260            .indexed
261            .iter()
262            .enumerate()
263            .filter_map(|(index, _)| self.score_document(index, &expansions, words.len(), id_query))
264            .collect();
265        hits.sort_by(|a, b| {
266            b.score
267                .total_cmp(&a.score)
268                .then_with(|| natural_cmp(&self.docs[a.index].id, &self.docs[b.index].id))
269        });
270        hits.truncate(limit);
271        hits
272    }
273}
274
275/// Compares text with runs of digits as numbers (`localeCompare` with
276/// `numeric: true`, without the locale).
277pub fn natural_cmp(a: &str, b: &str) -> Ordering {
278    let mut a = a.chars().peekable();
279    let mut b = b.chars().peekable();
280    loop {
281        match (a.peek().copied(), b.peek().copied()) {
282            (None, None) => return Ordering::Equal,
283            (None, Some(_)) => return Ordering::Less,
284            (Some(_), None) => return Ordering::Greater,
285            (Some(x), Some(y)) if x.is_ascii_digit() && y.is_ascii_digit() => {
286                let take = |it: &mut std::iter::Peekable<std::str::Chars<'_>>| {
287                    let mut run = String::new();
288                    while let Some(c) = it.next_if(char::is_ascii_digit) {
289                        run.push(c);
290                    }
291                    run
292                };
293                let (x, y) = (take(&mut a), take(&mut b));
294                let (xt, yt) = (x.trim_start_matches('0'), y.trim_start_matches('0'));
295                let order = xt.len().cmp(&yt.len()).then_with(|| xt.cmp(yt));
296                if order != Ordering::Equal {
297                    return order;
298                }
299            }
300            (Some(x), Some(y)) => {
301                let order = x
302                    .to_lowercase()
303                    .cmp(y.to_lowercase())
304                    .then_with(|| x.cmp(&y));
305                if order != Ordering::Equal {
306                    return order;
307                }
308                a.next();
309                b.next();
310            }
311        }
312    }
313}
314
315#[cfg(test)]
316mod tests {
317    use super::{SearchDoc, SearchIndex, natural_cmp, tokenize};
318
319    /// Invented items, mapped as a board maps its items: the short title,
320    /// the parent's short title, and type, state and person.
321    fn index() -> SearchIndex {
322        let doc = |id: u64, title: &str, parent: &str, kind: &str, state: &str| {
323            SearchDoc::new(id.to_string(), title)
324                .number(id)
325                .parent(parent)
326                .meta(format!("{kind} {state} Doe, Jane"))
327        };
328        SearchIndex::new(vec![
329            doc(
330                1204258,
331                "Write the crew onboarding guide for the job board",
332                "",
333                "Product Backlog Item",
334                "New",
335            ),
336            doc(
337                1204302,
338                "Add a reader role to the sample module",
339                "Write the crew onboarding guide for the job board",
340                "Task",
341                "To Do",
342            ),
343            doc(
344                1258950,
345                "Plan the job route for the harbour demo",
346                "",
347                "Task",
348                "Done",
349            ),
350            doc(1259313, "Tidy the sample lint rules", "", "Task", "To Do"),
351        ])
352    }
353
354    fn ids(index: &SearchIndex, query: &str) -> Vec<String> {
355        index
356            .search(query, 20)
357            .into_iter()
358            .map(|hit| index.docs()[hit.index].id.clone())
359            .collect()
360    }
361
362    #[test]
363    fn tokenize_lowercases_strips_accents_and_stop_words() {
364        assert_eq!(
365            tokenize("The Café-Onboarding of Ops"),
366            ["cafe", "onboarding", "ops"]
367        );
368        assert_eq!(
369            tokenize("file Wide"),
370            ["file", "wide"],
371            "NFKD folds compatibility forms"
372        );
373    }
374
375    #[test]
376    fn the_last_word_matches_as_a_prefix_while_typing() {
377        let index = index();
378        assert_eq!(ids(&index, "onbo")[0], "1204258");
379        // "job" is a whole term, so it matches exactly, not as a prefix;
380        // matching both words (the child through its parent's title) outranks
381        // matching one.
382        assert_eq!(ids(&index, "job onbo"), ["1204258", "1204302", "1258950"]);
383    }
384
385    #[test]
386    fn parent_titles_make_children_findable_below_the_parent() {
387        assert_eq!(ids(&index(), "onboarding"), ["1204258", "1204302"]);
388    }
389
390    #[test]
391    fn items_matching_more_words_rank_first() {
392        assert_eq!(ids(&index(), "harbour route")[0], "1258950");
393    }
394
395    #[test]
396    fn numbers_match_ids_by_prefix_and_exact_ids_rank_first() {
397        let index = index();
398        assert_eq!(ids(&index, "1258950")[0], "1258950");
399        assert_eq!(ids(&index, "#1258950")[0], "1258950");
400        assert_eq!(ids(&index, "12043"), ["1204302"]);
401    }
402
403    #[test]
404    fn empty_queries_return_nothing_and_the_limit_holds() {
405        let index = index();
406        assert!(ids(&index, "  ").is_empty());
407        assert!(ids(&index, "the of").is_empty());
408        assert_eq!(index.search("task", 2).len(), 2);
409    }
410
411    #[test]
412    fn ids_compare_numbers_as_numbers() {
413        use std::cmp::Ordering::Less;
414        assert_eq!(natural_cmp("item-9", "item-10"), Less);
415        assert_eq!(natural_cmp("a", "B"), Less);
416    }
417}