1use std::cmp::Reverse;
17use std::collections::BinaryHeap;
18use std::path::{Path, PathBuf};
19use std::sync::Mutex;
20
21use rustc_hash::FxHashSet;
22use tantivy::collector::{Collector, SegmentCollector};
23use tantivy::columnar::BytesColumn;
24use tantivy::{DocId, Index, IndexReader, IndexWriter, ReloadPolicy, Score, TantivyDocument};
25use waratah_storage::text_index::{TextIndexDoc, registered_analyzer};
26
27use crate::doc;
28use crate::error::TextIndexError;
29use crate::meta::{self, SKETCH_FILE, TextIndexMeta};
30use crate::query;
31use crate::schema::{self, FIELD_TERM, TextSchema};
32use waratah_storage::text_index::TextSearchRequest;
33
34pub const WRITER_MEMORY_BUDGET_BYTES: usize = 50_000_000;
38
39const WRITER_THREADS: usize = 1;
43
44const TANTIVY_META_FILE: &str = "meta.json";
46
47#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct TextIndexOptions {
50 pub analyzer: String,
52 pub seed_chars: usize,
54 pub fingerprint: String,
56}
57
58impl TextIndexOptions {
59 pub fn new(
61 analyzer: impl Into<String>,
62 seed_chars: usize,
63 fingerprint: impl Into<String>,
64 ) -> Self {
65 Self {
66 analyzer: analyzer.into(),
67 seed_chars,
68 fingerprint: fingerprint.into(),
69 }
70 }
71
72 pub fn validate(&self) -> Result<(), TextIndexError> {
74 if registered_analyzer(&self.analyzer).is_none() {
75 let names: Vec<&str> = waratah_storage::text_index::ANALYZERS
76 .iter()
77 .map(|(name, _)| *name)
78 .collect();
79 return Err(TextIndexError::Config(format!(
80 "unknown analyzer {:?}; expected one of {}",
81 self.analyzer,
82 names.join(", ")
83 )));
84 }
85 if self.seed_chars == 0 || self.seed_chars > waratah_storage::text_index::MAX_SEED_CHARS {
86 return Err(TextIndexError::Config(format!(
87 "seed_chars must be between 1 and {}, got {}",
88 waratah_storage::text_index::MAX_SEED_CHARS,
89 self.seed_chars
90 )));
91 }
92 if self.fingerprint.is_empty() {
93 return Err(TextIndexError::Config(
94 "the config fingerprint must not be empty".to_owned(),
95 ));
96 }
97 Ok(())
98 }
99}
100
101pub struct TextIndex {
104 index: Index,
105 schema: TextSchema,
106 analyzer: String,
107 seed_chars: usize,
108 fingerprint: String,
109 meta: Mutex<TextIndexMeta>,
113 reader: IndexReader,
114 writer: Mutex<IndexWriter<TantivyDocument>>,
115 wiping: std::sync::atomic::AtomicBool,
121 dir: Option<PathBuf>,
122}
123
124impl TextIndex {
125 pub fn open_or_create(dir: &Path, options: &TextIndexOptions) -> Result<Self, TextIndexError> {
134 options.validate()?;
135 std::fs::create_dir_all(dir)?;
136 let has_index = dir.join(TANTIVY_META_FILE).is_file();
137 let index = if has_index {
138 Index::open_in_dir(dir)?
139 } else {
140 Index::create_in_dir(dir, schema::build(&options.analyzer)?.schema.clone())?
141 };
142 let schema = if has_index {
143 schema::from_index(&index)?
144 } else {
145 schema::build(&options.analyzer)?
146 };
147 schema::register_analyzers(&index);
148 let meta = match meta::read_meta(dir)? {
149 Some(meta) => meta,
150 None => {
151 let meta = TextIndexMeta::configured(
152 options.analyzer.clone(),
153 options.seed_chars,
154 options.fingerprint.clone(),
155 );
156 meta::write_meta(dir, &meta)?;
157 meta
158 }
159 };
160 Self::assemble(index, schema, meta, Some(dir.to_path_buf()))
161 }
162
163 pub fn check_adoptable(dir: &Path, fingerprint: &str) -> Result<(), String> {
175 if !dir.join(TANTIVY_META_FILE).is_file() {
176 return Ok(());
177 }
178 let index = Index::open_in_dir(dir)
179 .map_err(|error| format!("cannot open the text index at {}: {error}", dir.display()))?;
180 schema::from_index(&index).map_err(|error| {
181 format!(
182 "the text index at {} was built by a schema this build cannot read: {error}",
183 dir.display()
184 )
185 })?;
186 let Some(meta) = meta::read_meta(dir)
187 .map_err(|error| format!("text index sidecar at {}: {error}", dir.display()))?
188 else {
189 return Err(format!(
190 "the text index at {} has no sidecar; it was built by an older Waratah",
191 dir.display()
192 ));
193 };
194 if meta.fingerprint != fingerprint {
195 return Err(format!(
196 "the text index at {} was built with {} but this build requires {fingerprint}",
197 dir.display(),
198 meta.fingerprint
199 ));
200 }
201 Ok(())
202 }
203
204 pub fn open_doc_count_read_only(dir: &Path) -> Result<u64, TextIndexError> {
211 let index = Index::open_in_dir(dir)?;
212 let reader: IndexReader = index
213 .reader_builder()
214 .reload_policy(ReloadPolicy::Manual)
215 .try_into()?;
216 Ok(reader.searcher().num_docs())
217 }
218
219 pub fn create_in_ram(options: &TextIndexOptions) -> Result<Self, TextIndexError> {
222 options.validate()?;
223 let schema = schema::build(&options.analyzer)?;
224 let index = Index::create_in_ram(schema.schema.clone());
225 schema::register_analyzers(&index);
226 let meta = TextIndexMeta::configured(
227 options.analyzer.clone(),
228 options.seed_chars,
229 options.fingerprint.clone(),
230 );
231 Self::assemble(index, schema, meta, None)
232 }
233
234 fn assemble(
235 index: Index,
236 schema: TextSchema,
237 meta: TextIndexMeta,
238 dir: Option<PathBuf>,
239 ) -> Result<Self, TextIndexError> {
240 let stored_tokenizer = schema::text_tokenizer(&schema);
244 let expected = registered_analyzer(&meta.analyzer).ok_or_else(|| {
245 TextIndexError::Config(format!("unknown analyzer {:?}", meta.analyzer))
246 })?;
247 if stored_tokenizer != Some(expected) {
248 return Err(TextIndexError::SchemaMismatch);
249 }
250 let reader: IndexReader = index
251 .reader_builder()
252 .reload_policy(ReloadPolicy::Manual)
253 .try_into()?;
254 let writer: IndexWriter<TantivyDocument> =
255 index.writer_with_num_threads(WRITER_THREADS, WRITER_MEMORY_BUDGET_BYTES)?;
256 Ok(Self {
257 index,
258 schema,
259 analyzer: meta.analyzer.clone(),
260 seed_chars: meta.seed_chars,
261 fingerprint: meta.fingerprint.clone(),
262 meta: Mutex::new(meta),
263 reader,
264 writer: Mutex::new(writer),
265 wiping: std::sync::atomic::AtomicBool::new(false),
266 dir,
267 })
268 }
269
270 pub fn add_batch(&self, documents: &[TextIndexDoc]) -> Result<(), TextIndexError> {
275 if documents.is_empty() {
276 return Ok(());
277 }
278 let mut writer = self
279 .writer
280 .lock()
281 .map_err(|_| TextIndexError::WriterPoisoned)?;
282 if self.wiping.load(std::sync::atomic::Ordering::SeqCst) {
293 return Err(TextIndexError::WipeInProgress);
294 }
295 let mut seen: FxHashSet<Vec<u8>> = FxHashSet::default();
303 for document in documents {
304 let key =
305 waratah_storage::text_index::text_index_key(&document.predicate, &document.term);
306 if !seen.insert(key.clone()) {
307 continue;
308 }
309 writer.delete_term(tantivy::schema::Term::from_field_bytes(
310 self.schema.key,
311 &key,
312 ));
313 writer.add_document(doc::to_tantivy(document, &self.schema, self.seed_chars))?;
314 }
315 writer.commit()?;
316 drop(writer);
317 self.reader.reload()?;
318 Ok(())
319 }
320
321 pub fn search(&self, request: &TextSearchRequest) -> Result<Vec<Vec<u8>>, TextIndexError> {
340 self.search_scoped(request, &[])
341 }
342
343 pub fn search_scoped(
351 &self,
352 request: &TextSearchRequest,
353 predicates: &[Vec<u8>],
354 ) -> Result<Vec<Vec<u8>>, TextIndexError> {
355 let searcher = self.reader.searcher();
356 let query = query::build_query_scoped(
357 &self.index,
358 &self.schema,
359 self.seed_chars,
360 request,
361 predicates,
362 )?;
363 let fruit: TermFruit = searcher
364 .search(&query, &TermCollector::new(request.limit))
365 .map_err(TextIndexError::from)?;
366 let distinct = fruit.terms;
372 if request.limit > 0 && distinct.len() as u64 > request.limit {
373 return Err(TextIndexError::CandidateLimitExceeded {
374 limit: request.limit,
375 });
376 }
377 debug_assert!(
381 distinct.windows(2).all(|pair| pair[0] < pair[1]),
382 "a drain result must be strictly ascending term bytes"
383 );
384 Ok(distinct)
385 }
386
387 pub fn wipe(&self) -> Result<(), TextIndexError> {
401 let mut writer = self
402 .writer
403 .lock()
404 .map_err(|_| TextIndexError::WriterPoisoned)?;
405 self.wiping.store(true, std::sync::atomic::Ordering::SeqCst);
413 let outcome = self.clear_trust().and_then(|()| {
414 writer.delete_all_documents()?;
415 writer.commit()?;
416 Ok(())
417 });
418 self.wiping
419 .store(false, std::sync::atomic::Ordering::SeqCst);
420 outcome?;
421 drop(writer);
422 self.reader.reload()?;
423 if let Some(dir) = &self.dir {
430 let _ = std::fs::remove_file(dir.join(SKETCH_FILE));
431 }
432 Ok(())
433 }
434
435 fn clear_trust(&self) -> Result<(), TextIndexError> {
440 let cleared = self.configured_meta();
441 if let Some(dir) = &self.dir {
442 meta::write_meta(dir, &cleared)?;
443 }
444 *self
445 .meta
446 .lock()
447 .map_err(|_| TextIndexError::WriterPoisoned)? = cleared;
448 Ok(())
449 }
450
451 #[doc(hidden)]
465 pub fn test_set_wiping(&self, wiping: bool) {
466 self.wiping
467 .store(wiping, std::sync::atomic::Ordering::SeqCst);
468 }
469
470 #[doc(hidden)]
475 pub fn test_wiping(&self) -> bool {
476 self.wiping.load(std::sync::atomic::Ordering::SeqCst)
477 }
478
479 pub fn doc_count(&self) -> u64 {
481 self.reader.searcher().num_docs()
482 }
483
484 pub fn schema(&self) -> &TextSchema {
486 &self.schema
487 }
488
489 pub fn analyzer(&self) -> &str {
491 &self.analyzer
492 }
493
494 pub fn seed_chars(&self) -> usize {
496 self.seed_chars
497 }
498
499 pub fn fingerprint(&self) -> &str {
501 &self.fingerprint
502 }
503
504 pub fn dir(&self) -> Option<&Path> {
506 self.dir.as_deref()
507 }
508
509 pub fn meta(&self) -> Result<TextIndexMeta, TextIndexError> {
514 Ok(self
515 .meta
516 .lock()
517 .map_err(|_| TextIndexError::WriterPoisoned)?
518 .clone())
519 }
520
521 pub fn stamp(&self, epoch: u64) -> Result<(), TextIndexError> {
523 let mut meta = self.configured_meta();
524 meta.epoch = Some(epoch);
525 if let Some(dir) = &self.dir {
526 meta::write_meta(dir, &meta)?;
527 }
528 *self
529 .meta
530 .lock()
531 .map_err(|_| TextIndexError::WriterPoisoned)? = meta;
532 Ok(())
533 }
534
535 fn configured_meta(&self) -> TextIndexMeta {
537 TextIndexMeta::configured(
538 self.analyzer.clone(),
539 self.seed_chars,
540 self.fingerprint.clone(),
541 )
542 }
543}
544
545impl std::fmt::Debug for TextIndex {
546 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
547 f.debug_struct("TextIndex")
550 .field("dir", &self.dir)
551 .field("analyzer", &self.analyzer)
552 .field("seed_chars", &self.seed_chars)
553 .field("fingerprint", &self.fingerprint)
554 .field("doc_count", &self.doc_count())
555 .finish()
556 }
557}
558
559#[derive(Debug, Default)]
560struct TermFruit {
561 terms: Vec<Vec<u8>>,
567 dictionary_error: Option<String>,
574}
575
576struct TermCollector {
591 limit: u64,
592}
593
594impl TermCollector {
595 fn new(limit: u64) -> Self {
596 Self { limit }
597 }
598}
599
600impl Collector for TermCollector {
601 type Fruit = TermFruit;
602 type Child = TermSegmentCollector;
603
604 fn for_segment(
605 &self,
606 _segment_local_id: u32,
607 segment: &tantivy::SegmentReader,
608 ) -> tantivy::Result<Self::Child> {
609 let column = segment.fast_fields().bytes(FIELD_TERM)?;
610 Ok(TermSegmentCollector {
611 column,
612 ords: FxHashSet::default(),
613 bound: if self.limit == 0 {
615 u64::MAX
616 } else {
617 self.limit.saturating_add(1)
618 },
619 })
620 }
621
622 fn requires_scoring(&self) -> bool {
623 false
624 }
625
626 fn merge_fruits(&self, fruits: Vec<TermFruit>) -> tantivy::Result<TermFruit> {
627 let mut streams: Vec<std::vec::IntoIter<Vec<u8>>> = Vec::with_capacity(fruits.len());
635 for fruit in fruits {
636 if let Some(error) = fruit.dictionary_error {
637 return Err(tantivy::TantivyError::InternalError(format!(
640 "the text index term dictionary walk failed: {error}"
641 )));
642 }
643 streams.push(fruit.terms.into_iter());
644 }
645 let mut heads: BinaryHeap<(Reverse<Vec<u8>>, usize)> =
646 BinaryHeap::with_capacity(streams.len());
647 for (index, stream) in streams.iter_mut().enumerate() {
648 if let Some(head) = stream.next() {
649 heads.push((Reverse(head), index));
650 }
651 }
652 let mut terms: Vec<Vec<u8>> = Vec::with_capacity(streams.iter().map(|s| s.len()).sum());
653 while let Some((Reverse(term), stream)) = heads.pop() {
654 if let Some(next) = streams[stream].next() {
658 heads.push((Reverse(next), stream));
659 }
660 if terms
661 .last()
662 .is_some_and(|last| last.as_slice() == term.as_slice())
663 {
664 continue;
665 }
666 terms.push(term);
667 }
668 Ok(TermFruit {
669 terms,
670 dictionary_error: None,
671 })
672 }
673}
674
675struct TermSegmentCollector {
676 column: Option<BytesColumn>,
677 ords: FxHashSet<u64>,
685 bound: u64,
689}
690
691impl SegmentCollector for TermSegmentCollector {
692 type Fruit = TermFruit;
693
694 fn collect(&mut self, doc: DocId, _score: Score) {
695 if self.ords.len() as u64 >= self.bound {
696 return;
697 }
698 let Some(column) = &self.column else {
699 return;
700 };
701 let Some(ord) = column.ords().first(doc) else {
702 return;
703 };
704 self.ords.insert(ord);
705 }
706
707 fn harvest(self) -> TermFruit {
708 let Some(column) = self.column else {
709 return TermFruit::default();
710 };
711 let mut ords: Vec<u64> = self.ords.into_iter().collect();
712 ords.sort_unstable();
713 let mut terms = Vec::with_capacity(ords.len());
714 let walk = column
720 .dictionary()
721 .sorted_ords_to_term_cb(&ords, |bytes| terms.push(bytes.to_vec()));
722 let dictionary_error = match walk {
723 Ok(true) => None,
724 Ok(false) => Some("the dictionary could not resolve every term ordinal".to_owned()),
725 Err(error) => Some(error.to_string()),
726 };
727 TermFruit {
728 terms,
729 dictionary_error,
730 }
731 }
732}
733
734#[cfg(test)]
735mod tests {
736 use super::*;
737 use waratah_storage::text_index::DEFAULT_ANALYZER;
738
739 fn options(seed_chars: usize) -> TextIndexOptions {
740 TextIndexOptions::new(DEFAULT_ANALYZER, seed_chars, "text-index-v1;test")
741 }
742
743 fn doc(term: u8, lexical: &str) -> TextIndexDoc {
744 TextIndexDoc::new(vec![term], lexical, None)
745 }
746
747 fn sorted_terms(index: &TextIndex, request: TextSearchRequest) -> Vec<Vec<u8>> {
748 let mut terms = index.search(&request).unwrap();
749 terms.sort();
750 terms
751 }
752
753 #[test]
754 fn a_fenced_add_is_rejected_while_the_wipe_flag_is_set() {
755 let index = TextIndex::create_in_ram(&options(8)).unwrap();
756 index.add_batch(&[doc(1, "alpha")]).unwrap();
757 index.test_set_wiping(true);
762 assert!(matches!(
763 index.add_batch(&[doc(2, "beta")]),
764 Err(TextIndexError::WipeInProgress)
765 ));
766 let request = TextSearchRequest::fts("alpha");
767 assert_eq!(index.search(&request).unwrap().len(), 1);
768 assert_eq!(
769 index.search(&TextSearchRequest::fts("beta")).unwrap().len(),
770 0
771 );
772 index.test_set_wiping(false);
774 index.add_batch(&[doc(2, "beta")]).unwrap();
775 assert_eq!(
776 index.search(&TextSearchRequest::fts("beta")).unwrap().len(),
777 1
778 );
779 }
780
781 #[test]
782 fn wipe_clears_the_fence_when_it_completes() {
783 let index = TextIndex::create_in_ram(&options(8)).unwrap();
787 index.add_batch(&[doc(1, "alpha")]).unwrap();
788 index.wipe().unwrap();
789 index.add_batch(&[doc(2, "beta")]).unwrap();
790 assert_eq!(
791 index.search(&TextSearchRequest::fts("beta")).unwrap().len(),
792 1
793 );
794 assert_eq!(
795 index
796 .search(&TextSearchRequest::fts("alpha"))
797 .unwrap()
798 .len(),
799 0
800 );
801 }
802
803 #[test]
804 fn concurrent_wipes_and_fenced_adds_stay_consistent() {
805 let index = std::sync::Arc::new(TextIndex::create_in_ram(&options(8)).unwrap());
812 let adds = {
813 let index = std::sync::Arc::clone(&index);
814 std::thread::spawn(move || {
815 for i in 0..200u8 {
816 let _ = index.add_batch(&[doc(i, "marker")]);
817 }
818 })
819 };
820 let wipes = {
821 let index = std::sync::Arc::clone(&index);
822 std::thread::spawn(move || {
823 for _ in 0..20 {
824 index.wipe().unwrap();
825 }
826 })
827 };
828 adds.join().unwrap();
829 wipes.join().unwrap();
830 index.wipe().unwrap();
831 assert_eq!(index.doc_count(), 0);
832 index.add_batch(&[doc(9, "post")]).unwrap();
833 assert_eq!(
834 index.search(&TextSearchRequest::fts("post")).unwrap().len(),
835 1
836 );
837 }
838
839 #[test]
840 fn documents_survive_reopen_with_the_same_schema() {
841 let dir = tempfile::tempdir().unwrap();
842 let opts = options(16);
843 {
844 let index = TextIndex::open_or_create(dir.path(), &opts).unwrap();
845 index
846 .add_batch(&[doc(1, "alpha"), doc(2, "beta"), doc(3, "alphabet")])
847 .unwrap();
848 assert_eq!(index.doc_count(), 3);
849 assert_eq!(index.meta().unwrap().epoch, None);
850 index.stamp(7).unwrap();
851 }
852 let reopened = TextIndex::open_or_create(dir.path(), &opts).unwrap();
853 assert_eq!(reopened.doc_count(), 3);
854 assert_eq!(reopened.meta().unwrap().epoch, Some(7));
855 assert_eq!(
856 sorted_terms(&reopened, TextSearchRequest::prefix("alph")),
857 vec![vec![1u8], vec![3u8]]
858 );
859 }
860
861 #[test]
862 fn the_stored_sidecar_wins_over_fresh_options_on_reopen() {
863 let dir = tempfile::tempdir().unwrap();
867 {
868 let index = TextIndex::open_or_create(dir.path(), &options(16)).unwrap();
869 index.add_batch(&[doc(1, "alpha")]).unwrap();
870 index.stamp(3).unwrap();
871 }
872 let different = TextIndexOptions::new(DEFAULT_ANALYZER, 8, "text-index-v1;other");
873 let reopened = TextIndex::open_or_create(dir.path(), &different).unwrap();
874 assert_eq!(reopened.seed_chars(), 16, "stored seed length wins");
875 assert_eq!(reopened.fingerprint(), "text-index-v1;test");
876 assert_eq!(reopened.meta().unwrap().epoch, Some(3));
877 }
878
879 #[test]
880 fn a_directory_that_is_not_a_text_index_is_refused() {
881 let dir = tempfile::tempdir().unwrap();
882 let mut builder = tantivy::schema::Schema::builder();
883 builder.add_text_field("other", tantivy::schema::TEXT);
884 let _index = Index::create_in_dir(dir.path(), builder.build()).unwrap();
885 assert!(matches!(
886 TextIndex::open_or_create(dir.path(), &options(16)),
887 Err(TextIndexError::SchemaMismatch)
888 ));
889 }
890
891 #[test]
892 fn wipe_empties_documents_and_trust_but_keeps_the_directory() {
893 let dir = tempfile::tempdir().unwrap();
894 let index = TextIndex::open_or_create(dir.path(), &options(16)).unwrap();
895 index.add_batch(&[doc(1, "alpha"), doc(2, "beta")]).unwrap();
896 index.stamp(9).unwrap();
897 index.wipe().unwrap();
898 assert_eq!(index.doc_count(), 0);
899 let meta = index.meta().unwrap();
900 assert_eq!(meta.epoch, None, "a wipe clears the epoch");
901 assert_eq!(
902 meta.analyzer, DEFAULT_ANALYZER,
903 "the config survives a wipe"
904 );
905 assert!(
906 index
907 .search(&TextSearchRequest::prefix("a"))
908 .unwrap()
909 .is_empty()
910 );
911 index.add_batch(&[doc(3, "gamma")]).unwrap();
913 assert_eq!(
914 sorted_terms(&index, TextSearchRequest::prefix("gam")),
915 vec![vec![3u8]]
916 );
917 }
918
919 #[test]
920 fn a_wipe_that_cannot_enter_leaves_the_index_untouched_and_the_fence_free() {
921 let dir = tempfile::tempdir().unwrap();
928 {
929 let index = TextIndex::open_or_create(dir.path(), &options(16)).unwrap();
930 index
931 .add_batch(&[doc(1, "alpha"), doc(2, "beta"), doc(3, "alphabet")])
932 .unwrap();
933 index.stamp(42).unwrap();
934 assert_eq!(
935 meta::read_meta(dir.path()).unwrap().unwrap().epoch,
936 Some(42)
937 );
938
939 let poison = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
943 let _guard = index.writer.lock().unwrap();
944 panic!("poison the writer mutex");
945 }));
946 assert!(poison.is_err());
947
948 index.wipe().unwrap_err();
949 assert_eq!(
952 meta::read_meta(dir.path()).unwrap().unwrap().epoch,
953 Some(42),
954 "a wipe that cannot enter changes nothing"
955 );
956 assert_eq!(index.doc_count(), 3, "the deletion never ran");
957 assert!(!index.test_wiping(), "the fence is not stuck");
958 }
959 let reopened = TextIndex::open_or_create(dir.path(), &options(16)).unwrap();
962 assert_eq!(reopened.meta().unwrap().epoch, Some(42));
963 assert_eq!(reopened.doc_count(), 3);
964 }
965
966 #[test]
967 fn empty_batches_do_not_commit_or_change_the_index() {
968 let index = TextIndex::create_in_ram(&options(16)).unwrap();
969 index.add_batch(&[]).unwrap();
970 assert_eq!(index.doc_count(), 0);
971 index.add_batch(&[doc(1, "alpha")]).unwrap();
972 index.add_batch(&[]).unwrap();
973 assert_eq!(index.doc_count(), 1);
974 }
975
976 #[test]
977 fn repeated_documents_dedupe_in_the_candidate_set() {
978 let index = TextIndex::create_in_ram(&options(16)).unwrap();
979 index
980 .add_batch(&[doc(1, "alpha"), doc(1, "alpha"), doc(2, "alpine")])
981 .unwrap();
982 assert_eq!(
983 index.doc_count(),
984 2,
985 "the upsert keeps one document per (predicate, literal) identity"
986 );
987 assert_eq!(
988 sorted_terms(&index, TextSearchRequest::prefix("alp")),
989 vec![vec![1u8], vec![2u8]],
990 "the candidate set is deduped by term"
991 );
992 }
993
994 #[test]
995 fn a_second_batch_upserts_the_same_identity() {
996 let index = TextIndex::create_in_ram(&options(16)).unwrap();
997 index.add_batch(&[doc(1, "alpha")]).unwrap();
998 assert_eq!(index.doc_count(), 1);
999 index.add_batch(&[doc(1, "alpha")]).unwrap();
1003 assert_eq!(index.doc_count(), 1, "cross-batch upsert");
1004 index
1007 .add_batch(&[
1008 TextIndexDoc::new_with_predicate(vec![1], vec![9], "alpha", None),
1009 TextIndexDoc::new_with_predicate(vec![1], vec![10], "alpha", None),
1010 ])
1011 .unwrap();
1012 assert_eq!(index.doc_count(), 3, "one per identity");
1013 }
1014
1015 #[test]
1016 fn ram_and_disk_backends_agree() {
1017 let dir = tempfile::tempdir().unwrap();
1018 let opts = options(6);
1019 let literals = ["alpha", "alphabet", "beta", "héllo", "🌳tree"];
1020 let docs: Vec<TextIndexDoc> = literals
1021 .iter()
1022 .enumerate()
1023 .map(|(i, literal)| doc(i as u8, literal))
1024 .collect();
1025 let ram = TextIndex::create_in_ram(&opts).unwrap();
1026 ram.add_batch(&docs).unwrap();
1027 let disk = TextIndex::open_or_create(dir.path(), &opts).unwrap();
1028 disk.add_batch(&docs).unwrap();
1029 for request in [
1030 TextSearchRequest::prefix("al"),
1031 TextSearchRequest::prefix("hé"),
1032 TextSearchRequest::prefix("🌳"),
1033 TextSearchRequest::suffix("ha"),
1034 TextSearchRequest::fts("beta"),
1035 ] {
1036 assert_eq!(
1037 sorted_terms(&ram, request.clone()),
1038 sorted_terms(&disk, request.clone()),
1039 "request {request:?}"
1040 );
1041 }
1042 }
1043
1044 #[test]
1045 fn suffix_searches_the_last_characters_not_the_first() {
1046 let index = TextIndex::create_in_ram(&options(3)).unwrap();
1047 index
1048 .add_batch(&[doc(1, "abcxyz"), doc(2, "xyzabc"), doc(3, "midxyzmid")])
1049 .unwrap();
1050 assert_eq!(
1051 sorted_terms(&index, TextSearchRequest::suffix("xyz")),
1052 vec![vec![1u8]],
1053 "only the literal ending in xyz matches"
1054 );
1055 assert_eq!(
1056 sorted_terms(&index, TextSearchRequest::prefix("xyz")),
1057 vec![vec![2u8]],
1058 "prefix and suffix must not be confused"
1059 );
1060 }
1061
1062 #[test]
1063 fn invalid_options_are_rejected_before_touching_disk() {
1064 let dir = tempfile::tempdir().unwrap();
1065 assert!(matches!(
1066 TextIndex::open_or_create(dir.path(), &TextIndexOptions::new("klingon", 16, "f")),
1067 Err(TextIndexError::Config(_))
1068 ));
1069 assert!(matches!(
1070 TextIndex::open_or_create(dir.path(), &TextIndexOptions::new(DEFAULT_ANALYZER, 0, "f")),
1071 Err(TextIndexError::Config(_))
1072 ));
1073 assert!(matches!(
1074 TextIndex::open_or_create(dir.path(), &TextIndexOptions::new(DEFAULT_ANALYZER, 16, "")),
1075 Err(TextIndexError::Config(_))
1076 ));
1077 }
1078
1079 #[test]
1080 fn check_adoptable_accepts_its_own_index_and_rejects_mismatches() {
1081 let dir = tempfile::tempdir().unwrap();
1082 assert!(TextIndex::check_adoptable(dir.path(), "text-index-v2;test").is_ok());
1084 {
1085 let index = TextIndex::open_or_create(dir.path(), &options(16)).unwrap();
1086 index.add_batch(&[doc(1, "alpha")]).unwrap();
1087 index.stamp(3).unwrap();
1088 }
1089 assert!(TextIndex::check_adoptable(dir.path(), "text-index-v1;test").is_ok());
1091
1092 let reason = TextIndex::check_adoptable(dir.path(), "text-index-v2;other")
1095 .expect_err("a fingerprint mismatch must be refused");
1096 assert!(reason.contains("text-index-v1;test"), "{reason}");
1097 assert!(reason.contains("text-index-v2;other"), "{reason}");
1098
1099 std::fs::remove_file(dir.path().join(crate::meta::META_FILE)).unwrap();
1102 let reason = TextIndex::check_adoptable(dir.path(), "text-index-v1;test")
1103 .expect_err("an index without a sidecar must be refused");
1104 assert!(reason.contains("no sidecar"), "{reason}");
1105 }
1106
1107 #[test]
1108 fn merge_fruits_returns_ascending_term_bytes_across_segments() {
1109 let odd = TermFruit {
1115 terms: vec![vec![1], vec![3], vec![5], vec![7]],
1116 dictionary_error: None,
1117 };
1118 let even = TermFruit {
1119 terms: vec![vec![2], vec![3], vec![4], vec![6]],
1120 dictionary_error: None,
1121 };
1122 let merged = TermCollector::new(0)
1123 .merge_fruits(vec![odd, even])
1124 .expect("clean fruits merge");
1125 assert_eq!(
1126 merged.terms,
1127 (1u8..=7).map(|byte| vec![byte]).collect::<Vec<_>>()
1128 );
1129 }
1130
1131 #[test]
1132 fn a_scoped_search_only_returns_literals_under_the_named_predicates() {
1133 let p1 = b"http://ex/p1".to_vec();
1136 let p2 = b"http://ex/p2".to_vec();
1137 let p3 = b"http://ex/p3".to_vec();
1138 let index = TextIndex::create_in_ram(&options(16)).unwrap();
1139 index
1140 .add_batch(&[
1141 TextIndexDoc::new_with_predicate(vec![1], p1.clone(), "alpha", None),
1142 TextIndexDoc::new_with_predicate(vec![2], p1.clone(), "alpha", None),
1143 TextIndexDoc::new_with_predicate(vec![3], p2.clone(), "alpha", None),
1144 TextIndexDoc::new_with_predicate(vec![4], p3.clone(), "alpha", None),
1148 ])
1149 .unwrap();
1150 let request = TextSearchRequest::fts("alpha");
1151 assert_eq!(
1152 index
1153 .search_scoped(&request, std::slice::from_ref(&p1))
1154 .unwrap(),
1155 vec![vec![1u8], vec![2u8]]
1156 );
1157 assert_eq!(
1158 index
1159 .search_scoped(&request, std::slice::from_ref(&p2))
1160 .unwrap(),
1161 vec![vec![3u8]]
1162 );
1163 assert_eq!(
1166 index
1167 .search_scoped(&request, &[p1.clone(), p2.clone()])
1168 .unwrap(),
1169 vec![vec![1u8], vec![2u8], vec![3u8]]
1170 );
1171 let absent = b"http://ex/absent".to_vec();
1173 assert_eq!(
1174 index
1175 .search_scoped(&request, &[absent.clone(), p2.clone()])
1176 .unwrap(),
1177 vec![vec![3u8]]
1178 );
1179 assert_eq!(
1181 index.search_scoped(&request, &[]).unwrap(),
1182 vec![vec![1u8], vec![2u8], vec![3u8], vec![4u8]]
1183 );
1184 assert!(
1186 index
1187 .search_scoped(&request, std::slice::from_ref(&absent))
1188 .unwrap()
1189 .is_empty()
1190 );
1191 }
1192
1193 #[test]
1194 fn a_named_predicate_set_does_not_match_a_literal_under_another_predicate() {
1195 let p1 = b"http://ex/p1".to_vec();
1199 let p2 = b"http://ex/p2".to_vec();
1200 let p3 = b"http://ex/p3".to_vec();
1201 let index = TextIndex::create_in_ram(&options(16)).unwrap();
1202 index
1203 .add_batch(&[TextIndexDoc::new_with_predicate(
1204 vec![9],
1205 p3.clone(),
1206 "alpha",
1207 None,
1208 )])
1209 .unwrap();
1210 let request = TextSearchRequest::fts("alpha");
1211 assert!(
1212 index.search_scoped(&request, &[p1, p2]).unwrap().is_empty(),
1213 "a literal indexed only under p3 is not under p1 or p2"
1214 );
1215 assert_eq!(
1216 index
1217 .search_scoped(&request, std::slice::from_ref(&p3))
1218 .unwrap(),
1219 vec![vec![9u8]]
1220 );
1221 }
1222
1223 #[test]
1224 fn the_scoped_filter_composes_with_prefix_suffix_and_language() {
1225 let p1 = b"http://ex/p1".to_vec();
1229 let p2 = b"http://ex/p2".to_vec();
1230 let index = TextIndex::create_in_ram(&options(16)).unwrap();
1231 index
1232 .add_batch(&[
1233 TextIndexDoc::new_with_predicate(vec![1], p1.clone(), "alpha", None),
1234 TextIndexDoc::new_with_predicate(vec![2], p2.clone(), "alpha", None),
1235 TextIndexDoc::new_with_predicate(vec![3], p1.clone(), "beta", None),
1236 TextIndexDoc::new_with_predicate(vec![4], p2.clone(), "beta", None),
1237 ])
1238 .unwrap();
1239 let only_p1 = std::slice::from_ref(&p1);
1240 assert_eq!(
1241 index
1242 .search_scoped(&TextSearchRequest::prefix("al"), only_p1)
1243 .unwrap(),
1244 vec![vec![1u8]],
1245 "a prefix match under p2 must not leak into a p1-scoped drain"
1246 );
1247 assert_eq!(
1248 index
1249 .search_scoped(&TextSearchRequest::suffix("ta"), only_p1)
1250 .unwrap(),
1251 vec![vec![3u8]],
1252 "a suffix match under p2 must not leak into a p1-scoped drain"
1253 );
1254
1255 let index = TextIndex::create_in_ram(&options(16)).unwrap();
1258 index
1259 .add_batch(&[
1260 TextIndexDoc::new_with_predicate(
1261 vec![5],
1262 p1.clone(),
1263 "gamma",
1264 Some("en".to_owned()),
1265 ),
1266 TextIndexDoc::new_with_predicate(vec![6], p1.clone(), "gamma", None),
1267 ])
1268 .unwrap();
1269 let mut english = TextSearchRequest::fts("gamma");
1270 english.language = Some("en".to_owned());
1271 assert_eq!(
1272 index.search_scoped(&english, only_p1).unwrap(),
1273 vec![vec![5u8]],
1274 "the language conjunct survives the predicate filter"
1275 );
1276 assert_eq!(
1277 index
1278 .search_scoped(&TextSearchRequest::fts("gamma"), only_p1)
1279 .unwrap(),
1280 vec![vec![5u8], vec![6u8]]
1281 );
1282 }
1283
1284 #[test]
1285 fn a_multi_commit_search_emits_ascending_term_bytes() {
1286 let index = TextIndex::create_in_ram(&options(16)).unwrap();
1289 index
1290 .add_batch(&[doc(3, "alpha"), doc(1, "alpha"), doc(5, "alpha")])
1291 .unwrap();
1292 index
1293 .add_batch(&[doc(4, "alpha"), doc(2, "alpha")])
1294 .unwrap();
1295 let terms = index.search(&TextSearchRequest::fts("alpha")).unwrap();
1296 assert_eq!(terms, (1u8..=5).map(|byte| vec![byte]).collect::<Vec<_>>());
1297 }
1298
1299 #[test]
1300 fn a_failed_dictionary_walk_fails_the_merge_instead_of_truncating() {
1301 let collector = TermCollector::new(0);
1306 let failed = TermFruit {
1307 terms: vec![vec![1u8]],
1308 dictionary_error: Some("block read failed".to_owned()),
1309 };
1310 let error = collector
1311 .merge_fruits(vec![TermFruit::default(), failed])
1312 .expect_err("a failed dictionary walk must fail the merge");
1313 assert!(error.to_string().contains("block read failed"), "{error}");
1314 }
1315}