Skip to main content

waratah_text_index/
index.rs

1//! The partition-side text index: one Tantivy directory per O partition.
2//!
3//! Engineering rules this type enforces:
4//!
5//! - **One writer.** Tantivy permits one `IndexWriter` per directory; the
6//!   partition holds it behind a mutex and commits per batch.
7//! - **Commit then reload then acknowledge.** Readers use
8//!   [`ReloadPolicy::Manual`], and [`TextIndex::add_batch`] reloads before it
9//!   returns. The write path sends documents before the hexastore rows, so a
10//!   searchable document must exist before its row can become visible.
11//! - **The sidecar travels with the directory.** It records the analyzer, the
12//!   seed length, the fingerprint and the build epoch; [`TextIndex::wipe`]
13//!   clears the epoch, so an emptied index reads untrusted while its
14//!   configuration survives.
15
16use 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
34/// Writer memory arena. Large enough to batch a few thousand documents per
35/// segment before each per-batch commit, small enough that a plugin running
36/// beside the hexastore does not compete for RAM.
37pub const WRITER_MEMORY_BUDGET_BYTES: usize = 50_000_000;
38
39/// Number of indexing worker threads. One: the partition already has a
40/// blocking thread pool for storage, and a per-batch commit is the latency
41/// floor either way.
42const WRITER_THREADS: usize = 1;
43
44/// Tantivy's marker for a directory that already holds an index.
45const TANTIVY_META_FILE: &str = "meta.json";
46
47/// The configuration an index is created with, or adopted from its sidecar.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct TextIndexOptions {
50    /// Analyzer menu value (`simple`, `en_stem`, `whitespace`).
51    pub analyzer: String,
52    /// Characters stored in the bounded prefix and suffix fields.
53    pub seed_chars: usize,
54    /// Config fingerprint, stored for compute to compare against its own.
55    pub fingerprint: String,
56}
57
58impl TextIndexOptions {
59    /// Build options.
60    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    /// Reject values the engine cannot honour.
73    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
101/// A text index directory, or an in-memory index in tests and the memory
102/// backend.
103pub struct TextIndex {
104    index: Index,
105    schema: TextSchema,
106    analyzer: String,
107    seed_chars: usize,
108    fingerprint: String,
109    /// Sidecar contents as currently held. The in-memory backend has nowhere
110    /// else to keep the epoch, and the disk backend avoids a file read per
111    /// Describe.
112    meta: Mutex<TextIndexMeta>,
113    reader: IndexReader,
114    writer: Mutex<IndexWriter<TantivyDocument>>,
115    /// The wipe fence. Set at the start of [`TextIndex::wipe`] and cleared
116    /// at its end, both under the writer mutex — the same hold a put's
117    /// fence-check-and-commit runs under, so no document can commit
118    /// between the flag rising and the delete. Storage-only: the mutex is
119    /// the serialization point.
120    wiping: std::sync::atomic::AtomicBool,
121    dir: Option<PathBuf>,
122}
123
124impl TextIndex {
125    /// Open the index at `dir`, creating it when the directory holds no index
126    /// yet.
127    ///
128    /// A directory that already holds one is authoritative: its stored schema
129    /// and sidecar decide the analyzer and seed length, so reopening never has
130    /// to reconstruct them from configuration. `options` is used only when the
131    /// directory is empty. A directory that is not ours (wrong fields, wrong
132    /// field types) is an error rather than a silent mismatch.
133    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    /// Whether the index at `dir` can be adopted by a build configured with
164    /// `fingerprint`.
165    ///
166    /// Read-only and lock-free: reads the Tantivy meta and the sidecar, never
167    /// creates a directory, opens a writer, or rebuilds. `Ok(())` when `dir`
168    /// holds no index (a fresh store, which the normal build path covers) or
169    /// when the stored schema and fingerprint both match. A mismatch returns a
170    /// human-readable reason; the caller turns it into a fail-fast error,
171    /// because this build never rebuilds an existing index automatically —
172    /// its documents precede every axis write, so a schema mismatch later
173    /// fails every insert, not just `text:query`.
174    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    /// Live document count of an on-disk index, WITHOUT taking the writer
205    /// lock or creating anything: opens the committed segments read-only,
206    /// so `waratah text status` can inspect a directory without contending
207    /// with a live cluster's writer and without materializing an index in
208    /// a directory that has no Tantivy meta yet. Errors when the directory
209    /// holds no index.
210    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    /// An in-memory index. Used by the memory storage backend and by tests; the
220    /// documents vanish with the process, exactly like the store they mirror.
221    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        // The sidecar and the stored schema must agree about the analyzer: one
241        // of them is the source of truth for every query, and a disagreement
242        // would silently analyse queries with the wrong tokenizer.
243        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    /// Append one batch and publish it.
271    ///
272    /// `add_document` → `commit` → `IndexReader::reload` before returning. An
273    /// empty batch is a no-op: no commit, no reload.
274    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        // The wipe fence, checked under the SAME writer hold as the commit:
283        // a put either commits entirely before the wipe's flag rises (a
284        // pre-wipe put — its rows land before the walk's page and the walk
285        // re-derives them) or is rejected here. The rejection surfaces as a
286        // transient status, but the standard retry budget (milliseconds) is
287        // far shorter than any wipe, so in practice the insert FAILS
288        // LOUDLY and the load is rerun — documents are idempotent (dedup
289        // by term bytes) and no row lands on the rejected path. No commit
290        // can land between the flag rising and the delete — the
291        // check-then-act gap the old lease-based fence left open.
292        if self.wiping.load(std::sync::atomic::Ordering::SeqCst) {
293            return Err(TextIndexError::WipeInProgress);
294        }
295        // Upsert by the `(predicate, literal)` identity. The delete is a
296        // tombstone at an earlier opstamp, so it removes the previously
297        // committed document with this key AND one added earlier in this same
298        // commit; the add that follows survives, which makes the last write
299        // win. A per-batch `seen` set keeps the operation count down (and
300        // matches the ingest-side per-chunk dedup); it is not required for
301        // correctness.
302        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    /// Drain one candidate request into distinct encoded terms.
322    ///
323    /// The returned list is deduplicated by term bytes and sorted in
324    /// ascending encoded-term-byte order — the same byte order as the
325    /// hexastore's object key prefix. A consumer that walks one OPSG prefix
326    /// per literal therefore seeks in ascending key order, which keeps the
327    /// walk deterministic and avoids backtracking in the block cache; the
328    /// walks are still one prefix seek per literal, not a shared cursor.
329    /// Unlike the scan RPCs this is not a cursor: calling again restarts the
330    /// drain with an identical result for the same index state.
331    ///
332    /// The drain is UNBOUNDED in v1: every minted request carries
333    /// `limit: 0` (no caller arms the guard), so the whole distinct
334    /// candidate set materializes in one partition-side allocation — a
335    /// broad FTS query over a large vocabulary pays for it here. The
336    /// `CandidateLimitExceeded` arm below is therefore unreachable in v1;
337    /// it exists so arming a limit later is a one-line change, not a new
338    /// error path.
339    pub fn search(&self, request: &TextSearchRequest) -> Result<Vec<Vec<u8>>, TextIndexError> {
340        self.search_scoped(request, &[])
341    }
342
343    /// [`Self::search`] restricted to documents whose stored predicate is in
344    /// `predicates` (the encoded predicate bytes a document carries).
345    ///
346    /// An empty slice is no filter. The subject resolve passes the request's
347    /// whole predicate set in one call — the drain then returns each matching
348    /// literal once, and the OPSG walk (which uses the same set) resolves it
349    /// under every named predicate.
350    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        // The limit is a GLOBAL distinct count over the merged segments:
367        // exceeding it errors rather than truncating, because dropped
368        // candidates would drop rows. `merge_fruits` already collapses
369        // duplicates while it merges the sorted segment streams, so the
370        // length here is the distinct candidate count — no extra dedupe pass.
371        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        // The ascending order is a contract `search` documents (a consumer's
378        // per-literal prefix seeks advance monotonically); pin it where the
379        // segments merge.
380        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    /// Remove every document, keeping the configuration and clearing trust.
388    ///
389    /// Trust is cleared FIRST — the sidecar is rewritten with no epoch and
390    /// fsynced before any document is deleted — so every crash point leaves
391    /// a consistent on-disk state: either the old (complete) index under its
392    /// stamped epoch, or any document state under a cleared epoch. The
393    /// forbidden state — an empty index that still reads trusted — is
394    /// unreachable, and the next start rebuilds from the cleared epoch.
395    ///
396    /// Used by the startup build, which runs before anything serves and can
397    /// therefore safely start from an empty index. A build that runs while
398    /// serving must be additive instead: an in-progress write's document may be
399    /// committed while its row is not yet visible to the walk.
400    pub fn wipe(&self) -> Result<(), TextIndexError> {
401        let mut writer = self
402            .writer
403            .lock()
404            .map_err(|_| TextIndexError::WriterPoisoned)?;
405        // The fence flag lives exactly as long as the delete, under the
406        // same writer hold: a put's fence-check-and-commit serialises
407        // against this whole block, so nothing commits between the flag
408        // rising and the documents going. The wipe itself runs inside the
409        // hold — clear trust BEFORE deleting (the crash-safe order: any
410        // crash window leaves the old complete index under its stamp or
411        // any document state under a cleared epoch).
412        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        // The seed sketch is derived state of the wiped documents: remove
424        // it with them, so the next finish rebuilds it fresh and no stale
425        // sketch can outlive its index. (The sketch's own epoch gate is
426        // the correctness backstop; this is hygiene.) Every rebuild path
427        // wipes first — startup auto-build, this partition's lease begin,
428        // and the offline CLI — so removal here covers all of them.
429        if let Some(dir) = &self.dir {
430            let _ = std::fs::remove_file(dir.join(SKETCH_FILE));
431        }
432        Ok(())
433    }
434
435    /// Clear the trust marker: rewrite the sidecar with no epoch (atomic +
436    /// fsynced) and mirror it in memory, keeping analyzer, seed length, and
437    /// fingerprint. Documents are untouched — a crash after this step leaves
438    /// a populated but untrusted index, which the next start rebuilds.
439    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    /// Force the wipe fence flag. TEST-ONLY — deliberately shipped as
452    /// `#[doc(hidden)] pub` because `#[cfg(test)]` cannot work here: the
453    /// fence tests live in `waratah_partition`, which compiles this crate
454    /// as an ordinary dependency (cfg(test) off), and the flag is only up
455    /// for the microseconds of a real wipe's delete, so a deterministic
456    /// fence test needs it raised OUTSIDE a real wipe's hold.
457    ///
458    /// MISUSE IS LOUD AND STICKY: arming this outside tests fences EVERY
459    /// put — all text-index writes fail with `WipeInProgress` until
460    /// something calls this again with `false`. There is no automatic
461    /// disarm and no production path that disarms. Production code sets
462    /// the flag exclusively inside [`TextIndex::wipe`], under the writer
463    /// mutex; never call this from non-test code.
464    #[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    /// Read the wipe fence flag. TEST-ONLY, the observation half of
471    /// [`TextIndex::test_set_wiping`] (assertions like "the fence is not
472    /// stuck after a wipe"). Reading is harmless; the hazard is arming the
473    /// flag with the setter — see that method's warning.
474    #[doc(hidden)]
475    pub fn test_wiping(&self) -> bool {
476        self.wiping.load(std::sync::atomic::Ordering::SeqCst)
477    }
478
479    /// Number of live documents (one per indexed literal).
480    pub fn doc_count(&self) -> u64 {
481        self.reader.searcher().num_docs()
482    }
483
484    /// The schema this index was opened with.
485    pub fn schema(&self) -> &TextSchema {
486        &self.schema
487    }
488
489    /// The analyzer this index analyses `text` with.
490    pub fn analyzer(&self) -> &str {
491        &self.analyzer
492    }
493
494    /// The seed length the documents were built with.
495    pub fn seed_chars(&self) -> usize {
496        self.seed_chars
497    }
498
499    /// The config fingerprint the index was created under.
500    pub fn fingerprint(&self) -> &str {
501        &self.fingerprint
502    }
503
504    /// The directory, `None` for an in-memory index.
505    pub fn dir(&self) -> Option<&Path> {
506        self.dir.as_deref()
507    }
508
509    /// The index metadata, including the build epoch (`None` = not built).
510    ///
511    /// Held in memory so the RAM backend can report a stamped epoch exactly
512    /// like the disk backend; on disk it mirrors the sidecar.
513    pub fn meta(&self) -> Result<TextIndexMeta, TextIndexError> {
514        Ok(self
515            .meta
516            .lock()
517            .map_err(|_| TextIndexError::WriterPoisoned)?
518            .clone())
519    }
520
521    /// Stamp the index as built up to `epoch`.
522    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    /// The sidecar contents for this index, with no epoch.
536    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        // The Tantivy writer has no Debug, so summarize the identity and the
548        // live document count instead of mirroring every handle.
549        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    /// Distinct term bytes in ascending order. A segment's harvest emits
562    /// dictionary order: Tantivy assigns fast-field term ordinals by position
563    /// in the lexicographically sorted term list, so walking ordinals in
564    /// ascending order yields byte-ascending terms. `merge_fruits` preserves
565    /// that order across segments, so the whole search result is sorted.
566    terms: Vec<Vec<u8>>,
567    /// A term-dictionary walk that could not materialize every matching
568    /// ordinal (an I/O failure, or an ordinal the dictionary cannot resolve).
569    /// `SegmentCollector::harvest` cannot return an error, so the failure rides
570    /// the fruit and `merge_fruits` fails the whole search: a truncated
571    /// candidate set would silently drop rows for `text:query`, which has no
572    /// exact residual to answer them.
573    dictionary_error: Option<String>,
574}
575
576/// Collects the `term` fast field of every matching document.
577///
578/// A `TopDocs` collector plus a stored-document read would decompress one
579/// document per hit; the fast column gives the bytes directly.
580///
581/// The candidate limit is a GLOBAL distinct count: two segments with
582/// disjoint terms must not return `2 × limit` terms. So the segments only
583/// dedup their own documents — each one bounded at `limit + 1` distinct
584/// terms, because a segment holding more than `limit` already proves the
585/// union exceeds — and [`Collector::merge_fruits`] merges them into one
586/// ordered, deduplicated list. The exceed decision itself lives in `search()`, which
587/// errors `CandidateLimitExceeded` from the merged distinct count (dropped
588/// candidates would drop rows, so exceeding errors instead of truncating).
589/// `limit == 0` means unlimited: no stop, never exceeded.
590struct 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            // `limit == 0` means unlimited — the bound must never reject.
614            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        // k-way merge, not a hash-set union: each segment's `terms` is
628        // already ascending (`harvest` walks the segment's term dictionary by
629        // sorted ordinal, and ordinals follow the lexicographically sorted
630        // term list), and the search result's order is a contract — ascending
631        // encoded-term bytes, so a consumer's per-literal prefix seeks advance
632        // monotonically. Equal terms from different segments pop adjacently, so
633        // the first copy wins and the rest are skipped.
634        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                // Fail rather than answer from the terms that did resolve: a
638                // short candidate set is a silently wrong `text:query`.
639                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            // Advance this segment before deciding on the popped term: the
655            // next term from the same segment may be smaller than every other
656            // head.
657            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    /// Distinct term ordinals of the matching documents.
678    ///
679    /// Deduping by ordinal instead of by term bytes avoids one dictionary
680    /// seek (`ord_to_bytes`) and one `Vec<u8>` allocation per matching
681    /// document. `harvest` sorts these once and streams the dictionary SSTable
682    /// sequentially, so a multi-million-hit drain costs one dictionary pass
683    /// instead of millions of random block reads.
684    ords: FxHashSet<u64>,
685    /// Per-segment distinct-term bound (`limit + 1`): enough to prove the
686    /// merged union exceeds the limit, small enough to bound the collector's
687    /// memory on a guarded search.
688    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        // The ords are sorted, so this is a single sequential walk of the
715        // dictionary with one block open at a time. `Ok(false)` means the walk
716        // stopped before the last requested ordinal (the dictionary could not
717        // advance to it), so both that and an `Err` leave `terms` incomplete —
718        // see the fruit's `dictionary_error`.
719        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        // The flag raised is exactly what `wipe` holds across its
758        // flag-and-delete: a put is rejected BEFORE committing (no
759        // committed-then-deleted document) — the insert fails loudly and
760        // the load is rerun.
761        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        // The flag down: the retried frame lands.
773        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        // The walker's own re-derivation frames arrive AFTER the wipe —
784        // they must pass, or the startup rebuild could never index an
785        // existing store.
786        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        // Stress the serialization: adds and wipes racing on one writer.
806        // Every add either lands entirely before a wipe (and is deleted by
807        // it — the pre-wipe put the walk re-derives) or after it (and
808        // survives); a rejected add committed nothing. After all threads
809        // join with one final wipe, the index is empty and the writer is
810        // healthy.
811        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        // A seed-length change is data, not schema: the reopened index keeps
864        // the stored seed length, and compute detects the config change by
865        // comparing fingerprints.
866        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        // Still usable after the wipe.
912        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        // The fence flag lives under the writer hold, so a wipe that cannot
922        // even acquire the writer (here: the mutex poisoned; in production:
923        // a prior panic) fails at the DOOR: the index keeps its stamp and
924        // its documents (no partial state — the crash window lives INSIDE
925        // the hold, where trust is cleared before the delete), and the
926        // fence is NOT left stuck for later puts.
927        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            // Poison the writer mutex so the wipe cannot even enter: the
940            // panic is caught here, and the poisoning it leaves behind is
941            // the point.
942            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            // The wipe never entered: the stamp AND the documents are
950            // untouched, and the fence did not rise.
951            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        // Reopening (after the original handle released the directory lock)
960        // reads the untouched state — populated, trusted, stamp intact.
961        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        // Same `(predicate, literal)` identity across commits: the
1000        // delete-by-key tombstones the first document, so the index still
1001        // holds one.
1002        index.add_batch(&[doc(1, "alpha")]).unwrap();
1003        assert_eq!(index.doc_count(), 1, "cross-batch upsert");
1004        // A different predicate is a different identity, so it adds a
1005        // document.
1006        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        // No index yet: a fresh store, nothing to adopt.
1083        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        // Same schema and fingerprint: adoptable.
1090        assert!(TextIndex::check_adoptable(dir.path(), "text-index-v1;test").is_ok());
1091
1092        // A different fingerprint over the same schema (an older config or
1093        // generation) is refused, and the reason names both values.
1094        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        // A sidecar-less index (built by an older Waratah) is refused rather
1100        // than adopted with guessed settings.
1101        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        // Two segments whose terms interleave, with one term present in both.
1110        // The search result's order is a contract: ascending encoded-term
1111        // bytes, so a consumer's per-literal prefix seeks advance
1112        // monotonically. Equal terms must collapse and the survivors must be
1113        // strictly ascending.
1114        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        // The stored predicate is opaque bytes to this crate; any distinct
1134        // byte strings model three predicates.
1135        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                // The same literal under a predicate the query does not name:
1145                // the union must not pick it up, and its rows are not "under
1146                // p1 or p2" for the subject form's contract.
1147                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        // A set is a union, and each literal appears once even when it is
1164        // stored under several of the named predicates.
1165        assert_eq!(
1166            index
1167                .search_scoped(&request, &[p1.clone(), p2.clone()])
1168                .unwrap(),
1169            vec![vec![1u8], vec![2u8], vec![3u8]]
1170        );
1171        // A set with one absent member still matches the present ones.
1172        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        // No filter means every literal, whatever predicate carries it.
1180        assert_eq!(
1181            index.search_scoped(&request, &[]).unwrap(),
1182            vec![vec![1u8], vec![2u8], vec![3u8], vec![4u8]]
1183        );
1184        // A set of predicates the index does not hold matches nothing.
1185        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        // Regression for the should-only `BooleanQuery`: a query naming p1
1196        // and p2 must NOT return a document whose only predicate is p3. The
1197        // union is a requirement, not a scoring hint.
1198        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        // The predicate set is not an FTS-only concern: PREFIX/SUFFIX build a
1226        // different mode query, and the language filter nests another Must, so
1227        // the predicate OR must still conjoin with all of them.
1228        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        // The language restriction is a `Must` term on top of the mode query;
1256        // the predicate OR must not weaken it.
1257        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        // Two commits produce at least one segment per commit; whichever way
1287        // Tantivy groups them, the drain must come back sorted and deduped.
1288        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        // `harvest` cannot return an error, so a failed walk rides the fruit
1302        // and the merge turns it into an error. Answering from the terms that
1303        // did resolve would silently drop rows for `text:query`, which has no
1304        // exact residual to add the missing literals back.
1305        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}