ld-lucivy 0.26.1

BM25 search engine with cross-token fuzzy matching, substring search, regex, and highlights
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
//! N-gram based contains query for fast substring search.
//!
//! Uses a `._ngram` field (trigrams) to quickly identify candidate documents,
//! then verifies matches by reading stored text. Replaces the expensive FST walk
//! (levels 3–4 of the cascade) with O(k lookups + candidates) via trigram index.
//!
//! Cascade:
//!   1. **Exact**: term dict lookup on raw field — O(1)
//!   2. **Ngram**: trigram lookup on ngram field + verification — O(k + candidates)
//!
//! Verification mode:
//!   - **Fuzzy**: token-by-token matching with Levenshtein distance (default)
//!   - **Regex**: compiled regex on stored text, with optional fuzzy on extracted literals

use std::cmp::{max, min};
use std::sync::Arc;

use regex::Regex;

use super::scoring_utils::{
    edit_distance, fold_with_byte_map, generate_trigrams, intersect_sorted_vecs, ngram_threshold,
    token_match_distance, tokenize_raw, HighlightSink,
};
use crate::fieldnorm::FieldNormReader;
use crate::query::bm25::Bm25Weight;
use crate::query::{EmptyScorer, EnableScoring, Explanation, Query, Scorer, Weight};
use crate::schema::document::Value;
use crate::schema::{Field, IndexRecordOption, Term};
use crate::index::SegmentId;
use crate::{DocId, DocSet, InvertedIndexReader, Score, SegmentReader, LucivyDocument, TERMINATED};

// ─── Candidate Collection ──────────────────────────────────────────────────

/// Collect doc_ids from a single term's posting list.
fn collect_posting_docs(
    inverted_index: &InvertedIndexReader,
    term: &Term,
) -> crate::Result<Vec<DocId>> {
    let term_info = match inverted_index.get_term_info(term)? {
        Some(ti) => ti,
        None => return Ok(Vec::new()),
    };
    let mut docs = Vec::new();
    let mut block_postings =
        inverted_index.read_block_postings_from_terminfo(&term_info, IndexRecordOption::Basic)?;
    loop {
        let block = block_postings.docs();
        if block.is_empty() {
            break;
        }
        docs.extend_from_slice(block);
        block_postings.advance();
    }
    Ok(docs)
}

/// Get candidate doc_ids for a query token via threshold-based trigram intersection.
fn ngram_candidates_for_token(
    token: &str,
    ngram_field: Field,
    ngram_inverted: &InvertedIndexReader,
    fuzzy_distance: u8,
) -> crate::Result<Vec<DocId>> {
    let trigrams = generate_trigrams(token);
    let threshold = ngram_threshold(trigrams.len(), fuzzy_distance);

    if trigrams.is_empty() {
        return Ok(Vec::new());
    }

    // Collect all doc_ids from all trigram posting lists.
    let mut all_docs: Vec<DocId> = Vec::new();
    for trigram in &trigrams {
        let term = Term::from_field_text(ngram_field, trigram);
        let docs = collect_posting_docs(ngram_inverted, &term)?;
        all_docs.extend(docs);
    }

    // Sort and count: keep doc_ids appearing >= threshold times.
    all_docs.sort_unstable();

    let mut candidates = Vec::new();
    let mut i = 0;
    while i < all_docs.len() {
        let doc = all_docs[i];
        let mut count = 0usize;
        while i < all_docs.len() && all_docs[i] == doc {
            count += 1;
            i += 1;
        }
        if count >= threshold {
            candidates.push(doc);
        }
    }

    Ok(candidates)
}

// ─── Verification Mode ──────────────────────────────────────────────────────

/// Parameters for fuzzy substring verification.
#[derive(Clone, Debug)]
#[allow(missing_docs)]
pub struct FuzzyParams {
    pub tokens: Vec<String>,
    pub separators: Vec<String>,
    pub prefix: String,
    pub suffix: String,
    pub fuzzy_distance: u8,
    pub distance_budget: u32,
    pub strict_separators: bool,
}

/// Parameters for regex verification (with optional fuzzy on extracted literals).
#[derive(Clone, Debug)]
pub struct RegexParams {
    /// Compiled regex pattern for verification on stored text.
    pub compiled: Regex,
    /// Literals extracted from the regex AST (for hybrid fuzzy + trigram generation).
    pub literals: Vec<String>,
    /// Fuzzy distance for hybrid verification: 0 = regex only, >0 = regex OR fuzzy on literals.
    pub fuzzy_distance: u8,
}

/// Verification mode for NgramContainsQuery.
///
/// Determines how candidate documents are verified after trigram-based
/// candidate collection.
#[derive(Clone, Debug)]
pub enum VerificationMode {
    /// Fuzzy substring verification: token-by-token matching with
    /// Levenshtein distance, separator validation, and prefix/suffix checks.
    Fuzzy(FuzzyParams),
    /// Regex verification on stored text, with optional hybrid fuzzy on extracted literals.
    Regex(RegexParams),
}

// ─── Query ─────────────────────────────────────────────────────────────────

/// N-gram based contains query: trigram lookup + stored text verification.
///
/// Uses a trigram field to quickly narrow candidates, then verifies matches
/// by reading stored text. This avoids expensive FST walks for substring matching.
#[derive(Clone, Debug)]
pub struct NgramContainsQuery {
    raw_field: Field,
    ngram_field: Field,
    stored_field: Option<Field>,
    trigram_sources: Vec<String>,
    verification: VerificationMode,
    highlight_sink: Option<Arc<HighlightSink>>,
    highlight_field_name: String,
}

impl NgramContainsQuery {
    /// Creates a new `NgramContainsQuery`.
    ///
    /// * `raw_field` - Lowercase raw field for exact term lookups and BM25 stats.
    /// * `ngram_field` - Trigram field for candidate collection.
    /// * `stored_field` - Field to load stored text from (if different from `raw_field`).
    /// * `trigram_sources` - Strings used for trigram generation (tokens in fuzzy mode,
    ///   extracted literals in regex mode).
    /// * `verification` - How to verify candidates (fuzzy or regex).
    pub fn new(
        raw_field: Field,
        ngram_field: Field,
        stored_field: Option<Field>,
        trigram_sources: Vec<String>,
        verification: VerificationMode,
    ) -> Self {
        NgramContainsQuery {
            raw_field,
            ngram_field,
            stored_field,
            trigram_sources,
            verification,
            highlight_sink: None,
            highlight_field_name: String::new(),
        }
    }

    /// Attach a highlight sink to capture byte offsets during scoring.
    pub fn with_highlight_sink(mut self, sink: Arc<HighlightSink>, field_name: String) -> Self {
        self.highlight_sink = Some(sink);
        self.highlight_field_name = field_name;
        self
    }
}

impl Query for NgramContainsQuery {
    fn weight(&self, enable_scoring: EnableScoring) -> crate::Result<Box<dyn Weight>> {
        let bm25_weight = match enable_scoring {
            EnableScoring::Enabled {
                statistics_provider,
                ..
            } => {
                // Use trigram_sources as reference terms for BM25 stats.
                // In fuzzy mode these are the query tokens; in regex mode
                // they will be the extracted literals.
                let terms: Vec<Term> = self
                    .trigram_sources
                    .iter()
                    .map(|t| Term::from_field_text(self.raw_field, t))
                    .collect();
                if terms.is_empty() {
                    Bm25Weight::for_one_term(0, 1, 1.0)
                } else {
                    Bm25Weight::for_terms(statistics_provider, &terms)?
                }
            }
            EnableScoring::Disabled { .. } => Bm25Weight::for_one_term(0, 1, 1.0),
        };

        Ok(Box::new(NgramContainsWeight {
            raw_field: self.raw_field,
            ngram_field: self.ngram_field,
            stored_field: self.stored_field,
            trigram_sources: self.trigram_sources.clone(),
            verification: self.verification.clone(),
            highlight_sink: self.highlight_sink.clone(),
            highlight_field_name: self.highlight_field_name.clone(),
            bm25_weight,
        }))
    }
}

// ─── Weight ────────────────────────────────────────────────────────────────

struct NgramContainsWeight {
    raw_field: Field,
    ngram_field: Field,
    stored_field: Option<Field>,
    trigram_sources: Vec<String>,
    verification: VerificationMode,
    highlight_sink: Option<Arc<HighlightSink>>,
    highlight_field_name: String,
    bm25_weight: Bm25Weight,
}

impl Weight for NgramContainsWeight {
    fn scorer(&self, reader: &SegmentReader, boost: Score) -> crate::Result<Box<dyn Scorer>> {
        let segment_id = reader.segment_id();
        let raw_inverted = reader.inverted_index(self.raw_field)?;
        let ngram_inverted = reader.inverted_index(self.ngram_field)?;

        let final_candidates = match &self.verification {
            VerificationMode::Fuzzy(params) => {
                // Fuzzy mode: exact lookup first, then ngram, intersect across tokens.
                let mut per_token_candidates: Vec<Vec<DocId>> = Vec::new();
                for source in &self.trigram_sources {
                    let term = Term::from_field_text(self.raw_field, source);
                    let exact_docs = collect_posting_docs(&raw_inverted, &term)?;
                    if !exact_docs.is_empty() {
                        per_token_candidates.push(exact_docs);
                        continue;
                    }
                    let candidates = ngram_candidates_for_token(
                        source,
                        self.ngram_field,
                        &ngram_inverted,
                        params.fuzzy_distance,
                    )?;
                    per_token_candidates.push(candidates);
                }
                intersect_sorted_vecs(per_token_candidates)
            }
            VerificationMode::Regex(params) => {
                if self.trigram_sources.is_empty() {
                    // No usable trigrams (literals < 3 chars): full segment scan.
                    // All docs are candidates; regex verification will filter.
                    (0..reader.max_doc()).collect()
                } else {
                    // Ngram lookup: union across literals (alternatives).
                    let mut all_candidates: Vec<DocId> = Vec::new();
                    for source in &self.trigram_sources {
                        let candidates = ngram_candidates_for_token(
                            source,
                            self.ngram_field,
                            &ngram_inverted,
                            params.fuzzy_distance,
                        )?;
                        all_candidates.extend(candidates);
                    }
                    all_candidates.sort_unstable();
                    all_candidates.dedup();
                    all_candidates
                }
            }
        };

        if final_candidates.is_empty() {
            return Ok(Box::new(EmptyScorer));
        }

        // Create scorer that verifies each candidate via stored text.
        let store_reader = reader
            .get_store_reader(50)
            .map_err(crate::LucivyError::from)?;
        let text_field = self.stored_field.unwrap_or(self.raw_field);

        let fieldnorm_reader = if let Some(fnr) = reader
            .fieldnorms_readers()
            .get_field(self.raw_field)?
        {
            fnr
        } else {
            FieldNormReader::constant(reader.max_doc(), 1)
        };

        Ok(Box::new(NgramContainsScorer::new(
            final_candidates,
            store_reader,
            text_field,
            self.verification.clone(),
            self.bm25_weight.boost_by(boost),
            fieldnorm_reader,
            self.highlight_sink.clone(),
            self.highlight_field_name.clone(),
            segment_id,
        )))
    }

    fn explain(&self, reader: &SegmentReader, doc: DocId) -> crate::Result<Explanation> {
        let mut scorer = self.scorer(reader, 1.0)?;
        if scorer.seek(doc) != doc {
            return Err(crate::LucivyError::InvalidArgument(format!(
                "Document {doc} does not match"
            )));
        }
        Ok(Explanation::new("NgramContainsScorer", scorer.score()))
    }
}

// ─── Fuzzy Verification ─────────────────────────────────────────────────────

/// Count all matching positions for a single-token fuzzy query.
fn count_single_token_fuzzy(
    stored_text: &str,
    doc_tokens: &[(usize, usize)],
    params: &FuzzyParams,
    highlight_sink: &Option<Arc<HighlightSink>>,
    highlight_field_name: &str,
    segment_id: SegmentId,
    doc_id: DocId,
) -> u32 {
    let query_token = &params.tokens[0];
    let mut count = 0u32;

    for &(start, end) in doc_tokens {
        let doc_token = stored_text[start..end].to_lowercase();

        let distance = match token_match_distance(&doc_token, query_token, params.fuzzy_distance) {
            Some(d) => {
                d
            },
            None => {
                continue;
            },
        };

        let mut total_distance = distance;

        // Validate prefix.
        if !params.prefix.is_empty() {
            if params.strict_separators {
                let prefix_len = params.prefix.len();
                let doc_prefix_start = start.saturating_sub(prefix_len);
                let doc_prefix = &stored_text[doc_prefix_start..start];
                total_distance += edit_distance(&params.prefix, doc_prefix);
                if total_distance > params.distance_budget {
                    continue;
                }
            } else {
                if start == 0 {
                    continue;
                }
                if stored_text.as_bytes()[start - 1].is_ascii_alphanumeric() {
                    continue;
                }
            }
        }

        // Validate suffix.
        if !params.suffix.is_empty() {
            if params.strict_separators {
                let suffix_len = params.suffix.len();
                let doc_suffix_end = min(end + suffix_len, stored_text.len());
                let doc_suffix = &stored_text[end..doc_suffix_end];
                total_distance += edit_distance(&params.suffix, doc_suffix);
                if total_distance > params.distance_budget {
                    continue;
                }
            } else {
                if end >= stored_text.len() {
                    continue;
                }
                if stored_text.as_bytes()[end].is_ascii_alphanumeric() {
                    continue;
                }
            }
        }

        count += 1;
        if let Some(sink) = highlight_sink {
            sink.insert(segment_id, doc_id, highlight_field_name, vec![[start, end]]);
        }
    }
    count
}

/// Count all matching positions for a multi-token fuzzy query.
fn count_multi_token_fuzzy(
    stored_text: &str,
    doc_tokens: &[(usize, usize)],
    params: &FuzzyParams,
    highlight_sink: &Option<Arc<HighlightSink>>,
    highlight_field_name: &str,
    segment_id: SegmentId,
    doc_id: DocId,
) -> u32 {
    let num_query = params.tokens.len();
    if doc_tokens.len() < num_query {
        return 0;
    }

    let mut count = 0u32;
    for start_idx in 0..=(doc_tokens.len() - num_query) {
        if check_at_position_fuzzy(
            stored_text,
            doc_tokens,
            start_idx,
            params,
            highlight_sink,
            highlight_field_name,
            segment_id,
            doc_id,
        ) {
            count += 1;
        }
    }
    count
}

/// Check if a multi-token fuzzy query matches at a specific position.
fn check_at_position_fuzzy(
    stored_text: &str,
    doc_tokens: &[(usize, usize)],
    start_idx: usize,
    params: &FuzzyParams,
    highlight_sink: &Option<Arc<HighlightSink>>,
    highlight_field_name: &str,
    segment_id: SegmentId,
    doc_id: DocId,
) -> bool {
    let mut total_distance = 0u32;

    // Check each query token matches the corresponding doc token.
    for (q_idx, query_token) in params.tokens.iter().enumerate() {
        let (start, end) = doc_tokens[start_idx + q_idx];
        let doc_token = stored_text[start..end].to_lowercase();

        match token_match_distance(&doc_token, query_token, params.fuzzy_distance) {
            Some(d) => total_distance += d,
            None => return false,
        }

        if total_distance > params.distance_budget {
            return false;
        }
    }

    // Validate separators between consecutive tokens.
    for (sep_idx, query_sep) in params.separators.iter().enumerate() {
        let (_, end_i) = doc_tokens[start_idx + sep_idx];
        let (start_next, _) = doc_tokens[start_idx + sep_idx + 1];
        if end_i > stored_text.len() || start_next > stored_text.len() || end_i > start_next {
            return false;
        }
        let doc_sep = &stored_text[end_i..start_next];
        if params.strict_separators {
            total_distance += edit_distance(query_sep, doc_sep);
            if total_distance > params.distance_budget {
                return false;
            }
        } else if doc_sep.is_empty() || !doc_sep.bytes().any(|b| !b.is_ascii_alphanumeric()) {
            return false;
        }
    }

    // Validate prefix.
    if !params.prefix.is_empty() {
        let (first_start, _) = doc_tokens[start_idx];
        if params.strict_separators {
            let prefix_len = params.prefix.len();
            let doc_prefix_start = first_start.saturating_sub(prefix_len);
            let doc_prefix = &stored_text[doc_prefix_start..first_start];
            total_distance += edit_distance(&params.prefix, doc_prefix);
            if total_distance > params.distance_budget {
                return false;
            }
        } else {
            if first_start == 0 {
                return false;
            }
            let before = &stored_text[..first_start];
            if before
                .as_bytes()
                .last()
                .is_none_or(|b| b.is_ascii_alphanumeric())
            {
                return false;
            }
        }
    }

    // Validate suffix.
    if !params.suffix.is_empty() {
        let num_query = params.tokens.len();
        let (_, last_end) = doc_tokens[start_idx + num_query - 1];
        if params.strict_separators {
            let suffix_len = params.suffix.len();
            let doc_suffix_end = min(last_end + suffix_len, stored_text.len());
            let doc_suffix = &stored_text[last_end..doc_suffix_end];
            total_distance += edit_distance(&params.suffix, doc_suffix);
            if total_distance > params.distance_budget {
                return false;
            }
        } else {
            if last_end >= stored_text.len() {
                return false;
            }
            if stored_text.as_bytes()[last_end].is_ascii_alphanumeric() {
                return false;
            }
        }
    }

    if let Some(sink) = highlight_sink {
        let offsets: Vec<[usize; 2]> = (0..params.tokens.len())
            .map(|i| {
                let (s, e) = doc_tokens[start_idx + i];
                [s, e]
            })
            .collect();
        sink.insert(segment_id, doc_id, highlight_field_name, offsets);
    }
    true
}

// ─── Regex Verification ──────────────────────────────────────────────────────

/// Verify a candidate document using regex (pure or hybrid with fuzzy on literals).
///
/// - Pure regex (`fuzzy_distance == 0`): run `compiled.find_iter()` on stored text.
/// - Hybrid (`fuzzy_distance > 0`): also try fuzzy matching on extracted literals;
///   `tf = max(tf_regex, tf_fuzzy)`.
fn verify_regex(
    stored_text: &str,
    params: &RegexParams,
    highlight_sink: &Option<Arc<HighlightSink>>,
    highlight_field_name: &str,
    segment_id: SegmentId,
    doc_id: DocId,
) -> u32 {
    // 1. Regex verification on ASCII-folded text (accent-insensitive).
    //    The byte map lets us translate folded match offsets back to original text offsets.
    let (folded_text, byte_map) = fold_with_byte_map(stored_text);
    let regex_matches: Vec<regex::Match> = params.compiled.find_iter(&folded_text).collect();
    let tf_regex = regex_matches.len() as u32;

    // 2. Hybrid fuzzy verification on extracted literals (if distance > 0)
    let tf_fuzzy = if params.fuzzy_distance > 0 && !params.literals.is_empty() {
        let doc_tokens = tokenize_raw(stored_text);
        // For each literal, count fuzzy matches in the document tokens.
        // Use the max across all literals (each literal is an alternative).
        params
            .literals
            .iter()
            .map(|lit| {
                let lit_lower = lit.to_lowercase();
                let mut count = 0u32;
                for &(start, end) in &doc_tokens {
                    let doc_token = stored_text[start..end].to_lowercase();
                    if token_match_distance(&doc_token, &lit_lower, params.fuzzy_distance).is_some()
                    {
                        count += 1;
                    }
                }
                count
            })
            .max()
            .unwrap_or(0)
    } else {
        0
    };

    let tf = max(tf_regex, tf_fuzzy);

    // Highlights: prefer regex offsets if available, otherwise no offsets for fuzzy-only matches.
    if tf > 0 {
        if let Some(sink) = highlight_sink {
            if tf_regex > 0 {
                // Map folded byte offsets back to original text byte offsets.
                let offsets: Vec<[usize; 2]> = regex_matches
                    .iter()
                    .map(|m| [byte_map[m.start()], byte_map[m.end()]])
                    .collect();
                sink.insert(segment_id, doc_id, highlight_field_name, offsets);
            }
            // When only fuzzy matched (tf_regex == 0), we don't have precise byte offsets.
        }
    }

    tf
}

// ─── Scorer ────────────────────────────────────────────────────────────────

struct NgramContainsScorer {
    candidates: Vec<DocId>,
    cursor: usize,
    store_reader: crate::store::StoreReader,
    text_field: Field,
    verification: VerificationMode,
    bm25_weight: Bm25Weight,
    fieldnorm_reader: FieldNormReader,
    last_tf: u32,
    highlight_sink: Option<Arc<HighlightSink>>,
    highlight_field_name: String,
    segment_id: SegmentId,
}

impl NgramContainsScorer {
    fn new(
        candidates: Vec<DocId>,
        store_reader: crate::store::StoreReader,
        text_field: Field,
        verification: VerificationMode,
        bm25_weight: Bm25Weight,
        fieldnorm_reader: FieldNormReader,
        highlight_sink: Option<Arc<HighlightSink>>,
        highlight_field_name: String,
        segment_id: SegmentId,
    ) -> Self {
        let mut scorer = NgramContainsScorer {
            candidates,
            cursor: 0,
            store_reader,
            text_field,
            verification,
            bm25_weight,
            fieldnorm_reader,
            last_tf: 0,
            highlight_sink,
            highlight_field_name,
            segment_id,
        };
        // Advance to first valid doc.
        if scorer.doc() != TERMINATED && !scorer.verify() {
            scorer.advance();
        }
        scorer
    }

    /// Verify the current candidate doc by reading stored text.
    /// Dispatches to the appropriate verification mode.
    fn verify(&mut self) -> bool {
        self.last_tf = 0;
        let doc_id = self.doc();
        if doc_id == TERMINATED {
            return false;
        }

        let doc: LucivyDocument = match self.store_reader.get(doc_id) {
            Ok(d) => d,
            Err(_) => return false,
        };
        let stored_text = match doc.get_first(self.text_field).and_then(|v| v.as_str()) {
            Some(s) => s,
            None => {
                return false;
            }
        };

        let tf = match &self.verification {
            VerificationMode::Fuzzy(params) => {
                let doc_tokens = tokenize_raw(stored_text);
                if params.tokens.len() == 1 {
                    count_single_token_fuzzy(
                        stored_text,
                        &doc_tokens,
                        params,
                        &self.highlight_sink,
                        &self.highlight_field_name,
                        self.segment_id,
                        doc_id,
                    )
                } else {
                    count_multi_token_fuzzy(
                        stored_text,
                        &doc_tokens,
                        params,
                        &self.highlight_sink,
                        &self.highlight_field_name,
                        self.segment_id,
                        doc_id,
                    )
                }
            }
            VerificationMode::Regex(params) => {
                verify_regex(
                    stored_text,
                    params,
                    &self.highlight_sink,
                    &self.highlight_field_name,
                    self.segment_id,
                    doc_id,
                )
            }
        };
        self.last_tf = tf;
        tf > 0
    }
}

impl DocSet for NgramContainsScorer {
    fn advance(&mut self) -> DocId {
        loop {
            self.cursor += 1;
            let doc = self.doc();
            if doc == TERMINATED || self.verify() {
                return doc;
            }
        }
    }

    fn seek(&mut self, target: DocId) -> DocId {
        while self.cursor < self.candidates.len() && self.candidates[self.cursor] < target {
            self.cursor += 1;
        }
        if self.doc() == TERMINATED || self.verify() {
            return self.doc();
        }
        let result = self.advance();
        result
    }

    fn doc(&self) -> DocId {
        if self.cursor < self.candidates.len() {
            self.candidates[self.cursor]
        } else {
            TERMINATED
        }
    }

    fn size_hint(&self) -> u32 {
        self.candidates.len().saturating_sub(self.cursor) as u32
    }
}

impl Scorer for NgramContainsScorer {
    fn score(&mut self) -> Score {
        let doc = self.doc();
        let fieldnorm_id = self.fieldnorm_reader.fieldnorm_id(doc);
        self.bm25_weight.score(fieldnorm_id, self.last_tf)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::index::SegmentId;

    /// Dummy SegmentId for unit tests (all functions now require SegmentId instead of u32).
    fn test_seg_id() -> SegmentId {
        SegmentId::generate_random()
    }

    fn make_regex_params(pattern: &str, literals: Vec<&str>, fuzzy_distance: u8) -> RegexParams {
        // Fold the pattern to ASCII (mirrors build_contains_regex in production code).
        let mut folded = String::new();
        crate::tokenizer::to_ascii(pattern, &mut folded);
        RegexParams {
            compiled: Regex::new(&format!("(?i){folded}")).unwrap(),
            literals: literals.into_iter().map(|s| s.to_string()).collect(),
            fuzzy_distance,
        }
    }

    // ─── verify_regex: pure regex ────────────────────────────────────────

    #[test]
    fn test_regex_pure_match() {
        let params = make_regex_params(r"program[a-z]+", vec!["program"], 0);
        let tf = verify_regex("Rust is a systems programming language", &params, &None, "", test_seg_id(), 0);
        assert_eq!(tf, 1); // "programming" matches
    }

    #[test]
    fn test_regex_pure_no_match() {
        let params = make_regex_params(r"program[a-z]+", vec!["program"], 0);
        let tf = verify_regex("the cat sat on the mat", &params, &None, "", test_seg_id(), 0);
        assert_eq!(tf, 0);
    }

    #[test]
    fn test_regex_pure_multiple_matches() {
        let params = make_regex_params(r"program[a-z]+", vec!["program"], 0);
        let tf = verify_regex(
            "Programming in Rust: a programmer's guide to programming",
            &params,
            &None,
            "",
            test_seg_id(),
            0,
        );
        assert_eq!(tf, 3); // "Programming", "programmer", "programming"
    }

    #[test]
    fn test_regex_case_insensitive() {
        let params = make_regex_params(r"rust", vec!["rust"], 0);
        let tf = verify_regex("Rust is great", &params, &None, "", test_seg_id(), 0);
        assert_eq!(tf, 1);
    }

    // ─── verify_regex: hybrid (regex + fuzzy) ────────────────────────────

    #[test]
    fn test_regex_hybrid_typo_in_pattern() {
        // Pattern has typo "programing" (one m) — regex won't match "programming"
        // but fuzzy on literal "programing" with distance=1 should match.
        let params = make_regex_params(r"programing[a-z]+", vec!["programing"], 1);
        let tf = verify_regex("Rust is a systems programming language", &params, &None, "", test_seg_id(), 0);
        assert!(tf > 0, "hybrid should match via fuzzy on literal");
    }

    #[test]
    fn test_regex_hybrid_exact_wins() {
        // Pattern is correct — regex matches directly, fuzzy also matches.
        // tf = max(regex, fuzzy).
        let params = make_regex_params(r"program[a-z]+", vec!["program"], 1);
        let tf = verify_regex("Rust programming is fun", &params, &None, "", test_seg_id(), 0);
        assert!(tf > 0);
    }

    #[test]
    fn test_regex_hybrid_no_match() {
        let params = make_regex_params(r"python[a-z]+", vec!["python"], 1);
        let tf = verify_regex("Rust is a systems programming language", &params, &None, "", test_seg_id(), 0);
        assert_eq!(tf, 0);
    }

    // ─── verify_regex: highlights ────────────────────────────────────────

    #[test]
    fn test_regex_highlights() {
        let sink = Arc::new(HighlightSink::new());
        let sid = test_seg_id();
        let params = make_regex_params(r"program[a-z]+", vec!["program"], 0);
        let text = "Rust programming is fun";
        let tf = verify_regex(text, &params, &Some(sink.clone()), "", sid, 42);
        assert_eq!(tf, 1);
        let by_field = sink.get(sid, 42).expect("should have highlights");
        let offsets = by_field.get("").expect("should have field offsets");
        assert_eq!(offsets.len(), 1);
        // "programming" starts at index 5 in "Rust programming is fun"
        assert_eq!(offsets[0], [5, 16]);
    }

    // ─── verify_regex: edge cases ────────────────────────────────────────

    #[test]
    fn test_regex_empty_text() {
        let params = make_regex_params(r"program[a-z]+", vec!["program"], 0);
        let tf = verify_regex("", &params, &None, "", test_seg_id(), 0);
        assert_eq!(tf, 0);
    }

    #[test]
    fn test_regex_dot_star() {
        let params = make_regex_params(r".*", vec![], 0);
        let tf = verify_regex("anything", &params, &None, "", test_seg_id(), 0);
        assert!(tf > 0); // .* matches everything
    }

    #[test]
    fn test_regex_word_boundary() {
        let params = make_regex_params(r"\brust\b", vec!["rust"], 0);
        let tf = verify_regex("Rust is great but rusty is not", &params, &None, "", test_seg_id(), 0);
        assert_eq!(tf, 1); // "Rust" matches, "rusty" does not
    }

    #[test]
    fn test_regex_unicode() {
        let params = make_regex_params(r"café", vec!["café"], 0);
        let tf = verify_regex("I love café au lait", &params, &None, "", test_seg_id(), 0);
        assert_eq!(tf, 1);
    }

    #[test]
    fn test_regex_hybrid_fuzzy_only_match() {
        // Regex "xyz[0-9]+" won't match any text, but fuzzy on literal "database"
        // with distance=1 should match "databse" (typo).
        let params = make_regex_params(r"databse", vec!["databse"], 1);
        let tf = verify_regex("Graph databases store data", &params, &None, "", test_seg_id(), 0);
        // "databse" is distance 1 from "database" (substring of "databases")
        assert!(tf > 0, "hybrid should match via fuzzy on literal");
    }

    #[test]
    fn test_regex_multiple_highlights() {
        let sink = Arc::new(HighlightSink::new());
        let sid = test_seg_id();
        let params = make_regex_params(r"[a-z]+ing", vec!["ing"], 0);
        let text = "programming and testing are fun";
        let tf = verify_regex(text, &params, &Some(sink.clone()), "", sid, 99);
        assert_eq!(tf, 2); // "programming" and "testing"
        let by_field = sink.get(sid, 99).expect("should have highlights");
        let offsets = by_field.get("").expect("should have field offsets");
        assert_eq!(offsets.len(), 2);
    }

    // ─── count_single_token_fuzzy ──────────────────────────────────────

    fn make_fuzzy_params(
        tokens: Vec<&str>,
        separators: Vec<&str>,
        prefix: &str,
        suffix: &str,
        distance: u8,
        budget: u32,
    ) -> FuzzyParams {
        FuzzyParams {
            tokens: tokens.into_iter().map(|s| s.to_string()).collect(),
            separators: separators.into_iter().map(|s| s.to_string()).collect(),
            prefix: prefix.to_string(),
            suffix: suffix.to_string(),
            fuzzy_distance: distance,
            distance_budget: budget,
            strict_separators: true,
        }
    }

    #[test]
    fn test_fuzzy_single_exact() {
        let text = "Rust is a programming language";
        let tokens = tokenize_raw(text);
        let params = make_fuzzy_params(vec!["programming"], vec![], "", "", 1, 1);
        assert_eq!(
            count_single_token_fuzzy(text, &tokens, &params, &None, "", test_seg_id(), 0),
            1
        );
    }

    #[test]
    fn test_fuzzy_single_typo() {
        let text = "Rust is a programming language";
        let tokens = tokenize_raw(text);
        let params = make_fuzzy_params(vec!["programing"], vec![], "", "", 1, 1);
        assert_eq!(
            count_single_token_fuzzy(text, &tokens, &params, &None, "", test_seg_id(), 0),
            1
        );
    }

    #[test]
    fn test_fuzzy_single_no_match() {
        let text = "Rust is a programming language";
        let tokens = tokenize_raw(text);
        let params = make_fuzzy_params(vec!["python"], vec![], "", "", 1, 1);
        assert_eq!(
            count_single_token_fuzzy(text, &tokens, &params, &None, "", test_seg_id(), 0),
            0
        );
    }

    #[test]
    fn test_fuzzy_single_multiple_matches() {
        let text = "programming in Rust: a programmer guide";
        let tokens = tokenize_raw(text);
        // "program" is a substring of both "programming" and "programmer"
        let params = make_fuzzy_params(vec!["program"], vec![], "", "", 1, 1);
        assert_eq!(
            count_single_token_fuzzy(text, &tokens, &params, &None, "", test_seg_id(), 0),
            2
        );
    }

    #[test]
    fn test_fuzzy_single_distance_zero_no_match() {
        let text = "Rust is a programming language";
        let tokens = tokenize_raw(text);
        // distance=0: "programing" is not exact, not a substring
        let params = make_fuzzy_params(vec!["programing"], vec![], "", "", 0, 0);
        assert_eq!(
            count_single_token_fuzzy(text, &tokens, &params, &None, "", test_seg_id(), 0),
            0
        );
    }

    #[test]
    fn test_fuzzy_single_highlights() {
        let sink = Arc::new(HighlightSink::new());
        let sid = test_seg_id();
        let text = "Rust programming is fun";
        let tokens = tokenize_raw(text);
        let params = make_fuzzy_params(vec!["programming"], vec![], "", "", 1, 1);
        let tf =
            count_single_token_fuzzy(text, &tokens, &params, &Some(sink.clone()), "", sid, 42);
        assert_eq!(tf, 1);
        let by_field = sink.get(sid, 42).expect("should have highlights");
        let offsets = by_field.get("").expect("should have field offsets");
        assert_eq!(offsets.len(), 1);
        assert_eq!(offsets[0], [5, 16]); // "programming" at bytes 5..16
    }

    // ─── count_multi_token_fuzzy ──────────────────────────────────────

    #[test]
    fn test_fuzzy_multi_exact() {
        let text = "Rust is a systems programming language";
        let tokens = tokenize_raw(text);
        let params =
            make_fuzzy_params(vec!["systems", "programming"], vec![" "], "", "", 1, 1);
        assert_eq!(
            count_multi_token_fuzzy(text, &tokens, &params, &None, "", test_seg_id(), 0),
            1
        );
    }

    #[test]
    fn test_fuzzy_multi_typo() {
        let text = "Rust is a systems programming language";
        let tokens = tokenize_raw(text);
        let params =
            make_fuzzy_params(vec!["sistems", "programing"], vec![" "], "", "", 1, 2);
        assert_eq!(
            count_multi_token_fuzzy(text, &tokens, &params, &None, "", test_seg_id(), 0),
            1
        );
    }

    #[test]
    fn test_fuzzy_multi_budget_exceeded() {
        let text = "Rust is a systems programming language";
        let tokens = tokenize_raw(text);
        // 2 edits total but budget=1
        let params =
            make_fuzzy_params(vec!["sistems", "programing"], vec![" "], "", "", 1, 1);
        assert_eq!(
            count_multi_token_fuzzy(text, &tokens, &params, &None, "", test_seg_id(), 0),
            0
        );
    }

    #[test]
    fn test_fuzzy_multi_no_match() {
        let text = "Rust is a systems programming language";
        let tokens = tokenize_raw(text);
        let params =
            make_fuzzy_params(vec!["machine", "learning"], vec![" "], "", "", 1, 1);
        assert_eq!(
            count_multi_token_fuzzy(text, &tokens, &params, &None, "", test_seg_id(), 0),
            0
        );
    }

    #[test]
    fn test_fuzzy_multi_not_enough_tokens() {
        let text = "Rust";
        let tokens = tokenize_raw(text);
        let params =
            make_fuzzy_params(vec!["systems", "programming"], vec![" "], "", "", 1, 1);
        assert_eq!(
            count_multi_token_fuzzy(text, &tokens, &params, &None, "", test_seg_id(), 0),
            0
        );
    }

    #[test]
    fn test_fuzzy_multi_highlights() {
        let sink = Arc::new(HighlightSink::new());
        let sid = test_seg_id();
        let text = "Rust is a systems programming language";
        let tokens = tokenize_raw(text);
        let params =
            make_fuzzy_params(vec!["systems", "programming"], vec![" "], "", "", 1, 1);
        let tf =
            count_multi_token_fuzzy(text, &tokens, &params, &Some(sink.clone()), "", sid, 42);
        assert_eq!(tf, 1);
        let by_field = sink.get(sid, 42).expect("should have highlights");
        let offsets = by_field.get("").expect("should have field offsets");
        assert_eq!(offsets.len(), 2);
        assert_eq!(offsets[0], [10, 17]); // "systems" at bytes 10..17
        assert_eq!(offsets[1], [18, 29]); // "programming" at bytes 18..29
    }

    // ─── Integration: BooleanQuery + multi-field highlights ──────────────
    //
    // These tests reproduce the segment_ord mismatch bug that caused
    // highlights to be lost for the 2nd sub-query in a BooleanQuery.

    use crate::collector::TopDocs;
    use crate::query::boolean_query::BooleanQuery;
    use crate::query::Occur;
    use crate::schema::{Schema, TextFieldIndexing, TextOptions, STORED};
    use crate::tokenizer::NgramTokenizer;
    use crate::Index;

    /// Build a 2-field index (_title + _content) with raw+ngram variants.
    fn create_two_field_index(docs: &[(&str, &str)]) -> crate::Result<Index> {
        let mut sb = Schema::builder();

        let raw_opts = TextOptions::default()
            .set_indexing_options(
                TextFieldIndexing::default()
                    .set_tokenizer("default")
                    .set_index_option(crate::schema::IndexRecordOption::WithFreqsAndPositionsAndOffsets),
            )
            .set_stored();

        let ngram_opts = TextOptions::default()
            .set_indexing_options(
                TextFieldIndexing::default()
                    .set_tokenizer("ngram3")
                    .set_index_option(crate::schema::IndexRecordOption::WithFreqs),
            );

        let title_raw = sb.add_text_field("_title", raw_opts.clone());
        let title_ngram = sb.add_text_field("_title._ngram", ngram_opts.clone());
        let content_raw = sb.add_text_field("_content", raw_opts);
        let content_ngram = sb.add_text_field("_content._ngram", ngram_opts);

        let schema = sb.build();
        let index = Index::create_in_ram(schema);
        index
            .tokenizers()
            .register("ngram3", NgramTokenizer::all_ngrams(3, 3).unwrap());
        let mut writer = index.writer_for_tests()?;

        for &(title, content) in docs {
            let mut doc = crate::LucivyDocument::new();
            doc.add_text(title_raw, title);
            doc.add_text(title_ngram, title);
            doc.add_text(content_raw, content);
            doc.add_text(content_ngram, content);
            writer.add_document(doc)?;
        }
        writer.commit()?;
        Ok(index)
    }

    /// Regression test: BooleanQuery(should) with NgramContainsQuery on 2 fields.
    /// Before the fix, the 2nd sub-query's highlights were lost because the
    /// HighlightSink used a global counter (next_segment) as key, which gave
    /// different ordinals to sub-queries on the same segment.
    #[test]
    fn test_boolean_multi_field_highlights_not_lost() -> crate::Result<()> {
        let index = create_two_field_index(&[
            ("login page", "authentication and authorization"),
        ])?;
        let schema = index.schema();
        let title_raw = schema.get_field("_title").unwrap();
        let title_ngram = schema.get_field("_title._ngram").unwrap();
        let content_raw = schema.get_field("_content").unwrap();
        let content_ngram = schema.get_field("_content._ngram").unwrap();

        let sink = Arc::new(HighlightSink::new());

        // Build regex-based NgramContainsQuery for "auth" on both fields
        let q_title = NgramContainsQuery::new(
            title_raw,
            title_ngram,
            None,
            vec!["auth".into()],
            VerificationMode::Regex(RegexParams {
                compiled: Regex::new("(?i)auth").unwrap(),
                literals: vec!["auth".into()],
                fuzzy_distance: 0,
            }),
        )
        .with_highlight_sink(sink.clone(), "_title".into());

        let q_content = NgramContainsQuery::new(
            content_raw,
            content_ngram,
            None,
            vec!["auth".into()],
            VerificationMode::Regex(RegexParams {
                compiled: Regex::new("(?i)auth").unwrap(),
                literals: vec!["auth".into()],
                fuzzy_distance: 0,
            }),
        )
        .with_highlight_sink(sink.clone(), "_content".into());

        let bool_query = BooleanQuery::new(vec![
            (Occur::Should, Box::new(q_title)),
            (Occur::Should, Box::new(q_content)),
        ]);

        let reader = index.reader()?;
        let searcher = reader.searcher();
        let top_docs = searcher.search(&bool_query, &TopDocs::with_limit(10).order_by_score())?;

        assert_eq!(top_docs.len(), 1, "should find 1 document");
        let (_score, doc_addr) = top_docs[0];

        // Key assertion: use the real SegmentId (same as what the scorer uses)
        let seg_id = searcher.segment_reader(doc_addr.segment_ord).segment_id();
        let by_field = sink.get(seg_id, doc_addr.doc_id)
            .expect("highlights should exist for matching document");

        // "auth" appears in _content ("authentication") but NOT in _title ("login page")
        assert!(
            by_field.contains_key("_content"),
            "should have _content highlights, got: {:?}",
            by_field.keys().collect::<Vec<_>>()
        );
        let content_offsets = &by_field["_content"];
        assert!(!content_offsets.is_empty(), "content highlights should not be empty");
        // "authentication" starts at byte 0 in "authentication and authorization"
        assert_eq!(content_offsets[0][0], 0);

        Ok(())
    }

    /// Test that both fields get highlights when the query matches in both.
    #[test]
    fn test_boolean_both_fields_highlighted() -> crate::Result<()> {
        let index = create_two_field_index(&[
            ("source code review", "the source of truth"),
        ])?;
        let schema = index.schema();
        let title_raw = schema.get_field("_title").unwrap();
        let title_ngram = schema.get_field("_title._ngram").unwrap();
        let content_raw = schema.get_field("_content").unwrap();
        let content_ngram = schema.get_field("_content._ngram").unwrap();

        let sink = Arc::new(HighlightSink::new());

        let q_title = NgramContainsQuery::new(
            title_raw, title_ngram, None,
            vec!["source".into()],
            VerificationMode::Regex(RegexParams {
                compiled: Regex::new("(?i)source").unwrap(),
                literals: vec!["source".into()],
                fuzzy_distance: 0,
            }),
        ).with_highlight_sink(sink.clone(), "_title".into());

        let q_content = NgramContainsQuery::new(
            content_raw, content_ngram, None,
            vec!["source".into()],
            VerificationMode::Regex(RegexParams {
                compiled: Regex::new("(?i)source").unwrap(),
                literals: vec!["source".into()],
                fuzzy_distance: 0,
            }),
        ).with_highlight_sink(sink.clone(), "_content".into());

        let bool_query = BooleanQuery::new(vec![
            (Occur::Should, Box::new(q_title)),
            (Occur::Should, Box::new(q_content)),
        ]);

        let reader = index.reader()?;
        let searcher = reader.searcher();
        let top_docs = searcher.search(&bool_query, &TopDocs::with_limit(10).order_by_score())?;

        assert_eq!(top_docs.len(), 1);
        let (_score, doc_addr) = top_docs[0];

        let seg_id = searcher.segment_reader(doc_addr.segment_ord).segment_id();
        let by_field = sink.get(seg_id, doc_addr.doc_id)
            .expect("highlights should exist");

        assert!(
            by_field.contains_key("_title"),
            "should have _title highlights, got: {:?}", by_field.keys().collect::<Vec<_>>()
        );
        assert!(
            by_field.contains_key("_content"),
            "should have _content highlights, got: {:?}", by_field.keys().collect::<Vec<_>>()
        );

        // "source" in "_title" = "source code review" → offset [0, 6]
        assert_eq!(by_field["_title"][0], [0, 6]);
        // "source" in "_content" = "the source of truth" → offset [4, 10]
        assert_eq!(by_field["_content"][0], [4, 10]);

        Ok(())
    }
}