Skip to main content

hermes_core/query/
boolean.rs

1//! Boolean query with MUST, SHOULD, and MUST_NOT clauses
2
3use std::sync::Arc;
4
5use crate::segment::SegmentReader;
6use crate::structures::TERMINATED;
7use crate::{DocId, Score};
8
9use super::planner::{
10    build_combined_bitset, build_sparse_bmp_results, build_sparse_bmp_results_filtered,
11    build_sparse_maxscore_executor, chain_predicates, combine_sparse_results, compute_idf,
12    extract_all_sparse_infos, finish_text_maxscore, prepare_per_field_grouping,
13    prepare_text_maxscore,
14};
15use super::{CountFuture, EmptyScorer, GlobalStats, Query, Scorer, ScorerFuture};
16
17/// Boolean query with MUST, SHOULD, and MUST_NOT clauses
18///
19/// When all clauses are SHOULD term queries on the same field, automatically
20/// uses MaxScore optimization for efficient top-k retrieval.
21#[derive(Default, Clone)]
22pub struct BooleanQuery {
23    pub must: Vec<Arc<dyn Query>>,
24    pub should: Vec<Arc<dyn Query>>,
25    pub must_not: Vec<Arc<dyn Query>>,
26    /// Optional global statistics for cross-segment IDF
27    global_stats: Option<Arc<GlobalStats>>,
28}
29
30impl std::fmt::Debug for BooleanQuery {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        f.debug_struct("BooleanQuery")
33            .field("must_count", &self.must.len())
34            .field("should_count", &self.should.len())
35            .field("must_not_count", &self.must_not.len())
36            .field("has_global_stats", &self.global_stats.is_some())
37            .finish()
38    }
39}
40
41impl std::fmt::Display for BooleanQuery {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        write!(f, "Boolean(")?;
44        let mut first = true;
45        for q in &self.must {
46            if !first {
47                write!(f, " ")?;
48            }
49            write!(f, "+{}", q)?;
50            first = false;
51        }
52        for q in &self.should {
53            if !first {
54                write!(f, " ")?;
55            }
56            write!(f, "{}", q)?;
57            first = false;
58        }
59        for q in &self.must_not {
60            if !first {
61                write!(f, " ")?;
62            }
63            write!(f, "-{}", q)?;
64            first = false;
65        }
66        write!(f, ")")
67    }
68}
69
70impl BooleanQuery {
71    pub fn new() -> Self {
72        Self::default()
73    }
74
75    pub fn must(mut self, query: impl Query + 'static) -> Self {
76        self.must.push(Arc::new(query));
77        self
78    }
79
80    pub fn should(mut self, query: impl Query + 'static) -> Self {
81        self.should.push(Arc::new(query));
82        self
83    }
84
85    pub fn must_not(mut self, query: impl Query + 'static) -> Self {
86        self.must_not.push(Arc::new(query));
87        self
88    }
89
90    /// Set global statistics for cross-segment IDF
91    pub fn with_global_stats(mut self, stats: Arc<GlobalStats>) -> Self {
92        self.global_stats = Some(stats);
93        self
94    }
95}
96
97/// Build a SHOULD-only scorer from a vec of optimized scorers.
98fn build_should_scorer<'a>(scorers: Vec<Box<dyn Scorer + 'a>>) -> Box<dyn Scorer + 'a> {
99    if scorers.is_empty() {
100        return Box::new(EmptyScorer);
101    }
102    if scorers.len() == 1 {
103        return scorers.into_iter().next().unwrap();
104    }
105    let mut scorer = BooleanScorer {
106        must: vec![],
107        should: scorers,
108        must_not: vec![],
109        current_doc: 0,
110    };
111    scorer.current_doc = scorer.find_next_match();
112    Box::new(scorer)
113}
114
115// ── Planner macro ────────────────────────────────────────────────────────
116//
117// Unified planner for both async and sync paths.  Parameterised on:
118//   $scorer_fn      – scorer_with_options | scorer_sync_with_options
119//   $get_postings_fn – get_postings | get_postings_sync
120//   $execute_fn     – execute | execute_sync
121//   $($aw)*         – .await  (present for async, absent for sync)
122//
123// Decision order:
124//   1. Single-clause unwrap
125//   2. Pure OR → text MaxScore | sparse MaxScore | per-field MaxScore
126//   3. Filter push-down → predicate-aware sparse MaxScore | PredicatedScorer
127//   4. Standard BooleanScorer fallback
128macro_rules! boolean_plan {
129    ($must:expr, $should:expr, $must_not:expr, $global_stats:expr,
130     $reader:expr, $limit:expr, $scorer_options:expr,
131     $scorer_fn:ident, $get_postings_fn:ident, $execute_fn:ident
132     $(, $aw:tt)*) => {{
133        let must: &[Arc<dyn Query>] = &$must;
134        let should_all: &[Arc<dyn Query>] = &$should;
135        let must_not: &[Arc<dyn Query>] = &$must_not;
136        let global_stats: Option<&Arc<GlobalStats>> = $global_stats;
137        let reader: &SegmentReader = $reader;
138        let limit: usize = $limit;
139        let scorer_options: super::ScorerOptions = $scorer_options;
140
141        // Cap SHOULD clauses to MAX_QUERY_TERMS, but only count queries that need
142        // posting-list cursors. Fast-field predicates (O(1) per doc) are exempt.
143        let should_capped: Vec<Arc<dyn Query>>;
144        let should: &[Arc<dyn Query>] = if should_all.len() > super::MAX_QUERY_TERMS {
145            let is_predicate: Vec<bool> = should_all
146                .iter()
147                .map(|q| q.is_filter() || q.as_doc_predicate(reader).is_some())
148                .collect();
149            let cursor_count = is_predicate.iter().filter(|&&p| !p).count();
150
151            if cursor_count > super::MAX_QUERY_TERMS {
152                let mut kept = Vec::with_capacity(should_all.len());
153                let mut cursor_kept = 0usize;
154                for (q, &is_pred) in should_all.iter().zip(is_predicate.iter()) {
155                    if is_pred {
156                        kept.push(q.clone());
157                    } else if cursor_kept < super::MAX_QUERY_TERMS {
158                        kept.push(q.clone());
159                        cursor_kept += 1;
160                    }
161                }
162                log::debug!(
163                    "BooleanQuery: capping cursor SHOULD from {} to {} ({} fast-field predicates exempt)",
164                    cursor_count,
165                    super::MAX_QUERY_TERMS,
166                    kept.len() - cursor_kept,
167                );
168                should_capped = kept;
169                &should_capped
170            } else {
171                log::debug!(
172                    "BooleanQuery: {} SHOULD clauses OK ({} need cursors, {} fast-field predicates)",
173                    should_all.len(),
174                    cursor_count,
175                    should_all.len() - cursor_count,
176                );
177                should_all
178            }
179        } else {
180            should_all
181        };
182
183        // ── 1. Single-clause optimisation ────────────────────────────────
184        if must_not.is_empty() {
185            if must.len() == 1 && should.is_empty() {
186                return must[0].$scorer_fn(reader, limit, scorer_options) $(.  $aw)* ;
187            }
188            if should.len() == 1 && must.is_empty() {
189                return should[0].$scorer_fn(reader, limit, scorer_options) $(. $aw)* ;
190            }
191        }
192
193        // ── 2. Pure OR → MaxScore optimisations ──────────────────────────
194        if must.is_empty() && must_not.is_empty() && should.len() >= 2 {
195            // 2a. Text MaxScore (single-field, all term queries)
196            if !scorer_options.collect_positions
197                && let Some((mut infos, text_field, avg_field_len, num_docs)) =
198                prepare_text_maxscore(should, reader, global_stats)
199            {
200                let mut posting_lists = Vec::with_capacity(infos.len());
201                for info in infos.drain(..) {
202                    if let Some(pl) = reader.$get_postings_fn(info.field, &info.term)
203                        $(. $aw)* ?
204                    {
205                        let idf = compute_idf(&pl, info.field, &info.term, num_docs, global_stats);
206                        posting_lists.push((pl, idf));
207                    }
208                }
209                // Seed from the cross-segment floor: this path scores final
210                // per-doc BM25 into a top-`limit` heap, so a floor carried from
211                // an already-searched segment prunes exactly (see
212                // SharedThreshold). The per-field path below stays at 0.0 —
213                // its per-field partial scores are not the final doc score.
214                let shared_threshold = std::cell::Cell::new(scorer_options.initial_threshold);
215                return finish_text_maxscore(
216                    posting_lists,
217                    avg_field_len,
218                    limit,
219                    &shared_threshold,
220                    reader.schema().index_label(),
221                    reader.schema().get_field_name(text_field).unwrap_or("?"),
222                );
223            }
224
225            // 2b. Sparse (single-field, all sparse term queries)
226            // Auto-detect: BMP executor if field has BMP index, else MaxScore
227            if let Some(infos) = extract_all_sparse_infos(should) {
228                if let Some((raw, info)) =
229                    build_sparse_bmp_results(&infos, reader, limit, &scorer_options)
230                {
231                    return Ok(combine_sparse_results(raw, info.combiner, info.field, limit));
232                }
233                if let Some((executor, info)) =
234                    build_sparse_maxscore_executor(&infos, reader, limit, None)
235                {
236                    let raw = executor.$execute_fn() $(. $aw)* ?;
237                    return Ok(combine_sparse_results(raw, info.combiner, info.field, limit));
238                }
239            }
240
241            // 2c. Per-field text MaxScore (multi-field term grouping)
242            if !scorer_options.collect_positions
243                && let Some(grouping) =
244                    prepare_per_field_grouping(should, reader, limit, global_stats)
245            {
246                let mut scorers: Vec<Box<dyn Scorer + '_>> = Vec::new();
247                // Query-local cross-group threshold seeding (see finish_text_maxscore)
248                let shared_threshold = std::cell::Cell::new(0.0f32);
249                for (field, avg_field_len, infos) in &grouping.multi_term_groups {
250                    let mut posting_lists = Vec::with_capacity(infos.len());
251                    for info in infos {
252                        if let Some(pl) = reader.$get_postings_fn(info.field, &info.term)
253                            $(. $aw)* ?
254                        {
255                            let idf = compute_idf(
256                                &pl, *field, &info.term, grouping.num_docs, global_stats,
257                            );
258                            posting_lists.push((pl, idf));
259                        }
260                    }
261                    if !posting_lists.is_empty() {
262                        scorers.push(finish_text_maxscore(
263                            posting_lists,
264                            *avg_field_len,
265                            grouping.per_field_limit,
266                            &shared_threshold,
267                            reader.schema().index_label(),
268                            reader.schema().get_field_name(*field).unwrap_or("?"),
269                        )?);
270                    }
271                }
272                for &idx in &grouping.fallback_indices {
273                    scorers.push(should[idx].$scorer_fn(
274                        reader,
275                        limit,
276                        scorer_options.without_threshold(),
277                    ) $(. $aw)* ?);
278                }
279                return Ok(build_should_scorer(scorers));
280            }
281        }
282
283        // ── 3. Filter push-down (MUST + SHOULD) ─────────────────────────
284        if !scorer_options.collect_positions
285            && !should.is_empty()
286            && !must.is_empty()
287            && limit < usize::MAX / 4
288        {
289            // Pre-check: is SHOULD all-sparse? This determines whether we can
290            // use bitset fallback for MUST clauses that lack fast-field predicates.
291            // For sparse SHOULD, the predicate is pushed into BMP/MaxScore traversal
292            // so all qualifying docs are found. For text SHOULD, we must NOT convert
293            // MUST to a predicate (PredicatedScorer would drop MUST-only docs that
294            // don't match SHOULD), so those go to verifier → BooleanScorer.
295            let should_is_sparse = extract_all_sparse_infos(should).is_some();
296
297            // 3a. Compile MUST → predicates (O(1)) vs verifier scorers (seek)
298            //
299            // Priority: as_doc_predicate (fast-field O(1)) > as_doc_bitset
300            // (posting-list materialization, O(1) lookup, sparse-SHOULD only)
301            // > verifier scorer (seek).
302            let mut predicates: Vec<super::DocPredicate<'_>> = Vec::new();
303            let mut must_verifiers: Vec<Box<dyn super::Scorer + '_>> = Vec::new();
304            for q in must {
305                if let Some(pred) = q.as_doc_predicate(reader) {
306                    log::debug!("BooleanQuery planner 3a: MUST clause → predicate ({})", q);
307                    predicates.push(pred);
308                } else if should_is_sparse {
309                    if let Some(bitset) = q.as_doc_bitset(reader) {
310                        log::debug!("BooleanQuery planner 3a: MUST clause → bitset predicate ({})", q);
311                        predicates.push(Box::new(move |doc_id| bitset.contains(doc_id)));
312                    } else {
313                        log::debug!("BooleanQuery planner 3a: MUST clause → verifier scorer ({})", q);
314                        must_verifiers.push(q.$scorer_fn(
315                            reader, limit, scorer_options.without_threshold()
316                        ) $(. $aw)* ?);
317                    }
318                } else {
319                    log::debug!("BooleanQuery planner 3a: MUST clause → verifier scorer ({})", q);
320                    must_verifiers.push(q.$scorer_fn(
321                        reader, limit, scorer_options.without_threshold()
322                    ) $(. $aw)* ?);
323                }
324            }
325            // Compile MUST_NOT → negated predicates vs verifier scorers
326            let mut must_not_verifiers: Vec<Box<dyn super::Scorer + '_>> = Vec::new();
327            for q in must_not {
328                if let Some(pred) = q.as_doc_predicate(reader) {
329                    let negated: super::DocPredicate<'_> =
330                        Box::new(move |doc_id| !pred(doc_id));
331                    predicates.push(negated);
332                } else if should_is_sparse {
333                    if let Some(bitset) = q.as_doc_bitset(reader) {
334                        log::debug!("BooleanQuery planner 3a: MUST_NOT clause → bitset predicate ({})", q);
335                        predicates.push(Box::new(move |doc_id| !bitset.contains(doc_id)));
336                    } else {
337                        must_not_verifiers.push(q.$scorer_fn(
338                            reader, limit, scorer_options.without_threshold()
339                        ) $(. $aw)* ?);
340                    }
341                } else {
342                    must_not_verifiers.push(q.$scorer_fn(
343                        reader, limit, scorer_options.without_threshold()
344                    ) $(. $aw)* ?);
345                }
346            }
347
348            // 3b. Fast path: pure predicates + sparse SHOULD → BMP or MaxScore w/ predicate
349            if must_verifiers.is_empty()
350                && must_not_verifiers.is_empty()
351                && !predicates.is_empty()
352            {
353                if let Some(infos) = extract_all_sparse_infos(should) {
354                    // Try BMP with bitset first: build compact bitset from MUST/MUST_NOT
355                    // posting lists (O(M) for term queries) for fast per-slot lookup.
356                    let bitset_result = build_combined_bitset(must, must_not, reader);
357                    if let Some(ref bitset) = bitset_result {
358                        let bitset_pred = |doc_id: crate::DocId| bitset.contains(doc_id);
359                        if let Some((raw, info)) =
360                            build_sparse_bmp_results_filtered(
361                                &infos, reader, limit, &bitset_pred, &scorer_options
362                            )
363                        {
364                            log::debug!(
365                                "BooleanQuery planner: bitset-aware sparse BMP, {} dims, {} matching docs",
366                                infos.len(),
367                                bitset.count()
368                            );
369                            return Ok(combine_sparse_results(raw, info.combiner, info.field, limit));
370                        }
371                    }
372
373                    // Fallback: closure predicate (for queries that don't support bitsets)
374                    let combined = chain_predicates(predicates);
375                    if let Some((raw, info)) =
376                        build_sparse_bmp_results_filtered(
377                            &infos, reader, limit, &*combined, &scorer_options
378                        )
379                    {
380                        log::debug!(
381                            "BooleanQuery planner: predicate-aware sparse BMP, {} dims",
382                            infos.len()
383                        );
384                        return Ok(combine_sparse_results(raw, info.combiner, info.field, limit));
385                    }
386                    // Try MaxScore with predicate
387                    if let Some((executor, info)) =
388                        build_sparse_maxscore_executor(&infos, reader, limit, Some(combined))
389                    {
390                        log::debug!(
391                            "BooleanQuery planner: predicate-aware sparse MaxScore, {} dims",
392                            infos.len()
393                        );
394                        let raw = executor.$execute_fn() $(. $aw)* ?;
395                        return Ok(combine_sparse_results(raw, info.combiner, info.field, limit));
396                    }
397                    // predicates consumed — cannot fall through; rebuild them
398                    // (this path only triggers if neither sparse index exists)
399                    // should_is_sparse is true here (we're inside extract_all_sparse_infos)
400                    predicates = Vec::new();
401                    for q in must {
402                        if let Some(pred) = q.as_doc_predicate(reader) {
403                            predicates.push(pred);
404                        } else if let Some(bitset) = q.as_doc_bitset(reader) {
405                            predicates.push(Box::new(move |doc_id| bitset.contains(doc_id)));
406                        }
407                    }
408                    for q in must_not {
409                        if let Some(pred) = q.as_doc_predicate(reader) {
410                            let negated: super::DocPredicate<'_> =
411                                Box::new(move |doc_id| !pred(doc_id));
412                            predicates.push(negated);
413                        } else if let Some(bitset) = q.as_doc_bitset(reader) {
414                            predicates.push(Box::new(move |doc_id| !bitset.contains(doc_id)));
415                        }
416                    }
417                }
418            }
419
420            // 3c. PredicatedScorer fallback (over-fetch 4x when any filter is present)
421            let has_filters = !predicates.is_empty()
422                || !must_verifiers.is_empty()
423                || !must_not_verifiers.is_empty();
424            let should_limit = if has_filters { limit * 4 } else { limit };
425            let should_scorer = if should.len() == 1 {
426                should[0].$scorer_fn(
427                    reader, should_limit, scorer_options.without_threshold()
428                ) $(. $aw)* ?
429            } else {
430                let sub = BooleanQuery {
431                    must: Vec::new(),
432                    should: should.to_vec(),
433                    must_not: Vec::new(),
434                    global_stats: global_stats.cloned(),
435                };
436                sub.$scorer_fn(
437                    reader, should_limit, scorer_options.without_threshold()
438                ) $(. $aw)* ?
439            };
440
441            let use_predicated =
442                must_verifiers.is_empty() || should_scorer.size_hint() >= limit as u32;
443
444            if use_predicated {
445                log::debug!(
446                    "BooleanQuery planner: PredicatedScorer {} preds + {} must_v + {} must_not_v, \
447                     SHOULD size_hint={}, over_fetch={}",
448                    predicates.len(), must_verifiers.len(), must_not_verifiers.len(),
449                    should_scorer.size_hint(), should_limit
450                );
451                return Ok(Box::new(super::PredicatedScorer::new(
452                    should_scorer, predicates, must_verifiers, must_not_verifiers,
453                )));
454            }
455
456            // size_hint < limit with verifiers → BooleanScorer
457            log::debug!(
458                "BooleanQuery planner: BooleanScorer fallback, size_hint={} < limit={}, \
459                 {} must_v + {} must_not_v",
460                should_scorer.size_hint(), limit,
461                must_verifiers.len(), must_not_verifiers.len()
462            );
463            let mut scorer = BooleanScorer {
464                must: must_verifiers,
465                should: vec![should_scorer],
466                must_not: must_not_verifiers,
467                current_doc: 0,
468            };
469            scorer.current_doc = scorer.find_next_match();
470            return Ok(Box::new(scorer));
471        }
472
473        // ── 4. Standard BooleanScorer fallback ───────────────────────────
474        let mut must_scorers = Vec::with_capacity(must.len());
475        for q in must {
476            must_scorers.push(q.$scorer_fn(
477                reader, limit, scorer_options.without_threshold()
478            ) $(. $aw)* ?);
479        }
480        let mut should_scorers = Vec::with_capacity(should.len());
481        for q in should {
482            should_scorers.push(q.$scorer_fn(
483                reader, limit, scorer_options.without_threshold()
484            ) $(. $aw)* ?);
485        }
486        let mut must_not_scorers = Vec::with_capacity(must_not.len());
487        for q in must_not {
488            must_not_scorers.push(q.$scorer_fn(
489                reader, limit, scorer_options.without_threshold()
490            ) $(. $aw)* ?);
491        }
492        let mut scorer = BooleanScorer {
493            must: must_scorers,
494            should: should_scorers,
495            must_not: must_not_scorers,
496            current_doc: 0,
497        };
498        scorer.current_doc = scorer.find_next_match();
499        Ok(Box::new(scorer) as Box<dyn Scorer + '_>)
500    }};
501}
502
503impl Query for BooleanQuery {
504    fn scorer<'a>(&self, reader: &'a SegmentReader, limit: usize) -> ScorerFuture<'a> {
505        self.scorer_with_options(reader, limit, super::ScorerOptions::with_positions())
506    }
507
508    fn scorer_with_options<'a>(
509        &self,
510        reader: &'a SegmentReader,
511        limit: usize,
512        options: super::ScorerOptions,
513    ) -> ScorerFuture<'a> {
514        let must = self.must.clone();
515        let should = self.should.clone();
516        let must_not = self.must_not.clone();
517        let global_stats = self.global_stats.clone();
518        Box::pin(async move {
519            boolean_plan!(
520                must,
521                should,
522                must_not,
523                global_stats.as_ref(),
524                reader,
525                limit,
526                options,
527                scorer_with_options,
528                get_postings,
529                execute,
530                await
531            )
532        })
533    }
534
535    #[cfg(feature = "sync")]
536    fn scorer_sync<'a>(
537        &self,
538        reader: &'a SegmentReader,
539        limit: usize,
540    ) -> crate::Result<Box<dyn Scorer + 'a>> {
541        self.scorer_sync_with_options(reader, limit, super::ScorerOptions::with_positions())
542    }
543
544    #[cfg(feature = "sync")]
545    fn scorer_sync_with_options<'a>(
546        &self,
547        reader: &'a SegmentReader,
548        limit: usize,
549        options: super::ScorerOptions,
550    ) -> crate::Result<Box<dyn Scorer + 'a>> {
551        boolean_plan!(
552            self.must,
553            self.should,
554            self.must_not,
555            self.global_stats.as_ref(),
556            reader,
557            limit,
558            options,
559            scorer_sync_with_options,
560            get_postings_sync,
561            execute_sync
562        )
563    }
564
565    fn as_doc_bitset(&self, reader: &SegmentReader) -> Option<super::DocBitset> {
566        if self.must.is_empty() && self.should.is_empty() {
567            return None;
568        }
569
570        let num_docs = reader.num_docs();
571
572        // MUST clauses: intersect bitsets (AND)
573        let mut result: Option<super::DocBitset> = None;
574        for q in &self.must {
575            let bs = q.as_doc_bitset(reader)?;
576            match result {
577                None => result = Some(bs),
578                Some(ref mut acc) => acc.intersect_with(&bs),
579            }
580        }
581
582        // SHOULD clauses: union bitsets (OR), then intersect with MUST result
583        if !self.should.is_empty() {
584            let mut should_union = super::DocBitset::new(num_docs);
585            for q in &self.should {
586                let bs = q.as_doc_bitset(reader)?;
587                should_union.union_with(&bs);
588            }
589            match result {
590                None => result = Some(should_union),
591                Some(ref mut acc) => {
592                    // When MUST clauses exist, SHOULD is optional (doesn't filter).
593                    // When no MUST clauses, at least one SHOULD must match.
594                    if self.must.is_empty() {
595                        *acc = should_union;
596                    }
597                }
598            }
599        }
600
601        // MUST_NOT clauses: subtract bitsets (ANDNOT)
602        if let Some(ref mut acc) = result {
603            for q in &self.must_not {
604                {
605                    let bs = q.as_doc_bitset(reader)?;
606                    acc.subtract(&bs);
607                }
608            }
609        }
610
611        result
612    }
613
614    fn as_doc_predicate<'a>(&self, reader: &'a SegmentReader) -> Option<super::DocPredicate<'a>> {
615        // Need at least some clauses
616        if self.must.is_empty() && self.should.is_empty() {
617            return None;
618        }
619
620        // Try converting all clauses to predicates; bail if any child can't
621        let must_preds: Vec<_> = self
622            .must
623            .iter()
624            .map(|q| q.as_doc_predicate(reader))
625            .collect::<Option<Vec<_>>>()?;
626        let should_preds: Vec<_> = self
627            .should
628            .iter()
629            .map(|q| q.as_doc_predicate(reader))
630            .collect::<Option<Vec<_>>>()?;
631        let must_not_preds: Vec<_> = self
632            .must_not
633            .iter()
634            .map(|q| q.as_doc_predicate(reader))
635            .collect::<Option<Vec<_>>>()?;
636
637        let has_must = !must_preds.is_empty();
638
639        Some(Box::new(move |doc_id| {
640            // All MUST predicates must pass
641            if !must_preds.iter().all(|p| p(doc_id)) {
642                return false;
643            }
644            // When there are no MUST clauses, at least one SHOULD must pass
645            if !has_must && !should_preds.is_empty() && !should_preds.iter().any(|p| p(doc_id)) {
646                return false;
647            }
648            // No MUST_NOT predicate should pass
649            must_not_preds.iter().all(|p| !p(doc_id))
650        }))
651    }
652
653    fn count_estimate<'a>(&self, reader: &'a SegmentReader) -> CountFuture<'a> {
654        let must = self.must.clone();
655        let should = self.should.clone();
656
657        Box::pin(async move {
658            if !must.is_empty() {
659                let mut estimates = Vec::with_capacity(must.len());
660                for q in &must {
661                    estimates.push(q.count_estimate(reader).await?);
662                }
663                estimates
664                    .into_iter()
665                    .min()
666                    .ok_or_else(|| crate::Error::Corruption("Empty must clause".to_string()))
667            } else if !should.is_empty() {
668                let mut sum = 0u32;
669                for q in &should {
670                    sum = sum.saturating_add(q.count_estimate(reader).await?);
671                }
672                Ok(sum)
673            } else {
674                Ok(0)
675            }
676        })
677    }
678}
679
680struct BooleanScorer<'a> {
681    must: Vec<Box<dyn Scorer + 'a>>,
682    should: Vec<Box<dyn Scorer + 'a>>,
683    must_not: Vec<Box<dyn Scorer + 'a>>,
684    current_doc: DocId,
685}
686
687impl BooleanScorer<'_> {
688    fn find_next_match(&mut self) -> DocId {
689        if self.must.is_empty() && self.should.is_empty() {
690            return TERMINATED;
691        }
692
693        loop {
694            let candidate = if !self.must.is_empty() {
695                let mut max_doc = self
696                    .must
697                    .iter()
698                    .map(|s| s.doc())
699                    .max()
700                    .unwrap_or(TERMINATED);
701
702                if max_doc == TERMINATED {
703                    return TERMINATED;
704                }
705
706                loop {
707                    let mut all_match = true;
708                    for scorer in &mut self.must {
709                        let doc = scorer.seek(max_doc);
710                        if doc == TERMINATED {
711                            return TERMINATED;
712                        }
713                        if doc > max_doc {
714                            max_doc = doc;
715                            all_match = false;
716                            break;
717                        }
718                    }
719                    if all_match {
720                        break;
721                    }
722                }
723                max_doc
724            } else {
725                self.should
726                    .iter()
727                    .map(|s| s.doc())
728                    .filter(|&d| d != TERMINATED)
729                    .min()
730                    .unwrap_or(TERMINATED)
731            };
732
733            if candidate == TERMINATED {
734                return TERMINATED;
735            }
736
737            let excluded = self.must_not.iter_mut().any(|scorer| {
738                let doc = scorer.seek(candidate);
739                doc == candidate
740            });
741
742            if !excluded {
743                // Seek SHOULD scorers to candidate so score() can see their contributions
744                for scorer in &mut self.should {
745                    scorer.seek(candidate);
746                }
747                self.current_doc = candidate;
748                return candidate;
749            }
750
751            // Advance past excluded candidate
752            if !self.must.is_empty() {
753                for scorer in &mut self.must {
754                    scorer.advance();
755                }
756            } else {
757                // For SHOULD-only: seek all scorers past the excluded candidate
758                for scorer in &mut self.should {
759                    if scorer.doc() <= candidate && scorer.doc() != TERMINATED {
760                        scorer.seek(candidate + 1);
761                    }
762                }
763            }
764        }
765    }
766}
767
768impl super::docset::DocSet for BooleanScorer<'_> {
769    fn doc(&self) -> DocId {
770        self.current_doc
771    }
772
773    fn advance(&mut self) -> DocId {
774        if !self.must.is_empty() {
775            for scorer in &mut self.must {
776                scorer.advance();
777            }
778        } else {
779            for scorer in &mut self.should {
780                if scorer.doc() == self.current_doc {
781                    scorer.advance();
782                }
783            }
784        }
785
786        self.current_doc = self.find_next_match();
787        self.current_doc
788    }
789
790    fn seek(&mut self, target: DocId) -> DocId {
791        for scorer in &mut self.must {
792            scorer.seek(target);
793        }
794
795        for scorer in &mut self.should {
796            scorer.seek(target);
797        }
798
799        self.current_doc = self.find_next_match();
800        self.current_doc
801    }
802
803    fn size_hint(&self) -> u32 {
804        if !self.must.is_empty() {
805            self.must.iter().map(|s| s.size_hint()).min().unwrap_or(0)
806        } else {
807            self.should.iter().map(|s| s.size_hint()).sum()
808        }
809    }
810}
811
812impl Scorer for BooleanScorer<'_> {
813    fn score(&self) -> Score {
814        let mut total = 0.0;
815
816        for scorer in &self.must {
817            if scorer.doc() == self.current_doc {
818                total += scorer.score();
819            }
820        }
821
822        for scorer in &self.should {
823            if scorer.doc() == self.current_doc {
824                total += scorer.score();
825            }
826        }
827
828        total
829    }
830
831    fn matched_positions(&self) -> Option<super::MatchedPositions> {
832        let mut all_positions: super::MatchedPositions = Vec::new();
833
834        for scorer in &self.must {
835            if scorer.doc() == self.current_doc
836                && let Some(positions) = scorer.matched_positions()
837            {
838                all_positions.extend(positions);
839            }
840        }
841
842        for scorer in &self.should {
843            if scorer.doc() == self.current_doc
844                && let Some(positions) = scorer.matched_positions()
845            {
846                all_positions.extend(positions);
847            }
848        }
849
850        if all_positions.is_empty() {
851            None
852        } else {
853            Some(all_positions)
854        }
855    }
856}
857
858#[cfg(test)]
859mod tests {
860    use super::*;
861    use crate::dsl::Field;
862    use crate::query::{QueryDecomposition, TermQuery};
863
864    #[test]
865    fn test_maxscore_eligible_pure_or_same_field() {
866        // Pure OR query with multiple terms in same field should be MaxScore-eligible
867        let query = BooleanQuery::new()
868            .should(TermQuery::text(Field(0), "hello"))
869            .should(TermQuery::text(Field(0), "world"))
870            .should(TermQuery::text(Field(0), "foo"));
871
872        // All clauses should return term info
873        assert!(
874            query
875                .should
876                .iter()
877                .all(|q| matches!(q.decompose(), QueryDecomposition::TextTerm(_)))
878        );
879
880        // All should be same field
881        let infos: Vec<_> = query
882            .should
883            .iter()
884            .filter_map(|q| match q.decompose() {
885                QueryDecomposition::TextTerm(info) => Some(info),
886                _ => None,
887            })
888            .collect();
889        assert_eq!(infos.len(), 3);
890        assert!(infos.iter().all(|i| i.field == Field(0)));
891    }
892
893    #[test]
894    fn test_maxscore_not_eligible_different_fields() {
895        // OR query with terms in different fields should NOT use MaxScore
896        let query = BooleanQuery::new()
897            .should(TermQuery::text(Field(0), "hello"))
898            .should(TermQuery::text(Field(1), "world")); // Different field!
899
900        let infos: Vec<_> = query
901            .should
902            .iter()
903            .filter_map(|q| match q.decompose() {
904                QueryDecomposition::TextTerm(info) => Some(info),
905                _ => None,
906            })
907            .collect();
908        assert_eq!(infos.len(), 2);
909        // Fields are different, MaxScore should not be used
910        assert!(infos[0].field != infos[1].field);
911    }
912
913    #[test]
914    fn test_maxscore_not_eligible_with_must() {
915        // Query with MUST clause should NOT use MaxScore optimization
916        let query = BooleanQuery::new()
917            .must(TermQuery::text(Field(0), "required"))
918            .should(TermQuery::text(Field(0), "hello"))
919            .should(TermQuery::text(Field(0), "world"));
920
921        // Has MUST clause, so MaxScore optimization should not kick in
922        assert!(!query.must.is_empty());
923    }
924
925    #[test]
926    fn test_maxscore_not_eligible_with_must_not() {
927        // Query with MUST_NOT clause should NOT use MaxScore optimization
928        let query = BooleanQuery::new()
929            .should(TermQuery::text(Field(0), "hello"))
930            .should(TermQuery::text(Field(0), "world"))
931            .must_not(TermQuery::text(Field(0), "excluded"));
932
933        // Has MUST_NOT clause, so MaxScore optimization should not kick in
934        assert!(!query.must_not.is_empty());
935    }
936
937    #[test]
938    fn test_maxscore_not_eligible_single_term() {
939        // Single SHOULD clause should NOT use MaxScore (no benefit)
940        let query = BooleanQuery::new().should(TermQuery::text(Field(0), "hello"));
941
942        // Only one term, MaxScore not beneficial
943        assert_eq!(query.should.len(), 1);
944    }
945
946    #[test]
947    fn test_term_query_info_extraction() {
948        let term_query = TermQuery::text(Field(42), "test");
949        match term_query.decompose() {
950            QueryDecomposition::TextTerm(info) => {
951                assert_eq!(info.field, Field(42));
952                assert_eq!(info.term, b"test");
953            }
954            _ => panic!("Expected TextTerm decomposition"),
955        }
956    }
957
958    #[test]
959    fn test_boolean_query_no_term_info() {
960        // BooleanQuery itself should not return term info
961        let query = BooleanQuery::new().should(TermQuery::text(Field(0), "hello"));
962
963        assert!(matches!(query.decompose(), QueryDecomposition::Opaque));
964    }
965}