airust 0.3.1

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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
#![cfg_attr(feature="shared-index", doc=include_str!("../docs/SHARED-INDEX.md"))]
use crate::context::Context;
use crate::knowledge::{KnowledgeEntry, RelationKind, RelationSuggestion};
use crate::matching::{MatchError, MatchOptions, MatchResult, MatchStrategy, Similarity};
use crate::ranking::TopK;
use crate::search::{tfidf_idf, SearchAlgorithm, SearchOptions, SearchResult};
use crate::text;
use std::collections::{BTreeMap, BTreeSet};
use thiserror::Error;

#[cfg(feature = "shared-index")]
pub(crate) type Shared<T> = std::sync::Arc<T>;
#[cfg(not(feature = "shared-index"))]
pub(crate) type Shared<T> = T;
pub(crate) fn shared_new<T>(value: T) -> Shared<T> {
    #[cfg(feature = "shared-index")]
    {
        std::sync::Arc::new(value)
    }
    #[cfg(not(feature = "shared-index"))]
    {
        value
    }
}
pub(crate) fn shared_mut<T: Clone>(value: &mut Shared<T>) -> &mut T {
    #[cfg(feature = "shared-index")]
    {
        std::sync::Arc::make_mut(value)
    }
    #[cfg(not(feature = "shared-index"))]
    {
        value
    }
}
pub(crate) fn shared_owned<T: Clone>(value: Shared<T>) -> T {
    #[cfg(feature = "shared-index")]
    {
        std::sync::Arc::unwrap_or_clone(value)
    }
    #[cfg(not(feature = "shared-index"))]
    {
        value
    }
}
pub(crate) fn shared_ref<T>(value: &Shared<T>) -> &T {
    #[cfg(feature = "shared-index")]
    {
        value.as_ref()
    }
    #[cfg(not(feature = "shared-index"))]
    {
        value
    }
}

#[derive(Debug, Error)]
pub enum IndexError {
    #[error("entry ID must not be empty")]
    EmptyId,
    #[error("entry {0:?} must have nonempty text")]
    EmptyText(String),
    #[error("duplicate entry ID: {0}")]
    DuplicateId(String),
    #[error("unknown entry ID: {0}")]
    UnknownId(String),
    #[error(transparent)]
    Json(#[from] serde_json::Error),
}

#[derive(Debug, Clone)]
struct IndexedEntry {
    entry: KnowledgeEntry,
    normalized: String,
    terms: BTreeMap<String, usize>,
    length: usize,
    char_length: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub struct IndexStats {
    pub entries: usize,
    pub terms: usize,
    pub tokens: usize,
}

#[derive(Debug, Clone, Default)]
pub struct KnowledgeIndex {
    documents: BTreeMap<String, Shared<IndexedEntry>>,
    postings: BTreeMap<String, Shared<BTreeMap<String, usize>>>,
    normalized_ids: BTreeMap<String, Shared<BTreeSet<String>>>,
    total_tokens: usize,
}

impl KnowledgeIndex {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn from_entries(
        entries: impl IntoIterator<Item = KnowledgeEntry>,
    ) -> Result<Self, IndexError> {
        let mut index = Self::new();
        for entry in entries {
            if index.documents.contains_key(&entry.id) {
                return Err(IndexError::DuplicateId(entry.id));
            }
            let normalized = validate_entry(&entry)?;
            index.insert_validated(entry, normalized);
        }
        Ok(index)
    }

    pub fn upsert(&mut self, entry: KnowledgeEntry) -> Result<Option<KnowledgeEntry>, IndexError> {
        let entry = match self.replace_unchanged_entry(entry) {
            Ok(previous) => return Ok(Some(previous)),
            Err(entry) => entry,
        };
        let normalized = validate_entry(&entry)?;
        Ok(self.insert_validated(entry, normalized))
    }

    pub(crate) fn replace_unchanged_entry(
        &mut self,
        entry: KnowledgeEntry,
    ) -> Result<KnowledgeEntry, KnowledgeEntry> {
        let Some(old) = self.documents.get_mut(&entry.id) else {
            return Err(entry);
        };
        if old.entry.text != entry.text {
            return Err(entry);
        }
        if crate::knowledge::entries_identical(&old.entry, &entry) {
            return Ok(entry);
        }
        Ok(std::mem::replace(&mut shared_mut(old).entry, entry))
    }
    pub(crate) fn insert_validated(
        &mut self,
        entry: KnowledgeEntry,
        normalized: String,
    ) -> Option<KnowledgeEntry> {
        let terms = text::frequencies_normalized(&normalized);
        self.insert_analyzed(entry, normalized, terms)
    }

    pub(crate) fn insert_analyzed(
        &mut self,
        entry: KnowledgeEntry,
        normalized: String,
        terms: BTreeMap<String, usize>,
    ) -> Option<KnowledgeEntry> {
        let char_length = normalized.chars().count();
        let length = terms.values().sum();
        let previous = self.remove(&entry.id);
        for (term, count) in &terms {
            shared_mut(self.postings.entry(term.clone()).or_default())
                .insert(entry.id.clone(), *count);
        }
        shared_mut(self.normalized_ids.entry(normalized.clone()).or_default())
            .insert(entry.id.clone());
        self.total_tokens += length;
        self.documents.insert(
            entry.id.clone(),
            shared_new(IndexedEntry {
                entry,
                normalized,
                terms,
                length,
                char_length,
            }),
        );
        previous
    }

    pub fn remove(&mut self, id: &str) -> Option<KnowledgeEntry> {
        let document = shared_owned(self.documents.remove(id)?);
        self.total_tokens -= document.length;
        for term in document.terms.keys() {
            if let Some(postings) = self.postings.get_mut(term) {
                shared_mut(postings).remove(id);
                if postings.is_empty() {
                    self.postings.remove(term);
                }
            }
        }
        if let Some(ids) = self.normalized_ids.get_mut(&document.normalized) {
            shared_mut(ids).remove(id);
            if ids.is_empty() {
                self.normalized_ids.remove(&document.normalized);
            }
        }
        Some(document.entry)
    }

    pub fn clear(&mut self) {
        *self = Self::new();
    }
    pub fn len(&self) -> usize {
        self.documents.len()
    }
    pub fn is_empty(&self) -> bool {
        self.documents.is_empty()
    }
    pub fn get(&self, id: &str) -> Option<&KnowledgeEntry> {
        self.documents.get(id).map(|d| &d.entry)
    }
    #[cfg(feature = "context-assembly")]
    pub(crate) fn normalized_text(&self, id: &str) -> Option<&str> {
        self.documents.get(id).map(|d| d.normalized.as_str())
    }
    pub fn entries(&self) -> impl Iterator<Item = &KnowledgeEntry> {
        self.documents.values().map(|d| &d.entry)
    }
    pub fn stats(&self) -> IndexStats {
        IndexStats {
            entries: self.len(),
            terms: self.postings.len(),
            tokens: self.total_tokens,
        }
    }

    pub fn search(&self, query: &str, limit: usize) -> Vec<SearchResult<'_>> {
        self.search_with_options(
            query,
            &SearchOptions {
                limit,
                ..SearchOptions::default()
            },
        )
    }

    pub fn search_in_context(
        &self,
        query: &str,
        context: &Context,
        limit: usize,
    ) -> Vec<SearchResult<'_>> {
        self.search_with_options(
            query,
            &SearchOptions {
                limit,
                context: Some(context.clone()),
                ..SearchOptions::default()
            },
        )
    }

    pub fn search_with_options(
        &self,
        query: &str,
        options: &SearchOptions,
    ) -> Vec<SearchResult<'_>> {
        if options.limit == 0 || self.is_empty() {
            return Vec::new();
        }
        let query_terms = text::term_frequencies(query);
        self.search_analyzed(&query_terms, options, |_| true)
    }

    pub(crate) fn search_analyzed(
        &self,
        query_terms: &BTreeMap<String, usize>,
        options: &SearchOptions,
        includes: impl Fn(&str) -> bool,
    ) -> Vec<SearchResult<'_>> {
        match self.search_analyzed_checked(
            query_terms,
            options,
            includes,
            || Ok::<_, std::convert::Infallible>(()),
            #[cfg(feature = "execution")]
            None,
        ) {
            Ok(results) => results,
            Err(error) => match error {},
        }
    }
    #[cfg(feature = "execution")]
    pub fn search_controlled(
        &self,
        query: &str,
        options: &SearchOptions,
        control: &crate::execution::WorkControl,
    ) -> Result<Vec<SearchResult<'_>>, crate::execution::ExecutionError> {
        control.checkpoint()?;
        let terms = text::term_frequencies(query);
        self.search_analyzed_checked(
            &terms,
            options,
            |_| true,
            || control.checkpoint(),
            Some(control),
        )
    }
    pub(crate) fn search_analyzed_checked<E>(
        &self,
        query_terms: &BTreeMap<String, usize>,
        options: &SearchOptions,
        includes: impl Fn(&str) -> bool,
        mut checkpoint: impl FnMut() -> Result<(), E>,
        #[cfg(feature = "execution")] control: Option<&crate::execution::WorkControl>,
    ) -> Result<Vec<SearchResult<'_>>, E> {
        checkpoint()?;
        if options.limit == 0 || self.is_empty() {
            return Ok(Vec::new());
        }
        #[cfg(feature = "execution")]
        if let Some(control) = control {
            control.progress(crate::execution::WorkPhase::CollectingCandidates, 0, None);
        }
        #[cfg(feature = "execution")]
        let mut visited = 0usize;
        let mut candidates = BTreeSet::new();
        for term in query_terms.keys() {
            checkpoint()?;
            if let Some(postings) = self.postings.get(term) {
                for id in postings.keys() {
                    checkpoint()?;
                    #[cfg(feature = "execution")]
                    {
                        visited += 1;
                        if visited.is_multiple_of(512) {
                            if let Some(control) = control {
                                control.progress(
                                    crate::execution::WorkPhase::CollectingCandidates,
                                    visited,
                                    None,
                                );
                            }
                        }
                    }
                    candidates.insert(id.as_str());
                }
            }
        }
        #[cfg(feature = "execution")]
        let candidate_count = candidates.len();
        #[cfg(feature = "execution")]
        if let Some(control) = control {
            control.progress(
                crate::execution::WorkPhase::CollectingCandidates,
                visited,
                Some(visited),
            );
            control.progress(
                crate::execution::WorkPhase::Ranking,
                0,
                Some(candidate_count),
            );
        }
        let average = self.total_tokens as f64 / self.len() as f64;
        let query_norm = if options.algorithm == SearchAlgorithm::Tfidf {
            query_terms
                .iter()
                .filter_map(|(term, tf)| {
                    self.postings
                        .get(term)
                        .map(|p| (*tf as f64 * tfidf_idf(self.len(), p.len())).powi(2))
                })
                .sum::<f64>()
                .sqrt()
        } else {
            0.0
        };
        let mut results = TopK::new(options.limit);
        for (position, id) in candidates.into_iter().enumerate() {
            #[cfg(not(feature = "execution"))]
            let _ = position;
            checkpoint()?;
            #[cfg(feature = "execution")]
            if position.is_multiple_of(512) {
                if let Some(control) = control {
                    control.progress(
                        crate::execution::WorkPhase::Ranking,
                        position,
                        Some(candidate_count),
                    );
                }
            }
            let document = &self.documents[id];
            if options
                .context
                .as_ref()
                .is_some_and(|context| !context.includes(&document.entry))
            {
                continue;
            }
            if !includes(id) {
                continue;
            }
            let matched_terms: Vec<String> = query_terms
                .keys()
                .filter(|term| document.terms.contains_key(*term))
                .cloned()
                .collect();
            let score = match options.algorithm {
                SearchAlgorithm::Bm25 => matched_terms
                    .iter()
                    .map(|term| {
                        options.bm25.term_score(
                            document.terms[term],
                            self.postings[term].len(),
                            self.len(),
                            document.length,
                            average,
                        )
                    })
                    .sum(),
                SearchAlgorithm::Tfidf => {
                    let dot = matched_terms
                        .iter()
                        .map(|term| {
                            let idf = tfidf_idf(self.len(), self.postings[term].len());
                            query_terms[term] as f64 * document.terms[term] as f64 * idf * idf
                        })
                        .sum::<f64>();
                    let norm = document
                        .terms
                        .iter()
                        .map(|(term, tf)| {
                            (*tf as f64 * tfidf_idf(self.len(), self.postings[term].len())).powi(2)
                        })
                        .sum::<f64>()
                        .sqrt();
                    if norm > 0.0 && query_norm > 0.0 {
                        (dot / (norm * query_norm)).clamp(0.0, 1.0)
                    } else {
                        0.0
                    }
                }
            };
            if score > 0.0 && score.is_finite() {
                results.push(SearchResult {
                    entry: &document.entry,
                    score,
                    matched_terms,
                });
            }
        }
        checkpoint()?;
        let result = results.finish();
        #[cfg(feature = "execution")]
        if let Some(control) = control {
            control.progress(
                crate::execution::WorkPhase::Ranking,
                candidate_count,
                Some(candidate_count),
            );
        }
        checkpoint()?;
        Ok(result)
    }

    pub fn find_matches(&self, text: &str, limit: usize) -> Vec<MatchResult<'_>> {
        self.match_validated(
            text,
            &MatchOptions {
                limit,
                ..MatchOptions::default()
            },
        )
    }

    pub fn r#match(&self, text: &str, limit: usize) -> Vec<MatchResult<'_>> {
        self.find_matches(text, limit)
    }

    pub fn match_with_options(
        &self,
        text: &str,
        options: &MatchOptions,
    ) -> Result<Vec<MatchResult<'_>>, MatchError> {
        options.validate()?;
        Ok(self.match_validated(text, options))
    }

    fn match_validated(&self, input: &str, options: &MatchOptions) -> Vec<MatchResult<'_>> {
        let normalized = text::normalize(input);
        if normalized.is_empty() || options.limit == 0 {
            return Vec::new();
        }
        let query_terms: BTreeSet<&str> = text::tokens_normalized(&normalized).collect();
        let query_len = normalized.chars().count();
        let exact_ids = self.normalized_ids.get(&normalized);
        let candidates: Box<dyn Iterator<Item = &IndexedEntry> + '_> = match options.strategy {
            MatchStrategy::Exact => Box::new(
                exact_ids
                    .into_iter()
                    .flat_map(|ids| ids.iter())
                    .map(|id| shared_ref(&self.documents[id])),
            ),
            MatchStrategy::TokenOverlap => Box::new(
                self.candidates(query_terms.iter().copied())
                    .into_iter()
                    .map(|id| shared_ref(&self.documents[id])),
            ),
            MatchStrategy::Fuzzy => Box::new(self.documents.values().map(shared_ref)),
        };
        let mut results = TopK::new(options.limit);
        for document in candidates {
            let shared = query_terms
                .iter()
                .filter(|term| document.terms.contains_key(**term))
                .count();
            let union = query_terms.len() + document.terms.len() - shared;
            let token_score = if union == 0 {
                0.0
            } else {
                shared as f64 / union as f64
            };
            if options.strategy == MatchStrategy::TokenOverlap
                && token_score < options.min_similarity
            {
                continue;
            }
            let max_len = query_len.max(document.char_length);
            if options.strategy == MatchStrategy::Fuzzy
                && (1.0 - query_len.abs_diff(document.char_length) as f64 / max_len as f64)
                    < options.min_similarity
            {
                continue;
            }
            let character = if normalized == document.normalized {
                1.0
            } else {
                let distance = if options.strategy == MatchStrategy::Fuzzy {
                    let Some(distance) = crate::matching::bounded_distance(
                        &normalized,
                        &document.normalized,
                        crate::matching::distance_limit(max_len, options.min_similarity),
                    ) else {
                        continue;
                    };
                    distance
                } else {
                    crate::matching::levenshtein_distance(&normalized, &document.normalized)
                };
                1.0 - distance as f64 / max_len as f64
            };
            let similarity = Similarity {
                exact: normalized == document.normalized,
                character,
                token: token_score,
            };
            let score = match options.strategy {
                MatchStrategy::Exact => {
                    if similarity.exact {
                        1.0
                    } else {
                        0.0
                    }
                }
                MatchStrategy::Fuzzy => similarity.character,
                MatchStrategy::TokenOverlap => similarity.token,
            };
            if score > 0.0 && score >= options.min_similarity {
                results.push(MatchResult {
                    entry: &document.entry,
                    score,
                    similarity,
                });
            }
        }
        results.finish()
    }

    pub fn duplicates(&self) -> Vec<Vec<&KnowledgeEntry>> {
        self.normalized_ids
            .values()
            .filter(|ids| ids.len() > 1)
            .map(|ids| ids.iter().map(|id| &self.documents[id].entry).collect())
            .collect()
    }

    pub fn relate(&self, id: &str, limit: usize) -> Result<Vec<RelationSuggestion>, IndexError> {
        let source = self
            .documents
            .get(id)
            .ok_or_else(|| IndexError::UnknownId(id.to_owned()))?;
        if limit == 0 {
            return Ok(Vec::new());
        }
        let source_terms: BTreeSet<&String> = source
            .terms
            .keys()
            .filter(|term| !text::is_stopword(term))
            .collect();
        let candidates = self.candidates(source_terms.iter().map(|term| term.as_str()));
        let mut suggestions = TopK::new(limit);
        for target_id in candidates {
            if target_id == id {
                continue;
            }
            let target_terms: BTreeSet<&String> = self.documents[target_id]
                .terms
                .keys()
                .filter(|term| !text::is_stopword(term))
                .collect();
            let shared_terms: Vec<String> = source_terms
                .intersection(&target_terms)
                .map(|term| (*term).clone())
                .collect();
            let union = source_terms.union(&target_terms).count();
            if !shared_terms.is_empty() {
                suggestions.push(RelationSuggestion {
                    source_id: id.to_owned(),
                    target_id: target_id.to_owned(),
                    kind: RelationKind::Related,
                    score: shared_terms.len() as f64 / union as f64,
                    shared_terms,
                });
            }
        }
        Ok(suggestions.finish())
    }

    pub fn to_json(&self) -> Result<String, IndexError> {
        Ok(serde_json::to_string_pretty(
            &self.entries().collect::<Vec<_>>(),
        )?)
    }

    pub fn from_json(json: &str) -> Result<Self, IndexError> {
        Self::from_entries(serde_json::from_str::<Vec<KnowledgeEntry>>(json)?)
    }

    fn candidates<'a>(&'a self, terms: impl IntoIterator<Item = &'a str>) -> BTreeSet<&'a str> {
        terms
            .into_iter()
            .filter_map(|term| self.postings.get(term))
            .flat_map(|postings| postings.keys().map(String::as_str))
            .collect()
    }
}

pub(crate) fn validate_entry(entry: &KnowledgeEntry) -> Result<String, IndexError> {
    check_source_entry(entry)?;
    let normalized = text::normalize(&entry.text);
    if normalized.is_empty() {
        return Err(IndexError::EmptyText(entry.id.clone()));
    }
    Ok(normalized)
}

pub(crate) fn check_source_entry(entry: &KnowledgeEntry) -> Result<(), IndexError> {
    if entry.id.trim().is_empty() {
        return Err(IndexError::EmptyId);
    }
    if entry.text.trim().is_empty() {
        return Err(IndexError::EmptyText(entry.id.clone()));
    }
    Ok(())
}

#[cfg(feature = "cache")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub(crate) struct CacheDocumentHeader {
    pub id: String,
    pub normalized: String,
    pub length: usize,
    pub char_length: usize,
    pub term_count: usize,
}
#[cfg(feature = "cache")]
#[derive(serde::Serialize)]
struct CacheDocumentRef<'a> {
    id: &'a str,
    normalized: &'a str,
    length: usize,
    char_length: usize,
    term_count: usize,
}
#[cfg(feature = "cache")]
#[derive(Debug, Clone)]
pub(crate) struct CacheDocument {
    pub id: String,
    pub normalized: String,
    pub length: usize,
    pub char_length: usize,
    pub terms: BTreeMap<String, usize>,
}
#[cfg(feature = "cache")]
impl KnowledgeIndex {
    pub(crate) fn cache_term_bindings(&self) -> Result<usize, crate::cache::CacheError> {
        self.documents.values().try_fold(0usize, |total, document| {
            total
                .checked_add(document.terms.len())
                .ok_or(crate::cache::CacheError::Limit("term bindings"))
        })
    }
    pub(crate) fn write_cached_documents(
        &self,
        writer: &mut impl std::io::Write,
    ) -> Result<(), postcard::Error> {
        for document in self.documents.values() {
            postcard::to_io(
                &CacheDocumentRef {
                    id: &document.entry.id,
                    normalized: &document.normalized,
                    length: document.length,
                    char_length: document.char_length,
                    term_count: document.terms.len(),
                },
                &mut *writer,
            )?;
            for item in &document.terms {
                postcard::to_io(&item, &mut *writer)?;
            }
        }
        Ok(())
    }
}

#[cfg(feature = "cache")]
pub(crate) struct PreparedCache {
    documents: BTreeMap<String, CacheDocument>,
    total_tokens: usize,
}
#[cfg(feature = "cache")]
pub(crate) fn prepare_cached_documents(
    originals: &[KnowledgeEntry],
    documents: Vec<CacheDocument>,
) -> Result<PreparedCache, crate::cache::CacheError> {
    use crate::cache::CacheError;
    let ids: BTreeSet<_> = originals.iter().map(|entry| entry.id.as_str()).collect();
    if documents.len() != originals.len() || ids.len() != originals.len() {
        return Err(CacheError::InvalidData("cached document count"));
    }
    let mut prepared = BTreeMap::new();
    let mut total_tokens = 0usize;
    for document in documents {
        if !ids.contains(document.id.as_str()) || prepared.contains_key(&document.id) {
            return Err(CacheError::InvalidData("cached document IDs"));
        }
        if document.normalized.trim().is_empty()
            || document.char_length != document.normalized.chars().count()
        {
            return Err(CacheError::InvalidData("cached normalized text"));
        }
        let mut length = 0usize;
        for (term, &frequency) in &document.terms {
            let mut words = text::tokens_normalized(term);
            if frequency == 0 || words.next() != Some(term.as_str()) || words.next().is_some() {
                return Err(CacheError::InvalidData("cached term"));
            }
            length = length
                .checked_add(frequency)
                .ok_or(CacheError::InvalidData("cached token count overflow"))?;
        }
        if length != document.length || length > document.char_length {
            return Err(CacheError::InvalidData("cached document length"));
        }
        total_tokens = total_tokens
            .checked_add(length)
            .ok_or(CacheError::InvalidData("cached total token count overflow"))?;
        prepared.insert(document.id.clone(), document);
    }
    Ok(PreparedCache {
        documents: prepared,
        total_tokens,
    })
}
#[cfg(feature = "cache")]
impl PreparedCache {
    pub(crate) fn restore(mut self, originals: Vec<KnowledgeEntry>) -> KnowledgeIndex {
        let mut index = KnowledgeIndex {
            total_tokens: self.total_tokens,
            ..KnowledgeIndex::new()
        };
        for entry in originals {
            let cached = self
                .documents
                .remove(&entry.id)
                .expect("validated cached source ID");
            for (term, &frequency) in &cached.terms {
                shared_mut(index.postings.entry(term.clone()).or_default())
                    .insert(entry.id.clone(), frequency);
            }
            shared_mut(
                index
                    .normalized_ids
                    .entry(cached.normalized.clone())
                    .or_default(),
            )
            .insert(entry.id.clone());
            index.documents.insert(
                entry.id.clone(),
                shared_new(IndexedEntry {
                    entry,
                    normalized: cached.normalized,
                    terms: cached.terms,
                    length: cached.length,
                    char_length: cached.char_length,
                }),
            );
        }
        index
    }
}

#[cfg(all(test, feature = "execution"))]
mod execution_tests {
    use super::*;
    #[test]
    fn cancellation_inside_shared_candidate_build_returns_no_partial_results() {
        let index = KnowledgeIndex::from_entries(
            (0..1000).map(|i| KnowledgeEntry::new(i.to_string(), "Rust ownership")),
        )
        .unwrap();
        let terms = text::term_frequencies("Rust");
        let mut checkpoints = 0;
        let result = index.search_analyzed_checked(
            &terms,
            &SearchOptions::default(),
            |_| true,
            || {
                checkpoints += 1;
                if checkpoints == 30 {
                    Err(crate::execution::ExecutionError::Cancelled)
                } else {
                    Ok(())
                }
            },
            None,
        );
        assert!(matches!(
            result,
            Err(crate::execution::ExecutionError::Cancelled)
        ));
        assert_eq!(checkpoints, 30);
    }
}
#[cfg(all(test, feature = "shared-index"))]
mod sharing_tests {
    use super::*;
    use std::sync::Arc;
    #[test]
    fn copies_share_immutable_payloads_and_detach_only_modified_bindings() {
        let original = KnowledgeIndex::from_entries([
            KnowledgeEntry::new("a", "common one"),
            KnowledgeEntry::new("b", "common two"),
            KnowledgeEntry::new("c", "untouched unique"),
        ])
        .unwrap();
        let mut changed = original.clone();
        assert!(Arc::ptr_eq(
            &original.documents["a"],
            &changed.documents["a"]
        ));
        assert!(Arc::ptr_eq(
            &original.postings["common"],
            &changed.postings["common"]
        ));
        changed
            .upsert(KnowledgeEntry::new("a", "replacement different"))
            .unwrap();
        assert!(Arc::ptr_eq(
            &original.documents["b"],
            &changed.documents["b"]
        ));
        assert!(!Arc::ptr_eq(
            &original.postings["common"],
            &changed.postings["common"]
        ));
        assert!(Arc::ptr_eq(
            &original.postings["unique"],
            &changed.postings["unique"]
        ));
        assert!(original.postings["common"].contains_key("a"));
        assert!(!changed.postings["common"].contains_key("a"));
    }
    #[test]
    fn duplicate_sets_detach_without_leaking_removal_to_old_views() {
        let original = KnowledgeIndex::from_entries([
            KnowledgeEntry::new("a", "same text"),
            KnowledgeEntry::new("b", "same text"),
        ])
        .unwrap();
        let mut changed = original.clone();
        assert!(Arc::ptr_eq(
            &original.normalized_ids["same text"],
            &changed.normalized_ids["same text"]
        ));
        changed.remove("a");
        assert_eq!(original.normalized_ids["same text"].len(), 2);
        assert_eq!(changed.normalized_ids["same text"].len(), 1);
        changed.remove("b");
        assert!(changed.normalized_ids.is_empty());
        assert_eq!(original.len(), 2);
    }
}