zeppelin-embed 0.7.0

In-process vector, lexical, and hybrid search for macOS and Apple silicon
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
//! Scoped ownership of text returned from a ranked store query.

use super::{PublishedSnapshot, QueryCancellation, QueryError, SnapshotLease, Store, StoreError};
use crate::ingest::{
    ActiveSegment, DocId, DocumentVersion, GlobalRowId, RowSource, SearchCandidate,
};
use std::cell::Cell;
use std::num::NonZeroUsize;
use std::sync::Arc;

/// Per-hit hybrid snippets in rank order, or the failure to read a ranked
/// row's text. `None` marks a hit without stored text or without a match.
pub type HybridSnippets =
    Result<Vec<Option<crate::fts::query::OwnedLexicalSnippet>>, MaterializationError>;

/// Preserves a deferred vector producer's typed error separately from search.
#[derive(Debug)]
pub enum HybridPreparationError<E> {
    /// The caller could not produce a validated query vector.
    Preparation(E),
    /// Admission, retrieval, fusion, cancellation or materialization failed.
    Search(crate::fusion::FusionError),
}

impl<E> From<crate::fusion::FusionError> for HybridPreparationError<E> {
    fn from(error: crate::fusion::FusionError) -> Self {
        Self::Search(error)
    }
}

impl<E> From<QueryError> for HybridPreparationError<E> {
    fn from(error: QueryError) -> Self {
        Self::Search(error.into())
    }
}

impl<E: std::fmt::Display> std::fmt::Display for HybridPreparationError<E> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Preparation(error) => error.fmt(formatter),
            Self::Search(error) => error.fmt(formatter),
        }
    }
}

impl<E: std::error::Error + 'static> std::error::Error for HybridPreparationError<E> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Preparation(error) => Some(error),
            Self::Search(error) => Some(error),
        }
    }
}

#[cfg(any(test, feature = "test-seams"))]
#[derive(Default)]
pub(super) struct TestMaterializationWork {
    pub(super) admissions: std::sync::atomic::AtomicU64,
    pub(super) reverse_version_lookups: std::sync::atomic::AtomicU64,
    pub(super) direct_row_lookups: std::sync::atomic::AtomicU64,
    #[cfg(feature = "query-timing")]
    pub(super) lexical_admission_locks: std::sync::atomic::AtomicU64,
    #[cfg(feature = "query-timing")]
    pub(super) lexical_admission_lock_nanos: std::sync::atomic::AtomicU64,
}

#[cfg(all(feature = "query-timing", any(test, feature = "test-seams")))]
impl TestMaterializationWork {
    pub(super) fn observe_lexical_lock(&self, started: std::time::Instant) {
        use std::sync::atomic::Ordering::Relaxed;
        self.lexical_admission_locks.fetch_add(1, Relaxed);
        self.lexical_admission_lock_nanos.fetch_add(
            started.elapsed().as_nanos().min(u128::from(u64::MAX)) as u64,
            Relaxed,
        );
    }
}

/// Literal lifecycle and source-lookup observations for directed query tests.
#[cfg(any(test, feature = "test-seams"))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MaterializationTestCounters {
    /// Invocations of vector or lexical admission, including standalone stored_text.
    pub admissions: u64,
    /// Invocations of active or sealed reverse document-version lookup.
    pub reverse_version_lookups: u64,
    /// Ranked physical rows requested through the scoped materializer.
    pub direct_row_lookups: u64,
    /// Measured state, active, and snapshot lock acquisitions in lexical admission.
    #[cfg(feature = "query-timing")]
    pub lexical_admission_locks: u64,
    /// Wall nanoseconds in those acquisitions, including uncontended call overhead.
    #[cfg(feature = "query-timing")]
    pub lexical_admission_lock_nanos: u64,
}

/// One owned source row corresponding to a ranked query hit.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MaterializedRow {
    /// The exact document version whose row was scored.
    pub document: DocumentVersion,
    /// Original physical row coordinates within the retrieval snapshot.
    pub row_id: GlobalRowId,
    /// One owned copy of the stored UTF-8 body.
    pub text: String,
}

/// A ranked row could not be materialized faithfully.
#[derive(Debug)]
pub enum MaterializationError {
    /// The caller requested a rank outside the returned list.
    RankOutOfRange {
        /// Zero-based rank requested by the caller.
        rank: usize,
        /// Number of ranked hits available.
        returned: usize,
    },
    /// The ranked row has no application identity.
    MissingIdentity {
        /// Physical row lacking an application identity.
        row_id: GlobalRowId,
    },
    /// The ranked document has no stored text.
    MissingText {
        /// Physical row lacking stored text.
        row_id: GlobalRowId,
        /// Ranked application identity.
        document: DocumentVersion,
    },
    /// The ranked physical source is absent from the admitted snapshot.
    MissingSource {
        /// Physical row whose source is absent.
        row_id: GlobalRowId,
    },
    /// A lexical source ordinal has no physical source in the admitted assembly.
    InvalidLexicalSource {
        /// Source ordinal from the ranked lexical hit.
        source: u32,
    },
    /// A fused application key has no retained source identity.
    MissingFusedIdentity {
        /// Fused application key lacking source coordinates.
        document: DocId,
    },
    /// The physical row does not contain the version that was ranked.
    IdentityMismatch {
        /// Physical row that failed identity validation.
        row_id: GlobalRowId,
        /// Application identity retained during ranking.
        expected: DocumentVersion,
        /// Application identity found at the physical row.
        actual: Option<DocumentVersion>,
    },
    /// The result could not reserve its owned text buffer.
    AllocationFailed {
        /// UTF-8 text bytes requested from the allocator.
        bytes: usize,
    },
    /// A materialization work count overflowed.
    ArithmeticOverflow,
    /// Cancellation or deadline prevented complete materialization.
    Query(QueryError),
    /// Storage validation or lifecycle failure.
    Storage(StoreError),
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct VersionMismatch {
    pub(crate) expected: DocumentVersion,
    pub(crate) actual: Option<DocumentVersion>,
}

pub(crate) fn require_document_version(
    expected: DocumentVersion,
    actual: Option<DocumentVersion>,
) -> Result<(), VersionMismatch> {
    if actual == Some(expected) {
        Ok(())
    } else {
        Err(VersionMismatch { expected, actual })
    }
}

impl std::fmt::Display for MaterializationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::RankOutOfRange { rank, returned } => {
                write!(f, "result rank {rank} is outside {returned} returned rows")
            }
            Self::MissingIdentity { row_id } => {
                write!(f, "result row {row_id:?} has no document identity")
            }
            Self::MissingText { row_id, document } => write!(
                f,
                "result row {row_id:?} for {document:?} has no stored text"
            ),
            Self::MissingSource { row_id } => {
                write!(f, "result row {row_id:?} is outside the admitted snapshot")
            }
            Self::InvalidLexicalSource { source } => write!(
                f,
                "lexical result source {source} is outside the admitted assembly"
            ),
            Self::MissingFusedIdentity { document } => write!(
                f,
                "fused document {document:?} has no ranked source identity"
            ),
            Self::IdentityMismatch {
                row_id,
                expected,
                actual,
            } => write!(
                f,
                "result row {row_id:?} expected {expected:?}, found {actual:?}"
            ),
            Self::AllocationFailed { bytes } => {
                write!(f, "result text allocation of {bytes} bytes failed")
            }
            Self::ArithmeticOverflow => f.write_str("result materialization counter overflow"),
            Self::Query(error) => error.fmt(f),
            Self::Storage(error) => error.fmt(f),
        }
    }
}
impl std::error::Error for MaterializationError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Storage(error) => Some(error),
            Self::Query(error) => Some(error),
            _ => None,
        }
    }
}

/// Rank-addressed text access available only inside a Store query callback.
pub struct QueryMaterializer<'a> {
    #[cfg(any(test, feature = "test-seams"))]
    pub(super) store: &'a Store,
    pub(super) snapshot: &'a PublishedSnapshot,
    pub(super) active: &'a ActiveSegment,
    pub(super) cancellation: &'a QueryCancellation<'a>,
    pub(super) address: &'a dyn Fn(usize) -> Result<ResultAddress, MaterializationError>,
    pub(super) counts: Cell<crate::diag::MaterializationCounters>,
}

#[derive(Clone, Copy, Eq, PartialEq)]
pub(super) struct ResultAddress {
    pub(super) row_id: GlobalRowId,
    pub(super) document: Option<DocumentVersion>,
}

pub(super) type HybridAddresses = super::stats::Accounted<Vec<(DocId, ResultAddress)>>;

impl From<&SearchCandidate> for ResultAddress {
    fn from(candidate: &SearchCandidate) -> Self {
        Self {
            row_id: candidate.row_id(),
            document: candidate.document(),
        }
    }
}

impl QueryMaterializer<'_> {
    /// Copies the exact stored text and version associated with one result rank.
    pub fn text(&self, rank: usize) -> Result<MaterializedRow, MaterializationError> {
        self.check()?;
        let address = (self.address)(rank)?;
        self.materialize_address(address)
    }

    /// Plants a wrong or missing ranked identity at the actual physical-row validation seam.
    #[cfg(any(test, feature = "test-seams"))]
    pub fn text_with_test_document(
        &self,
        rank: usize,
        document: Option<DocumentVersion>,
    ) -> Result<MaterializedRow, MaterializationError> {
        self.check()?;
        let mut address = (self.address)(rank)?;
        address.document = document;
        self.materialize_address(address)
    }

    fn materialize_address(
        &self,
        address: ResultAddress,
    ) -> Result<MaterializedRow, MaterializationError> {
        let row_id = address.row_id;
        let document = address
            .document
            .ok_or(MaterializationError::MissingIdentity { row_id })?;
        #[cfg(any(test, feature = "test-seams"))]
        self.store
            .text_materialization_work
            .direct_row_lookups
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let mut counts = self.counts.get();
        counts.row_lookups = counts
            .row_lookups
            .checked_add(1)
            .ok_or(MaterializationError::ArithmeticOverflow)?;
        self.counts.set(counts);
        let row = row_id.local_row() as usize;
        let (actual, source) = match row_id.source() {
            RowSource::Active => (
                self.active.document(row),
                self.active
                    .text(row)
                    .map_err(MaterializationError::Storage)?,
            ),
            RowSource::Sealed(id) => {
                let segment = self
                    .snapshot
                    .segments()
                    .iter()
                    .find(|segment| segment.meta().id == id)
                    .ok_or(MaterializationError::MissingSource { row_id })?;
                let actual = segment
                    .document_version(row)
                    .map_err(StoreError::Segment)
                    .map_err(MaterializationError::Storage)?;
                let source = segment
                    .query_stored_text()
                    .map_err(StoreError::Segment)
                    .map_err(MaterializationError::Storage)?
                    .and_then(|text| text.row(row).flatten());
                (actual, source)
            }
        };
        require_document_version(document, actual).map_err(|mismatch| {
            MaterializationError::IdentityMismatch {
                row_id,
                expected: mismatch.expected,
                actual: mismatch.actual,
            }
        })?;
        let source = source.ok_or(MaterializationError::MissingText { row_id, document })?;
        let mut text = String::new();
        text.try_reserve_exact(source.len()).map_err(|_| {
            MaterializationError::AllocationFailed {
                bytes: source.len(),
            }
        })?;
        text.push_str(source);
        let mut counts = self.counts.get();
        counts.text_copies = counts
            .text_copies
            .checked_add(1)
            .ok_or(MaterializationError::ArithmeticOverflow)?;
        counts.text_bytes = counts
            .text_bytes
            .checked_add(source.len() as u64)
            .ok_or(MaterializationError::ArithmeticOverflow)?;
        self.counts.set(counts);
        self.check()?;
        Ok(MaterializedRow {
            document,
            row_id,
            text,
        })
    }

    fn check(&self) -> Result<(), MaterializationError> {
        self.cancellation
            .check_graph()
            .map_err(super::map_scan_error)
            .map_err(MaterializationError::Query)
    }
}

impl Store {
    /// Starts lexical retrieval before obtaining a caller-owned query vector.
    /// Both legs and returned text use one admission pinned before the producer
    /// runs. All submitted lexical work is joined on producer failure or panic.
    ///
    /// The returned vector borrow must remain valid for the complete query.
    /// Producer errors retain their original type; core failures are separate.
    ///
    /// # Errors
    /// Returns the producer's error or a typed admission/search failure.
    pub fn search_hybrid_with_text_deferred<'vector, E, R>(
        &self,
        prepare_vector: impl FnOnce() -> Result<crate::ingest::SearchRequest<'vector>, E>,
        lexical: &crate::fts::search::TermQuery,
        query: &crate::fusion::HybridQuery,
        options: impl Into<super::SearchOptions>,
        control: super::QueryControl,
        finish: impl FnOnce(&crate::ingest::StoreHybridSearchOutcome, &QueryMaterializer<'_>) -> R,
    ) -> Result<(crate::ingest::StoreHybridSearchOutcome, R), HybridPreparationError<E>> {
        self.search_hybrid_pinned_with_text(
            prepare_vector,
            None,
            None,
            super::PinnedLexicalQuery::Term(lexical),
            query,
            options.into(),
            control,
            finish,
        )
    }

    #[allow(clippy::too_many_arguments)] // Pinned query inputs plus its scoped continuation.
    fn search_hybrid_pinned_with_text<'vector, E, R>(
        &self,
        prepare_vector: impl FnOnce() -> Result<crate::ingest::SearchRequest<'vector>, E>,
        filter: Option<&super::QueryFilter>,
        eligible: Option<&[crate::ingest::DocId]>,
        lexical: super::PinnedLexicalQuery<'_>,
        query: &crate::fusion::HybridQuery,
        options: super::SearchOptions,
        control: super::QueryControl,
        finish: impl FnOnce(&crate::ingest::StoreHybridSearchOutcome, &QueryMaterializer<'_>) -> R,
    ) -> Result<(crate::ingest::StoreHybridSearchOutcome, R), HybridPreparationError<E>> {
        self.search_hybrid_prepared_then(
            prepare_vector,
            filter,
            eligible,
            lexical,
            query,
            options,
            control,
            true,
            None,
            |mut outcome, snapshot, active, cancellation, addresses| {
                cancellation.check_graph().map_err(super::map_scan_error)?;
                let address = |rank| {
                    let hit =
                        outcome
                            .hits
                            .get(rank)
                            .ok_or(MaterializationError::RankOutOfRange {
                                rank,
                                returned: outcome.hits.len(),
                            })?;
                    let addresses = addresses
                        .ok_or(MaterializationError::MissingFusedIdentity { document: hit.key })?;
                    let index = addresses
                        .binary_search_by_key(&hit.key, |(key, _)| *key)
                        .map_err(|_| MaterializationError::MissingFusedIdentity {
                            document: hit.key,
                        })?;
                    addresses
                        .get(index)
                        .map(|(_, address)| *address)
                        .ok_or(MaterializationError::MissingFusedIdentity { document: hit.key })
                };
                let materializer = QueryMaterializer {
                    #[cfg(any(test, feature = "test-seams"))]
                    store: self,
                    snapshot,
                    active,
                    cancellation,
                    address: &address,
                    counts: Cell::new(Default::default()),
                };
                let value = finish(&outcome, &materializer);
                let counts = materializer.counts.get();
                outcome.diagnostics.materialization = Some(counts);
                cancellation.check_graph().map_err(super::map_scan_error)?;
                Ok((outcome, value))
            },
        )
    }

    /// Reads literal counters without resetting concurrent observations.
    #[cfg(any(test, feature = "test-seams"))]
    #[must_use]
    pub fn query_materialization_test_counters(&self) -> MaterializationTestCounters {
        use std::sync::atomic::Ordering::Relaxed;
        MaterializationTestCounters {
            admissions: self.text_materialization_work.admissions.load(Relaxed),
            reverse_version_lookups: self
                .text_materialization_work
                .reverse_version_lookups
                .load(Relaxed),
            direct_row_lookups: self
                .text_materialization_work
                .direct_row_lookups
                .load(Relaxed),
            #[cfg(feature = "query-timing")]
            lexical_admission_locks: self
                .text_materialization_work
                .lexical_admission_locks
                .load(Relaxed),
            #[cfg(feature = "query-timing")]
            lexical_admission_lock_nanos: self
                .text_materialization_work
                .lexical_admission_lock_nanos
                .load(Relaxed),
        }
    }
    /// Runs hybrid fusion and constructs caller-owned results before releasing its snapshot.
    pub fn search_hybrid_with_text<R>(
        &self,
        vector: crate::ingest::SearchRequest<'_>,
        lexical: &crate::fts::search::TermQuery,
        query: &crate::fusion::HybridQuery,
        options: impl Into<super::SearchOptions>,
        control: super::QueryControl,
        finish: impl FnOnce(&crate::ingest::StoreHybridSearchOutcome, &QueryMaterializer<'_>) -> R,
    ) -> Result<(crate::ingest::StoreHybridSearchOutcome, R), crate::fusion::FusionError> {
        self.search_hybrid_pinned_with_text(
            || Ok::<_, std::convert::Infallible>(vector),
            vector.filter,
            vector.eligible,
            super::PinnedLexicalQuery::Term(lexical),
            query,
            options.into(),
            control,
            finish,
        )
        .map_err(|error| match error {
            HybridPreparationError::Preparation(never) => match never {},
            HybridPreparationError::Search(error) => error,
        })
    }

    /// Runs a flat-term lexical query and returns one snippet per candidate,
    /// in rank order, cut from the text pinned for the query's generation.
    ///
    /// Highlights are the tokens the store's own analyzer produces from that
    /// text whose analyzed term is one of the query's terms, which is exactly
    /// what the lexical leg scored.
    ///
    /// # Errors
    /// Returns the search failure, or [`crate::ingest::StoreLexicalError::MissingSnippetMatch`]
    /// when a ranked row's stored text contains none of the query's terms.
    pub fn search_lexical_with_snippets(
        &self,
        query: &crate::fts::search::TermQuery,
        k: usize,
        window: NonZeroUsize,
        control: super::QueryControl,
    ) -> Result<
        (
            crate::ingest::StoreLexicalSearchOutcome,
            Vec<crate::fts::query::OwnedLexicalSnippet>,
        ),
        crate::ingest::StoreLexicalError,
    > {
        self.search_lexical_filtered_with_snippets(query, k, window, control, None)
    }

    /// Searches eligible lexical rows and materializes snippets at the same generation.
    pub fn search_lexical_filtered_with_snippets(
        &self,
        query: &crate::fts::search::TermQuery,
        k: usize,
        window: NonZeroUsize,
        control: super::QueryControl,
        filter: Option<&super::QueryFilter>,
    ) -> Result<
        (
            crate::ingest::StoreLexicalSearchOutcome,
            Vec<crate::fts::query::OwnedLexicalSnippet>,
        ),
        crate::ingest::StoreLexicalError,
    > {
        self.search_lexical_then(
            query,
            k,
            control,
            filter,
            |outcome, snapshot, active, assembly, hits, cancellation| {
                let mut snippets = Vec::with_capacity(hits.len());
                for hit in hits {
                    cancellation.check_graph().map_err(super::map_scan_error)?;
                    let (text, _) = super::structured_lexical_row(
                        snapshot,
                        active,
                        &assembly.sources,
                        hit.doc,
                    )?;
                    snippets.push(
                        crate::fts::snippet::owned_window(
                            &self.tokenizer,
                            text,
                            &query.terms,
                            window,
                        )
                        .ok_or(
                            crate::ingest::StoreLexicalError::MissingSnippetMatch {
                                segment: hit.doc.segment,
                                row: hit.doc.row,
                            },
                        )?,
                    );
                }
                Ok((outcome, snippets))
            },
        )
    }

    /// Runs hybrid fusion over a flat-term lexical leg and returns one
    /// optional snippet per fused hit, in rank order, cut from the text pinned
    /// for the query's generation. A hit gets no snippet when its row has no
    /// stored text or the text contains none of the query's terms.
    ///
    /// # Errors
    /// Returns the search failure; the inner result carries a failure to read
    /// a ranked row's text.
    pub fn search_hybrid_with_snippets(
        &self,
        vector: crate::ingest::SearchRequest<'_>,
        lexical: &crate::fts::search::TermQuery,
        query: &crate::fusion::HybridQuery,
        options: impl Into<super::SearchOptions>,
        control: super::QueryControl,
        window: NonZeroUsize,
    ) -> Result<(crate::ingest::StoreHybridSearchOutcome, HybridSnippets), crate::fusion::FusionError>
    {
        self.hybrid_snippets(
            vector,
            super::PinnedLexicalQuery::Term(lexical),
            query,
            options.into(),
            control,
            window,
        )
    }

    /// [`Self::search_hybrid_with_snippets`] for a structured lexical leg.
    /// Highlights mark the terms of the leg's reported expansions, so a prefix
    /// marks every indexed term it expanded to.
    ///
    /// # Errors
    /// As [`Self::search_hybrid_with_snippets`].
    pub fn search_hybrid_structured_with_snippets(
        &self,
        vector: crate::ingest::SearchRequest<'_>,
        lexical: &crate::fts::query::LexicalQuery,
        query: &crate::fusion::HybridQuery,
        options: impl Into<super::SearchOptions>,
        control: super::QueryControl,
        window: NonZeroUsize,
    ) -> Result<(crate::ingest::StoreHybridSearchOutcome, HybridSnippets), crate::fusion::FusionError>
    {
        self.hybrid_snippets(
            vector,
            super::PinnedLexicalQuery::Structured(lexical),
            query,
            options.into(),
            control,
            window,
        )
    }

    fn hybrid_snippets(
        &self,
        vector: crate::ingest::SearchRequest<'_>,
        lexical: super::PinnedLexicalQuery<'_>,
        query: &crate::fusion::HybridQuery,
        options: super::SearchOptions,
        control: super::QueryControl,
        window: NonZeroUsize,
    ) -> Result<(crate::ingest::StoreHybridSearchOutcome, HybridSnippets), crate::fusion::FusionError>
    {
        let flat_terms = match lexical {
            super::PinnedLexicalQuery::Term(query) => Some(&query.terms),
            super::PinnedLexicalQuery::Structured(_) => None,
        };
        self.search_hybrid_pinned_with_text(
            || Ok::<_, std::convert::Infallible>(vector),
            vector.filter,
            vector.eligible,
            lexical,
            query,
            options,
            control,
            |outcome, materializer| {
                let expanded;
                let terms: &[Vec<u8>] = match flat_terms {
                    Some(terms) => terms,
                    None => {
                        expanded = outcome
                            .lexical_expansions
                            .iter()
                            .map(|expansion| expansion.term.clone())
                            .collect::<Vec<_>>();
                        &expanded
                    }
                };
                let mut snippets = Vec::with_capacity(outcome.hits.len());
                for rank in 0..outcome.hits.len() {
                    let row = match materializer.text(rank) {
                        Ok(row) => row,
                        Err(MaterializationError::MissingText { .. }) => {
                            snippets.push(None);
                            continue;
                        }
                        Err(error) => return Err(error),
                    };
                    snippets.push(crate::fts::snippet::owned_window(
                        &self.tokenizer,
                        &row.text,
                        terms,
                        window,
                    ));
                }
                Ok(snippets)
            },
        )
        .map_err(|error| match error {
            HybridPreparationError::Preparation(never) => match never {},
            HybridPreparationError::Search(error) => error,
        })
    }

    /// Runs a lexical query and constructs caller-owned results before releasing its snapshot.
    pub fn search_lexical_with_text<R>(
        &self,
        query: &crate::fts::search::TermQuery,
        k: usize,
        control: super::QueryControl,
        finish: impl FnOnce(&crate::ingest::StoreLexicalSearchOutcome, &QueryMaterializer<'_>) -> R,
    ) -> Result<(crate::ingest::StoreLexicalSearchOutcome, R), crate::ingest::StoreLexicalError>
    {
        self.search_lexical_then(
            query,
            k,
            control,
            None,
            |mut outcome, snapshot, active, assembly, hits, cancellation| {
                cancellation.check_graph().map_err(super::map_scan_error)?;
                let address = |rank| {
                    let candidate = outcome.candidates.get(rank).ok_or(
                        MaterializationError::RankOutOfRange {
                            rank,
                            returned: outcome.candidates.len(),
                        },
                    )?;
                    let hit = hits.get(rank).ok_or(MaterializationError::RankOutOfRange {
                        rank,
                        returned: hits.len(),
                    })?;
                    Ok(ResultAddress {
                        row_id: lexical_row_id(snapshot, &assembly.sources, hit.doc)?,
                        document: Some(candidate.document),
                    })
                };
                let materializer = QueryMaterializer {
                    #[cfg(any(test, feature = "test-seams"))]
                    store: self,
                    snapshot,
                    active,
                    cancellation,
                    address: &address,
                    counts: Cell::new(Default::default()),
                };
                let value = finish(&outcome, &materializer);
                let counts = materializer.counts.get();
                outcome.diagnostics.materialization = Some(counts);
                cancellation.check_graph().map_err(super::map_scan_error)?;
                Ok((outcome, value))
            },
        )
    }

    /// Runs a dense query and constructs owned caller results through rank-addressed text access.
    pub fn search_with_text<R>(
        &self,
        request: crate::ingest::SearchRequest<'_>,
        k: usize,
        options: impl Into<super::SearchOptions>,
        control: super::QueryControl,
        finish: impl FnOnce(&crate::ingest::SearchOutcome, &QueryMaterializer<'_>) -> R,
    ) -> Result<(crate::ingest::SearchOutcome, R), super::QueryError> {
        self.search_with_graph_bound_mode_then(
            request,
            k,
            options.into(),
            control,
            super::GraphBoundMode::Shared,
            |mut outcome, admitted, control| {
                let lease =
                    SnapshotLease::new_at(Arc::clone(&admitted.snapshot), admitted.generation);
                let cancellation = QueryCancellation::new(control, &lease);
                cancellation.check_graph().map_err(super::map_scan_error)?;
                let address = |rank| {
                    outcome.candidates.get(rank).map(ResultAddress::from).ok_or(
                        MaterializationError::RankOutOfRange {
                            rank,
                            returned: outcome.candidates.len(),
                        },
                    )
                };
                let materializer = QueryMaterializer {
                    #[cfg(any(test, feature = "test-seams"))]
                    store: self,
                    counts: Cell::new(Default::default()),
                    snapshot: &admitted.snapshot,
                    active: &admitted.active_segment,
                    cancellation: &cancellation,
                    address: &address,
                };
                let value = finish(&outcome, &materializer);
                let counts = materializer.counts.get();
                outcome.diagnostics.materialization = Some(counts);
                cancellation.check_graph().map_err(super::map_scan_error)?;
                Ok((outcome, value))
            },
        )
    }
}

fn lexical_row_id(
    snapshot: &PublishedSnapshot,
    sources: &[super::StructuredLexicalSource],
    doc: crate::fts::search::GlobalDocId,
) -> Result<GlobalRowId, MaterializationError> {
    let source =
        sources
            .get(doc.segment as usize)
            .ok_or(MaterializationError::InvalidLexicalSource {
                source: doc.segment,
            })?;
    let source = match source {
        super::StructuredLexicalSource::Active => RowSource::Active,
        super::StructuredLexicalSource::Sealed(ordinal) => RowSource::Sealed(
            snapshot
                .segments()
                .get(*ordinal)
                .ok_or(MaterializationError::InvalidLexicalSource {
                    source: doc.segment,
                })?
                .meta()
                .id,
        ),
    };
    Ok(GlobalRowId::new(source, doc.row))
}