Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

150 KB
Raw Blame
//! Search execution over a segment's FTS index.
//!
//! ## Query types
//!
//! | Query       | Description                                      |
//! |-------------|--------------------------------------------------|
//! | `TermQuery` | Single-term lookup: FST → postings → BM25 score  |
//! | `PhraseQuery`| Ordered adjacent term positions in same document |
//! | `BoolQuery` | must / should / must_not / filter combinator      |
//! | `PrefixQuery`| FST range scan for all terms with a given prefix |
//!
//! ## Parallelism
//!
//! When searching multiple segments, `FtsSearcher` uses rayon to fan out the
//! per-segment search in parallel and merge sorted results.

use crate::{
    analyzer::AnalyzerRegistry,
    bm25::{Bm25Scorer, CollectionStats, QueryExplanation, ScoreBreakdown},
    index::FtsIndexReader,
    postings::PostingsReader,
};
use anyhow::Result;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// Per-term phrase postings: `doc_id → (term_freq, positions)`.
type TermPostingsMap = std::collections::HashMap<u32, (u32, Vec<u32>)>;

// ── Scored hit ────────────────────────────────────────────────────────────────

/// One scored result document.
#[derive(Debug, Clone)]
pub struct ScoredHit {
    /// Segment-local document ID.
    pub doc_id: u32,
    /// BM25 relevance score (higher = more relevant).
    pub score: f32,
    /// Optional score breakdown (populated when `explain=true`).
    pub explanation: Option<QueryExplanation>,
}

impl PartialEq for ScoredHit {
    fn eq(&self, other: &Self) -> bool {
        self.doc_id == other.doc_id
    }
}
impl Eq for ScoredHit {}

impl PartialOrd for ScoredHit {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ScoredHit {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // Higher score first; break ties by doc_id ascending
        other
            .score
            .partial_cmp(&self.score)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| self.doc_id.cmp(&other.doc_id))
    }
}

// ── Bounded top-N collector ─────────────────────────────────────────────────

/// Bounded min-by-quality top-N collector.
///
/// Retains only the best `cap` hits seen so far while counting **every** hit
/// pushed (the exact match total).  `push` is O(log cap); memory is O(cap)
/// regardless of how many matches the query produces — this is what turns the
/// size>0 scored FTS path from O(N log N) (build + full sort) into O(N log cap)
/// with O(cap) memory.
///
/// ## Ordering identity (why the output is byte-identical to `sort` + `truncate`)
///
/// `ScoredHit`'s `Ord` makes the BEST hit compare **`Less`** (higher score
/// first, doc_id ascending on ties).  A [`BinaryHeap`](std::collections::BinaryHeap)
/// is a MAX-heap, so `peek()` returns the GREATEST element by `Ord` = the
/// **worst** retained hit.  A new hit is admitted iff it is strictly better
/// (`hit < worst`).  Because `doc_id` is unique, `Ord` is a total order with no
/// real ties, so the retained set is exactly the `cap` best hits, and
/// [`into_sorted_vec`](std::collections::BinaryHeap::into_sorted_vec) yields
/// them in ascending `Ord` order = best-first — identical to the legacy
/// `execute()` → `sort_unstable()` → `truncate(cap)`.
pub struct TopN {
    heap: std::collections::BinaryHeap<ScoredHit>,
    cap: usize,
    total: u64,
}

impl TopN {
    pub fn new(cap: usize) -> Self {
        Self {
            // Bound the pre-allocation: `cap` is a page limit (hundreds to a
            // few thousand), but guard against a pathological caller value.
            heap: std::collections::BinaryHeap::with_capacity(cap.min(4096)),
            cap,
            total: 0,
        }
    }

    /// Offer one hit: always counted toward `total`; retained only if it ranks
    /// among the best `cap` seen so far.
    #[inline]
    pub fn push(&mut self, hit: ScoredHit) {
        self.total += 1;
        if self.cap == 0 {
            return;
        }
        if self.heap.len() < self.cap {
            self.heap.push(hit);
        } else if let Some(mut worst) = self.heap.peek_mut() {
            // `worst` is the heap max = the worst retained hit.  Replace it
            // only when the incoming hit is strictly better (`Ord::Less`).
            // Dropping the `PeekMut` sifts the new element back into place.
            if hit < *worst {
                *worst = hit;
            }
        }
    }

    /// Exact number of hits pushed so far (independent of `cap`).
    pub fn total(&self) -> u64 {
        self.total
    }

    /// The worst hit currently RETAINED (the heap's max by `Ord` = the
    /// next eviction victim), or `None` while the heap is below `cap` (or
    /// `cap == 0`).  Read by the WAND walk's pruning check: a candidate
    /// whose score upper bound is below this cannot be admitted, so it
    /// never needs scoring at all.
    pub fn worst(&self) -> Option<&ScoredHit> {
        if self.cap == 0 || self.heap.len() < self.cap {
            None
        } else {
            self.heap.peek()
        }
    }

    /// Consume the collector: `(best-first sorted hits, exact total)`.
    pub fn finish(self) -> (Vec<ScoredHit>, u64) {
        let total = self.total;
        (self.heap.into_sorted_vec(), total)
    }
}

// ── Query types ───────────────────────────────────────────────────────────────

/// A single field + term lookup.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TermQuery {
    pub field: String,
    pub term: String,
    /// Boost multiplier for the score (default = 1.0, matches ES default).
    #[serde(default = "default_boost")]
    pub boost: f32,
}

fn default_boost() -> f32 {
    1.0
}

impl TermQuery {
    pub fn new(field: impl Into<String>, term: impl Into<String>) -> Self {
        Self {
            field: field.into(),
            term: term.into(),
            boost: 1.0,
        }
    }

    pub fn boosted(field: impl Into<String>, term: impl Into<String>, boost: f32) -> Self {
        Self {
            field: field.into(),
            term: term.into(),
            boost,
        }
    }
}

/// A phrase — terms must appear with adjacent positions in the given order
/// (`slop == 0`, the default), or within `slop` under Lucene move-distance
/// semantics (transpositions cost 2; see `phrase_positions_match`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PhraseQuery {
    pub field: String,
    /// Pre-analyzed phrase terms in order.
    pub terms: Vec<String>,
    /// Allowed Lucene move-distance (slop).
    #[serde(default)]
    pub slop: u32,
    #[serde(default = "default_boost")]
    pub boost: f32,
}

impl PhraseQuery {
    pub fn new(field: impl Into<String>, terms: Vec<String>) -> Self {
        Self {
            field: field.into(),
            terms,
            slop: 0,
            boost: 1.0,
        }
    }
}

/// A prefix query — finds all terms beginning with `prefix` in the FST.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrefixQuery {
    pub field: String,
    pub prefix: String,
    #[serde(default = "default_boost")]
    pub boost: f32,
    /// Maximum number of terms to expand (prevents explosion on short prefixes).
    #[serde(default = "default_max_expansions")]
    pub max_expansions: usize,
    /// When `true`, every matching doc scores a flat `boost` (ES rewrites
    /// `prefix` to a `constant_score` query).  When `false` (default, keyword
    /// path), the per-expansion BM25 scores are summed.
    #[serde(default)]
    pub constant_score: bool,
}

fn default_max_expansions() -> usize {
    50
}

impl PrefixQuery {
    pub fn new(field: impl Into<String>, prefix: impl Into<String>) -> Self {
        Self {
            field: field.into(),
            prefix: prefix.into(),
            boost: 1.0,
            max_expansions: 50,
            constant_score: false,
        }
    }
}

/// A wildcard query — expands the field's FST term dictionary to every term
/// matching `pattern` (`*` = zero-or-more chars, `?` = exactly one), then
/// scores each as a term.  Matching is **case-insensitive** and applied to the
/// whole indexed term AND its non-alphanumeric-split sub-tokens, byte-identical
/// to the engine's `doc_matches_query` wildcard predicate — so routing a
/// keyword-field wildcard through the FST returns exactly the same hit set as
/// the per-doc stored scan, only far faster (term dictionary ≪ documents).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WildcardQuery {
    pub field: String,
    pub pattern: String,
    #[serde(default = "default_boost")]
    pub boost: f32,
    /// When `true` (the default, used for keyword fields) the pattern and each
    /// indexed term are case-folded before matching, and the whole term OR any
    /// non-alphanumeric sub-token may match — byte-identical to the engine's
    /// stored-scan wildcard predicate.  When `false` (analyzed **text** fields)
    /// the raw pattern is matched CASE-SENSITIVELY against the whole indexed
    /// term.  ES indexes text terms lowercased but does NOT analyze the wildcard
    /// pattern, so an uppercase pattern matches nothing — exactly what
    /// case-sensitive matching against the already-lowercased term dictionary
    /// reproduces.
    #[serde(default = "default_case_insensitive")]
    pub case_insensitive: bool,
    /// When `true`, every matching doc scores a flat `boost` (ES rewrites
    /// `wildcard` to a `constant_score` query).  When `false` (default, keyword
    /// path), the per-matching-term BM25 scores are summed.
    #[serde(default)]
    pub constant_score: bool,
}

fn default_case_insensitive() -> bool {
    true
}

impl WildcardQuery {
    pub fn new(field: impl Into<String>, pattern: impl Into<String>) -> Self {
        Self {
            field: field.into(),
            pattern: pattern.into(),
            boost: 1.0,
            case_insensitive: true,
            constant_score: false,
        }
    }
}

/// A fuzzy query — expands the field's FST term dictionary to every term within
/// `max_edits` Damerau-Levenshtein distance of `value`, then scores each as a
/// term.  Distance is computed **case-insensitively** over the whole indexed
/// term AND its sub-tokens, byte-identical to the engine's `doc_matches_query`
/// fuzzy predicate.  `max_edits` is precomputed by the caller from the ES
/// `fuzziness` (AUTO resolves off the query term length), so the searcher needs
/// no `Fuzziness` type.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FuzzyQuery {
    pub field: String,
    pub value: String,
    pub max_edits: usize,
    #[serde(default = "default_boost")]
    pub boost: f32,
    /// See [`WildcardQuery::case_insensitive`].  `true` (default) folds both
    /// sides and also compares sub-tokens (keyword fields).  `false` compares
    /// the raw query value against the whole indexed term case-sensitively —
    /// ES fuzzy on a **text** field measures edit distance against the
    /// lowercased term dictionary without lowercasing the query term.
    #[serde(default = "default_case_insensitive")]
    pub case_insensitive: bool,
    /// #848: ES `prefix_length` — the leading characters that must match
    /// exactly (not subject to edits) before Levenshtein applies. Default `0`
    /// (no constraint).
    #[serde(default)]
    pub prefix_length: usize,
}

impl FuzzyQuery {
    pub fn new(field: impl Into<String>, value: impl Into<String>, max_edits: usize) -> Self {
        Self {
            field: field.into(),
            value: value.into(),
            max_edits,
            boost: 1.0,
            case_insensitive: true,
            prefix_length: 0,
        }
    }
}

/// A phrase-prefix query — mirrors Elasticsearch's `match_phrase_prefix`.
///
/// The leading `terms[..n-1]` must appear as an ordered adjacent phrase; the
/// LAST element is treated as a **prefix** that expands against the field's
/// analyzed term dictionary (bounded by `max_expansions`, in FST/lexicographic
/// order — the same order ES takes its first `max_expansions` terms).  A doc
/// matches when any expansion term follows a head-phrase occurrence within
/// `slop` intervening positions (`slop == 0`, the default, means immediately).
/// `terms` are already analyzed by the caller (standard analyzer → lowercased),
/// so the prefix expansion is a plain case-sensitive `starts_with` against the
/// (lowercased) term dictionary — byte-identical to ES, whose analyzer
/// lowercases the query but does not re-case the indexed terms.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PhrasePrefixQuery {
    pub field: String,
    pub terms: Vec<String>,
    #[serde(default = "default_max_expansions")]
    pub max_expansions: usize,
    /// Allowed number of intervening positions across the WHOLE phrase,
    /// including the expanded trailing prefix term.  ES honours `slop` on
    /// `match_phrase_prefix`: `TextFieldMapper.createPhrasePrefixQuery` builds
    /// a `MultiPhrasePrefixQuery` and calls `setSlop(slop)` alongside
    /// `setMaxExpansions` (elasticsearch/server/src/main/java/org/
    /// elasticsearch/index/mapper/TextFieldMapper.java:2019, the two setters
    /// at :2028-:2029, reached from `phrasePrefixQuery` at :1269 — AGPL, read
    /// for semantics only, no code copied).  Defaults to 0 (adjacency), which is
    /// the pre-existing behaviour for every caller that does not set it.
    #[serde(default)]
    pub slop: u32,
    #[serde(default = "default_boost")]
    pub boost: f32,
}

/// Boolean combinator query — mirrors Elasticsearch's `bool` query.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoolQuery {
    /// All must clauses must match.
    #[serde(default)]
    pub must: Vec<Query>,
    /// At least `min_should_match` should clauses must match.
    #[serde(default)]
    pub should: Vec<Query>,
    /// No must_not clause must match.
    #[serde(default)]
    pub must_not: Vec<Query>,
    /// All filter clauses must match, but they contribute NOTHING to
    /// `_score` — the same split Lucene draws in `BooleanClause.isScoring()`
    /// (`occur == MUST || occur == SHOULD`, BooleanClause.java:84-87) and
    /// enforces structurally in `BooleanWeight`'s ctor by building a FILTER
    /// clause's `Weight` with `ScoreMode.COMPLETE_NO_SCORES`
    /// (BooleanWeight.java:49-64). Projecting a `filter` child as `must`
    /// instead (what this crate's caller used to do) makes the clause
    /// scoring, which is #361.
    #[serde(default)]
    pub filter: Vec<Query>,
    /// Minimum number of `should` clauses that must match (default = 1 when
    /// there are no `must` clauses, 0 otherwise — same as ES).
    pub min_should_match: Option<u32>,
    #[serde(default = "default_boost")]
    pub boost: f32,
}

impl Default for BoolQuery {
    /// NOTE: `boost` must default to **1.0**, not `f32::default()` (0.0).
    /// A derived `Default` zeroed the boost, and because `execute_bool`
    /// multiplies the combined clause score by `boost`, every query built
    /// through `BoolQuery::new()` (multi_match, multi-token match, bool)
    /// returned `_score: 0.0` for all hits on the segment FTS path.
    fn default() -> Self {
        Self {
            must: Vec::new(),
            should: Vec::new(),
            must_not: Vec::new(),
            filter: Vec::new(),
            min_should_match: None,
            boost: 1.0,
        }
    }
}

/// Disjunction-max query — mirrors Elasticsearch's `dis_max`.
///
/// A document's score is the MAXIMUM of its sub-query scores, plus
/// `tie_breaker` × the sum of the remaining matching sub-query scores.
/// `multi_match` with `type: best_fields` (the ES default) lowers to this.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DisMaxQuery {
    pub queries: Vec<Query>,
    /// Fraction of the non-best sub-scores added on top of the max (ES
    /// default = 0.0, i.e. pure max).
    #[serde(default)]
    pub tie_breaker: f32,
    #[serde(default = "default_boost")]
    pub boost: f32,
}

impl DisMaxQuery {
    pub fn new(queries: Vec<Query>) -> Self {
        Self {
            queries,
            tie_breaker: 0.0,
            boost: 1.0,
        }
    }

    pub fn tie_breaker(mut self, t: f32) -> Self {
        self.tie_breaker = t;
        self
    }

    pub fn boost(mut self, b: f32) -> Self {
        self.boost = b;
        self
    }
}

/// A leaf whose match set and per-document scores are supplied by the
/// CALLER, already resolved to this segment's stored positions
/// (#892).
///
/// Every other leaf in this enum resolves its documents through the term
/// dictionary. Some match sets cannot be expressed that way — the engine's
/// `_id` primary keys are not indexed as FTS terms — yet they still have to
/// take part in an inverted-index query instead of forcing the whole request
/// onto a stored-document scan. The engine's kNN-beside-`query` hybrid is
/// exactly that shape: the vector leg has already run, so its top-k documents
/// and their scores are known facts, and this node carries them into the same
/// `BoolQuery` combination as the lexical half.
///
/// Contract for the caller:
///   * `docs` holds `(doc_id, score)` pairs for ONE segment — the doc ids are
///     that segment's stored positions, exactly what the postings lists use.
///   * ids that do not live in this segment are simply absent; the segment's
///     own projection is responsible for resolving them.
///   * duplicates are the caller's business (scores are emitted verbatim).
///
/// Liveness is NOT applied here — like every other leaf, this one reports
/// physical positions and the engine filters tombstones/superseded copies
/// during materialisation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocScoresQuery {
    /// `(doc_id, score)`, ascending by `doc_id` so the emitted hits keep the
    /// ascending-doc_id order every other leaf produces.
    pub docs: Vec<(u32, f32)>,
}

impl DocScoresQuery {
    pub fn new(mut docs: Vec<(u32, f32)>) -> Self {
        docs.sort_unstable_by_key(|&(doc_id, _)| doc_id);
        Self { docs }
    }
}

/// ES `constant_score`: the docs `query` matches, each scored exactly
/// `score` (the wrapper's `boost`). The inner query's own score is dropped.
///
/// #2654: without this leaf the engine projected a nested `constant_score`
/// to its inner query. Inside a `bool` on flushed segments, that clause then
/// added the inner query's BM25 instead of the boost.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConstantScoreQuery {
    pub query: Query,
    pub score: f32,
}

/// Top-level query enum.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Query {
    Term(TermQuery),
    Phrase(PhraseQuery),
    PhrasePrefix(PhrasePrefixQuery),
    Prefix(PrefixQuery),
    Wildcard(WildcardQuery),
    Fuzzy(FuzzyQuery),
    Bool(Box<BoolQuery>),
    DisMax(Box<DisMaxQuery>),
    MatchAll,
    /// Caller-supplied `(doc_id, score)` set — see [`DocScoresQuery`].
    DocScores(DocScoresQuery),
    /// See [`ConstantScoreQuery`].
    ConstantScore(Box<ConstantScoreQuery>),
}

// ── FtsSearcher ───────────────────────────────────────────────────────────────

/// Executes queries against a single segment's FTS index.
pub struct FtsSearcher {
    reader: Arc<FtsIndexReader>,
    /// Kept for future use: query-time analysis (e.g., synonym expansion, normalization).
    #[allow(dead_code)]
    registry: Arc<AnalyzerRegistry>,
    /// Cooperative wall-clock deadline (RC4 blocker 12). Multi-term
    /// expansion (prefix/wildcard/fuzzy) walks the WHOLE term dictionary
    /// — O(unique terms) predicate probes, multi-second on wide
    /// vocabularies — and the engine runs searches to completion inside
    /// `block_in_place`, so the outer `tokio::time::timeout` can never
    /// interrupt it. When set, the expansion loops poll this every 1 024
    /// terms and stop early, latching [`Self::deadline_tripped`] so the
    /// caller returns partial results with `timed_out: true` (ES shard
    /// timeout semantics).
    deadline: Option<std::time::Instant>,
    /// Set when any cooperative deadline check fired — results from this
    /// searcher are partial. Atomic (not `Cell`) so the searcher stays
    /// `Sync`.
    deadline_tripped: std::sync::atomic::AtomicBool,
    /// Index-wide BM25 statistics (#188). When set, every scorer this
    /// searcher builds uses the union `avgdl`/`N` over ALL segments plus the
    /// memtable, and every scoring `doc_freq` is the union df — so a
    /// document's score no longer depends on which segment it landed in.
    /// `None` keeps the historical per-segment statistics, which the engine
    /// uses when the index has at most one live scoring arm (where the union
    /// is the identity).
    collection: Option<Arc<CollectionStats>>,
}

impl FtsSearcher {
    pub fn new(reader: Arc<FtsIndexReader>, registry: Arc<AnalyzerRegistry>) -> Self {
        Self {
            reader,
            registry,
            deadline: None,
            deadline_tripped: std::sync::atomic::AtomicBool::new(false),
            collection: None,
        }
    }

    /// Builder: arm the cooperative deadline. `None` disables (default).
    pub fn with_deadline(mut self, deadline: Option<std::time::Instant>) -> Self {
        self.deadline = deadline;
        self
    }

    /// Builder: score against index-wide collection statistics instead of
    /// this segment's own (#188). `None` (default) keeps per-segment stats.
    pub fn with_collection_stats(mut self, stats: Option<Arc<CollectionStats>>) -> Self {
        self.collection = stats;
        self
    }

    /// True when any expansion loop stopped early because the deadline
    /// passed — the hits/totals produced by this searcher are partial.
    pub fn deadline_tripped(&self) -> bool {
        self.deadline_tripped
            .load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Poll the deadline (called every N iterations, not every item):
    /// true once the deadline has passed, latching `deadline_tripped`.
    #[inline]
    fn deadline_hit(&self) -> bool {
        match self.deadline {
            Some(d) if std::time::Instant::now() >= d => {
                self.deadline_tripped
                    .store(true, std::sync::atomic::Ordering::Relaxed);
                true
            }
            _ => false,
        }
    }

    /// Execute a query and return up to `limit` scored hits, sorted by descending score.
    pub fn search(&self, query: &Query, limit: usize, explain: bool) -> Result<Vec<ScoredHit>> {
        Ok(self.search_bounded(query, limit, explain)?.0)
    }

    /// Execute a query returning `(top-`cap` hits best-first, EXACT match total)`.
    ///
    /// The `total` is the full segment match count regardless of `cap`, so the
    /// caller's `hits.total` stays exact even when only the best `cap` sources
    /// are materialised.
    ///
    /// - `cap == usize::MAX` keeps the **legacy** full-set path (`execute()` +
    ///   `sort_unstable()`).  Callers that need the complete match set — an
    ///   active field sort (which narrows *all* matching doc_ids to sort
    ///   candidates), delete/dup-aware materialisation, or a count that must
    ///   not be page-capped — pass this and get behaviour byte-identical to the
    ///   historical `search(usize::MAX)`.
    /// - Any smaller `cap` streams into a bounded [`TopN`]: O(N log cap) work,
    ///   O(cap) memory, no O(N log N) sort.  Leaf `Term` queries stream each
    ///   scored posting straight into the heap (no intermediate `Vec`); the
    ///   compound arms (`Bool`/`DisMax`/`Prefix`/`Phrase`) build their
    ///   de-duplicated hit set once via `execute()` and drain it — still
    ///   O(matches) but with the sort removed.
    pub fn search_bounded(
        &self,
        query: &Query,
        cap: usize,
        explain: bool,
    ) -> Result<(Vec<ScoredHit>, u64)> {
        // WAND fast path for the shape a `match`/`multi_match` query becomes
        // after planning (`bool{should: [Term..]}`, nothing else).  Only when
        // nothing downstream needs the generic walk: `explain` needs every
        // retained hit's breakdown, and `cap == usize::MAX` callers want the
        // complete match set.
        if !explain && cap != usize::MAX {
            if let Some(res) = self.wand_should_bool(query, cap)? {
                return Ok(res);
            }
        }
        // The no-op observer monomorphises away, so this stays byte-identical to
        // the pre-#179 bounded search on the hot (no-delete) path.
        self.search_bounded_observed(query, cap, explain, |_| {})
    }

    /// Doc-at-a-time top-`cap` evaluation for the exact shape a `match` /
    /// `multi_match` query becomes after planning: a `bool` with ONLY
    /// `should` clauses, every clause a plain [`TermQuery`], effective
    /// `min_should_match == 1`.  Returns `None` for any other shape so the
    /// caller falls back to the generic path unchanged.
    ///
    /// Why this exists: the generic path materialises a `Vec<ScoredHit>` per
    /// clause, folds them through a `HashMap<u32, u32>` match counter plus a
    /// `HashMap<u32, f32>` score map, collects the union, and sorts it — fine
    /// for rare terms, quadratic-feeling for stopwords.  A three-stopword
    /// `match` over a 120k-doc index (~180k postings, ~100k distinct docs)
    /// spent ~28 ms there, almost all of it per-posting work that could not
    /// change the answer: BM25 evaluation + a `field_length` lookup for docs
    /// that never had a chance of entering a size-10 page.
    ///
    /// Design: WAND-style upper-bound pruning (Broder et al., *Faster Top-k
    /// Document Retrieval Using Block-Max Indexes*; the same dynamic-pruning
    /// idea as tantivy's `block_wand`, MIT — quickwit-oss/tantivy
    /// `src/query/boolean_query/block_wand_union.rs`, whose block-max half
    /// needs impact-ordered postings and skip tables this postings format
    /// does not carry).  The walk still visits EVERY matching doc — postings
    /// have no skip lists, and the caller needs an EXACT total — but a doc
    /// is scored only when the sum of its matched terms' score upper bounds
    /// (`idf × (k1+1) × boost`, the supremum of `score_term` over any tf/dl)
    /// can still enter the heap.  For stopword-only docs that bound sum sits
    //    below the 10th-best score almost immediately, so the entire scoring
    ///   cost for them disappears; what remains per skipped doc is one
    ///   cursor compare and one `next()`.
    ///
    /// Output identity with the generic path, by construction:
    /// - **Scores are bit-identical**: the matched terms are summed in
    ///   CLAUSE order — the same order `execute_bool`'s `score_map`
    ///   accumulates in — then multiplied by `bq.boost`, so every f32
    ///   addition happens in the same sequence.
    /// - **Ordering is identical**: hits pass through the same [`TopN`] /
    ///   [`ScoredHit`] `Ord`.  A doc is skipped only when its upper bound is
    ///   STRICTLY below the worst retained score, so a tie-score doc with a
    ///   smaller `doc_id` (which `Ord` ranks better and `TopN` would admit)
    ///   is never pruned.
    /// - **The total is identical**: every matching doc is visited and
    ///   counted, `[TopN::total]` or not.
    ///
    /// Deadline: the walk polls every 4 096 docs; stopping early yields a
    /// subset of the true hits and an undercount — the same partial-implies-
    /// narrower contract `execute_bool`'s `run_clauses` already upholds for
    /// abandoned `should` clauses, surfaced as `timed_out: true` by
    /// [`Self::deadline_tripped`].
    fn wand_should_bool(&self, query: &Query, cap: usize) -> Result<Option<(Vec<ScoredHit>, u64)>> {
        let Query::Bool(bq) = query else {
            return Ok(None);
        };
        if bq.must.is_empty()
            && bq.filter.is_empty()
            && bq.must_not.is_empty()
            && !bq.should.is_empty()
            && bq.min_should_match.unwrap_or(1) == 1
        {
            // All clauses must be plain terms (the common `match` shape);
            // anything richer — phrases, nested bools, wildcards — keeps the
            // generic path.
            for q in &bq.should {
                if !matches!(q, Query::Term(_)) {
                    return Ok(None);
                }
            }
        } else {
            return Ok(None);
        }

        // One cursor per clause, mirroring `scan_term`'s term-lookup and
        // reader construction (positions decoded per the field's real
        // layout and simply never read — the format is positions-dependent,
        // so a docs-only reader would misparse the stream).
        struct WandTerm<'a, 'b> {
            /// Clause index — the f32 summation order (see above) and the
            /// cursor-order tiebreak.
            ord: usize,
            tq: &'b TermQuery,
            bm25: crate::bm25::Bm25Scorer,
            /// The `doc_freq` the generic path would score with
            /// (`scoring_df`, i.e. index-wide when collection stats are on).
            score_df: u64,
            reader: PostingsReader<'a>,
            doc: u32,
            tf: u32,
            /// Supremum of this term's contribution over any (tf, dl):
            /// `idf × (k1+1) × boost`.  `tf_norm < k1+1` always, so this
            /// never underestimates `score_term`.
            ubound: f32,
        }
        let mut scorers: Vec<WandTerm> = Vec::with_capacity(bq.should.len());
        for (ord, q) in bq.should.iter().enumerate() {
            // Cooperative deadline on the clause fan-out axis, mirroring
            // `run_clauses` (poll every 64 clauses): a projected disjunction
            // can carry tens of thousands of clauses, and dropping a should
            // clause only narrows the answer — the partial-implies-narrower
            // contract `execute_bool` already upholds.
            if ord & 63 == 0 && self.deadline_hit() {
                break;
            }
            let Query::Term(tq) = q else {
                unreachable!("checked above")
            };
            let Some(tp) = self.reader.lookup_term(&tq.field, &tq.term) else {
                // Term absent from this segment: the clause matches nothing
                // and contributes no score — exactly the generic path's
                // empty per-clause `Vec`.
                continue;
            };
            // The factory reads the field's real positions layout and the
            // envelope's block codec — a docs-only reader must synthesise
            // tf=1 rather than misparse a positions-bearing stream, exactly
            // like `scan_term`; the decoded positions are simply never read.
            let Some(mut reader) = self.reader.postings_reader(&tq.field, &tp) else {
                continue;
            };
            let Some(first) = reader.next() else { continue };
            let bm25 = self.make_scorer(&tq.field);
            let score_df = self.scoring_df(&tq.field, &tq.term, tp.doc_frequency as u64);
            let ubound = bm25.idf(score_df) * (bm25.k1 + 1.0) * tq.boost;
            scorers.push(WandTerm {
                ord,
                tq,
                bm25,
                score_df,
                reader,
                doc: first.doc_id,
                tf: first.term_freq,
                ubound,
            });
        }
        // Cursor order: (doc, ord).  Deterministic, and keeps the scorers
        // sitting on the same doc contiguous.
        scorers.sort_by_key(|s| (s.doc, s.ord));
        if scorers.is_empty() {
            return Ok(Some((Vec::new(), 0)));
        }

        let mut top = TopN::new(cap);
        let mut total: u64 = 0;
        let mut since_poll: u32 = 0;
        loop {
            let d = scorers[0].doc;
            let k = scorers.iter().take_while(|s| s.doc == d).count();

            // Skip-or-score.  While the heap is below `cap` there is no bar
            // to clear (and `cap == 0` retains nothing, so never score).
            // Once full, prune only STRICTLY below the worst retained score:
            // at equality the candidate could tie the worst score and win
            // the `doc_id` tiebreak, which `TopN` would admit — so equality
            // must still be scored.
            let score_it = match top.worst() {
                None => cap > 0,
                Some(worst) => {
                    let bound: f32 = scorers[..k].iter().map(|s| s.ubound).sum();
                    bound >= worst.score
                }
            };
            if score_it {
                // Sum the matched terms in CLAUSE order (bit-identical to
                // `execute_bool`'s `score_map` accumulation), then apply the
                // bool boost exactly where the generic path applies it.
                // `scorers[..k]` is reordered by `ord` IN PLACE — ords are
                // unique, so the unstable sort is deterministic, and no
                // per-doc buffer is allocated (a heap alloc per scored doc
                // was measurable at 120k-doc disjunctions).
                scorers[..k].sort_unstable_by_key(|s| s.ord);
                let first_field = scorers[0].tq.field.as_str();
                let first_len = self.reader.field_length(first_field, d).unwrap_or(1) as u32;
                let mut sum = 0.0f32;
                for s in &scorers[..k] {
                    // Clauses usually share one field (`match`) — look the
                    // length up once; only multi-field queries pay per field.
                    let doc_len = if s.tq.field == first_field {
                        first_len
                    } else {
                        self.reader.field_length(&s.tq.field, d).unwrap_or(1) as u32
                    };
                    sum += s.bm25.score_term(s.score_df, s.tf, doc_len) * s.tq.boost;
                }
                top.push(ScoredHit {
                    doc_id: d,
                    score: sum * bq.boost,
                    explanation: None,
                });
            }

            total += 1;

            // Advance every scorer sitting on `d` — exactly `scorers[..k]`
            // (the sort invariant makes the at-d cursors a prefix).
            // Exhausted cursors are marked `u32::MAX`, which sorts last, and
            // pop off after the re-sort.  `sort_unstable` never allocates the
            // scratch buffer a stable sort spills to on >20-element slices —
            // this re-sort runs once per DOC, so that alloc was per-doc too.
            for s in scorers.iter_mut().take(k) {
                match s.reader.next() {
                    Some(next) => {
                        s.doc = next.doc_id;
                        s.tf = next.term_freq;
                    }
                    None => s.doc = u32::MAX,
                }
            }
            scorers.sort_unstable_by_key(|s| (s.doc, s.ord));
            while scorers.last().is_some_and(|s| s.doc == u32::MAX) {
                scorers.pop();
            }
            if scorers.is_empty() {
                break;
            }

            // Cooperative deadline, polled like the expansion loops: partial
            // = subset of hits + undercount, latched for `timed_out: true`.
            since_poll += 1;
            if since_poll & 4095 == 0 && self.deadline_hit() {
                break;
            }
        }
        let (hits, _) = top.finish();
        Ok(Some((hits, total)))
    }

    /// Like [`Self::search_bounded`], but invokes `observe(doc_id)` once for
    /// EVERY match in the full match set — before the `cap` is applied — so a
    /// caller can derive an exact per-match statistic without materialising the
    /// whole hit list.  The returned total is the exact physical match count
    /// regardless of `cap` ([`TopN`] counts every push).
    ///
    /// #179: the delete-present read path uses this to tally LIVE matches (via
    /// the segment ghost bitmap) during a BOUNDED scan, instead of forcing
    /// `cap == usize::MAX` purely to hold the complete hit list for the count.
    /// The scan already visits every posting on the bounded path, so the
    /// observer is free; the win is shedding the full-set sort and the
    /// O(matches) `Vec` that the unbounded path built on any index that had ever
    /// seen a delete.
    pub fn search_bounded_observed<F: FnMut(u32)>(
        &self,
        query: &Query,
        cap: usize,
        explain: bool,
        mut observe: F,
    ) -> Result<(Vec<ScoredHit>, u64)> {
        if cap == usize::MAX {
            let mut hits = self.execute(query, explain)?;
            let total = hits.len() as u64;
            for h in &hits {
                observe(h.doc_id);
            }
            hits.sort_unstable();
            return Ok((hits, total));
        }

        let mut top = TopN::new(cap);
        match query {
            // Streaming leaf: push each scored posting directly into the heap.
            Query::Term(tq) => self.scan_term(tq, explain, |h| {
                observe(h.doc_id);
                top.push(h);
            })?,
            // Compound / positional arms: reuse the exact hit-set builder, then
            // drain into the bounded heap (the sort is what we shed here).
            _ => {
                for hit in self.execute(query, explain)? {
                    observe(hit.doc_id);
                    top.push(hit);
                }
            }
        }
        Ok(top.finish())
    }

    fn execute(&self, query: &Query, explain: bool) -> Result<Vec<ScoredHit>> {
        match query {
            Query::Term(tq) => self.execute_term(tq, explain),
            Query::Phrase(pq) => self.execute_phrase(pq, explain),
            Query::PhrasePrefix(pq) => self.execute_phrase_prefix(pq, explain),
            Query::Prefix(pq) => self.execute_prefix(pq, explain),
            Query::Wildcard(wq) => self.execute_wildcard(wq, explain),
            Query::Fuzzy(fq) => self.execute_fuzzy(fq, explain),
            Query::Bool(bq) => self.execute_bool(bq, explain),
            Query::DisMax(dq) => self.execute_dis_max(dq, explain),
            Query::MatchAll => self.execute_match_all(),
            // #892: the pairs are already this segment's answer — no term
            // dictionary, no postings decode, no scorer. `explain` produces
            // no breakdown because there is no term-level derivation to
            // show; the engine never asks this leaf to explain (its FTS
            // calls all pass `explain: false`).
            Query::DocScores(ds) => Ok(ds
                .docs
                .iter()
                .map(|&(doc_id, score)| ScoredHit {
                    doc_id,
                    score,
                    explanation: None,
                })
                .collect()),
            // #2654: match with the inner query, score every match `score`.
            Query::ConstantScore(cq) => {
                let mut hits = self.execute(&cq.query, false)?;
                for hit in &mut hits {
                    hit.score = cq.score;
                    hit.explanation = explain.then(|| QueryExplanation {
                        total_score: cq.score,
                        term_breakdowns: Vec::new(),
                    });
                }
                Ok(hits)
            }
        }
    }

    // ── Term query ────────────────────────────────────────────────────────────

    fn execute_term(&self, tq: &TermQuery, explain: bool) -> Result<Vec<ScoredHit>> {
        let mut hits = Vec::new();
        self.scan_term(tq, explain, |h| hits.push(h))?;
        Ok(hits)
    }

    /// Shared scoring scan used by both [`Self::execute_term`] (Vec) and the
    /// bounded [`Self::search_bounded_observed`] path (which offers each scored
    /// posting straight to the `TopN` heap, so a keyword term matching tens of
    /// thousands of docs never materialises the full hit `Vec` for a size:10
    /// request).  Emits one `ScoredHit` per matching posting in ascending
    /// doc_id order.
    fn scan_term<F: FnMut(ScoredHit)>(
        &self,
        tq: &TermQuery,
        explain: bool,
        mut emit: F,
    ) -> Result<()> {
        let tp = match self.reader.lookup_term(&tq.field, &tq.term) {
            Some(tp) => tp,
            None => return Ok(()),
        };

        let scorer = self.make_scorer(&tq.field);
        // IDF df: index-wide when the engine supplied collection stats (#188).
        // `tp.doc_frequency` below stays LOCAL — it is the postings-decode
        // length for this segment's list, a different quantity that happens to
        // share a name.
        let score_df = self.scoring_df(&tq.field, &tq.term, tp.doc_frequency as u64);
        let mut reader = match self.reader.postings_reader(&tq.field, &tp) {
            Some(r) => r,
            None => return Ok(()),
        };

        while let Some(posting) = reader.next() {
            let doc_len = self
                .reader
                .field_length(&tq.field, posting.doc_id)
                .unwrap_or(1) as u32;

            let (score, explanation) = if explain {
                let bd = scorer.score_term_explain(&tq.term, score_df, posting.term_freq, doc_len);
                let s = bd.score * tq.boost;
                let boosted_bd = ScoreBreakdown { score: s, ..bd };
                (s, Some(QueryExplanation::new(vec![boosted_bd])))
            } else {
                let s = scorer.score_term(score_df, posting.term_freq, doc_len) * tq.boost;
                (s, None)
            };

            emit(ScoredHit {
                doc_id: posting.doc_id,
                score,
                explanation,
            });
        }

        Ok(())
    }

    // ── Phrase query ──────────────────────────────────────────────────────────

    fn execute_phrase(&self, pq: &PhraseQuery, explain: bool) -> Result<Vec<ScoredHit>> {
        if pq.terms.is_empty() {
            return Ok(Vec::new());
        }

        if pq.terms.len() == 1 {
            return self.execute_term(
                &TermQuery::boosted(&pq.field, &pq.terms[0], pq.boost),
                explain,
            );
        }

        // Phrase matching needs positions.  A docs-only field (keyword,
        // numeric, ip) can never satisfy a multi-term phrase.
        if !self.reader.field_has_positions(&pq.field) {
            return Ok(Vec::new());
        }

        // Load postings for every term into a per-term
        // `doc_id → (term_freq, positions)` map.  This is O(Σ df) once and
        // turns the per-anchor-doc term lookup into O(1) — the previous
        // implementation `.find()`-scanned each other term's FULL posting list
        // for every anchor doc (O(anchor_df × other_df), quadratic on common
        // terms like a non-stop-worded "the").
        let mut term_maps: Vec<(TermPostingsMap, u32)> = Vec::with_capacity(pq.terms.len());
        for term in &pq.terms {
            let tp = match self.reader.lookup_term(&pq.field, term) {
                Some(tp) => tp,
                None => return Ok(Vec::new()), // missing term → no phrase matches
            };
            let mut reader = match self.reader.postings_reader(&pq.field, &tp) {
                Some(r) => r,
                None => return Ok(Vec::new()),
            };
            let mut map: TermPostingsMap =
                TermPostingsMap::with_capacity(tp.doc_frequency as usize);
            while let Some(p) = reader.next() {
                map.insert(p.doc_id, (p.term_freq, p.positions));
            }
            term_maps.push((map, tp.doc_frequency));
        }

        // Anchor on the rarest term (smallest doc_freq) so the outer loop is
        // as short as possible; every candidate doc must contain it.
        let min_idx = term_maps
            .iter()
            .enumerate()
            .min_by_key(|(_, (_, df))| *df)
            .map(|(i, _)| i)
            .unwrap_or(0);

        let scorer = self.make_scorer(&pq.field);
        // Per-term IDF df, index-wide when available (#188).  `term_maps[i].1`
        // remains the segment-local postings length used to size the decode.
        let score_dfs: Vec<u64> = pq
            .terms
            .iter()
            .enumerate()
            .map(|(i, term)| self.scoring_df(&pq.field, term, term_maps[i].1 as u64))
            .collect();
        let mut hits = Vec::new();

        'doc: for &doc_id in term_maps[min_idx].0.keys() {
            // Gather each term's positions for this doc, in TERM ORDER (raw —
            // no offset games; the matcher below handles adjacency + slop).
            let mut all_positions: Vec<&[u32]> = Vec::with_capacity(pq.terms.len());
            for (map, _) in &term_maps {
                match map.get(&doc_id) {
                    Some((_, positions)) => all_positions.push(positions.as_slice()),
                    None => continue 'doc, // term absent from this doc
                }
            }

            if !phrase_positions_match(&all_positions, pq.slop) {
                continue;
            }

            let doc_len = self.reader.field_length(&pq.field, doc_id).unwrap_or(1) as u32;
            let mut total_score = 0.0f32;
            let mut breakdowns = Vec::new();
            for (term_idx, term) in pq.terms.iter().enumerate() {
                let (map, _local_df) = &term_maps[term_idx];
                let df = score_dfs[term_idx];
                let tf = map.get(&doc_id).map(|(f, _)| *f).unwrap_or(1);
                if explain {
                    let bd = scorer.score_term_explain(term, df, tf, doc_len);
                    total_score += bd.score;
                    breakdowns.push(bd);
                } else {
                    total_score += scorer.score_term(df, tf, doc_len);
                }
            }
            total_score *= pq.boost;

            hits.push(ScoredHit {
                doc_id,
                score: total_score,
                explanation: if explain {
                    Some(QueryExplanation::new(breakdowns))
                } else {
                    None
                },
            });
        }

        Ok(hits)
    }

    // ── Phrase-prefix query ─────────────────────────────────────────────────────

    /// ES `match_phrase_prefix`: the head `terms[..n-1]` form an ordered phrase
    /// and the last term is a prefix expanded against the analyzed term
    /// dictionary.  A doc matches when any expansion term immediately follows a
    /// head-phrase occurrence.  Implemented as a union of concrete phrase
    /// queries (one per expansion) — bounded by `max_expansions`, which caps the
    /// number of prefix terms exactly as ES does.
    fn execute_phrase_prefix(
        &self,
        ppq: &PhrasePrefixQuery,
        explain: bool,
    ) -> Result<Vec<ScoredHit>> {
        if ppq.terms.is_empty() {
            return Ok(Vec::new());
        }
        let last = ppq.terms.last().expect("non-empty");
        // Expand the trailing prefix against the field's term dictionary in FST
        // (lexicographic) order — matches ES's first-`max_expansions` selection.
        let expansions = self.expand_prefix(&ppq.field, last, ppq.max_expansions);
        if expansions.is_empty() {
            return Ok(Vec::new());
        }

        // Single-token phrase_prefix == prefix query (scored, not constant —
        // ES match_phrase_prefix is a real scoring query).
        if ppq.terms.len() == 1 {
            return self.score_expanded_terms(&ppq.field, &expansions, ppq.boost, explain, false);
        }

        let head = &ppq.terms[..ppq.terms.len() - 1];
        // Per-doc best score across expansions (ES takes the max-scoring
        // expansion for a doc; the exact hit SET — what `hits.total` counts — is
        // the union, which the accumulator captures).
        let mut score_map: std::collections::HashMap<u32, (f32, Option<QueryExplanation>)> =
            std::collections::HashMap::new();
        for exp in &expansions {
            // Cooperative deadline (RC4 blocker 12): each expansion runs a
            // full positional phrase query — poll per expansion.
            if self.deadline_hit() {
                break;
            }
            let mut terms: Vec<String> = head.to_vec();
            terms.push(exp.clone());
            let pq = PhraseQuery {
                field: ppq.field.clone(),
                terms,
                // `slop` spans the whole phrase INCLUDING the expanded
                // trailing term — ES's `MultiPhrasePrefixQuery.setSlop`
                // applies to the multi-term position too, so the union of
                // per-expansion sloppy phrase queries is the same hit set.
                slop: ppq.slop,
                boost: ppq.boost,
            };
            for hit in self.execute_phrase(&pq, explain)? {
                let entry = score_map
                    .entry(hit.doc_id)
                    .or_insert((f32::NEG_INFINITY, None));
                if hit.score > entry.0 {
                    entry.0 = hit.score;
                    entry.1 = hit.explanation;
                }
            }
        }
        Ok(score_map
            .into_iter()
            .map(|(doc_id, (score, explanation))| ScoredHit {
                doc_id,
                score,
                explanation,
            })
            .collect())
    }

    // ── Prefix query ──────────────────────────────────────────────────────────

    fn execute_prefix(&self, pq: &PrefixQuery, explain: bool) -> Result<Vec<ScoredHit>> {
        // Expand prefix to term list using FST range scan
        let expanded_terms = self.expand_prefix(&pq.field, &pq.prefix, pq.max_expansions);
        self.score_expanded_terms(
            &pq.field,
            &expanded_terms,
            pq.boost,
            explain,
            pq.constant_score,
        )
    }

    fn expand_prefix(&self, field: &str, prefix: &str, max: usize) -> Vec<String> {
        // Streaming FST scan with a cooperative deadline poll every 1 024
        // terms (RC4 blocker 12) — a wide dictionary made the old
        // materialise-then-filter walk a multi-second uninterruptible unit.
        let mut out: Vec<String> = Vec::new();
        let mut seen = 0usize;
        self.reader.for_each_term(field, |t| {
            seen += 1;
            if seen & 1023 == 0 && self.deadline_hit() {
                return false;
            }
            if t.starts_with(prefix) {
                out.push(t.to_owned());
                if out.len() >= max {
                    return false;
                }
            }
            true
        });
        out
    }

    // ── Wildcard query ──────────────────────────────────────────────────────────

    fn execute_wildcard(&self, wq: &WildcardQuery, explain: bool) -> Result<Vec<ScoredHit>> {
        let terms = self.expand_wildcard(&wq.field, &wq.pattern, wq.case_insensitive);
        self.score_expanded_terms(&wq.field, &terms, wq.boost, explain, wq.constant_score)
    }

    /// Enumerate the field's FST term dictionary and keep every term matching
    /// the wildcard pattern.
    ///
    /// - `case_insensitive` (keyword fields): fold both sides and match the
    ///   whole term OR any non-alphanumeric-split sub-token — identical to the
    ///   engine's doc-scan wildcard predicate.
    /// - case-**sensitive** (analyzed text fields): match the RAW pattern
    ///   against the whole indexed term.  Text terms are already lowercased by
    ///   the standard analyzer and ES does not lowercase the pattern, so an
    ///   uppercase pattern correctly matches nothing.
    fn expand_wildcard(&self, field: &str, pattern: &str, case_insensitive: bool) -> Vec<String> {
        // Streaming FST scan + deadline poll every 1 024 terms (RC4
        // blocker 12): the per-term wildcard walk over a wide dictionary
        // was the reproduced 3.7 s uninterruptible unit.
        let mut out: Vec<String> = Vec::new();
        let mut seen = 0usize;
        if case_insensitive {
            let pat_lc = pattern.to_lowercase();
            self.reader.for_each_term(field, |t| {
                seen += 1;
                if seen & 1023 == 0 && self.deadline_hit() {
                    return false;
                }
                if term_matches_wildcard(t, &pat_lc) {
                    out.push(t.to_owned());
                }
                true
            });
        } else {
            self.reader.for_each_term(field, |t| {
                seen += 1;
                if seen & 1023 == 0 && self.deadline_hit() {
                    return false;
                }
                if wildcard_match(t, pattern) {
                    out.push(t.to_owned());
                }
                true
            });
        }
        out
    }

    // ── Fuzzy query ─────────────────────────────────────────────────────────────

    fn execute_fuzzy(&self, fq: &FuzzyQuery, explain: bool) -> Result<Vec<ScoredHit>> {
        let terms = self.expand_fuzzy(
            &fq.field,
            &fq.value,
            fq.max_edits,
            fq.case_insensitive,
            fq.prefix_length,
        );
        // Fuzzy keeps per-term scoring (ES rewrites fuzzy to a blended-frequency
        // scoring query, NOT constant_score).
        self.score_expanded_terms(&fq.field, &terms, fq.boost, explain, false)
    }

    /// Enumerate the field's FST term dictionary and keep every term within
    /// `max_edits` Damerau-Levenshtein distance of `value`.
    ///
    /// - `case_insensitive` (keyword fields): fold both sides and also compare
    ///   sub-tokens — identical to the engine's doc-scan fuzzy predicate.
    /// - case-**sensitive** (analyzed text fields): measure distance from the
    ///   RAW query value to the whole indexed (lowercased) term, matching ES,
    ///   which does not lowercase the fuzzy query term.
    fn expand_fuzzy(
        &self,
        field: &str,
        value: &str,
        max_edits: usize,
        case_insensitive: bool,
        prefix_length: usize,
    ) -> Vec<String> {
        // Streaming FST scan + deadline poll every 1 024 terms (RC4
        // blocker 12): per-term edit distance is the most expensive
        // expansion predicate — the reproduced 8.3 s uninterruptible unit.
        let mut out: Vec<String> = Vec::new();
        let mut seen = 0usize;
        if case_insensitive {
            let q_lower = value.to_lowercase();
            self.reader.for_each_term(field, |t| {
                seen += 1;
                if seen & 1023 == 0 && self.deadline_hit() {
                    return false;
                }
                if term_matches_fuzzy(t, &q_lower, max_edits, prefix_length) {
                    out.push(t.to_owned());
                }
                true
            });
        } else {
            self.reader.for_each_term(field, |t| {
                seen += 1;
                if seen & 1023 == 0 && self.deadline_hit() {
                    return false;
                }
                if fuzzy_prefix_ok(t, value, prefix_length)
                    && levenshtein_distance(t, value) <= max_edits
                {
                    out.push(t.to_owned());
                }
                true
            });
        }
        out
    }

    /// Run one term query per expanded term and merge their per-doc scores — the
    /// shared scoring core behind prefix/wildcard/fuzzy multi-term expansion.
    /// (A doc's score is the sum of its matching-term BM25 scores; among
    /// constant-ish keyword matches this is effectively a flat score.)
    fn score_expanded_terms(
        &self,
        field: &str,
        terms: &[String],
        boost: f32,
        explain: bool,
        constant_score: bool,
    ) -> Result<Vec<ScoredHit>> {
        if terms.is_empty() {
            return Ok(Vec::new());
        }
        // Constant-score (ES prefix/wildcard rewrite): every doc that matches
        // ANY expansion term scores a flat `boost`, so we only need the matching
        // doc-id set.  Deduplicate across expansions and emit `boost` once.
        if constant_score {
            let mut docs: std::collections::HashSet<u32> = std::collections::HashSet::new();
            for term in terms {
                // Cooperative deadline (RC4 blocker 12): a pathological
                // pattern can expand to hundreds of thousands of terms,
                // each with its own postings walk — poll per term.
                if self.deadline_hit() {
                    break;
                }
                let tp = match self.reader.lookup_term(field, term) {
                    Some(tp) => tp,
                    None => continue,
                };
                let mut reader = match self.reader.postings_reader(field, &tp) {
                    Some(r) => r,
                    None => continue,
                };
                while let Some(p) = reader.next() {
                    docs.insert(p.doc_id);
                }
            }
            return Ok(docs
                .into_iter()
                .map(|doc_id| ScoredHit {
                    doc_id,
                    score: boost,
                    explanation: None,
                })
                .collect());
        }
        let mut score_map: std::collections::HashMap<u32, (f32, Option<QueryExplanation>)> =
            std::collections::HashMap::new();
        for term in terms {
            // Cooperative deadline (RC4 blocker 12) — see the
            // constant_score arm above.
            if self.deadline_hit() {
                break;
            }
            let tq = TermQuery::boosted(field, term, boost);
            let term_hits = self.execute_term(&tq, explain)?;
            for hit in term_hits {
                let entry = score_map.entry(hit.doc_id).or_insert((0.0, None));
                entry.0 += hit.score;
                if explain {
                    if let Some(exp) = hit.explanation {
                        if let Some(ref mut existing) = entry.1 {
                            existing.term_breakdowns.extend(exp.term_breakdowns);
                            existing.total_score = entry.0;
                        } else {
                            entry.1 = Some(exp);
                        }
                    }
                }
            }
        }
        Ok(score_map
            .into_iter()
            .map(|(doc_id, (score, explanation))| ScoredHit {
                doc_id,
                score,
                explanation,
            })
            .collect())
    }

    // ── Bool query ────────────────────────────────────────────────────────────

    fn execute_bool(&self, bq: &BoolQuery, explain: bool) -> Result<Vec<ScoredHit>> {
        // Determine effective min_should_match.  `filter` counts as a
        // required clause here exactly like `must` — ES defaults the minimum
        // to 1 only when the bool has should clauses and NO must/filter
        // clause — so a `bool{filter, should}` keeps optional shoulds.
        let min_should =
            bq.min_should_match
                .unwrap_or(if bq.must.is_empty() && bq.filter.is_empty() {
                    if bq.should.is_empty() {
                        0
                    } else {
                        1
                    }
                } else {
                    0
                });

        // Execute all sub-queries.
        //
        // Cooperative deadline (RC4 blocker 12, extended to clause fan-out):
        // clause COUNT is a second unbounded axis alongside the term-dictionary
        // walks the expansion loops already poll. A projected disjunction is
        // one clause per (token × field) — a field-less `query_string` over a
        // wide mapping reaches tens of thousands — and each clause here
        // materialises a full `Vec<ScoredHit>` before anything is combined. The
        // engine runs the search to completion inside `block_in_place`, so the
        // outer `tokio::time::timeout` cannot interrupt it: without this poll
        // one request holds a worker for as long as the clause list takes,
        // whatever the request's own timeout said. Stopping early yields
        // partial hits, which `deadline_tripped` reports so the response says
        // `timed_out: true` (ES shard-timeout semantics).
        //
        // Partial must ALWAYS mean narrower, never broader. Abandoning a
        // `should` clause only removes disjuncts, so the surviving hits are a
        // subset of the true answer — safe. Abandoning a `must` or `must_not`
        // clause would RELAX the query and admit documents it excludes, so
        // those bail the whole bool to an empty result instead.
        let mut clauses_run: usize = 0;
        let mut run_clauses =
            |slice: &[Query], partial_ok: bool| -> Result<Option<Vec<Vec<ScoredHit>>>> {
                let mut out = Vec::with_capacity(slice.len());
                for q in slice {
                    // Poll every 64 clauses: one clause is a postings decode,
                    // orders of magnitude coarser than the per-term probes the
                    // expansion loops poll every 1 024 of.
                    if clauses_run & 63 == 0 && self.deadline_hit() {
                        return Ok(if partial_ok { Some(out) } else { None });
                    }
                    clauses_run += 1;
                    out.push(self.execute(q, explain)?);
                }
                Ok(Some(out))
            };
        let Some(must_hits) = run_clauses(&bq.must, false)? else {
            return Ok(Vec::new());
        };
        // `filter` narrows exactly like `must` (partial_ok = false for the
        // same reason: dropping one would RELAX the query).
        let Some(filter_hits) = run_clauses(&bq.filter, false)? else {
            return Ok(Vec::new());
        };
        let Some(should_hits) = run_clauses(&bq.should, true)? else {
            return Ok(Vec::new());
        };
        let Some(must_not_hits) = run_clauses(&bq.must_not, false)? else {
            return Ok(Vec::new());
        };

        // Build must_not doc_id set
        let must_not_docs: std::collections::HashSet<u32> = must_not_hits
            .iter()
            .flat_map(|hits| hits.iter().map(|h| h.doc_id))
            .collect();

        // Intersect must clauses
        let mut candidate_docs: Option<std::collections::HashSet<u32>> = None;
        let mut score_map: std::collections::HashMap<u32, f32> = std::collections::HashMap::new();

        for must_result in &must_hits {
            let doc_set: std::collections::HashSet<u32> =
                must_result.iter().map(|h| h.doc_id).collect();
            candidate_docs = Some(match candidate_docs {
                None => doc_set,
                Some(prev) => prev.intersection(&doc_set).copied().collect(),
            });
            for hit in must_result {
                *score_map.entry(hit.doc_id).or_insert(0.0) += hit.score;
            }
        }

        // Intersect filter clauses — membership ONLY.  Lucene builds a FILTER
        // clause's Weight with `ScoreMode.COMPLETE_NO_SCORES`
        // (BooleanWeight.java:49-64, gated on `BooleanClause.isScoring()` at
        // BooleanClause.java:84-87), so a filter is structurally incapable of
        // contributing to the score; there is nothing to add and then
        // subtract.  Deliberately no `score_map` update below (#361).
        for filter_result in &filter_hits {
            let doc_set: std::collections::HashSet<u32> =
                filter_result.iter().map(|h| h.doc_id).collect();
            candidate_docs = Some(match candidate_docs {
                None => doc_set,
                Some(prev) => prev.intersection(&doc_set).copied().collect(),
            });
        }

        // Should clauses: track per-doc match count and scores
        let mut should_match_count: std::collections::HashMap<u32, u32> =
            std::collections::HashMap::new();
        for should_result in &should_hits {
            for hit in should_result {
                *should_match_count.entry(hit.doc_id).or_insert(0) += 1;
                *score_map.entry(hit.doc_id).or_insert(0.0) += hit.score;
            }
        }

        // If no REQUIRED clauses at all (must ∪ filter), the candidate set is
        // the union of should docs.
        if bq.must.is_empty() && bq.filter.is_empty() {
            candidate_docs = Some(should_match_count.keys().copied().collect());
        }

        let candidates = match candidate_docs {
            Some(c) => c,
            None => {
                if bq.must.is_empty() && bq.should.is_empty() && !bq.must_not.is_empty() {
                    // must_not only — need all docs; treat as empty (no positive scoring)
                    return Ok(Vec::new());
                }
                return Ok(Vec::new());
            }
        };

        let hits = candidates
            .into_iter()
            .filter(|doc_id| !must_not_docs.contains(doc_id))
            .filter(|doc_id| {
                // Check min_should_match
                let matched_should = should_match_count.get(doc_id).copied().unwrap_or(0);
                matched_should >= min_should
            })
            .map(|doc_id| {
                let score = score_map.get(&doc_id).copied().unwrap_or(0.0) * bq.boost;
                ScoredHit {
                    doc_id,
                    score,
                    explanation: None,
                }
            })
            .collect();

        Ok(hits)
    }

    // ── Dis-max query ─────────────────────────────────────────────────────────

    /// ES `dis_max` scoring: docs matching ANY sub-query are candidates;
    /// score = max(sub scores) + tie_breaker × Σ(other matching sub scores),
    /// all multiplied by the query boost.
    fn execute_dis_max(&self, dq: &DisMaxQuery, explain: bool) -> Result<Vec<ScoredHit>> {
        // Per-doc (max, sum) accumulator over sub-query scores.
        let mut acc: std::collections::HashMap<u32, (f32, f32)> = std::collections::HashMap::new();
        for sub in &dq.queries {
            for hit in self.execute(sub, explain)? {
                let e = acc.entry(hit.doc_id).or_insert((f32::NEG_INFINITY, 0.0));
                if hit.score > e.0 {
                    e.0 = hit.score;
                }
                e.1 += hit.score;
            }
        }
        Ok(acc
            .into_iter()
            .map(|(doc_id, (max, sum))| {
                let score = (max + dq.tie_breaker * (sum - max)) * dq.boost;
                ScoredHit {
                    doc_id,
                    score,
                    explanation: None,
                }
            })
            .collect())
    }

    // ── Match all ─────────────────────────────────────────────────────────────

    fn execute_match_all(&self) -> Result<Vec<ScoredHit>> {
        // Return all docs with uniform score 1.0
        // In practice, the caller should maintain a doc count; we signal "all" with empty set
        // and let the segment scan handle it. For now return empty — callers layer this above.
        Ok(Vec::new())
    }

    // ── Helpers ───────────────────────────────────────────────────────────────

    /// The scorer for `field`: index-wide statistics when the engine supplied
    /// them (#188), else this segment's own — the historical behaviour, kept
    /// as the fallback for direct `xerj-fts` users and for fields the union
    /// never saw.
    fn make_scorer(&self, field: &str) -> Bm25Scorer {
        if let Some(scorer) = self.collection.as_ref().and_then(|c| c.scorer(field)) {
            return scorer;
        }
        self.reader
            .field_stats(field)
            .map(|stats| stats.to_scorer())
            .unwrap_or_else(|| Bm25Scorer::new(1.0, 1))
    }

    /// The `doc_freq` to FEED THE SCORER for `(field, term)`.
    ///
    /// NOT interchangeable with the segment-local `TermPostings::doc_frequency`
    /// used to size a `PostingsReader` — that one is the number of postings to
    /// decode from THIS segment's list and must stay local.  Only the IDF
    /// argument becomes index-wide.
    #[inline]
    fn scoring_df(&self, field: &str, term: &str, local: u64) -> u64 {
        self.collection
            .as_ref()
            .and_then(|c| c.df(field, term))
            .unwrap_or(local)
    }
}

// ── Wildcard / fuzzy term-matching predicates ─────────────────────────────────
//
// These reproduce, byte-for-byte, the wildcard/fuzzy predicates the engine's
// `doc_matches_query` applies per stored document, so expanding a keyword
// field's FST term dictionary through them yields exactly the same hit set as
// the per-doc stored scan — just far cheaper (terms ≪ documents).  Keep them in
// lock-step with `xerj-engine/src/index.rs::{wildcard_match, levenshtein_distance}`.

/// `true` if `term` (case-folded) matches the already-lowercased `pat_lc`,
/// either as the whole value or as any non-alphanumeric-split sub-token.
fn term_matches_wildcard(term: &str, pat_lc: &str) -> bool {
    let lc = term.to_lowercase();
    if wildcard_match(&lc, pat_lc) {
        return true;
    }
    lc.split(|c: char| !c.is_alphanumeric())
        .any(|tok| !tok.is_empty() && wildcard_match(tok, pat_lc))
}

/// `true` if `term` (case-folded) is within `max_edits` Damerau-Levenshtein
/// distance of the already-lowercased `q_lower`, as the whole value or any
/// sub-token.
fn term_matches_fuzzy(term: &str, q_lower: &str, max_edits: usize, prefix_length: usize) -> bool {
    let s_lower = term.to_lowercase();
    if fuzzy_prefix_ok(&s_lower, q_lower, prefix_length)
        && levenshtein_distance(&s_lower, q_lower) <= max_edits
    {
        return true;
    }
    s_lower
        .split(|c: char| !c.is_alphanumeric())
        .filter(|t| !t.is_empty())
        .any(|tok| {
            fuzzy_prefix_ok(tok, q_lower, prefix_length)
                && levenshtein_distance(tok, q_lower) <= max_edits
        })
}

/// #848: ES `prefix_length` guard — the first `prefix_length` characters of the
/// query and a candidate term must be identical before Levenshtein applies.
/// `0` (ES default) imposes no constraint. Lock-step with the engine's copy in
/// `xerj-engine/src/index.rs`.
#[inline]
fn fuzzy_prefix_ok(candidate: &str, query: &str, prefix_length: usize) -> bool {
    prefix_length == 0
        || candidate
            .chars()
            .take(prefix_length)
            .eq(query.chars().take(prefix_length))
}

/// Glob match: `*` = zero-or-more chars, `?` = exactly one.  No case folding —
/// callers fold both sides first.  Verbatim copy of the engine's helper.
fn wildcard_match(text: &str, pattern: &str) -> bool {
    let text: Vec<char> = text.chars().collect();
    let pattern: Vec<char> = pattern.chars().collect();
    wildcard_match_inner(&text, &pattern)
}

fn wildcard_match_inner(text: &[char], pattern: &[char]) -> bool {
    match (text, pattern) {
        (_, []) => text.is_empty(),
        (_, ['*', rest @ ..]) => {
            wildcard_match_inner(text, rest)
                || (!text.is_empty() && wildcard_match_inner(&text[1..], pattern))
        }
        ([], _) => false,
        ([tc, trest @ ..], [pc, prest @ ..]) => {
            (*pc == '?' || tc == pc) && wildcard_match_inner(trest, prest)
        }
    }
}

/// Damerau-Levenshtein edit distance (adjacent transposition = 1 edit), matching
/// ES `fuzzy_transpositions: true`.  Verbatim copy of the engine's helper.
fn levenshtein_distance(a: &str, b: &str) -> usize {
    let a_chars: Vec<char> = a.chars().collect();
    let b_chars: Vec<char> = b.chars().collect();
    let m = a_chars.len();
    let n = b_chars.len();
    if m == 0 {
        return n;
    }
    if n == 0 {
        return m;
    }
    let mut dp = vec![vec![0usize; n + 1]; m + 1];
    #[allow(clippy::needless_range_loop)]
    for i in 0..=m {
        dp[i][0] = i;
    }
    #[allow(clippy::needless_range_loop)]
    for j in 0..=n {
        dp[0][j] = j;
    }
    for i in 1..=m {
        for j in 1..=n {
            let cost = if a_chars[i - 1] == b_chars[j - 1] {
                0
            } else {
                1
            };
            let mut best = (dp[i - 1][j] + 1)
                .min(dp[i][j - 1] + 1)
                .min(dp[i - 1][j - 1] + cost);
            if i >= 2
                && j >= 2
                && a_chars[i - 1] == b_chars[j - 2]
                && a_chars[i - 2] == b_chars[j - 1]
            {
                best = best.min(dp[i - 2][j - 2] + 1);
            }
            dp[i][j] = best;
        }
    }
    dp[m][n]
}

// ── Multi-segment parallel search ─────────────────────────────────────────────

/// Search across multiple segment searchers in parallel via rayon.
///
/// Results are merged and re-sorted. `limit` is applied after merge.
pub fn search_segments(
    searchers: &[FtsSearcher],
    query: &Query,
    limit: usize,
    explain: bool,
) -> Result<Vec<ScoredHit>> {
    let results: Vec<Result<Vec<ScoredHit>>> = searchers
        .par_iter()
        .map(|s| s.search(query, limit, explain))
        .collect();

    let mut merged: Vec<ScoredHit> = Vec::new();
    for result in results {
        merged.extend(result?);
    }

    merged.sort_unstable();
    merged.truncate(limit);
    Ok(merged)
}

// ── Phrase matching helper ────────────────────────────────────────────────────

/// Returns `true` if the per-term **raw** position lists (in TERM ORDER)
/// contain an occurrence of the phrase within `slop` — Lucene sloppy-phrase
/// semantics, transpositions included.
///
/// `all_positions[i]` is the ascending list of positions at which the i-th
/// phrase term occurs in one document.
///
/// - `slop == 0`: exact adjacency.  There must be a start `p` such that term i
///   occupies exactly `p + i` for every i (start-position intersection).
/// - `slop > 0`: Lucene `SloppyPhraseMatcher` semantics.  Slop is an edit
///   distance in single-position term MOVES: pick one document position per
///   phrase term, and the match distance is the span of the ADJUSTED
///   positions (document position minus the term's query offset), i.e.
///   `max(p_i - i) - min(p_i - i)`; the phrase matches when some choice keeps
///   that distance `<= slop`.  An in-order pick has strictly increasing
///   `p_i`, so `p_i - i` is non-decreasing and the span telescopes to
///   `(p_last - p_first) - (n-1)` — exactly the summed-gaps value the
///   pre-#830 walk measured — and its positions are automatically distinct.
///   Every phrase that walk matched therefore still matches here, which is
///   a property of the DECISION PROCEDURE being complete, not of the cost
///   function alone: an incomplete search over assignments can lose an
///   in-order match it never tries (it did, for repeated terms, before this
///   evaluator got its SDR window test).  Unlike that walk this also admits
///   REORDERED terms — an out-of-order pair costs at least 2, so `"a b"~2`
///   matches a document reading `b a` (Lucene's class javadoc example: for
///   query `"a b"~2`, document `x a b a y` matches once at distance 0 and
///   once, as `b a`, at distance 2).  Issue #830.
///
/// Adapted (algorithm, not code) from Lucene's `SloppyPhraseMatcher`
/// (lucene/core/src/java/org/apache/lucene/search/SloppyPhraseMatcher.java,
/// Apache-2.0): `nextMatch` (:205-:237) pops the minimum `PhrasePositions`
/// from a priority queue ordered by adjusted position (`pp.position` is set
/// to `position - offset` in PhrasePositions.java `nextPosition`, :53-:59)
/// and measures `matchLength = end - pp.position` — max minus min adjusted
/// position.  That plain "advance the minimum" walk is only complete once
/// REPEATS have been resolved: a repeated query term needs as many DISTINCT
/// document positions as it has slots, and Lucene therefore advances the
/// colliding repeat rather than the current minimum (`advanceRpts`, :317).
/// This implementation reaches the same completeness differently, because
/// it has no term identity to group by (see the distinctness note below):
/// it sweeps every candidate window floor `lo` — each adjusted position is
/// one — and asks whether the window `[lo, lo + slop]` admits a choice of
/// one position per slot with all positions DISTINCT, i.e. a system of
/// distinct representatives, decided by bipartite matching.  The sweep is
/// complete: if any assignment has span `<= slop`, then the window floored
/// at that assignment's own minimum adjusted position contains all of it.
///
/// Distinctness is enforced pairwise over ALL slots rather than only over
/// repeated terms.  Under the standard analyzer the two are the same thing
/// (one token per position, so only a repeated term can collide).  It is
/// stricter than Lucene on a field whose analyzer co-locates DIFFERENT
/// terms — XERJ's `SynonymFilter` emits synonyms at the same position —
/// where Lucene would let two distinct query terms share one position and
/// this does not.  That is a deliberate, conservative divergence: it can
/// only withhold a match, never invent one, and it is what the pre-#830
/// walk did too (it required strictly increasing positions).
///
/// Both arms share this evaluator: the segment positional clause calls it
/// with real postings positions, and the engine's stored-scan/memtable arm
/// (`phrase_walk` in xerj-engine's `index.rs`) materialises token-index
/// lists and calls it too, so slop is evaluated identically on both sides.
/// What they do NOT share is the position model — the memtable arm
/// re-analyses text with the standard analyzer while the segment arm reads
/// indexed positions — so a custom analyzer (synonyms,
/// `position_increment_gap`) can still hand the two arms different inputs.
pub fn phrase_positions_match(all_positions: &[&[u32]], slop: u32) -> bool {
    if all_positions.iter().any(|p| p.is_empty()) {
        return false;
    }
    if all_positions.len() == 1 {
        return true;
    }

    if slop == 0 {
        // Exact phrase: term i must sit at start + i.  Probe each candidate
        // start from the first term; membership via binary search (positions
        // are ascending).
        'start: for &start in all_positions[0] {
            for (i, positions) in all_positions.iter().enumerate().skip(1) {
                let want = match start.checked_add(i as u32) {
                    Some(w) => w,
                    None => continue 'start,
                };
                if positions.binary_search(&want).is_err() {
                    continue 'start;
                }
            }
            return true;
        }
        return false;
    }

    sloppy_phrase_match(all_positions, slop)
}

/// Is there a choice of one document position per phrase slot, all DISTINCT,
/// whose adjusted positions (`p_i - i`) span at most `slop`?
///
/// Sweeps candidate window floors in ascending order.  Every adjusted
/// position is a candidate floor, and the optimal window is floored at the
/// minimum adjusted position of its own assignment, so the sweep misses
/// nothing.  For a floor `lo` each slot's admissible positions are the
/// contiguous run `L_i ∩ [lo + i, lo + slop + i]`, tracked with pointers
/// that only ever move forward as `lo` grows, so the pointer work over the
/// whole sweep is linear in the total number of positions.
///
/// Feasibility inside one window is a system-of-distinct-representatives
/// test.  It only needs the first `n` admissible positions of each slot: a
/// slot with `n` or more candidates can always be re-pointed at a free one
/// (the other `n - 1` slots occupy at most `n - 1` positions), so truncating
/// there cannot turn a feasible window infeasible.
fn sloppy_phrase_match(all_positions: &[&[u32]], slop: u32) -> bool {
    let n = all_positions.len();
    let slop = i64::from(slop);
    let adj = |i: usize, k: usize| i64::from(all_positions[i][k]) - i as i64;

    // Cursors generating the candidate floors, plus the [lo_ptr, hi_ptr)
    // admissible run per slot.  All three only move forward.
    let mut cursor = vec![0usize; n];
    let mut lo_ptr = vec![0usize; n];
    let mut hi_ptr = vec![0usize; n];
    // Scratch reused across windows so the sweep does not allocate per step.
    let mut cand: Vec<&[u32]> = Vec::with_capacity(n);
    let mut pool: Vec<u32> = Vec::with_capacity(n * n);
    let mut owner: Vec<usize> = Vec::with_capacity(n * n);
    let mut seen: Vec<bool> = Vec::with_capacity(n * n);

    loop {
        // Next candidate floor: the smallest adjusted position not yet used
        // as a floor.  Exhausted cursors mean no window is left.
        let mut lo = i64::MAX;
        for i in 0..n {
            if cursor[i] < all_positions[i].len() {
                lo = lo.min(adj(i, cursor[i]));
            }
        }
        if lo == i64::MAX {
            return false;
        }
        for i in 0..n {
            while cursor[i] < all_positions[i].len() && adj(i, cursor[i]) <= lo {
                cursor[i] += 1;
            }
        }

        // Admissible run per slot for the window [lo, lo + slop].
        let hi = lo + slop;
        let mut window_full = true;
        for i in 0..n {
            let list = all_positions[i];
            let first = lo + i as i64;
            let last = hi + i as i64;
            while lo_ptr[i] < list.len() && i64::from(list[lo_ptr[i]]) < first {
                lo_ptr[i] += 1;
            }
            if hi_ptr[i] < lo_ptr[i] {
                hi_ptr[i] = lo_ptr[i];
            }
            while hi_ptr[i] < list.len() && i64::from(list[hi_ptr[i]]) <= last {
                hi_ptr[i] += 1;
            }
            if hi_ptr[i] == lo_ptr[i] {
                window_full = false;
            }
        }
        if !window_full {
            continue;
        }

        // Fast path — and the whole story whenever no term repeats: if the
        // earliest admissible position of every slot is a different document
        // position, that assignment is already a match.
        let earliest_are_distinct = (0..n).all(|i| {
            (i + 1..n).all(|j| all_positions[i][lo_ptr[i]] != all_positions[j][lo_ptr[j]])
        });
        if earliest_are_distinct {
            return true;
        }

        // Repeats collide here.  Decide the window exactly instead of
        // guessing which pointer to advance: an SDR over the truncated
        // candidate runs.
        cand.clear();
        for i in 0..n {
            let end = hi_ptr[i].min(lo_ptr[i].saturating_add(n));
            cand.push(&all_positions[i][lo_ptr[i]..end]);
        }
        if window_admits_distinct_choice(&cand, &mut pool, &mut owner, &mut seen) {
            return true;
        }
    }
}

/// Bipartite matching (Kuhn's augmenting-path algorithm) of phrase slots to
/// document positions: `true` when every slot can be given a position from
/// its own candidate list with no position used twice.  Both sides are
/// bounded by the phrase term count, so this is a handful of steps.
fn window_admits_distinct_choice(
    cand: &[&[u32]],
    pool: &mut Vec<u32>,
    owner: &mut Vec<usize>,
    seen: &mut Vec<bool>,
) -> bool {
    let n = cand.len();
    pool.clear();
    for c in cand {
        pool.extend_from_slice(c);
    }
    pool.sort_unstable();
    pool.dedup();
    if pool.len() < n {
        return false;
    }
    owner.clear();
    owner.resize(pool.len(), usize::MAX);
    for slot in 0..n {
        seen.clear();
        seen.resize(pool.len(), false);
        if !augment_slot(slot, cand, pool, seen, owner) {
            return false;
        }
    }
    true
}

/// One augmenting-path step for `window_admits_distinct_choice`: try to seat
/// `slot`, displacing an already-seated slot only if that slot can move.
fn augment_slot(
    slot: usize,
    cand: &[&[u32]],
    pool: &[u32],
    seen: &mut [bool],
    owner: &mut [usize],
) -> bool {
    for &position in cand[slot] {
        let Ok(p) = pool.binary_search(&position) else {
            continue;
        };
        if seen[p] {
            continue;
        }
        seen[p] = true;
        if owner[p] == usize::MAX || augment_slot(owner[p], cand, pool, seen, owner) {
            owner[p] = slot;
            return true;
        }
    }
    false
}

// ── Query builder helpers ─────────────────────────────────────────────────────

impl BoolQuery {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn must(mut self, q: Query) -> Self {
        self.must.push(q);
        self
    }

    pub fn should(mut self, q: Query) -> Self {
        self.should.push(q);
        self
    }

    pub fn must_not(mut self, q: Query) -> Self {
        self.must_not.push(q);
        self
    }

    /// Required, but non-scoring — see the `filter` field's note.
    pub fn filter(mut self, q: Query) -> Self {
        self.filter.push(q);
        self
    }

    pub fn min_should_match(mut self, n: u32) -> Self {
        self.min_should_match = Some(n);
        self
    }

    pub fn boost(mut self, b: f32) -> Self {
        self.boost = b;
        self
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        analyzer::AnalyzerRegistry,
        index::{FieldIndexConfig, FieldValues, FtsIndexReader, FtsIndexWriter},
    };
    use std::collections::HashMap;
    use tempfile::TempDir;

    fn setup_searcher(dir: &std::path::Path) -> FtsSearcher {
        let registry = Arc::new(AnalyzerRegistry::default());

        let mut writer = FtsIndexWriter::new(dir, "seg0", Arc::clone(&registry));

        // Use whitespace analyzer to avoid stemming surprises in tests
        let cfg = FieldIndexConfig {
            analyzer: "whitespace".to_owned(),
            ..Default::default()
        };
        writer.configure_field("body", cfg);

        let docs = [
            "the quick brown fox jumps over the lazy dog",
            "quick brown fox",
            "the lazy dog slept",
            "rust is fast and memory safe",
            "fox fox fox triple fox count",
        ];

        for (i, text) in docs.iter().enumerate() {
            let fields: HashMap<String, FieldValues> =
                [("body".to_owned(), FieldValues::from(text.to_string()))]
                    .into_iter()
                    .collect();
            writer.add_document(i as u32, &fields);
        }
        writer.finish().unwrap();

        let reader = Arc::new(FtsIndexReader::open(dir, "seg0", &["body"]).unwrap());
        FtsSearcher::new(reader, registry)
    }

    #[test]
    fn term_query_finds_docs() {
        let dir = TempDir::new().unwrap();
        let searcher = setup_searcher(dir.path());

        let q = Query::Term(TermQuery::new("body", "fox"));
        let hits = searcher.search(&q, 10, false).unwrap();

        // "fox" appears in docs 0, 1, 4
        assert!(
            hits.len() >= 2,
            "expected at least 2 hits for 'fox', got {}",
            hits.len()
        );
        let doc_ids: Vec<u32> = hits.iter().map(|h| h.doc_id).collect();
        assert!(doc_ids.contains(&1), "doc 1 should match");
        assert!(doc_ids.contains(&4), "doc 4 should match (triple fox)");
    }

    #[test]
    fn term_query_scoring_favors_high_tf() {
        let dir = TempDir::new().unwrap();
        let searcher = setup_searcher(dir.path());

        let q = Query::Term(TermQuery::new("body", "fox"));
        let hits = searcher.search(&q, 10, false).unwrap();

        // Doc 4 has "fox fox fox triple fox count" — high TF should score highest
        let doc4_score = hits.iter().find(|h| h.doc_id == 4).map(|h| h.score);
        let doc1_score = hits.iter().find(|h| h.doc_id == 1).map(|h| h.score);
        if let (Some(s4), Some(s1)) = (doc4_score, doc1_score) {
            assert!(
                s4 > s1,
                "doc4 (TF=4) should outscore doc1 (TF=1): {} vs {}",
                s4,
                s1
            );
        }
    }

    #[test]
    fn term_query_with_explain() {
        let dir = TempDir::new().unwrap();
        let searcher = setup_searcher(dir.path());

        let q = Query::Term(TermQuery::new("body", "fox"));
        let hits = searcher.search(&q, 10, true).unwrap();

        for hit in &hits {
            assert!(
                hit.explanation.is_some(),
                "explain mode should populate explanation"
            );
            let exp = hit.explanation.as_ref().unwrap();
            assert!(!exp.term_breakdowns.is_empty());
            assert!(exp.total_score > 0.0);
        }
    }

    #[test]
    fn prefix_query_expands_terms() {
        let dir = TempDir::new().unwrap();
        let searcher = setup_searcher(dir.path());

        // "la" should match "lazy" (and "last" if present)
        let q = Query::Prefix(PrefixQuery::new("body", "la"));
        let hits = searcher.search(&q, 10, false).unwrap();

        // "lazy" appears in docs 0 and 2
        assert!(
            !hits.is_empty(),
            "prefix 'la' should match docs containing 'lazy'"
        );
    }

    #[test]
    fn bool_query_must_intersection() {
        let dir = TempDir::new().unwrap();
        let searcher = setup_searcher(dir.path());

        // Must contain both "fox" and "quick"
        let q = Query::Bool(Box::new(
            BoolQuery::new()
                .must(Query::Term(TermQuery::new("body", "fox")))
                .must(Query::Term(TermQuery::new("body", "quick"))),
        ));
        let hits = searcher.search(&q, 10, false).unwrap();

        // Docs 0 and 1 contain both "fox" and "quick"
        let doc_ids: Vec<u32> = hits.iter().map(|h| h.doc_id).collect();
        assert!(
            doc_ids.contains(&0),
            "doc0 should match must(fox AND quick)"
        );
        assert!(
            doc_ids.contains(&1),
            "doc1 should match must(fox AND quick)"
        );
        // Doc 4 has fox but not quick
        assert!(!doc_ids.contains(&4), "doc4 should NOT match (no 'quick')");
    }

    #[test]
    fn bool_query_should_scores_are_nonzero() {
        // Regression: BoolQuery's derived Default gave boost = 0.0, so every
        // bool-shaped query (multi_match, multi-token match) returned
        // _score 0.0 for all hits. The default boost must be 1.0, and a
        // single-should bool must score identically to the bare term query.
        let dir = TempDir::new().unwrap();
        let searcher = setup_searcher(dir.path());

        let term_hits = searcher
            .search(&Query::Term(TermQuery::new("body", "fox")), 10, false)
            .unwrap();
        let bool_hits = searcher
            .search(
                &Query::Bool(Box::new(
                    BoolQuery::new().should(Query::Term(TermQuery::new("body", "fox"))),
                )),
                10,
                false,
            )
            .unwrap();

        assert_eq!(term_hits.len(), bool_hits.len());
        for th in &term_hits {
            assert!(th.score > 0.0, "term score must be positive");
            let bh = bool_hits.iter().find(|h| h.doc_id == th.doc_id).unwrap();
            assert!(
                (bh.score - th.score).abs() < 1e-6,
                "bool(should:[term]) score {} must equal term score {} for doc {}",
                bh.score,
                th.score,
                th.doc_id
            );
        }
    }

    #[test]
    fn dis_max_takes_max_of_subquery_scores() {
        let dir = TempDir::new().unwrap();
        let registry = Arc::new(AnalyzerRegistry::default());
        let mut writer = FtsIndexWriter::new(dir.path(), "seg0", Arc::clone(&registry));
        let cfg = FieldIndexConfig {
            analyzer: "whitespace".to_owned(),
            ..Default::default()
        };
        writer.configure_field("title", cfg.clone());
        writer.configure_field("body", cfg);

        // doc 0: "golf" in both fields; doc 1: only title; doc 2: only body.
        let docs: Vec<(&str, &str)> = vec![
            ("golf highlights", "golf swing tips and golf drills"),
            ("golf weekly", "tennis recap"),
            ("morning news", "golf scores from sunday"),
        ];
        for (i, (title, body)) in docs.iter().enumerate() {
            let fields: HashMap<String, FieldValues> = [
                ("title".to_owned(), FieldValues::from(title.to_string())),
                ("body".to_owned(), FieldValues::from(body.to_string())),
            ]
            .into_iter()
            .collect();
            writer.add_document(i as u32, &fields);
        }
        writer.finish().unwrap();
        let reader =
            Arc::new(FtsIndexReader::open(dir.path(), "seg0", &["title", "body"]).unwrap());
        let searcher = FtsSearcher::new(reader, registry);

        let title_q = Query::Term(TermQuery::new("title", "golf"));
        let body_q = Query::Term(TermQuery::new("body", "golf"));
        let title_hits = searcher.search(&title_q, 10, false).unwrap();
        let body_hits = searcher.search(&body_q, 10, false).unwrap();

        let dm = Query::DisMax(Box::new(DisMaxQuery::new(vec![
            title_q.clone(),
            body_q.clone(),
        ])));
        let dm_hits = searcher.search(&dm, 10, false).unwrap();

        // Union of matching docs: all three.
        assert_eq!(
            dm_hits.len(),
            3,
            "dis_max must return the union of sub-query docs"
        );

        for hit in &dm_hits {
            let ts = title_hits
                .iter()
                .find(|h| h.doc_id == hit.doc_id)
                .map(|h| h.score);
            let bs = body_hits
                .iter()
                .find(|h| h.doc_id == hit.doc_id)
                .map(|h| h.score);
            let expected = ts.unwrap_or(0.0).max(bs.unwrap_or(0.0));
            assert!(hit.score > 0.0, "dis_max hit must have positive score");
            assert!(
                (hit.score - expected).abs() < 1e-6,
                "doc {}: dis_max score {} != max(field scores) {}",
                hit.doc_id,
                hit.score,
                expected
            );
        }

        // tie_breaker adds a fraction of the non-best scores on top of the max.
        let dm_tb = Query::DisMax(Box::new(
            DisMaxQuery::new(vec![title_q, body_q]).tie_breaker(0.5),
        ));
        let tb_hits = searcher.search(&dm_tb, 10, false).unwrap();
        let both = tb_hits.iter().find(|h| h.doc_id == 0).unwrap();
        let ts = title_hits.iter().find(|h| h.doc_id == 0).unwrap().score;
        let bs = body_hits.iter().find(|h| h.doc_id == 0).unwrap().score;
        let expected = ts.max(bs) + 0.5 * (ts + bs - ts.max(bs));
        assert!(
            (both.score - expected).abs() < 1e-6,
            "tie_breaker score {} != expected {}",
            both.score,
            expected
        );
    }

    /// #361 — a `filter` clause narrows exactly like a second `must`, and
    /// contributes exactly nothing to `_score`.  Lucene builds a FILTER
    /// clause's Weight with `ScoreMode.COMPLETE_NO_SCORES`
    /// (BooleanWeight.java:49-64, gated on `BooleanClause.isScoring()` at
    /// BooleanClause.java:84-87).
    #[test]
    fn bool_query_filter_narrows_without_scoring() {
        let dir = TempDir::new().unwrap();
        let searcher = setup_searcher(dir.path());

        let fox = || Query::Term(TermQuery::new("body", "fox"));
        let quick = || Query::Term(TermQuery::new("body", "quick"));

        let bare = searcher
            .search(
                &Query::Bool(Box::new(BoolQuery::new().must(fox()))),
                10,
                false,
            )
            .unwrap();
        let bare_scores: HashMap<u32, f32> = bare.iter().map(|h| (h.doc_id, h.score)).collect();

        let filtered = searcher
            .search(
                &Query::Bool(Box::new(BoolQuery::new().must(fox()).filter(quick()))),
                10,
                false,
            )
            .unwrap();
        let conjunction = searcher
            .search(
                &Query::Bool(Box::new(BoolQuery::new().must(fox()).must(quick()))),
                10,
                false,
            )
            .unwrap();

        // Same membership as the two-`must` conjunction …
        let mut filtered_ids: Vec<u32> = filtered.iter().map(|h| h.doc_id).collect();
        let mut conjunction_ids: Vec<u32> = conjunction.iter().map(|h| h.doc_id).collect();
        filtered_ids.sort_unstable();
        conjunction_ids.sort_unstable();
        assert_eq!(
            filtered_ids, conjunction_ids,
            "filter must narrow like must"
        );
        assert!(!filtered_ids.is_empty(), "fixture: docs 0 and 1 match both");

        // … the `fox` score unchanged …
        for hit in &filtered {
            let bare_score = bare_scores[&hit.doc_id];
            assert!(
                (hit.score - bare_score).abs() < 1e-6,
                "doc {} scored {} with a filter but {bare_score} without it",
                hit.doc_id,
                hit.score
            );
        }
        // … and the same clause as a `must` DOES add its BM25, which is the
        // behaviour the projection used to give every `bool.filter`.
        for hit in &conjunction {
            assert!(
                hit.score > bare_scores[&hit.doc_id],
                "doc {} did not gain score from a scoring `must` clause",
                hit.doc_id
            );
        }
    }

    #[test]
    fn bool_query_must_not_excludes() {
        let dir = TempDir::new().unwrap();
        let searcher = setup_searcher(dir.path());

        let q = Query::Bool(Box::new(
            BoolQuery::new()
                .must(Query::Term(TermQuery::new("body", "fox")))
                .must_not(Query::Term(TermQuery::new("body", "quick"))),
        ));
        let hits = searcher.search(&q, 10, false).unwrap();

        // Doc 4 has "fox" but not "quick"; docs 0 and 1 have both
        let doc_ids: Vec<u32> = hits.iter().map(|h| h.doc_id).collect();
        assert!(doc_ids.contains(&4), "doc4 should match (fox, no quick)");
        assert!(!doc_ids.contains(&0), "doc0 excluded by must_not(quick)");
        assert!(!doc_ids.contains(&1), "doc1 excluded by must_not(quick)");
    }

    #[test]
    fn bool_query_should_min_match() {
        let dir = TempDir::new().unwrap();
        let searcher = setup_searcher(dir.path());

        // Must match at least 2 of: fox, quick, lazy
        let q = Query::Bool(Box::new(
            BoolQuery::new()
                .should(Query::Term(TermQuery::new("body", "fox")))
                .should(Query::Term(TermQuery::new("body", "quick")))
                .should(Query::Term(TermQuery::new("body", "lazy")))
                .min_should_match(2),
        ));
        let hits = searcher.search(&q, 10, false).unwrap();

        // Doc 0: has all 3 → matches
        // Doc 1: has fox + quick → matches
        // Doc 2: has lazy only → does not match
        let doc_ids: Vec<u32> = hits.iter().map(|h| h.doc_id).collect();
        assert!(doc_ids.contains(&0), "doc0 should match (fox+quick+lazy)");
        assert!(doc_ids.contains(&1), "doc1 should match (fox+quick)");
        assert!(!doc_ids.contains(&2), "doc2 should not match (lazy only)");
    }

    #[test]
    fn phrase_query_matches_adjacent_terms() {
        let dir = TempDir::new().unwrap();
        let searcher = setup_searcher(dir.path());

        let q = Query::Phrase(PhraseQuery::new(
            "body",
            vec!["quick".to_owned(), "brown".to_owned()],
        ));
        let hits = searcher.search(&q, 10, false).unwrap();

        // "quick brown" appears in docs 0 and 1
        assert!(!hits.is_empty(), "phrase 'quick brown' should match");
        let doc_ids: Vec<u32> = hits.iter().map(|h| h.doc_id).collect();
        assert!(doc_ids.contains(&0) || doc_ids.contains(&1));
    }

    /// Regression: the phrase intersection must be correct when the rarest
    /// (anchor) term is NOT the first phrase term.  Doc 0 has
    /// "the quick brown fox …"; "quick"/"brown" are rarer than "the", so the
    /// anchor is a non-first term — the old offset-adjust logic mishandled this.
    #[test]
    fn phrase_query_correct_when_anchor_not_first() {
        let dir = TempDir::new().unwrap();
        let searcher = setup_searcher(dir.path());

        // "the quick" — "the" is the common (first) term, "quick" rarer.
        let hits = searcher
            .search(
                &Query::Phrase(PhraseQuery::new(
                    "body",
                    vec!["the".to_owned(), "quick".to_owned()],
                )),
                10,
                false,
            )
            .unwrap();
        let ids: Vec<u32> = hits.iter().map(|h| h.doc_id).collect();
        assert!(ids.contains(&0), "doc0 has 'the quick'");
        assert!(!ids.contains(&2), "doc2 has 'the lazy', not 'the quick'");

        // A NON-adjacent pair with a gap must NOT match at slop 0:
        // doc0 = "the quick brown fox jumps over the lazy dog" — "quick dog"
        // are not adjacent.
        let hits = searcher
            .search(
                &Query::Phrase(PhraseQuery::new(
                    "body",
                    vec!["quick".to_owned(), "dog".to_owned()],
                )),
                10,
                false,
            )
            .unwrap();
        assert!(
            hits.iter().all(|h| h.doc_id != 0),
            "'quick dog' is not an adjacent phrase in doc0"
        );
    }

    /// #830: `slop` is Lucene `SloppyPhraseMatcher` move-distance, so a
    /// transposed pair matches at slop >= 2 — the old walk was in-order-only
    /// and never matched a reordering at ANY slop.
    #[test]
    fn sloppy_phrase_transposition_semantics() {
        // Doc reading "brown quick" (brown@0, quick@1), query "quick brown".
        let quick: &[u32] = &[1];
        let brown: &[u32] = &[0];
        assert!(!phrase_positions_match(&[quick, brown], 0));
        assert!(
            !phrase_positions_match(&[quick, brown], 1),
            "a transposition costs 2, not 1"
        );
        assert!(
            phrase_positions_match(&[quick, brown], 2),
            "a transposition must match at slop 2"
        );
        assert!(phrase_positions_match(&[quick, brown], 3));

        // In-order forward gap still costs its width ("quick lazy brown").
        let quick_gap: &[u32] = &[0];
        let brown_gap: &[u32] = &[2];
        assert!(!phrase_positions_match(&[quick_gap, brown_gap], 0));
        assert!(phrase_positions_match(&[quick_gap, brown_gap], 1));

        // Lucene's class-javadoc example doc "x a b a y" (a@[1,3], b@2):
        // "a b" matches exactly at slop 0, and "b a" (b@2 → a@3) at slop 0
        // too via the in-order pair; both trivially within slop 2.
        let a: &[u32] = &[1, 3];
        let b: &[u32] = &[2];
        assert!(phrase_positions_match(&[a, b], 0));
        // NB "b a" here is satisfied by the IN-ORDER pair b@2 -> a@3, so it
        // pins the javadoc example, not transposition cost — the transposed
        // pair is pinned by quick/brown above, where no in-order pick exists.
        assert!(phrase_positions_match(&[b, a], 0));
        assert!(phrase_positions_match(&[b, a], 2));

        // Adjacent transposed pair inside a 3-term phrase: doc "one three
        // two" for query "one two three" — one@0, two@2, three@1 → adjusted
        // span (2-1) - (1-2) = 2.
        let one: &[u32] = &[0];
        let two: &[u32] = &[2];
        let three: &[u32] = &[1];
        assert!(!phrase_positions_match(&[one, two, three], 1));
        assert!(phrase_positions_match(&[one, two, three], 2));
    }

    /// A repeated phrase term must land on DISTINCT document positions —
    /// one document token cannot fill two phrase slots, however large the
    /// slop (Lucene's repeat-collision rule).
    #[test]
    fn sloppy_phrase_repeat_needs_distinct_positions() {
        let a_once: &[u32] = &[3];
        assert!(
            !phrase_positions_match(&[a_once, a_once], 10),
            "\"a a\" must not match a doc holding a single 'a'"
        );
        let a_gap: &[u32] = &[3, 5];
        assert!(
            !phrase_positions_match(&[a_gap, a_gap], 0),
            "'a x a' is not an adjacent \"a a\""
        );
        assert!(phrase_positions_match(&[a_gap, a_gap], 1));
        let a_adj: &[u32] = &[3, 4];
        assert!(phrase_positions_match(&[a_adj, a_adj], 0));
    }

    /// Regression for the defect the #830 review caught: a phrase holding a
    /// REPEATED term must keep every match the pre-#830 in-order walk gave.
    ///
    /// The minimal-window sweep as first written advanced the pointer at the
    /// MINIMUM adjusted position whenever a window collided.  That pointer is
    /// usually a non-colliding slot, so the sweep walked away from the very
    /// assignment that would separate the repeats and exhausted a
    /// single-occurrence slot instead: `"i said no no"~1` stopped matching
    /// `i said uh no no` at every slop.  The window/SDR formulation decides
    /// each window instead of guessing which pointer to move.
    #[test]
    fn sloppy_phrase_repeated_term_keeps_in_order_matches() {
        // Doc "i said uh no no": i@0, said@1, no@[3,4].  Query "i said no no"
        // picks no@3 and no@4 — adjusted 0,0,1,1, span 1.
        let i: &[u32] = &[0];
        let said: &[u32] = &[1];
        let no: &[u32] = &[3, 4];
        for slop in [1u32, 2, 3, 5, 10] {
            assert!(
                phrase_positions_match(&[i, said, no, no], slop),
                "\"i said no no\"~{slop} must match 'i said uh no no'"
            );
        }

        // Doc "a x b b": a@0, b@[2,3].  "a b b" is in order with one gap.
        let a: &[u32] = &[0];
        let b: &[u32] = &[2, 3];
        for slop in [1u32, 2, 4] {
            assert!(
                phrase_positions_match(&[a, b, b], slop),
                "\"a b b\"~{slop} must match 'a x b b'"
            );
        }

        // Doc "no way no no": every phrase slot is the same term (no@[0,2,3]).
        let no3: &[u32] = &[0, 2, 3];
        for slop in [1u32, 2, 3] {
            assert!(
                phrase_positions_match(&[no3, no3, no3], slop),
                "\"no no no\"~{slop} must match 'no way no no'"
            );
        }

        // The distinctness rule still binds: three slots cannot be filled by
        // two document tokens, at any slop.
        let two_tokens: &[u32] = &[3, 4];
        assert!(
            !phrase_positions_match(&[two_tokens, two_tokens, two_tokens], 10),
            "three repeats of one term need three distinct positions"
        );
    }

    /// Exhaustive cross-check of the sloppy evaluator over every document of
    /// length <= 5 and every phrase of length <= 3 from a 3-symbol alphabet,
    /// at slop 0..=3, against two independent oracles:
    ///
    /// 1. brute force over all assignments (one position per slot, all
    ///    distinct, adjusted span <= slop) — catches an INCOMPLETE search,
    ///    which is exactly what the #830 review found; and
    /// 2. the pre-#830 in-order walk, which must never match a phrase this
    ///    evaluator rejects.  That is the "no previously-matching document
    ///    stops matching" claim, checked rather than asserted.
    #[test]
    fn sloppy_phrase_agrees_with_brute_force_and_keeps_pre_830_hits() {
        /// The evaluator this replaced (main @ #830): greedy earliest
        /// in-order walk accumulating the gaps.
        fn pre_830_walk(all: &[&[u32]], slop: u32) -> bool {
            if all.iter().any(|p| p.is_empty()) {
                return false;
            }
            if all.len() == 1 {
                return true;
            }
            'outer: for &start_pos in all[0] {
                let mut current = start_pos;
                let mut gaps: u32 = 0;
                for positions in &all[1..] {
                    match positions.iter().copied().find(|&p| p > current) {
                        Some(next) => {
                            gaps += next - current - 1;
                            if gaps > slop {
                                continue 'outer;
                            }
                            current = next;
                        }
                        None => continue 'outer,
                    }
                }
                return true;
            }
            false
        }

        /// Reference semantics, stated directly: some assignment of one
        /// distinct position per slot has adjusted span <= slop (adjacency
        /// for slop 0).
        fn brute(all: &[&[u32]], slop: u32) -> bool {
            fn rec(k: usize, all: &[&[u32]], pick: &mut Vec<u32>, slop: u32) -> bool {
                if k == all.len() {
                    if slop == 0 {
                        return pick
                            .iter()
                            .enumerate()
                            .all(|(i, &p)| i64::from(p) == i64::from(pick[0]) + i as i64);
                    }
                    let adjusted = |i: usize, p: u32| i64::from(p) - i as i64;
                    let lo = pick
                        .iter()
                        .enumerate()
                        .map(|(i, &p)| adjusted(i, p))
                        .min()
                        .unwrap();
                    let hi = pick
                        .iter()
                        .enumerate()
                        .map(|(i, &p)| adjusted(i, p))
                        .max()
                        .unwrap();
                    return hi - lo <= i64::from(slop);
                }
                for &p in all[k] {
                    if pick.contains(&p) {
                        continue;
                    }
                    pick.push(p);
                    if rec(k + 1, all, pick, slop) {
                        return true;
                    }
                    pick.pop();
                }
                false
            }
            if all.iter().any(|p| p.is_empty()) {
                return false;
            }
            if all.len() == 1 {
                return true;
            }
            rec(0, all, &mut Vec::new(), slop)
        }

        fn sequences(len: usize, alphabet: u32) -> Vec<Vec<u32>> {
            let mut out = vec![Vec::new()];
            for _ in 0..len {
                let mut next = Vec::new();
                for prefix in &out {
                    for symbol in 0..alphabet {
                        let mut s = prefix.clone();
                        s.push(symbol);
                        next.push(s);
                    }
                }
                out = next;
            }
            out
        }

        let mut checked = 0u32;
        for doc_len in 1..=5usize {
            for doc in sequences(doc_len, 3) {
                for query_len in 1..=3usize {
                    for query in sequences(query_len, 3) {
                        let lists: Vec<Vec<u32>> = query
                            .iter()
                            .map(|t| {
                                doc.iter()
                                    .enumerate()
                                    .filter(|(_, d)| *d == t)
                                    .map(|(p, _)| p as u32)
                                    .collect()
                            })
                            .collect();
                        let all: Vec<&[u32]> = lists.iter().map(|v| v.as_slice()).collect();
                        for slop in 0..=3u32 {
                            checked += 1;
                            let got = phrase_positions_match(&all, slop);
                            assert_eq!(
                                got,
                                brute(&all, slop),
                                "doc {doc:?} query {query:?} slop {slop}: \
                                 evaluator disagrees with brute force"
                            );
                            if pre_830_walk(&all, slop) {
                                assert!(
                                    got,
                                    "doc {doc:?} query {query:?} slop {slop}: \
                                     matched before #830 and must still match"
                                );
                            }
                        }
                    }
                }
            }
        }
        assert!(checked > 50_000, "coverage collapsed to {checked} cases");
    }

    /// #830 segment arm end-to-end: a sloppy `PhraseQuery` admits the
    /// transposed pair at slop 2 and still rejects it at slop 0/1.  Docs 0
    /// and 1 read "… quick brown …"; the query asks for "brown quick".
    #[test]
    fn phrase_query_slop_transposition() {
        let dir = TempDir::new().unwrap();
        let searcher = setup_searcher(dir.path());

        let mk = |slop: u32| {
            let mut q = PhraseQuery::new("body", vec!["brown".to_owned(), "quick".to_owned()]);
            q.slop = slop;
            Query::Phrase(q)
        };
        assert!(searcher.search(&mk(0), 10, false).unwrap().is_empty());
        assert!(
            searcher.search(&mk(1), 10, false).unwrap().is_empty(),
            "transposition costs 2 — slop 1 must not admit it"
        );
        let ids: Vec<u32> = searcher
            .search(&mk(2), 10, false)
            .unwrap()
            .iter()
            .map(|h| h.doc_id)
            .collect();
        assert!(
            ids.contains(&0) && ids.contains(&1),
            "docs with 'quick brown' must match the reversed query at slop 2, got {ids:?}"
        );
    }

    /// Case-sensitive wildcard/fuzzy (text-field path): the whitespace analyzer
    /// preserves case, so an indexed term "Rust" is matched by "R*" but NOT by
    /// "r*" when `case_insensitive = false`.
    #[test]
    fn case_sensitive_wildcard_and_fuzzy() {
        let dir = TempDir::new().unwrap();
        let registry = Arc::new(AnalyzerRegistry::default());
        let mut writer = FtsIndexWriter::new(dir.path(), "seg0", Arc::clone(&registry));
        let cfg = FieldIndexConfig {
            analyzer: "whitespace".to_owned(),
            ..Default::default()
        };
        writer.configure_field("body", cfg);
        writer.add_document(
            0,
            &[("body".to_owned(), FieldValues::from("Rust Systems"))]
                .into_iter()
                .collect(),
        );
        writer.finish().unwrap();
        let reader = Arc::new(FtsIndexReader::open(dir.path(), "seg0", &["body"]).unwrap());
        let searcher = FtsSearcher::new(reader, registry);

        // Case-sensitive wildcard: "R*" matches, "r*" does not.
        let mut ci = WildcardQuery::new("body", "R*");
        ci.case_insensitive = false;
        assert_eq!(
            searcher
                .search(&Query::Wildcard(ci), 10, false)
                .unwrap()
                .len(),
            1
        );
        let mut cs = WildcardQuery::new("body", "r*");
        cs.case_insensitive = false;
        assert_eq!(
            searcher
                .search(&Query::Wildcard(cs), 10, false)
                .unwrap()
                .len(),
            0
        );
        // Case-insensitive (keyword-style) wildcard: "r*" DOES match.
        let ki = WildcardQuery::new("body", "r*"); // default case_insensitive = true
        assert_eq!(
            searcher
                .search(&Query::Wildcard(ki), 10, false)
                .unwrap()
                .len(),
            1
        );

        // Case-sensitive fuzzy: "Rist" (1 edit from "Rust") matches; "rist" does not.
        let mut fz = FuzzyQuery::new("body", "Rist", 1);
        fz.case_insensitive = false;
        assert_eq!(
            searcher.search(&Query::Fuzzy(fz), 10, false).unwrap().len(),
            1
        );
        let mut fzl = FuzzyQuery::new("body", "rist", 1);
        fzl.case_insensitive = false;
        assert_eq!(
            searcher
                .search(&Query::Fuzzy(fzl), 10, false)
                .unwrap()
                .len(),
            0
        );
    }

    #[test]
    fn wildcard_expansion_respects_cooperative_deadline() {
        // RC4 blocker 12 regression: multi-term expansion must stop at the
        // cooperative deadline and latch `deadline_tripped` so the engine
        // returns partial results with `timed_out: true`. Pre-fix the
        // expansion walked the entire dictionary regardless of the request
        // timeout (live: `timeout: 1ms` wildcard ran 3.7 s, fuzzy 8.3 s,
        // both `timed_out: false`).
        let dir = TempDir::new().unwrap();
        let registry = Arc::new(AnalyzerRegistry::default());
        let mut writer = FtsIndexWriter::new(dir.path(), "seg0", Arc::clone(&registry));
        let cfg = FieldIndexConfig {
            analyzer: "whitespace".to_owned(),
            ..Default::default()
        };
        writer.configure_field("body", cfg);
        // 5 000 unique terms — enough that the every-1 024-terms poll fires.
        let text: String = (0..5000)
            .map(|i| format!("term{i:05}"))
            .collect::<Vec<_>>()
            .join(" ");
        writer.add_document(
            0,
            &[("body".to_owned(), FieldValues::from(text))]
                .into_iter()
                .collect(),
        );
        writer.finish().unwrap();
        let reader = Arc::new(FtsIndexReader::open(dir.path(), "seg0", &["body"]).unwrap());

        let mut wq = WildcardQuery::new("body", "term*");
        wq.case_insensitive = false;
        let q = Query::Wildcard(wq);

        // Unarmed searcher (default): full expansion, flag stays clear.
        let searcher = FtsSearcher::new(Arc::clone(&reader), Arc::clone(&registry));
        let hits = searcher.search(&q, 10, false).unwrap();
        assert_eq!(hits.len(), 1, "the one doc matches via full expansion");
        assert!(!searcher.deadline_tripped(), "no deadline → never tripped");

        // Deadline already in the past: expansion stops at the first poll,
        // the search still returns Ok (graceful partial, not an error), and
        // the trip is latched for the caller to surface as timed_out:true.
        let expired = FtsSearcher::new(reader, registry).with_deadline(Some(
            std::time::Instant::now() - std::time::Duration::from_millis(1),
        ));
        let _ = expired.search(&q, 10, false).unwrap();
        assert!(
            expired.deadline_tripped(),
            "expired deadline must latch deadline_tripped"
        );
    }

    /// Clause COUNT is the second unbounded axis. A projected disjunction is
    /// one clause per (token × field), so a field-less `query_string` over a
    /// wide mapping arrives here with tens of thousands of `should` clauses,
    /// each materialising a full hit vector. Pre-fix nothing in this loop
    /// polled the request deadline, so the whole list ran to completion
    /// inside `block_in_place` — one request holding a worker for as long as
    /// the clause list took, whatever its timeout said.
    #[test]
    fn bool_clause_fan_out_respects_cooperative_deadline() {
        let dir = TempDir::new().unwrap();
        let registry = Arc::new(AnalyzerRegistry::default());
        let mut writer = FtsIndexWriter::new(dir.path(), "seg0", Arc::clone(&registry));
        let cfg = FieldIndexConfig {
            analyzer: "whitespace".to_owned(),
            ..Default::default()
        };
        writer.configure_field("body", cfg);
        let text: String = (0..2000)
            .map(|i| format!("term{i:05}"))
            .collect::<Vec<_>>()
            .join(" ");
        writer.add_document(
            0,
            &[("body".to_owned(), FieldValues::from(text))]
                .into_iter()
                .collect(),
        );
        writer.finish().unwrap();
        let reader = Arc::new(FtsIndexReader::open(dir.path(), "seg0", &["body"]).unwrap());

        // 2 000 `should` clauses — well past the every-64 poll interval.
        let mut bq = BoolQuery::new();
        for i in 0..2000 {
            bq = bq.should(Query::Term(TermQuery::new("body", format!("term{i:05}"))));
        }
        let q = Query::Bool(Box::new(bq));

        // Unarmed searcher: every clause runs, the doc matches, flag clear.
        let searcher = FtsSearcher::new(Arc::clone(&reader), Arc::clone(&registry));
        let hits = searcher.search(&q, 10, false).unwrap();
        assert_eq!(
            hits.len(),
            1,
            "the one doc matches via the full disjunction"
        );
        assert!(!searcher.deadline_tripped(), "no deadline → never tripped");

        // Deadline already past: the clause loop stops at its first poll,
        // returns Ok (graceful partial, not an error), and latches the trip
        // so the caller reports `timed_out: true`.
        let expired = FtsSearcher::new(Arc::clone(&reader), Arc::clone(&registry)).with_deadline(
            Some(std::time::Instant::now() - std::time::Duration::from_millis(1)),
        );
        let partial = expired.search(&q, 10, false).unwrap();
        assert!(
            expired.deadline_tripped(),
            "expired deadline must latch deadline_tripped on clause fan-out"
        );
        assert!(
            partial.len() <= 1,
            "partial results are a SUBSET, never more than the true answer"
        );
    }

    /// The poll interval of `execute_bool`'s clause loop. The two tests below
    /// depend on it: a clause list of EXACTLY this length is polled once, at
    /// its first clause, and the NEXT list is then polled at its first clause
    /// too — which is how the deadline is made to land between two lists.
    const CLAUSE_POLL_INTERVAL: usize = 64;

    /// Dictionary size for [`midlist_deadline_fixture`]. Measured on this
    /// machine, one full `term*` wildcard walk: ~38 ms release / ~341 ms
    /// debug, funding a ~19 ms / ~170 ms budget.
    const DICTIONARY_TERMS: usize = 100_000;

    /// Fixture for the "partial must never broaden" pair.
    ///
    /// Returns the segment reader, a wildcard clause expensive enough to spend
    /// a whole request budget on its own, and a budget MEASURED from that
    /// clause rather than hard-coded. Deriving it is what keeps the pair
    /// honest on a machine of any speed — a slower machine measures a slower
    /// walk and gets a proportionally larger budget, so the only absolute
    /// risk (the budget expiring before the bool's first clause poll, which
    /// would make both tests vacuous) shrinks rather than grows under load.
    /// A hard-coded 2 ms budget did expire that way once, in release, with
    /// the rest of this suite running in parallel; the precondition
    /// assertions caught it as a failure rather than a false pass.
    ///
    /// The document holds `alpha` (a hit), `beta` (an exclusion), and a
    /// 100 000-term dictionary for the wildcard to walk. That size is set by
    /// the RELEASE profile: at 20 000 terms an optimised walk is ~7 ms, which
    /// cannot fund a budget big enough to survive scheduling.
    fn midlist_deadline_fixture(
        dir: &TempDir,
    ) -> (
        Arc<FtsIndexReader>,
        Arc<AnalyzerRegistry>,
        Query,
        std::time::Duration,
    ) {
        let registry = Arc::new(AnalyzerRegistry::default());
        let mut writer = FtsIndexWriter::new(dir.path(), "seg0", Arc::clone(&registry));
        let cfg = FieldIndexConfig {
            analyzer: "whitespace".to_owned(),
            ..Default::default()
        };
        writer.configure_field("body", cfg);
        let mut text = String::from("alpha beta");
        for i in 0..DICTIONARY_TERMS {
            text.push_str(&format!(" term{i:06}"));
        }
        writer.add_document(
            0,
            &[("body".to_owned(), FieldValues::from(text))]
                .into_iter()
                .collect(),
        );
        writer.finish().unwrap();
        let reader = Arc::new(FtsIndexReader::open(dir.path(), "seg0", &["body"]).unwrap());

        let mut wq = WildcardQuery::new("body", "term*");
        wq.case_insensitive = false;
        let expensive = Query::Wildcard(wq);

        // Calibrate with no deadline armed, twice — the second run is warm,
        // and warm is what the timed runs will be.
        let cal = FtsSearcher::new(Arc::clone(&reader), Arc::clone(&registry));
        let _ = cal.search(&expensive, 10, false).unwrap();
        let t0 = std::time::Instant::now();
        let _ = cal.search(&expensive, 10, false).unwrap();
        let full_walk = t0.elapsed();
        assert!(!cal.deadline_tripped(), "no deadline → never tripped");

        // HALF the full walk. Below it, so the wildcard provably overruns and
        // the deadline is past when it returns; large in absolute terms, so
        // the microseconds between arming the deadline and the bool's first
        // clause poll cannot consume it.
        let budget = full_walk / 2;
        assert!(
            budget >= std::time::Duration::from_millis(10),
            "the calibration clause is too cheap to fund a budget that \
             survives scheduling (full walk {full_walk:?}); raise \
             DICTIONARY_TERMS"
        );
        (reader, registry, expensive, budget)
    }

    /// A truncated `must_not` would RELAX the query and admit documents it
    /// excludes. That clause list must bail the whole bool to empty rather
    /// than return a broader-than-asked-for set.
    ///
    /// The deadline has to expire strictly BETWEEN the `should` clauses and
    /// the `must_not` clauses, and that is the whole difficulty. An
    /// already-expired deadline cannot exercise this at all: the poll fires on
    /// the FIRST clause of the bool, so `should` truncates to nothing, the
    /// bool is empty whatever `must_not` does, and the assertion holds
    /// vacuously. An earlier version of this test did exactly that — it passed
    /// with the source change reverted AND with the hazard it is named after
    /// (`must_not` truncation made partial-ok) deliberately introduced.
    ///
    /// So the deadline is armed in the FUTURE and spent inside the `should`
    /// list by one deliberately expensive clause:
    ///
    ///   * `should` holds exactly one poll interval of clauses, so the only
    ///     poll inside it is at index 0, before any budget is spent. Clause 0
    ///     matches the document; clause 1 burns the budget; the rest are cheap
    ///     misses.
    ///   * `must_not` is therefore entered with the shared clause counter at
    ///     64, its first poll fires, and the excluding clause never runs.
    ///
    /// Verified to fail on the hazard: with `run_clauses(&bq.must_not, true)`
    /// the document comes back and the final assertion trips.
    ///
    /// Both preconditions are asserted rather than assumed, so an unlucky
    /// machine makes this test FAIL LOUDLY instead of passing vacuously.
    #[test]
    fn bool_deadline_never_broadens_a_must_not() {
        let dir = TempDir::new().unwrap();
        let (reader, registry, expensive, budget) = midlist_deadline_fixture(&dir);

        let mut base = BoolQuery::new().should(Query::Term(TermQuery::new("body", "alpha")));
        base = base.should(expensive);
        for i in 2..CLAUSE_POLL_INTERVAL {
            base = base.should(Query::Term(TermQuery::new("body", format!("absent{i}"))));
        }
        assert_eq!(base.should.len(), CLAUSE_POLL_INTERVAL);

        // Precondition: the same should list, same budget, no must_not. If
        // this comes back empty the deadline fired before the should clauses
        // ran and the real assertion below would prove nothing.
        let control = FtsSearcher::new(Arc::clone(&reader), Arc::clone(&registry))
            .with_deadline(Some(std::time::Instant::now() + budget));
        let control_hits = control
            .search(&Query::Bool(Box::new(base.clone())), 10, false)
            .unwrap();
        assert_eq!(
            control_hits.len(),
            1,
            "precondition: the should clauses must have produced the document \
             before the budget ({budget:?}) ran out"
        );

        let with_must_not = Query::Bool(Box::new(
            base.must_not(Query::Term(TermQuery::new("body", "beta"))),
        ));
        let expired = FtsSearcher::new(reader, registry)
            .with_deadline(Some(std::time::Instant::now() + budget));
        let hits = expired.search(&with_must_not, 10, false).unwrap();
        assert!(
            expired.deadline_tripped(),
            "precondition: the budget ({budget:?}) must have been spent \
             inside the clause list"
        );
        assert!(
            hits.is_empty(),
            "a must_not that could not be fully evaluated must not admit the \
             document it excludes — got {} hit(s)",
            hits.len()
        );
    }

    /// The other half of the same invariant: a truncated `must` drops
    /// conjuncts, and dropping a conjunct only ever ADMITS documents the full
    /// query rejects.
    ///
    /// Same construction, one list earlier: `must` holds one poll interval of
    /// clauses the document satisfies (clause 1 burns the budget), and the
    /// conjunct that would EXCLUDE it sits at index 64 — the first clause not
    /// reached before the poll fires. Truncating there and keeping the partial
    /// intersection returns the document; bailing returns nothing.
    ///
    /// Verified to fail on the hazard: with `run_clauses(&bq.must, true)` the
    /// document comes back and the final assertion trips.
    #[test]
    fn bool_deadline_never_broadens_a_must() {
        let dir = TempDir::new().unwrap();
        let (reader, registry, expensive, budget) = midlist_deadline_fixture(&dir);

        // Every clause here matches the one document, so the intersection is
        // non-empty right up to the clause that is never reached.
        let mut base = BoolQuery::new().must(Query::Term(TermQuery::new("body", "alpha")));
        base = base.must(expensive);
        for i in 2..CLAUSE_POLL_INTERVAL {
            base = base.must(Query::Term(TermQuery::new("body", format!("term{i:06}"))));
        }
        assert_eq!(base.must.len(), CLAUSE_POLL_INTERVAL);

        // Precondition: without the excluding conjunct the document survives,
        // so a later empty result can only come from the guard. This control
        // runs with NO deadline on purpose — it only has to prove the base
        // query matches doc 0. Sharing the real arm's tight budget here made
        // the precondition itself load-sensitive: under CI load the control's
        // deadline expired before the intersection finished and this assertion
        // tripped spuriously (#510). The deadline belongs only on the arm below,
        // which is the one that actually tests deadline behaviour.
        let control = FtsSearcher::new(Arc::clone(&reader), Arc::clone(&registry));
        let control_hits = control
            .search(&Query::Bool(Box::new(base.clone())), 10, false)
            .unwrap();
        assert_eq!(
            control_hits.len(),
            1,
            "precondition: the base must clauses must intersect to the document"
        );

        // `zebrafish` is in no document, so a FULL evaluation excludes doc 0.
        let with_excluding_conjunct = Query::Bool(Box::new(
            base.must(Query::Term(TermQuery::new("body", "zebrafish"))),
        ));
        let expired = FtsSearcher::new(reader, registry)
            .with_deadline(Some(std::time::Instant::now() + budget));
        let hits = expired.search(&with_excluding_conjunct, 10, false).unwrap();
        assert!(
            expired.deadline_tripped(),
            "precondition: the budget ({budget:?}) must have been spent \
             inside the clause list"
        );
        assert!(
            hits.is_empty(),
            "a must clause that could not be evaluated must not be silently \
             dropped from the conjunction — got {} hit(s)",
            hits.len()
        );
    }

    #[test]
    fn phrase_query_nonexistent_returns_empty() {
        let dir = TempDir::new().unwrap();
        let searcher = setup_searcher(dir.path());

        // "brown quick" is never in order in any doc
        let q = Query::Phrase(PhraseQuery::new(
            "body",
            vec!["brown".to_owned(), "quick".to_owned()],
        ));
        let hits = searcher.search(&q, 10, false).unwrap();
        assert!(hits.is_empty(), "reversed phrase should not match");
    }

    #[test]
    fn hits_sorted_by_descending_score() {
        let dir = TempDir::new().unwrap();
        let searcher = setup_searcher(dir.path());

        let q = Query::Term(TermQuery::new("body", "fox"));
        let hits = searcher.search(&q, 10, false).unwrap();

        let scores: Vec<f32> = hits.iter().map(|h| h.score).collect();
        for window in scores.windows(2) {
            assert!(
                window[0] >= window[1],
                "hits must be in descending score order: {:?}",
                scores
            );
        }
    }

    /// `search_bounded(cap)` must return EXACTLY the same top-`cap` hits (same
    /// order, same scores) as the legacy `execute() + sort_unstable() +
    /// truncate(cap)`, and its reported `total` must equal the full match count
    /// regardless of `cap`.  Exercises both the streaming leaf-`Term` path and
    /// the `execute()`-then-drain compound (`Bool`) path.
    #[test]
    fn search_bounded_matches_legacy_topk_and_total() {
        let dir = TempDir::new().unwrap();
        let searcher = setup_searcher(dir.path());

        // Two query shapes with a MULTI-score match set:
        //  - Term "fox": docs 0,1,4 with distinct BM25 (doc 4 TF=4 ranks top).
        //  - Bool should(fox|quick|lazy): a wider, differently-scored set that
        //    routes through execute()-then-drain, not the streaming leaf.
        let term_q = Query::Term(TermQuery::new("body", "fox"));
        let bool_q = Query::Bool(Box::new(
            BoolQuery::new()
                .should(Query::Term(TermQuery::new("body", "fox")))
                .should(Query::Term(TermQuery::new("body", "quick")))
                .should(Query::Term(TermQuery::new("body", "lazy"))),
        ));

        for q in [&term_q, &bool_q] {
            // Legacy reference: usize::MAX keeps the full-set sort path.
            let full = searcher.search(q, usize::MAX, false).unwrap();
            let total_full = full.len() as u64;
            assert!(total_full >= 3, "query should match several docs");

            // Order must already be strictly non-increasing by score.
            for w in full.windows(2) {
                assert!(w[0].score >= w[1].score);
            }

            for cap in [
                0usize,
                1,
                2,
                3,
                total_full as usize,
                total_full as usize + 5,
            ] {
                let (bounded, total) = searcher.search_bounded(q, cap, false).unwrap();

                // (1) Exact total is independent of the page cap.
                assert_eq!(
                    total, total_full,
                    "bounded total must equal full match count at cap={cap}"
                );

                // (2) Top-`cap` is byte-identical to legacy sort+truncate.
                let expected: Vec<(u32, u32)> = full
                    .iter()
                    .take(cap)
                    .map(|h| (h.doc_id, h.score.to_bits()))
                    .collect();
                let got: Vec<(u32, u32)> = bounded
                    .iter()
                    .map(|h| (h.doc_id, h.score.to_bits()))
                    .collect();
                assert_eq!(
                    got, expected,
                    "bounded top-{cap} must match legacy sort+truncate (doc_id+score)"
                );
            }
        }
    }

    /// Corpus sized to make the WAND bound actually bite: one term in every
    /// document (low idf → a tiny score upper bound) beside one term in three
    /// documents (high idf → the only scores that can fill a page).
    ///
    /// Returns the searcher.
    fn wand_fixture(dir: &std::path::Path) -> FtsSearcher {
        let registry = Arc::new(AnalyzerRegistry::default());
        let mut writer = FtsIndexWriter::new(dir, "seg0", Arc::clone(&registry));
        writer.configure_field(
            "body",
            FieldIndexConfig {
                analyzer: "whitespace".to_owned(),
                ..Default::default()
            },
        );
        for i in 0..300u32 {
            // Docs 0..3 carry "needle"; every doc carries "the". Lengths vary
            // so `field_length` lookups differ across the walk.
            let text = if i < 3 {
                format!("the needle pad{i}")
            } else {
                format!("the pad{i} filler{}", i % 7)
            };
            let fields: HashMap<String, FieldValues> =
                [("body".to_owned(), FieldValues::from(text))]
                    .into_iter()
                    .collect();
            writer.add_document(i, &fields);
        }
        writer.finish().unwrap();
        let reader = Arc::new(FtsIndexReader::open(dir, "seg0", &["body"]).unwrap());
        FtsSearcher::new(reader, registry)
    }

    /// The WAND path (`search_bounded` on a should-only bool of terms) must be
    /// indistinguishable from the generic path — same hits, same order,
    /// **bit-identical scores**, same exact total — on a corpus where the
    /// pruning branch genuinely fires, and it must fire by construction, not
    /// by luck.
    ///
    /// The pruning precondition is ASSERTED, not assumed (the lesson of
    /// `bool_deadline_never_broadens_a_must_not`): once the page holds the
    /// three needle docs, a "the"-only doc can enter only if
    /// `idf(the)·(k1+1) ≥ worst-retained-score` — and this test fails loudly
    /// if that ever stops holding, because then the 297 pruning decisions it
    /// relies on would not have happened and the equivalence above would be
    /// passing vacuously over the same docs the legacy test already covers.
    #[test]
    fn wand_should_bool_matches_generic_path_when_pruning_fires() {
        let dir = TempDir::new().unwrap();
        let searcher = wand_fixture(dir.path());

        let q = Query::Bool(Box::new(
            BoolQuery::new()
                .should(Query::Term(TermQuery::new("body", "the")))
                .should(Query::Term(TermQuery::new("body", "needle"))),
        ));

        // Reference: usize::MAX never takes the WAND path, so this is the
        // generic walk's answer in full.
        let full = searcher.search(&q, usize::MAX, false).unwrap();
        assert_eq!(full.len(), 300, "every doc matches 'the'");
        for w in full.windows(2) {
            assert!(w[0].score >= w[1].score);
        }

        // --- the non-vacuity precondition ---
        // The three needle docs must be the page at cap=3, and the common
        // term's score supremum must sit strictly below that page's worst —
        // exactly the comparison the walk makes for each of the 297
        // "the"-only docs.
        assert_eq!(
            full[..3].iter().map(|h| h.doc_id).collect::<Vec<_>>(),
            vec![0, 1, 2],
            "the three needle docs must lead the ranking"
        );
        let bm25 = searcher.make_scorer("body");
        let the_df = searcher.scoring_df("body", "the", 300);
        let the_ubound = bm25.idf(the_df) * (bm25.k1 + 1.0);
        assert!(
            the_ubound < full[2].score,
            "precondition: 'the'-only docs (bound {the_ubound:.4}) must be prunable \
             against the cap-3 page (worst {:.4}) — otherwise this test exercises \
             no pruning",
            full[2].score
        );

        for cap in [0usize, 1, 2, 3, 5, 300, 305] {
            let (bounded, total) = searcher.search_bounded(&q, cap, false).unwrap();
            assert_eq!(total, 300, "exact total must survive pruning at cap={cap}");
            let expected: Vec<(u32, u32)> = full
                .iter()
                .take(cap)
                .map(|h| (h.doc_id, h.score.to_bits()))
                .collect();
            let got: Vec<(u32, u32)> = bounded
                .iter()
                .map(|h| (h.doc_id, h.score.to_bits()))
                .collect();
            assert_eq!(
                got, expected,
                "WAND top-{cap} must be byte-identical to the generic path"
            );
        }
    }

    /// Clause shapes that must NOT take the WAND path (`min_should_match > 1`,
    /// `must` beside `should`, a non-`Term` should clause) still get correct
    /// bounded answers — the shape guard falls them through to the generic
    /// walk, and this pins that the fallthrough, not just the guard, is right.
    #[test]
    fn wand_should_bool_falls_back_for_richer_shapes() {
        let dir = TempDir::new().unwrap();
        let searcher = wand_fixture(dir.path());

        let shapes: Vec<(&str, Query)> = vec![
            (
                "min_should_match=2",
                Query::Bool(Box::new(
                    BoolQuery::new()
                        .should(Query::Term(TermQuery::new("body", "the")))
                        .should(Query::Term(TermQuery::new("body", "needle")))
                        .min_should_match(2),
                )),
            ),
            (
                "must + should",
                Query::Bool(Box::new(
                    BoolQuery::new()
                        .must(Query::Term(TermQuery::new("body", "needle")))
                        .should(Query::Term(TermQuery::new("body", "the"))),
                )),
            ),
            (
                "non-Term should clause",
                Query::Bool(Box::new(
                    BoolQuery::new()
                        .should(Query::Term(TermQuery::new("body", "the")))
                        .should(Query::Prefix(PrefixQuery::new("body", "needl"))),
                )),
            ),
        ];

        for (name, q) in &shapes {
            let full = searcher.search(q, usize::MAX, false).unwrap();
            assert!(!full.is_empty(), "{name}: fixture must match something");
            for cap in [0usize, 1, 2, 3, 10, full.len(), full.len() + 5] {
                let (bounded, total) = searcher.search_bounded(q, cap, false).unwrap();
                assert_eq!(total, full.len() as u64, "{name}: total at cap={cap}");
                let expected: Vec<(u32, u32)> = full
                    .iter()
                    .take(cap)
                    .map(|h| (h.doc_id, h.score.to_bits()))
                    .collect();
                let got: Vec<(u32, u32)> = bounded
                    .iter()
                    .map(|h| (h.doc_id, h.score.to_bits()))
                    .collect();
                assert_eq!(got, expected, "{name}: top-{cap}");
            }
        }
    }

    /// The WAND path's own clause bookkeeping on the awkward-but-legal edges:
    /// a DUPLICATE term (two cursors over the same postings, both must land in
    /// the clause-order sum), a boosted term (the bound must carry the boost
    /// or pruning would over-prune), an absent term (dropped like the generic
    /// path's empty per-clause vec), and a bool-level boost (applied exactly
    /// where the generic path applies it).
    #[test]
    fn wand_should_bool_duplicate_boosted_absent_and_bool_boost() {
        let dir = TempDir::new().unwrap();
        let searcher = wand_fixture(dir.path());

        let mut tq_dup = TermQuery::new("body", "needle");
        tq_dup.boost = 2.0;
        let q = Query::Bool(Box::new(
            BoolQuery::new()
                .should(Query::Term(tq_dup))
                // duplicate clause over the same postings, default boost
                .should(Query::Term(TermQuery::new("body", "needle")))
                .should(Query::Term(TermQuery::new("body", "the")))
                // absent from every doc
                .should(Query::Term(TermQuery::new("body", "absentterm")))
                .boost(1.5),
        ));

        let full = searcher.search(&q, usize::MAX, false).unwrap();
        assert_eq!(full.len(), 300, "the still matches everything");
        // The duplicate must actually double-count: each needle doc's score
        // here exceeds the same doc's single-needle score by roughly the
        // single contribution (boost 2.0 + 1.0 = 3× vs 1×).
        let single = Query::Bool(Box::new(
            BoolQuery::new().should(Query::Term(TermQuery::new("body", "needle"))),
        ));
        let single_hits = searcher.search(&single, usize::MAX, false).unwrap();
        let s0 = single_hits.iter().find(|h| h.doc_id == 0).unwrap().score;
        let d0 = full.iter().find(|h| h.doc_id == 0).unwrap().score;
        assert!(
            d0 > s0 * 4.0,
            "duplicate + 2.0 boost + 1.5 bool boost must compound: {d0:.4} vs {s0:.4}"
        );

        for cap in [0usize, 1, 2, 3, 7, 300] {
            let (bounded, total) = searcher.search_bounded(&q, cap, false).unwrap();
            assert_eq!(total, 300, "total at cap={cap}");
            let expected: Vec<(u32, u32)> = full
                .iter()
                .take(cap)
                .map(|h| (h.doc_id, h.score.to_bits()))
                .collect();
            let got: Vec<(u32, u32)> = bounded
                .iter()
                .map(|h| (h.doc_id, h.score.to_bits()))
                .collect();
            assert_eq!(
                got, expected,
                "top-{cap} with duplicate/boosted/absent clauses"
            );
        }
    }

    /// Micro-bench (ignored by default; run with `--ignored`): the WAND path
    /// vs the generic bounded walk on a stopword-heavy disjunction over a
    /// 200k-doc synthetic index — the shape that motivated the fast path.
    /// `WAND_BENCH="clauses,cap"` (default "3,10") selects the clause count
    /// and page size; `WAND_BENCH="1,0"` measures the pure walk (nothing ever
    /// scored).  Asserts result equivalence once so the timing cannot silently
    /// drift onto unequal answers.
    #[test]
    #[ignore]
    fn bench_wand_vs_generic_stopword_disjunction() {
        let cfg = std::env::var("WAND_BENCH").unwrap_or_else(|_| "3,10".to_owned());
        let (nclauses, cap): (usize, usize) = {
            let mut it = cfg.split(',');
            (
                it.next().unwrap_or("3").parse().unwrap(),
                it.next().unwrap_or("10").parse().unwrap(),
            )
        };
        let dir = tempfile::TempDir::new().unwrap();
        let registry = Arc::new(AnalyzerRegistry::default());
        let mut writer = FtsIndexWriter::new(dir.path(), "seg0", Arc::clone(&registry));
        writer.configure_field(
            "body",
            FieldIndexConfig {
                analyzer: "whitespace".to_owned(),
                ..Default::default()
            },
        );
        const N: u32 = 200_000;
        let stops = ["the", "of", "and", "to", "in", "is"];
        for i in 0..N {
            // Terms of full df (the "stopwords"), a graded mid-df term, and
            // unique padding for realistic lengths.
            let mid = if i % 4 == 0 { "mid" } else { "pad" };
            let text = format!(
                "{} {mid} u{i}",
                stops[..nclauses.min(stops.len())].join(" ")
            );
            let fields: HashMap<String, FieldValues> =
                [("body".to_owned(), FieldValues::from(text))]
                    .into_iter()
                    .collect();
            writer.add_document(i, &fields);
        }
        writer.finish().unwrap();
        let reader = Arc::new(FtsIndexReader::open(dir.path(), "seg0", &["body"]).unwrap());
        let searcher = FtsSearcher::new(reader, registry);

        let mut bq = BoolQuery::new();
        for t in &stops[..nclauses.min(stops.len())] {
            bq = bq.should(Query::Term(TermQuery::new("body", *t)));
        }
        let q = Query::Bool(Box::new(bq));
        const REPS: u32 = 20;
        let _ = searcher.search_bounded(&q, cap, false).unwrap(); // warm
        let mut wand_us = 0f64;
        for _ in 0..REPS {
            let t0 = std::time::Instant::now();
            let _ = searcher.search_bounded(&q, cap, false).unwrap();
            wand_us += t0.elapsed().as_secs_f64() * 1e6;
        }
        let (g_hits, g_total) = searcher
            .search_bounded_observed(&q, cap, false, |_| {})
            .unwrap();
        let mut gen_us = 0f64;
        for _ in 0..REPS {
            let t0 = std::time::Instant::now();
            let _ = searcher
                .search_bounded_observed(&q, cap, false, |_| {})
                .unwrap();
            gen_us += t0.elapsed().as_secs_f64() * 1e6;
        }
        let (w_hits, w_total) = searcher.search_bounded(&q, cap, false).unwrap();
        assert_eq!(w_total, g_total);
        assert_eq!(
            w_hits
                .iter()
                .map(|h| (h.doc_id, h.score.to_bits()))
                .collect::<Vec<_>>(),
            g_hits
                .iter()
                .map(|h| (h.doc_id, h.score.to_bits()))
                .collect::<Vec<_>>(),
        );
        println!(
            "{nclauses}-stopword disjunction over {N} docs (df={N} each), cap={cap}: \
             generic {gen_us:.0} µs vs WAND {wand_us:.0} µs ({:.1}×), total={w_total}",
            gen_us / wand_us
        );
    }
}