airust 0.5.2

A modular Rust knowledge engine: lexical search, text matching, optional semantic retrieval and reranking
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
#![doc = include_str!("../docs/TEXT-SEARCH.md")]

use crate::{
    index::validate_entry, text, Context, Engine, IndexError, IndexStats, KnowledgeEntry,
    SearchOptions,
};
use rust_stemmers::{Algorithm, Stemmer};
use serde::Serialize;
use std::collections::{BTreeMap, BTreeSet};
use thiserror::Error;
use unicode_normalization::char::is_combining_mark;
use unicode_segmentation::UnicodeSegmentation;

#[derive(Debug, Error)]
#[non_exhaustive]
pub enum TextSearchError {
    #[cfg(feature = "execution")]
    #[error(transparent)]
    Execution(#[from] crate::execution::ExecutionError),
    #[error("invalid text search configuration: {0}")]
    Configuration(&'static str),
    #[error("text search limit exceeded: {0}")]
    Limit(&'static str),
    #[error("invalid text query: {0}")]
    Query(&'static str),
    #[error(transparent)]
    Index(#[from] IndexError),
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub enum WordTokenizer {
    #[default]
    UnicodeWords,
    Alphanumeric,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub enum Stemming {
    #[default]
    None,
    German,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnalyzerConfig {
    tokenizer: WordTokenizer,
    stemming: Stemming,
    fold_apostrophes: bool,
    max_input_bytes: usize,
    max_normalized_bytes: usize,
    max_tokens: usize,
}
impl Default for AnalyzerConfig {
    fn default() -> Self {
        Self {
            tokenizer: WordTokenizer::UnicodeWords,
            stemming: Stemming::None,
            fold_apostrophes: true,
            max_input_bytes: 1024 * 1024,
            max_normalized_bytes: 4 * 1024 * 1024,
            max_tokens: 100_000,
        }
    }
}
impl AnalyzerConfig {
    pub fn german() -> Self {
        Self {
            stemming: Stemming::German,
            ..Self::default()
        }
    }
    pub fn with_tokenizer(mut self, tokenizer: WordTokenizer) -> Self {
        self.tokenizer = tokenizer;
        self
    }
    pub fn with_stemming(mut self, stemming: Stemming) -> Self {
        self.stemming = stemming;
        self
    }
    pub fn with_apostrophe_folding(mut self, enabled: bool) -> Self {
        self.fold_apostrophes = enabled;
        self
    }
    pub fn with_limits(
        mut self,
        input_bytes: usize,
        normalized_bytes: usize,
        tokens: usize,
    ) -> Result<Self, TextSearchError> {
        if input_bytes == 0 || normalized_bytes == 0 || tokens == 0 {
            return Err(TextSearchError::Configuration(
                "analysis limits must be positive",
            ));
        }
        self.max_input_bytes = input_bytes;
        self.max_normalized_bytes = normalized_bytes;
        self.max_tokens = tokens;
        Ok(self)
    }
    pub fn tokenizer(&self) -> WordTokenizer {
        self.tokenizer
    }
    pub fn stemming(&self) -> Stemming {
        self.stemming
    }
    pub fn folds_apostrophes(&self) -> bool {
        self.fold_apostrophes
    }
    pub fn max_input_bytes(&self) -> usize {
        self.max_input_bytes
    }
    pub fn max_normalized_bytes(&self) -> usize {
        self.max_normalized_bytes
    }
    pub fn max_tokens(&self) -> usize {
        self.max_tokens
    }
    pub fn recipe(&self) -> String {
        format!("airust-text-v1/nfkc-lower-nfkc/graphemes/unicode-{:?}-{:?}-{:?}/words-1.13.3/{:?}/stem-1.2.0-{:?}/apostrophes-{}",char::UNICODE_VERSION,unicode_normalization::UNICODE_VERSION,unicode_segmentation::UNICODE_VERSION,self.tokenizer,self.stemming,self.fold_apostrophes)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct TextSpan {
    pub start: usize,
    pub end: usize,
}
impl TextSpan {
    pub fn slice<'a>(&self, text: &'a str) -> Option<&'a str> {
        text.get(self.start..self.end)
    }
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Token {
    pub term: String,
    pub position: usize,
    pub span: TextSpan,
}

pub struct TextAnalyzer {
    config: AnalyzerConfig,
    stemmer: Option<Stemmer>,
}
impl TextAnalyzer {
    pub fn new(config: AnalyzerConfig) -> Self {
        let stemmer =
            (config.stemming == Stemming::German).then(|| Stemmer::create(Algorithm::German));
        Self { config, stemmer }
    }
    pub fn config(&self) -> &AnalyzerConfig {
        &self.config
    }
    pub fn analyze(&self, source: &str) -> Result<Vec<Token>, TextSearchError> {
        if source.len() > self.config.max_input_bytes {
            return Err(TextSearchError::Limit("input bytes"));
        }
        let mut normalized = String::new();
        let mut mapping = Vec::new();
        for (start, grapheme) in source.grapheme_indices(true) {
            let begin = normalized.len();
            for mut c in text::normalized_characters(grapheme) {
                if self.config.fold_apostrophes && matches!(c, '\u{2018}' | '\u{2019}' | '\u{02bc}')
                {
                    c = '\'';
                }
                if c.len_utf8()
                    > self
                        .config
                        .max_normalized_bytes
                        .saturating_sub(normalized.len())
                {
                    return Err(TextSearchError::Limit("normalized bytes"));
                }
                normalized.push(c);
            }
            if normalized.len() > begin {
                mapping.push((begin, normalized.len(), start, start + grapheme.len()));
            }
        }
        let words: Vec<(usize, &str)> = match self.config.tokenizer {
            WordTokenizer::UnicodeWords => normalized
                .unicode_word_indices()
                .take(self.config.max_tokens.saturating_add(1))
                .collect(),
            WordTokenizer::Alphanumeric => {
                let mut words = Vec::new();
                let mut start = None;
                for (offset, c) in normalized
                    .char_indices()
                    .chain(std::iter::once((normalized.len(), ' ')))
                {
                    if c.is_alphanumeric() || is_combining_mark(c) {
                        if start.is_none() {
                            start = Some(offset)
                        }
                    } else if let Some(begin) = start.take() {
                        let word = &normalized[begin..offset];
                        if word.chars().any(char::is_alphanumeric) {
                            if words.len() == self.config.max_tokens {
                                return Err(TextSearchError::Limit("token count"));
                            }
                            words.push((begin, word));
                        }
                    }
                }
                words
            }
        };
        if words.len() > self.config.max_tokens {
            return Err(TextSearchError::Limit("token count"));
        }
        let mut tokens = Vec::with_capacity(words.len());
        for (offset, word) in words {
            let first = mapping.partition_point(|m| m.1 <= offset);
            let last = mapping.partition_point(|m| m.0 < offset + word.len()) - 1;
            let mut term = text::normalize(word);
            if let Some(stemmer) = &self.stemmer {
                let stem = stemmer.stem(&term);
                if !stem.is_empty() {
                    term = stem.into_owned();
                }
            }
            tokens.push(Token {
                term,
                position: tokens.len(),
                span: TextSpan {
                    start: mapping[first].2,
                    end: mapping[last].3,
                },
            });
        }
        Ok(tokens)
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TermOperator {
    #[default]
    Any,
    All,
}
#[derive(Debug, Clone)]
pub struct TextSearchOptions {
    search: SearchOptions,
    operator: TermOperator,
    max_query_bytes: usize,
    max_query_tokens: usize,
    max_phrases: usize,
    max_phrase_tokens: usize,
    max_spans: usize,
}
impl Default for TextSearchOptions {
    fn default() -> Self {
        Self {
            search: SearchOptions::default(),
            operator: TermOperator::Any,
            max_query_bytes: 16 * 1024,
            max_query_tokens: 256,
            max_phrases: 16,
            max_phrase_tokens: 64,
            max_spans: 64,
        }
    }
}
impl TextSearchOptions {
    pub fn new(limit: usize) -> Self {
        Self {
            search: SearchOptions {
                limit,
                ..SearchOptions::default()
            },
            ..Self::default()
        }
    }
    pub fn with_search(mut self, search: SearchOptions) -> Self {
        self.search = search;
        self
    }
    pub fn with_context(mut self, context: Context) -> Self {
        self.search.context = Some(context);
        self
    }
    pub fn with_operator(mut self, operator: TermOperator) -> Self {
        self.operator = operator;
        self
    }
    pub fn with_query_limits(
        mut self,
        bytes: usize,
        tokens: usize,
        phrases: usize,
        phrase_tokens: usize,
    ) -> Result<Self, TextSearchError> {
        if [bytes, tokens, phrases, phrase_tokens].contains(&0) {
            return Err(TextSearchError::Configuration(
                "query limits must be positive",
            ));
        }
        self.max_query_bytes = bytes;
        self.max_query_tokens = tokens;
        self.max_phrases = phrases;
        self.max_phrase_tokens = phrase_tokens;
        Ok(self)
    }
    pub fn with_max_spans(mut self, max: usize) -> Result<Self, TextSearchError> {
        if max == 0 {
            return Err(TextSearchError::Configuration(
                "span limit must be positive",
            ));
        }
        self.max_spans = max;
        Ok(self)
    }
    pub fn search_options(&self) -> &SearchOptions {
        &self.search
    }
    pub fn operator(&self) -> TermOperator {
        self.operator
    }
    pub fn max_query_bytes(&self) -> usize {
        self.max_query_bytes
    }
    pub fn max_query_tokens(&self) -> usize {
        self.max_query_tokens
    }
    pub fn max_phrases(&self) -> usize {
        self.max_phrases
    }
    pub fn max_phrase_tokens(&self) -> usize {
        self.max_phrase_tokens
    }
    pub fn max_spans(&self) -> usize {
        self.max_spans
    }
}

struct Phrase {
    terms: Vec<String>,
    prefix: Vec<usize>,
}
impl Phrase {
    fn new(terms: Vec<String>) -> Self {
        let mut prefix = vec![0; terms.len()];
        let mut j = 0;
        for i in 1..terms.len() {
            while j > 0 && terms[i] != terms[j] {
                j = prefix[j - 1];
            }
            if terms[i] == terms[j] {
                j += 1;
            }
            prefix[i] = j;
        }
        Self { terms, prefix }
    }
    fn matches(&self, tokens: &[Token], max: usize) -> (Vec<TextSpan>, bool) {
        let mut j = 0;
        let mut spans = Vec::new();
        for (i, token) in tokens.iter().enumerate() {
            while j > 0 && token.term != self.terms[j] {
                j = self.prefix[j - 1];
            }
            if token.term == self.terms[j] {
                j += 1;
            }
            if j == self.terms.len() {
                if spans.len() == max {
                    return (spans, true);
                }
                spans.push(TextSpan {
                    start: tokens[i + 1 - j].span.start,
                    end: token.span.end,
                });
                j = self.prefix[j - 1];
            }
        }
        (spans, false)
    }
}
struct Plan {
    terms: BTreeMap<String, usize>,
    unquoted: BTreeSet<String>,
    phrases: Vec<Phrase>,
}
impl Plan {
    fn new(
        query: &str,
        analyzer: &TextAnalyzer,
        options: &TextSearchOptions,
    ) -> Result<Self, TextSearchError> {
        if query.trim().is_empty() {
            return Err(TextSearchError::Query("empty query"));
        }
        if query.len() > options.max_query_bytes {
            return Err(TextSearchError::Limit("query bytes"));
        }
        let mut parts = Vec::new();
        let mut text = String::new();
        let mut quoted = false;
        let mut chars = query.chars().peekable();
        while let Some(c) = chars.next() {
            match c {
                '\\' if chars.peek().is_some_and(|c| matches!(c, '"' | '\\')) => {
                    text.push(chars.next().unwrap())
                }
                '"' => {
                    if quoted && text.is_empty() {
                        return Err(TextSearchError::Query("empty phrase"));
                    }
                    if !text.is_empty() {
                        parts.push((quoted, std::mem::take(&mut text)));
                    }
                    quoted = !quoted;
                }
                _ => text.push(c),
            }
        }
        if quoted {
            return Err(TextSearchError::Query("unclosed quoted phrase"));
        }
        if !text.is_empty() {
            parts.push((false, text));
        }
        let mut plan = Self {
            terms: BTreeMap::new(),
            unquoted: BTreeSet::new(),
            phrases: Vec::new(),
        };
        let mut count = 0;
        for (quoted, text) in parts {
            let tokens = analyzer.analyze(&text)?;
            count += tokens.len();
            if count > options.max_query_tokens {
                return Err(TextSearchError::Limit("query tokens"));
            }
            if quoted {
                if tokens.is_empty() {
                    return Err(TextSearchError::Query("phrase has no searchable tokens"));
                }
                if tokens.len() > options.max_phrase_tokens {
                    return Err(TextSearchError::Limit("phrase tokens"));
                }
                if plan.phrases.len() >= options.max_phrases {
                    return Err(TextSearchError::Limit("phrase count"));
                }
            }
            let terms: Vec<_> = tokens.into_iter().map(|t| t.term).collect();
            for term in &terms {
                *plan.terms.entry(term.clone()).or_default() += 1;
                if !quoted {
                    plan.unquoted.insert(term.clone());
                }
            }
            if quoted {
                plan.phrases.push(Phrase::new(terms));
            }
        }
        Ok(plan)
    }
    fn includes(&self, tokens: &[Token], operator: TermOperator) -> bool {
        let unquoted = if self.unquoted.is_empty() {
            true
        } else {
            match operator {
                TermOperator::Any => tokens.iter().any(|t| self.unquoted.contains(&t.term)),
                TermOperator::All => {
                    let terms: BTreeSet<_> = tokens.iter().map(|t| t.term.as_str()).collect();
                    self.unquoted.iter().all(|t| terms.contains(t.as_str()))
                }
            }
        };
        unquoted && self.phrases.iter().all(|p| p.matches(tokens, 0).1)
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct PhraseEvidence {
    pub terms: Vec<String>,
    pub spans: Vec<TextSpan>,
    pub truncated: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct TextSearchResult<'a> {
    pub entry: &'a KnowledgeEntry,
    pub score: f64,
    pub matched_terms: Vec<String>,
    pub phrases: Vec<PhraseEvidence>,
}
#[cfg(feature = "reranking")]
impl crate::reranking::Rerankable for TextSearchResult<'_> {
    fn entry(&self) -> &KnowledgeEntry {
        self.entry
    }
}

pub struct TextIndex {
    index: Engine,
    analyzer: TextAnalyzer,
    tokens: BTreeMap<String, crate::index::Shared<Vec<Token>>>,
}
impl Clone for TextIndex {
    fn clone(&self) -> Self {
        Self {
            index: self.index.clone(),
            analyzer: TextAnalyzer::new(self.analyzer.config().clone()),
            tokens: self.tokens.clone(),
        }
    }
}
impl Default for TextIndex {
    fn default() -> Self {
        Self::new(AnalyzerConfig::default())
    }
}
impl TextIndex {
    pub fn new(config: AnalyzerConfig) -> Self {
        Self {
            index: Engine::new(),
            analyzer: TextAnalyzer::new(config),
            tokens: BTreeMap::new(),
        }
    }
    pub fn from_entries(
        config: AnalyzerConfig,
        entries: impl IntoIterator<Item = KnowledgeEntry>,
    ) -> Result<Self, TextSearchError> {
        let mut index = Self::new(config);
        for entry in entries {
            if index.get(&entry.id).is_some() {
                return Err(IndexError::DuplicateId(entry.id).into());
            }
            index.upsert_changed(entry)?;
        }
        Ok(index)
    }
    #[cfg(feature = "execution")]
    pub fn from_entries_controlled(
        config: AnalyzerConfig,
        entries: impl IntoIterator<Item = KnowledgeEntry>,
        control: &crate::execution::WorkControl,
    ) -> Result<Self, TextSearchError> {
        control.checkpoint()?;
        let mut index = Self::new(config);
        control.progress(crate::execution::WorkPhase::AnalyzingText, 0, None);
        for entry in entries {
            control.checkpoint()?;
            if index.get(&entry.id).is_some() {
                return Err(IndexError::DuplicateId(entry.id).into());
            }
            index.upsert_changed(entry)?;
            if index.len().is_multiple_of(512) {
                control.progress(
                    crate::execution::WorkPhase::AnalyzingText,
                    index.len(),
                    None,
                );
            }
        }
        control.progress(
            crate::execution::WorkPhase::AnalyzingText,
            index.len(),
            Some(index.len()),
        );
        control.checkpoint()?;
        Ok(index)
    }
    pub fn analyzer(&self) -> &TextAnalyzer {
        &self.analyzer
    }
    pub fn len(&self) -> usize {
        self.index.len()
    }
    pub fn is_empty(&self) -> bool {
        self.index.is_empty()
    }
    pub fn get(&self, id: &str) -> Option<&KnowledgeEntry> {
        self.index.get(id)
    }
    pub fn entries(&self) -> impl Iterator<Item = &KnowledgeEntry> {
        self.index.entries()
    }
    pub fn stats(&self) -> IndexStats {
        self.index.stats()
    }
    pub fn tokens(&self, id: &str) -> Option<&[Token]> {
        self.tokens
            .get(id)
            .map(|tokens| crate::index::shared_ref(tokens).as_slice())
    }
    pub fn upsert(
        &mut self,
        entry: KnowledgeEntry,
    ) -> Result<Option<KnowledgeEntry>, TextSearchError> {
        if entry.text.len() > self.analyzer.config.max_input_bytes {
            return Err(TextSearchError::Limit("input bytes"));
        }
        let entry = match self.index.replace_unchanged_entry(entry) {
            Ok(previous) => return Ok(Some(previous)),
            Err(entry) => entry,
        };
        self.upsert_changed(entry)
    }
    fn upsert_changed(
        &mut self,
        entry: KnowledgeEntry,
    ) -> Result<Option<KnowledgeEntry>, TextSearchError> {
        if entry.text.len() > self.analyzer.config.max_input_bytes {
            return Err(TextSearchError::Limit("input bytes"));
        }
        let normalized = validate_entry(&entry)?;
        let tokens = self.analyzer.analyze(&entry.text)?;
        let mut terms = BTreeMap::new();
        for token in &tokens {
            *terms.entry(token.term.clone()).or_default() += 1;
        }
        let id = entry.id.clone();
        let previous = self.index.insert_analyzed(entry, normalized, terms);
        self.tokens.insert(id, crate::index::shared_new(tokens));
        Ok(previous)
    }
    pub fn remove(&mut self, id: &str) -> Option<KnowledgeEntry> {
        let previous = self.index.remove(id);
        self.tokens.remove(id);
        previous
    }
    pub fn clear(&mut self) {
        self.index.clear();
        self.tokens.clear();
    }
    pub fn search(
        &self,
        query: &str,
        options: &TextSearchOptions,
    ) -> Result<Vec<TextSearchResult<'_>>, TextSearchError> {
        self.search_inner(
            query,
            options,
            #[cfg(feature = "execution")]
            None,
        )
    }
    #[cfg(feature = "execution")]
    pub fn search_controlled(
        &self,
        query: &str,
        options: &TextSearchOptions,
        control: &crate::execution::WorkControl,
    ) -> Result<Vec<TextSearchResult<'_>>, TextSearchError> {
        self.search_inner(query, options, Some(control))
    }
    fn search_inner(
        &self,
        query: &str,
        options: &TextSearchOptions,
        #[cfg(feature = "execution")] control: Option<&crate::execution::WorkControl>,
    ) -> Result<Vec<TextSearchResult<'_>>, TextSearchError> {
        let checkpoint = || -> Result<(), TextSearchError> {
            #[cfg(feature = "execution")]
            if let Some(control) = control {
                control.checkpoint()?;
            }
            Ok(())
        };
        checkpoint()?;
        let plan = Plan::new(query, &self.analyzer, options)?;
        let results = self.index.search_analyzed_checked(
            &plan.terms,
            &options.search,
            |id| {
                self.tokens
                    .get(id)
                    .is_some_and(|tokens| plan.includes(tokens, options.operator))
            },
            checkpoint,
            #[cfg(feature = "execution")]
            control,
        )?;
        checkpoint()?;
        Ok(results
            .into_iter()
            .map(|hit| TextSearchResult {
                entry: hit.entry,
                score: hit.score,
                matched_terms: hit.matched_terms,
                phrases: plan
                    .phrases
                    .iter()
                    .map(|p| {
                        let (spans, truncated) =
                            p.matches(&self.tokens[&hit.entry.id], options.max_spans);
                        PhraseEvidence {
                            terms: p.terms.clone(),
                            spans,
                            truncated,
                        }
                    })
                    .collect(),
            })
            .collect())
    }
}