lucisearch 0.8.1

Embeddable, in-process search engine — the SQLite/DuckDB of search
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
//! BoolQuery: boolean combination of sub-queries.
//!
//! - `must`: conjunction (AND) — all clauses must match, scores summed
//! - `should`: disjunction (OR) — any clause may match, scores summed
//! - `must_not`: exclusion — matching docs are removed
//! - `filter`: conjunction in filter context (AND, no scoring)
//!
//! See [[query-dsl#Compound Queries]] and [[architecture-query-execution#Step 7]].

use crate::core::{DocId, NO_MORE_DOCS, Result, ScoreMode, Scorer, TwoPhaseIterator};

use crate::query::{BoundQuery, Query, ScorerSupplier};
use crate::search::conjunction::ConjunctionScorer;
use crate::search::searcher::Searcher;
use crate::segment::reader::SegmentReader;

/// Boolean combination of sub-queries.
pub struct BoolQuery {
    pub(crate) must: Vec<Box<dyn Query>>,
    pub(crate) should: Vec<Box<dyn Query>>,
    pub(crate) must_not: Vec<Box<dyn Query>>,
    pub(crate) filter: Vec<Box<dyn Query>>,
    pub(crate) minimum_should_match: Option<u32>,
}

impl Query for BoolQuery {
    fn bind(&self, searcher: &Searcher, score_mode: ScoreMode) -> Result<Box<dyn BoundQuery>> {
        let must_weights: Vec<Box<dyn BoundQuery>> = self
            .must
            .iter()
            .map(|q| q.bind(searcher, score_mode))
            .collect::<Result<_>>()?;

        let should_weights: Vec<Box<dyn BoundQuery>> = self
            .should
            .iter()
            .map(|q| q.bind(searcher, score_mode))
            .collect::<Result<_>>()?;

        let must_not_weights: Vec<Box<dyn BoundQuery>> = self
            .must_not
            .iter()
            .map(|q| q.bind(searcher, ScoreMode::CompleteNoScores))
            .collect::<Result<_>>()?;

        let filter_weights: Vec<Box<dyn BoundQuery>> = self
            .filter
            .iter()
            .map(|q| q.bind(searcher, ScoreMode::CompleteNoScores))
            .collect::<Result<_>>()?;

        Ok(Box::new(BoundBoolQuery {
            must: must_weights,
            should: should_weights,
            must_not: must_not_weights,
            filter: filter_weights,
            minimum_should_match: self.minimum_should_match,
            score_mode,
        }))
    }
}

struct BoundBoolQuery {
    must: Vec<Box<dyn BoundQuery>>,
    should: Vec<Box<dyn BoundQuery>>,
    must_not: Vec<Box<dyn BoundQuery>>,
    filter: Vec<Box<dyn BoundQuery>>,
    minimum_should_match: Option<u32>,
    score_mode: ScoreMode,
}

impl BoundQuery for BoundBoolQuery {
    fn bulk_score(
        &self,
        reader: &SegmentReader,
        collector: &mut crate::search::collector::TopDocsCollector,
        segment_id: crate::core::SegmentId,
    ) -> Result<Option<u64>> {
        // Only for pure-should with 2+ clauses and min_should_match <= 1
        if !self.must.is_empty() || !self.filter.is_empty() || !self.must_not.is_empty() {
            return Ok(None);
        }
        if self.minimum_should_match.map_or(false, |m| m > 1) {
            return Ok(None);
        }
        if self.should.len() < 2 {
            return Ok(None);
        }

        let mut scorers: Vec<Box<dyn crate::core::Scorer>> = Vec::new();
        for w in &self.should {
            if let Some(supplier) = w.scorer_supplier(reader)? {
                scorers.push(supplier.scorer()?);
            }
        }
        if scorers.len() < 2 {
            return Ok(None);
        }

        let max_doc = reader.doc_count();
        let mut bulk = crate::search::bulk::MaxScoreBulkScorer::new(scorers);
        let hits = bulk.score(collector, segment_id, max_doc);
        Ok(Some(hits))
    }

    fn scorer_supplier(&self, reader: &SegmentReader) -> Result<Option<Box<dyn ScorerSupplier>>> {
        // Collect must suppliers
        let mut must_suppliers: Vec<Box<dyn ScorerSupplier>> = Vec::new();
        for w in &self.must {
            match w.scorer_supplier(reader)? {
                Some(s) => must_suppliers.push(s),
                None => return Ok(None), // must clause with no matches = no results
            }
        }

        // Collect filter suppliers
        let mut filter_suppliers: Vec<Box<dyn ScorerSupplier>> = Vec::new();
        for w in &self.filter {
            match w.scorer_supplier(reader)? {
                Some(s) => filter_suppliers.push(s),
                None => return Ok(None), // filter with no matches = no results
            }
        }

        // Collect should suppliers
        let mut should_suppliers: Vec<Box<dyn ScorerSupplier>> = Vec::new();
        for w in &self.should {
            if let Some(s) = w.scorer_supplier(reader)? {
                should_suppliers.push(s);
            }
        }

        // Collect must_not suppliers
        let mut must_not_suppliers: Vec<Box<dyn ScorerSupplier>> = Vec::new();
        for w in &self.must_not {
            if let Some(s) = w.scorer_supplier(reader)? {
                must_not_suppliers.push(s);
            }
        }

        // If no must and no filter and no should, nothing matches
        if must_suppliers.is_empty() && filter_suppliers.is_empty() && should_suppliers.is_empty() {
            return Ok(None);
        }

        // Estimate total cost as min of must/filter costs
        let cost = must_suppliers
            .iter()
            .chain(filter_suppliers.iter())
            .map(|s| s.cost())
            .min()
            .unwrap_or_else(|| should_suppliers.iter().map(|s| s.cost()).sum::<u64>());

        Ok(Some(Box::new(BoolScorerSupplier {
            must: must_suppliers,
            should: should_suppliers,
            must_not: must_not_suppliers,
            filter: filter_suppliers,
            minimum_should_match: self.minimum_should_match,
            score_mode: self.score_mode,
            cost,
        })))
    }
}

struct BoolScorerSupplier {
    must: Vec<Box<dyn ScorerSupplier>>,
    should: Vec<Box<dyn ScorerSupplier>>,
    must_not: Vec<Box<dyn ScorerSupplier>>,
    filter: Vec<Box<dyn ScorerSupplier>>,
    minimum_should_match: Option<u32>,
    score_mode: ScoreMode,
    cost: u64,
}

// SAFETY: All contained ScorerSuppliers are Send
unsafe impl Send for BoolScorerSupplier {}

impl ScorerSupplier for BoolScorerSupplier {
    fn cost(&self) -> u64 {
        self.cost
    }

    fn scorer(self: Box<Self>) -> Result<Box<dyn Scorer>> {
        // Build all sub-scorers
        let mut required_scorers: Vec<Box<dyn Scorer>> = Vec::new();

        // Must clauses (scored)
        // Sort by cost for conjunction efficiency
        let mut must_with_cost: Vec<_> = self
            .must
            .into_iter()
            .map(|s| {
                let c = s.cost();
                (s, c)
            })
            .collect();
        must_with_cost.sort_by_key(|(_, c)| *c);
        for (supplier, _) in must_with_cost {
            required_scorers.push(supplier.scorer()?);
        }

        // Filter clauses (not scored)
        let mut filter_with_cost: Vec<_> = self
            .filter
            .into_iter()
            .map(|s| {
                let c = s.cost();
                (s, c)
            })
            .collect();
        filter_with_cost.sort_by_key(|(_, c)| *c);
        for (supplier, _) in filter_with_cost {
            required_scorers.push(supplier.scorer()?);
        }

        // Must_not clauses → exclusion scorers
        let mut exclusion_scorers: Vec<Box<dyn Scorer>> = Vec::new();
        for supplier in self.must_not {
            exclusion_scorers.push(supplier.scorer()?);
        }

        // Should clauses
        let should_scorers: Vec<Box<dyn Scorer>> = self
            .should
            .into_iter()
            .map(|s| s.scorer())
            .collect::<Result<_>>()?;

        let min_should = self.minimum_should_match.unwrap_or(0) as usize;

        // Build the composite scorer
        let mut base_scorer: Box<dyn Scorer> = if !required_scorers.is_empty() {
            // Case A: must/filter exist — they form the required base
            if required_scorers.len() == 1 {
                required_scorers.pop().unwrap()
            } else {
                Box::new(ConjunctionScorer::new(required_scorers))
            }
        } else if !should_scorers.is_empty() {
            // Case B: no must/filter — should becomes the primary.
            let effective_min = if min_should > 0 { min_should } else { 1 };

            let mut scorer = build_should_scorer(should_scorers, effective_min, self.score_mode)?;

            // Apply must_not exclusions (previously skipped — bug fix)
            if !exclusion_scorers.is_empty() {
                scorer = Box::new(ExclusionScorer::new(scorer, exclusion_scorers));
            }

            return Ok(scorer);
        } else {
            return Ok(Box::new(EmptyScorer));
        };

        // Apply must_not exclusions
        if !exclusion_scorers.is_empty() {
            base_scorer = Box::new(ExclusionScorer::new(base_scorer, exclusion_scorers));
        }

        // Add should clauses — but only if scores are needed.
        // In filter context (CompleteNoScores) with required clauses,
        // optional should can't affect the hit set and scores aren't
        // consumed. Matches Lucene's BooleanWeight behavior
        // (BooleanWeight.java:321-326).
        // See [[optimization-bool-filter-disjunction]].
        if !should_scorers.is_empty() {
            if min_should > 0 {
                // minimum_should_match set — should becomes required
                // (affects hit set even in filter context).
                let should_scorer =
                    build_should_scorer(should_scorers, min_should, self.score_mode)?;
                base_scorer = Box::new(ConjunctionScorer::new(vec![base_scorer, should_scorer]));
            } else if self.score_mode.needs_scores() {
                // Scoring context: should is optional boost.
                base_scorer = Box::new(OptionalScorer::new(base_scorer, should_scorers));
            }
            // else: filter context with no MSM — drop should entirely.
        }

        Ok(base_scorer)
    }
}

/// Scorer that always returns NO_MORE_DOCS.
struct EmptyScorer;

impl Scorer for EmptyScorer {
    fn doc_id(&self) -> DocId {
        NO_MORE_DOCS
    }
    fn next(&mut self) -> DocId {
        NO_MORE_DOCS
    }
    fn advance(&mut self, _: DocId) -> DocId {
        NO_MORE_DOCS
    }
    fn score(&mut self) -> f32 {
        0.0
    }
    fn two_phase(&mut self) -> Option<&mut dyn TwoPhaseIterator> {
        None
    }
}

/// Wraps a base scorer and skips docs that appear in exclusion scorers (must_not).
struct ExclusionScorer {
    base: Box<dyn Scorer>,
    exclusions: Vec<Box<dyn Scorer>>,
}

impl ExclusionScorer {
    fn new(base: Box<dyn Scorer>, exclusions: Vec<Box<dyn Scorer>>) -> Self {
        let mut s = Self { base, exclusions };
        s.skip_excluded();
        s
    }

    fn is_excluded(&mut self) -> bool {
        let target = self.base.doc_id();
        for exc in &mut self.exclusions {
            let doc = exc.advance(target);
            if doc == target {
                return true;
            }
        }
        false
    }

    fn skip_excluded(&mut self) {
        while self.base.doc_id() != NO_MORE_DOCS && self.is_excluded() {
            self.base.next();
        }
    }
}

impl Scorer for ExclusionScorer {
    fn doc_id(&self) -> DocId {
        self.base.doc_id()
    }
    fn next(&mut self) -> DocId {
        self.base.next();
        self.skip_excluded();
        self.base.doc_id()
    }
    fn advance(&mut self, target: DocId) -> DocId {
        self.base.advance(target);
        self.skip_excluded();
        self.base.doc_id()
    }
    fn score(&mut self) -> f32 {
        self.base.score()
    }
    fn two_phase(&mut self) -> Option<&mut dyn TwoPhaseIterator> {
        None
    }
}

/// Wraps a required base scorer with optional should scorers that add to the score.
struct OptionalScorer {
    base: Box<dyn Scorer>,
    optionals: Vec<Box<dyn Scorer>>,
}

impl OptionalScorer {
    fn new(base: Box<dyn Scorer>, optionals: Vec<Box<dyn Scorer>>) -> Self {
        Self { base, optionals }
    }
}

impl Scorer for OptionalScorer {
    fn doc_id(&self) -> DocId {
        self.base.doc_id()
    }
    fn next(&mut self) -> DocId {
        self.base.next()
    }
    fn advance(&mut self, target: DocId) -> DocId {
        self.base.advance(target)
    }
    fn score(&mut self) -> f32 {
        let mut score = self.base.score();
        let target = self.base.doc_id();
        for opt in &mut self.optionals {
            if opt.advance(target) == target {
                score += opt.score();
            }
        }
        score
    }
    fn two_phase(&mut self) -> Option<&mut dyn TwoPhaseIterator> {
        None
    }
}

/// Build the right scorer for should clauses given the effective minimum
/// and the caller's score mode.
///
/// In filter context (`!score_mode.needs_scores()`) with `min_match <= 1`,
/// uses `BufferedUnionScorer` (windowed bitset, no scoring overhead).
/// In scoring context, uses `WANDScorer` (block-max WAND for top-K).
/// All `min_match` values 1..N-1 in scoring context dispatch to
/// `WANDScorer`, which handles both standard disjunction and
/// `min_should_match`. See [[fix-min-should-match-unit-cost]] and
/// [[optimization-bool-filter-disjunction]].
fn build_should_scorer(
    mut scorers: Vec<Box<dyn Scorer>>,
    min_match: usize,
    score_mode: ScoreMode,
) -> Result<Box<dyn Scorer>> {
    if min_match > scorers.len() {
        return Ok(Box::new(EmptyScorer));
    }
    if scorers.len() == 1 {
        return Ok(scorers.pop().unwrap());
    }
    if min_match == scorers.len() {
        // All required → conjunction (much faster than disjunction)
        return Ok(Box::new(ConjunctionScorer::new(scorers)));
    }
    // Filter context: use BufferedUnionScorer (no scoring overhead).
    // Only when min_match <= 1 — BufferedUnionScorer doesn't support MSM.
    if !score_mode.needs_scores() && min_match <= 1 {
        return Ok(Box::new(
            crate::search::buffered_union::BufferedUnionScorer::new(scorers),
        ));
    }
    if min_match <= 1 {
        return Ok(Box::new(crate::search::wand::WANDScorer::new(scorers)));
    }
    Ok(Box::new(
        crate::search::wand::WANDScorer::new_min_should_match(scorers, min_match),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::query::term::TermQuery;

    use crate::analysis::Token;
    use crate::core::{FieldId, SegmentId};
    use crate::mapping::{FieldType, Mapping};
    use crate::segment::builder::SegmentBuilder;

    fn make_tokens(terms: &[&str]) -> Vec<Token> {
        terms
            .iter()
            .enumerate()
            .map(|(i, t)| Token::new(*t, 0, t.len(), i as u32))
            .collect()
    }

    fn build_test_store() -> crate::search::segment_store::SegmentStore {
        let schema = Mapping::builder()
            .field("body", FieldType::Text)
            .field("tag", FieldType::Keyword)
            .build();
        let mut builder = SegmentBuilder::new(SegmentId::new(1), &schema);

        // Doc 0: body="hello world", tag="a"
        builder.add_document(
            &[
                (FieldId::new(0), make_tokens(&["hello", "world"])),
                (FieldId::new(1), make_tokens(&["a"])),
            ],
            b"{}",
        );
        // Doc 1: body="hello luci", tag="b"
        builder.add_document(
            &[
                (FieldId::new(0), make_tokens(&["hello", "luci"])),
                (FieldId::new(1), make_tokens(&["b"])),
            ],
            b"{}",
        );
        // Doc 2: body="goodbye world", tag="a"
        builder.add_document(
            &[
                (FieldId::new(0), make_tokens(&["goodbye", "world"])),
                (FieldId::new(1), make_tokens(&["a"])),
            ],
            b"{}",
        );
        // Doc 3: body="luci search", tag="c"
        builder.add_document(
            &[
                (FieldId::new(0), make_tokens(&["luci", "search"])),
                (FieldId::new(1), make_tokens(&["c"])),
            ],
            b"{}",
        );

        let reader = SegmentReader::open(builder.build()).unwrap();
        crate::search::segment_store::SegmentStore::new(
            vec![reader],
            crate::analysis::AnalyzerRegistry::new(),
            None,
            None,
        )
    }

    fn collect_doc_ids(scorer: &mut dyn Scorer) -> Vec<u32> {
        let mut ids = Vec::new();
        while scorer.doc_id() != NO_MORE_DOCS {
            ids.push(scorer.doc_id().as_u32());
            scorer.next();
        }
        ids
    }

    #[test]
    fn bool_must_two_clauses() {
        let store = build_test_store();
        let searcher = Searcher::new(&store);
        let query = BoolQuery {
            must: vec![
                Box::new(TermQuery {
                    field: "body".into(),
                    value: "hello".into(),
                }),
                Box::new(TermQuery {
                    field: "body".into(),
                    value: "world".into(),
                }),
            ],
            should: vec![],
            must_not: vec![],
            filter: vec![],
            minimum_should_match: None,
        };

        let weight = query.bind(&searcher, ScoreMode::Complete).unwrap();
        let supplier = weight
            .scorer_supplier(&searcher.segments()[0])
            .unwrap()
            .unwrap();
        let mut scorer = supplier.scorer().unwrap();

        // Only doc 0 has both "hello" AND "world"
        let ids = collect_doc_ids(scorer.as_mut());
        assert_eq!(ids, vec![0]);
    }

    #[test]
    fn bool_should_two_clauses() {
        let store = build_test_store();
        let searcher = Searcher::new(&store);
        let query = BoolQuery {
            must: vec![],
            should: vec![
                Box::new(TermQuery {
                    field: "body".into(),
                    value: "hello".into(),
                }),
                Box::new(TermQuery {
                    field: "body".into(),
                    value: "goodbye".into(),
                }),
            ],
            must_not: vec![],
            filter: vec![],
            minimum_should_match: None,
        };

        let weight = query.bind(&searcher, ScoreMode::Complete).unwrap();
        let supplier = weight
            .scorer_supplier(&searcher.segments()[0])
            .unwrap()
            .unwrap();
        let mut scorer = supplier.scorer().unwrap();

        // Docs 0, 1, 2: "hello" in 0,1 and "goodbye" in 2
        let ids = collect_doc_ids(scorer.as_mut());
        assert_eq!(ids, vec![0, 1, 2]);
    }

    #[test]
    fn bool_must_not() {
        let store = build_test_store();
        let searcher = Searcher::new(&store);
        let query = BoolQuery {
            must: vec![Box::new(TermQuery {
                field: "body".into(),
                value: "hello".into(),
            })],
            should: vec![],
            must_not: vec![Box::new(TermQuery {
                field: "body".into(),
                value: "world".into(),
            })],
            filter: vec![],
            minimum_should_match: None,
        };

        let weight = query.bind(&searcher, ScoreMode::Complete).unwrap();
        let supplier = weight
            .scorer_supplier(&searcher.segments()[0])
            .unwrap()
            .unwrap();
        let mut scorer = supplier.scorer().unwrap();

        // "hello" in docs 0,1. "world" in docs 0,2. Must_not removes doc 0.
        let ids = collect_doc_ids(scorer.as_mut());
        assert_eq!(ids, vec![1]);
    }

    #[test]
    fn bool_filter_no_scores() {
        let store = build_test_store();
        let searcher = Searcher::new(&store);
        let query = BoolQuery {
            must: vec![],
            should: vec![],
            must_not: vec![],
            filter: vec![Box::new(TermQuery {
                field: "tag".into(),
                value: "a".into(),
            })],
            minimum_should_match: None,
        };

        let weight = query.bind(&searcher, ScoreMode::Complete).unwrap();
        let supplier = weight
            .scorer_supplier(&searcher.segments()[0])
            .unwrap()
            .unwrap();
        let mut scorer = supplier.scorer().unwrap();

        // tag="a" in docs 0, 2
        let ids = collect_doc_ids(scorer.as_mut());
        assert_eq!(ids, vec![0, 2]);
    }

    #[test]
    fn bool_must_plus_filter() {
        let store = build_test_store();
        let searcher = Searcher::new(&store);
        let query = BoolQuery {
            must: vec![Box::new(TermQuery {
                field: "body".into(),
                value: "hello".into(),
            })],
            should: vec![],
            must_not: vec![],
            filter: vec![Box::new(TermQuery {
                field: "tag".into(),
                value: "a".into(),
            })],
            minimum_should_match: None,
        };

        let weight = query.bind(&searcher, ScoreMode::Complete).unwrap();
        let supplier = weight
            .scorer_supplier(&searcher.segments()[0])
            .unwrap()
            .unwrap();
        let mut scorer = supplier.scorer().unwrap();

        // "hello" in 0,1 AND tag="a" in 0,2 → only doc 0
        let ids = collect_doc_ids(scorer.as_mut());
        assert_eq!(ids, vec![0]);
    }

    #[test]
    fn bool_empty_must_returns_none() {
        let store = build_test_store();
        let searcher = Searcher::new(&store);
        let query = BoolQuery {
            must: vec![Box::new(TermQuery {
                field: "body".into(),
                value: "nonexistent".into(),
            })],
            should: vec![],
            must_not: vec![],
            filter: vec![],
            minimum_should_match: None,
        };

        let weight = query.bind(&searcher, ScoreMode::Complete).unwrap();
        let supplier = weight.scorer_supplier(&searcher.segments()[0]).unwrap();
        assert!(supplier.is_none());
    }

    /// Regression test for [[investigation-20260405-03-min-should-match-incomplete-scoring]].
    ///
    /// With min_should_match, the score must include ALL matching clauses,
    /// not just those pulled into the lead zone. The bug: tail entries that
    /// match the candidate are never advanced or scored.
    #[test]
    fn min_should_match_scores_all_matching_clauses() {
        use crate::analysis::AnalyzerRegistry;

        let schema = Mapping::builder().field("body", FieldType::Text).build();
        let mut builder = SegmentBuilder::new(SegmentId::new(1), &schema);

        // Doc 0: has all 4 terms
        builder.add_document(
            &[(FieldId::new(0), make_tokens(&["aaa", "bbb", "ccc", "ddd"]))],
            b"{}",
        );
        // Doc 1: has 2 terms
        builder.add_document(&[(FieldId::new(0), make_tokens(&["aaa", "bbb"]))], b"{}");
        // Doc 2: has 1 term (excluded by MSM=2)
        builder.add_document(&[(FieldId::new(0), make_tokens(&["aaa"]))], b"{}");

        let reader = crate::segment::reader::SegmentReader::open(builder.build()).unwrap();
        let store = crate::search::segment_store::SegmentStore::new(
            vec![reader],
            AnalyzerRegistry::new(),
            None,
            None,
        );
        let searcher = crate::search::searcher::Searcher::new(&store);

        // Get individual term scores for doc 0
        let terms = ["aaa", "bbb", "ccc", "ddd"];
        let mut expected_sum: f32 = 0.0;
        for term in &terms {
            let tq = TermQuery {
                field: "body".into(),
                value: (*term).into(),
            };
            let weight = tq.bind(&searcher, ScoreMode::Complete).unwrap();
            let supplier = weight
                .scorer_supplier(&searcher.segments()[0])
                .unwrap()
                .unwrap();
            let mut scorer = supplier.scorer().unwrap();
            assert_eq!(
                scorer.doc_id(),
                DocId::new(0),
                "term '{term}' must be in doc 0"
            );
            expected_sum += scorer.score();
        }

        // MSM query with min_should_match=2
        let msm_query = BoolQuery {
            must: vec![],
            should: vec![
                Box::new(TermQuery {
                    field: "body".into(),
                    value: "aaa".into(),
                }),
                Box::new(TermQuery {
                    field: "body".into(),
                    value: "bbb".into(),
                }),
                Box::new(TermQuery {
                    field: "body".into(),
                    value: "ccc".into(),
                }),
                Box::new(TermQuery {
                    field: "body".into(),
                    value: "ddd".into(),
                }),
            ],
            must_not: vec![],
            filter: vec![],
            minimum_should_match: Some(2),
        };

        let weight = msm_query.bind(&searcher, ScoreMode::Complete).unwrap();
        let supplier = weight
            .scorer_supplier(&searcher.segments()[0])
            .unwrap()
            .unwrap();
        let mut scorer = supplier.scorer().unwrap();

        assert_eq!(scorer.doc_id(), DocId::new(0));
        let msm_score = scorer.score();

        // Score must include ALL 4 matching clauses, not just the 3 in lead
        assert!(
            (msm_score - expected_sum).abs() < 1e-5,
            "MSM score ({msm_score}) must equal sum of all clause scores ({expected_sum}); \
             difference {} suggests tail entries were not scored",
            (msm_score - expected_sum).abs(),
        );
    }
}