From f36b1f7e92adb7adb54e4462da7da83eb7874870 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B6ren=20Brunk?= Date: Tue, 8 Sep 2026 11:40:49 +0200 Subject: [PATCH 1/2] perf(fts): prune combined_fields scoring with MAXSCORE The combined_fields scan scored every row that contains any query term. For top-k queries it now skips rows that cannot reach the current k-th score. Each term gets a fixed upper bound, `idf' * BM25_DOC_WEIGHT_UPPER_BOUND`, the cap `doc_weight` already clamps to. As in Lucene's `CombinedFieldQuery`, the bound is per term, not per block, because blending columns makes a per-block maximum meaningless. Terms whose bounds together cannot beat the k-th score no longer produce candidates and are only looked up for rows found through the other terms. The prune check reuses `wand::score_sum_cannot_compete`. Results are identical to the full scan. Candidates are found in row id order, so a row that only ties the k-th score would lose the tie anyway, and pruning it changes nothing. `MaxscoreStats` counts found, pruned and scored candidates. It is only exposed to tests and, through the new `test-scan-stats` feature, to benches via `combined_fields_search_with_stats`. The normal query path is unchanged. --- rust/lance-index/Cargo.toml | 4 + rust/lance-index/src/scalar/inverted.rs | 4 + .../src/scalar/inverted/combined.rs | 11 +- .../src/scalar/inverted/combined/cursor.rs | 148 ++++- .../src/scalar/inverted/combined/maxscore.rs | 536 ++++++++++++++++++ .../src/scalar/inverted/combined/search.rs | 203 +++++-- .../src/scalar/inverted/combined/testing.rs | 75 ++- rust/lance-index/src/scalar/inverted/wand.rs | 4 +- 8 files changed, 903 insertions(+), 82 deletions(-) create mode 100644 rust/lance-index/src/scalar/inverted/combined/maxscore.rs diff --git a/rust/lance-index/Cargo.toml b/rust/lance-index/Cargo.toml index 54d3094fe87..4836969e3d5 100644 --- a/rust/lance-index/Cargo.toml +++ b/rust/lance-index/Cargo.toml @@ -104,6 +104,10 @@ tokenizer-jieba = ["dep:jieba-rs", "lance-tokenizer/tokenizer-jieba"] # Exposes `scalar::inverted::oracle`, the brute-force scoring reference, to # downstream test and bench targets. Enable it as a dev-dependency feature only. test-oracle = [] +# Exposes `scalar::inverted::combined_fields_search_with_stats` and the +# `MaxscoreStats` it returns, so a bench can report how much candidate scoring +# the MAXSCORE pruning saves. Enable it as a dev-dependency feature only. +test-scan-stats = [] [build-dependencies] prost-build.workspace = true diff --git a/rust/lance-index/src/scalar/inverted.rs b/rust/lance-index/src/scalar/inverted.rs index 364b8df3251..f2fe3bba9e1 100644 --- a/rust/lance-index/src/scalar/inverted.rs +++ b/rust/lance-index/src/scalar/inverted.rs @@ -33,6 +33,10 @@ pub use combined::{ CombinedCorpusStats, CombinedFieldColumn, FlatFieldStats, build_combined_bm25_scorer, combined_fields_search, flat_combined_fields_search_stream, validate_combined_tokenizers, }; +/// The `combined_fields` MAXSCORE pruning counters, for tests and benches. Never +/// reachable on a normal build; see the `test-scan-stats` feature. +#[cfg(any(test, feature = "test-scan-stats"))] +pub use combined::{MaxscoreStats, combined_fields_search_with_stats}; pub use compound::{ compound_search, compound_search_prepared_match, compound_search_prepared_match_with_score_floor, compound_search_with_base_scorer, diff --git a/rust/lance-index/src/scalar/inverted/combined.rs b/rust/lance-index/src/scalar/inverted/combined.rs index e48f245b8a0..7f02c424ba6 100644 --- a/rust/lance-index/src/scalar/inverted/combined.rs +++ b/rust/lance-index/src/scalar/inverted/combined.rs @@ -19,11 +19,14 @@ //! ``` //! //! Scoring uses exact (non-quantized) document lengths and a shared tokenizer -//! across columns. Every candidate in the union of the query terms' postings is -//! scored; see [`combined_fields_search`]. +//! across columns. A term-at-a-time MAXSCORE (Lucene `CombinedFieldQuery`'s +//! constant per-term ceiling, ordinary MAXSCORE across terms) prunes candidate +//! scoring for a top-k query without changing the top-k it returns; see +//! [`combined_fields_search`]. mod cursor; mod flat; +mod maxscore; mod search; mod stats; #[cfg(test)] @@ -37,6 +40,10 @@ use lance_select::RowAddrTreeMap; pub use flat::flat_combined_fields_search_stream; pub use search::combined_fields_search; pub use stats::{CombinedCorpusStats, FlatFieldStats, build_combined_bm25_scorer}; +// The MAXSCORE candidate counters, for test and bench targets only; see the +// `test-scan-stats` feature. +#[cfg(any(test, feature = "test-scan-stats"))] +pub use {maxscore::MaxscoreStats, search::combined_fields_search_with_stats}; use super::index::InvertedIndex; use super::query::Tokens; diff --git a/rust/lance-index/src/scalar/inverted/combined/cursor.rs b/rust/lance-index/src/scalar/inverted/combined/cursor.rs index 33f538364f2..49ba4997292 100644 --- a/rust/lance-index/src/scalar/inverted/combined/cursor.rs +++ b/rust/lance-index/src/scalar/inverted/combined/cursor.rs @@ -1,9 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The Lance Authors -//! Per-term cross-column postings for `combined_fields`: one term's postings -//! merged across every target column into the shared row-id space, and the -//! loaded posting sources they are built from. +//! Per-term cross-column cursors for `combined_fields`: the [`TermCursor`] +//! abstraction, its full-read implementation, and the loaded posting sources it +//! is built from. use std::collections::HashMap; use std::sync::Arc; @@ -13,6 +13,37 @@ use lance_select::RowAddrMask; use super::super::documents::AddressKeyedDocuments; use super::super::index::{PostingList, live_posting_rows}; use super::super::scorer::CombinedFieldsBM25Scorer; +use super::maxscore::term_upper_bound; + +/// The MAXSCORE loop's view of one query term. [`MaterializedTerm`] implements it +/// by reading every posting up front; the trait keeps +/// [`combined_maxscore`](super::maxscore::combined_maxscore) independent of how a +/// `tf'` is fetched, so a lazier cursor can be substituted without touching the +/// algorithm. +/// +/// A term exposes a merged cross-column cursor over the shared row-id space: +/// [`head`](Self::head) is the smallest not-yet-consumed row id, advanced by +/// the essential terms during discovery; [`probe`](Self::probe) reads `tf'` at +/// an arbitrary (non-decreasing) target for the non-essential terms. +pub(super) trait TermCursor { + /// The constant per-term ceiling `idf · MAX_DOC_WEIGHT` (clamped, see + /// [`term_upper_bound`]). + fn upper_bound(&self) -> f32; + /// The blended IDF `idf'(t)`. + fn idf(&self) -> f32; + /// The smallest not-yet-consumed row id across the term's columns, or + /// `None` when the term is exhausted. + fn head(&self) -> Option; + /// `tf'` at [`head`](Self::head) (the weighted sum across the columns that + /// carry the head row id). Only meaningful while `head()` is `Some`. + fn head_tf(&self) -> f32; + /// Consume `row_id`: advance every column cursor currently sitting on it. + /// Called only for `row_id == head()`. + fn consume(&mut self, row_id: u64); + /// `tf'` at `target`, or 0 when the term is absent there. `target` never + /// decreases across calls to one cursor, so the lazy path can skip blocks. + fn probe(&mut self, target: u64) -> f32; +} /// One query term's postings, merged across every target column/partition into /// the shared row-id space. @@ -21,6 +52,7 @@ use super::super::scorer::CombinedFieldsBM25Scorer; /// frequency `tf'(t, d) = Σ_f w_f · freq_f(t, d)`. pub(super) struct CombinedTermPostings { pub(super) idf: f32, + pub(super) upper_bound: f32, pub(super) postings: Vec<(u64, f32)>, } @@ -35,6 +67,59 @@ impl CombinedTermPostings { } } +/// [`TermCursor`] over a [`CombinedTermPostings`] with an owned scan cursor. +pub(super) struct MaterializedTerm { + pub(super) postings: CombinedTermPostings, + cursor: usize, +} + +impl MaterializedTerm { + pub(super) fn new(postings: CombinedTermPostings) -> Self { + Self { + postings, + cursor: 0, + } + } +} + +impl TermCursor for MaterializedTerm { + #[inline] + fn upper_bound(&self) -> f32 { + self.postings.upper_bound + } + + #[inline] + fn idf(&self) -> f32 { + self.postings.idf + } + + #[inline] + fn head(&self) -> Option { + self.postings.postings.get(self.cursor).map(|(id, _)| *id) + } + + #[inline] + fn head_tf(&self) -> f32 { + self.postings + .postings + .get(self.cursor) + .map(|(_, tf)| *tf) + .unwrap_or(0.0) + } + + #[inline] + fn consume(&mut self, row_id: u64) { + if self.head() == Some(row_id) { + self.cursor += 1; + } + } + + #[inline] + fn probe(&mut self, target: u64) -> f32 { + self.postings.tf_prime(target) + } +} + /// A `(column, index, partition)` posting source loaded for one term. pub(super) struct LoadedSource { pub(super) weight: f32, @@ -43,14 +128,14 @@ pub(super) struct LoadedSource { pub(super) posting: PostingList, } -/// Merge every source's postings for `term` into the shared row-id space, -/// accumulating `tf'` in the canonical order. -pub(super) fn build_term_postings( +/// Build the full-read cursor for `term` by merging every source's postings into +/// the shared row-id space, accumulating `tf'` in the canonical order. +pub(super) fn build_materialized_term( term: &str, sources: Vec, mask: &Arc, scorer: &CombinedFieldsBM25Scorer, -) -> CombinedTermPostings { +) -> MaterializedTerm { let mut acc: HashMap = HashMap::new(); for source in &sources { for (row_id, freq) in live_posting_rows(&source.posting, &source.docs, source.is_legacy) { @@ -63,19 +148,25 @@ pub(super) fn build_term_postings( let idf = scorer.query_weight(term); let mut postings: Vec<(u64, f32)> = acc.into_iter().collect(); postings.sort_unstable_by_key(|(row_id, _)| *row_id); - CombinedTermPostings { idf, postings } + MaterializedTerm::new(CombinedTermPostings { + idf, + upper_bound: term_upper_bound(idf), + postings, + }) } #[cfg(test)] mod tests { + use super::super::maxscore::combined_maxscore; use super::super::testing::{compressed_list, modern_identity_docs}; use super::*; use lance_core::utils::address::RowAddress; use lance_select::RowAddrTreeMap; + use std::cmp::Reverse; #[tokio::test] - async fn test_build_term_postings_merges_legacy_and_compressed() { - // A legacy (Plain, row-id-keyed, list-multiplicity) + async fn test_build_materialized_term_merges_legacy_and_compressed() { + // Fallback data path: a legacy (Plain, row-id-keyed, list-multiplicity) // source and a compressed source merge into one ordered `tf'` stream, // masked rows dropped and contributions summed in column order. use super::super::super::index::PlainPostingList; @@ -110,20 +201,25 @@ mod tests { }, ]; let mask = Arc::new(RowAddrMask::all_rows().also_block(RowAddrTreeMap::from_iter([42u64]))); - let term = build_term_postings("t", sources, &mask, &scorer); + let term = build_materialized_term("t", sources, &mask, &scorer); // row 10: 2*1 = 2; row 20: 2*2 + 2*3 + 1*5 = 15; row 30: 2*1 = 2. // Row 42 is masked out entirely. - assert_eq!(term.postings, vec![(10, 2.0), (20, 15.0), (30, 2.0)]); + assert_eq!( + term.postings.postings, + vec![(10, 2.0), (20, 15.0), (30, 2.0)] + ); } #[tokio::test] - async fn test_build_term_postings_skips_tombstoned_addresses() { + async fn test_build_materialized_term_skips_tombstoned_addresses() { // A remapped partition keeps a deleted document's DocId slot so the // posting lists stay aligned and answers `TOMBSTONE_ROW` for its address. // Nothing else stops that address: a default mask is an empty block list, // which selects it, and `doc_length_at(TOMBSTONE_ROW) == 0` would give it - // the largest `doc_weight` there is, so it must be dropped at the source. + // the largest `doc_weight` there is. It stays out of the result today only + // because `TOMBSTONE_ROW == u64::MAX` collides with `combined_maxscore`'s + // exhausted-cursor sentinel, so it must be dropped at the source. const DEAD_ROW: u64 = 20; let scorer = CombinedFieldsBM25Scorer::new(1000, 12.0, HashMap::new()); let docs = modern_identity_docs(&[4u32; 40], &[DEAD_ROW]).await; @@ -135,7 +231,7 @@ mod tests { assert_eq!(docs.doc_length_at(RowAddress::TOMBSTONE_ROW), 0); let sources = vec![LoadedSource { weight: 2.0, - docs, + docs: docs.clone(), is_legacy: false, posting: PostingList::Compressed(compressed_list(&[ (10, 1), @@ -143,12 +239,30 @@ mod tests { (30, 3), ])), }]; - let term = build_term_postings("t", sources, &Arc::new(RowAddrMask::default()), &scorer); + let term = + build_materialized_term("t", sources, &Arc::new(RowAddrMask::default()), &scorer); assert_eq!( - term.postings, + term.postings.postings, vec![(10, 2.0), (30, 6.0)], "the tombstoned address must never be accumulated, and the live rows \ must keep their exact contributions" ); + + // Nor may it be collected: the two live rows are the whole top-k, scored + // exactly as if the dead slot's posting did not exist. + // + // `test_scorer` carries no document frequencies, so `query_weight` is 0 for + // every term and both rows score 0. The order is therefore the tiebreak, + // ascending by row id. + let mut cursors = vec![term]; + let dl_prime = |row_id: u64| -> f32 { 2.0 * docs.doc_length_at(row_id) as f32 }; + let (top, _) = combined_maxscore(&mut cursors, dl_prime, 10, false, &scorer); + let hits: Vec<(u64, u32)> = top + .into_sorted_vec() + .into_iter() + .map(|Reverse(doc)| (doc.row_id.0, doc.score.0.to_bits())) + .collect(); + let expected = |tf: f32| (scorer.query_weight("t") * scorer.doc_weight(tf, 8.0)).to_bits(); + assert_eq!(hits, vec![(10, expected(2.0)), (30, expected(6.0))]); } } diff --git a/rust/lance-index/src/scalar/inverted/combined/maxscore.rs b/rust/lance-index/src/scalar/inverted/combined/maxscore.rs new file mode 100644 index 00000000000..b96f35ebaeb --- /dev/null +++ b/rust/lance-index/src/scalar/inverted/combined/maxscore.rs @@ -0,0 +1,536 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +//! The term-at-a-time MAXSCORE loop shared by both `combined_fields` term +//! cursors, its per-term score ceiling, and its candidate-work accounting. + +use std::cmp::Reverse; +use std::collections::BinaryHeap; + +use super::super::scorer::{BM25_DOC_WEIGHT_UPPER_BOUND, CombinedFieldsBM25Scorer}; +use super::super::wand::{ + CompetitiveFloorMode, score_sum_cannot_compete, score_sum_upper_bound_factor, +}; +use super::cursor::TermCursor; +use super::search::RankedDoc; + +/// The constant per-term BM25F score ceiling, clamped to 0 when the term cannot +/// raise a score (`idf <= 0`). +/// +/// Lucene's `CombinedFieldQuery::getMaxScore` uses `idf · (K1 + 1)` because BM25 +/// saturates the `tf'` factor at `K1 + 1`. That product is not an upper bound +/// in f32: the evaluated weight can land above it, and a ceiling one ULP short +/// is enough for MAXSCORE to drop a document that outscores the running k-th (a +/// one-term `limit = 1` query suffices; see +/// `test_combined_maxscore_ceiling_is_conservative`). Scaling by +/// [`BM25_DOC_WEIGHT_UPPER_BOUND`] instead keeps +/// `term_upper_bound(idf) >= idf · doc_weight(tf', dl')` for every `tf'` / `dl'`, +/// because `doc_weight` clamps to that ceiling and `x -> fl(idf · x)` is +/// monotone for `idf >= 0`. +#[inline] +pub(super) fn term_upper_bound(idf: f32) -> f32 { + if idf > 0.0 { + idf * BM25_DOC_WEIGHT_UPPER_BOUND + } else { + 0.0 + } +} + +/// Candidate-work accounting for one MAXSCORE run: the scoring-side work the +/// essential/non-essential split saves. +/// +/// Per-candidate bookkeeping does not belong on the production +/// `MetricsCollector`, so this never leaves the crate on a normal build: the +/// `maxscore` module is private and only `cfg(test)` or the `test-scan-stats` +/// feature re-exports it, alongside `combined_fields_search_with_stats`. The +/// unit tests below are what keep the pruning honest: a gate that never fired +/// would leave every score correct and silently do nothing. +#[derive(Default, Debug, Clone, Copy)] +pub struct MaxscoreStats { + /// Candidates pulled from the essential terms' cursors. + pub discovered: u64, + /// Discovered candidates skipped by the upper-bound test (no length lookup, + /// no non-essential probe, no full score). + pub pruned: u64, + /// Candidates fully scored. + pub scored: u64, +} + +/// Term-at-a-time MAXSCORE over the cross-field combined postings. +/// +/// Terms are ordered ascending by their constant ceiling `upper_bound`. Once the +/// heap holds `limit` docs, the leading prefix whose cumulative ceiling cannot +/// beat the k-th score (`threshold`) becomes non-essential: candidate discovery +/// walks the essential terms' cursors alone, and a candidate is skipped whole +/// (no length lookup, no probe) when the essential terms it matches plus every +/// non-essential ceiling still cannot beat `threshold`. `threshold` only rises, +/// so a term never returns to essential once it crosses over. +/// +/// Every surviving candidate is scored exactly, summing `idf'(t) · +/// doc_weight(tf', dl')` over the terms in their original order, with `dl_prime` +/// supplying the blended length. Absent terms add `doc_weight(0, ·) == 0`, so the +/// score is bit-identical to the exact scan, which skips them. +/// +/// Both prunes only ever drop a candidate whose exact `score` is provably +/// `<= threshold`, i.e. one the collector would have rejected anyway, so the top-k +/// is the exact scan's top-k. That rests on two f32 facts, neither of which holds +/// for the textbook `idf · (K1 + 1)` ceiling: the per-term ceiling dominates every +/// per-term contribution ([`term_upper_bound`] over a clamped `doc_weight`), and +/// summing those ceilings is widened enough to dominate the differently-ordered f32 +/// summation that produces `score` ([`score_sum_upper_bound_factor`]). +/// +/// Generic over [`TermCursor`], so the lazy and eager paths share one algorithm. +pub(super) fn combined_maxscore( + cursors: &mut [C], + dl_prime: impl Fn(u64) -> f32, + limit: usize, + require_all_terms: bool, + scorer: &CombinedFieldsBM25Scorer, +) -> (BinaryHeap>, MaxscoreStats) { + let num_terms = cursors.len(); + // Term indices ordered ascending by ceiling; ties broken by index so the + // essential/non-essential split is deterministic. + let mut order: Vec = (0..num_terms).collect(); + order.sort_by(|&a, &b| { + cursors[a] + .upper_bound() + .partial_cmp(&cursors[b].upper_bound()) + .unwrap_or(std::cmp::Ordering::Equal) + .then(a.cmp(&b)) + }); + + let bound_factor = score_sum_upper_bound_factor(num_terms); + + let mut top: BinaryHeap> = BinaryHeap::new(); + let mut stats = MaxscoreStats::default(); + // The current k-th score; pruning is armed only once the heap is full. + let mut threshold = f32::NEG_INFINITY; + // Per-term score contributions, reused across candidates. Every scored + // candidate overwrites all slots before it is summed. + let mut contrib = vec![0.0f32; num_terms]; + + loop { + // Split `order` into non-essential (a leading prefix whose widened + // cumulative ceiling <= threshold) and essential. Recomputed each step + // because `threshold` may have risen. + let mut nonessential_upper_bound = 0.0f64; + let split = if top.len() < limit { + 0 + } else { + let mut cumulative = 0.0f64; + let mut boundary = 0; + while boundary < num_terms { + let bound = f64::from(cursors[order[boundary]].upper_bound()); + if score_sum_cannot_compete( + 0.0, + cumulative + bound, + threshold, + bound_factor, + CompetitiveFloorMode::Exclusive, + ) { + cumulative += bound; + boundary += 1; + } else { + break; + } + } + nonessential_upper_bound = cumulative; + boundary + }; + + // Next candidate = smallest row id at any essential term's cursor. Docs + // that match only non-essential terms are never discovered: their score is + // at most the widened `nonessential_upper_bound`, hence `<= threshold`, + // which the score-only strict-`<` collector could not admit anyway. + let mut doc = u64::MAX; + for &term in &order[split..] { + if let Some(row_id) = cursors[term].head() { + doc = doc.min(row_id); + } + } + if doc == u64::MAX { + break; // essential terms exhausted (or all terms non-essential) + } + stats.discovered += 1; + + let dl = dl_prime(doc); + // Exact contribution of the essential terms, consuming each cursor that + // sits on `doc`. The widened `essential_score + nonessential_upper_bound` + // then dominates the full `score`, so the prune below is safe (see this + // function's doc comment). + // + // The prune stays `Exclusive` (reject on `upper_bound <= threshold`) even + // though the collector now orders on `(score DESC, row_id ASC)`. A + // candidate that merely ties the k-th score cannot belong in the top-k + // here: `doc` only ever increases, so every candidate reaching this point + // has a higher row id than every incumbent, and an incumbent tied at + // `threshold` therefore wins the tiebreak. Rejecting on the tie is what the + // collector below does too, so the prune drops nothing the collector would + // have kept. See `test_combined_maxscore_ties_keep_lowest_row_ids`. + let mut essential_score = 0.0f32; + let mut missing_term = false; + for &term in &order[split..] { + let tf = if cursors[term].head() == Some(doc) { + let tf = cursors[term].head_tf(); + cursors[term].consume(doc); + tf + } else { + 0.0 + }; + missing_term |= tf <= 0.0; + contrib[term] = cursors[term].idf() * scorer.doc_weight(tf, dl); + essential_score += contrib[term]; + } + if top.len() >= limit + && score_sum_cannot_compete( + essential_score, + nonessential_upper_bound, + threshold, + bound_factor, + CompetitiveFloorMode::Exclusive, + ) + { + stats.pruned += 1; + continue; + } + + // Probe the non-essential terms on demand to complete the exact score. + // `doc` increases monotonically, so each probe seeks forward. + for &term in &order[..split] { + let tf = cursors[term].probe(doc); + missing_term |= tf <= 0.0; + contrib[term] = cursors[term].idf() * scorer.doc_weight(tf, dl); + } + if require_all_terms && missing_term { + continue; + } + stats.scored += 1; + + // Sum in original term order so the score is bit-identical to the exact + // scan. + let score: f32 = contrib.iter().sum(); + + // The replacement test stays score-only and strict, which is what + // `CompetitiveFloorMode::Exclusive` prunes against: a candidate that only + // ties the k-th score never displaces an incumbent, so pruning one is + // sound. [`RankedDoc`] does not weaken that. `doc` increases + // monotonically, so a tied candidate always carries the higher row id and + // would lose the tiebreak too; ordering the heap on `(score, row_id)` only + // fixes which of the retained ties comes out first. + if top.len() < limit { + top.push(Reverse(RankedDoc::new(doc, score))); + if top.len() == limit { + threshold = top.peek().expect("heap is full").0.score.0; + } + } else if top.peek().is_some_and(|worst| worst.0.score.0 < score) { + top.pop(); + top.push(Reverse(RankedDoc::new(doc, score))); + threshold = top.peek().expect("heap is full").0.score.0; + } + } + + (top, stats) +} + +#[cfg(test)] +mod tests { + use super::super::super::scorer::{K1, idf}; + use super::super::testing::{dl_of, exact_topk_scores, maxscore_scores, term, test_scorer}; + use super::*; + use std::collections::HashMap; + + #[test] + fn test_combined_maxscore_matches_exact_scan_or() { + let scorer = test_scorer(); + // Skewed idf: a rare high-value term, a medium term, a very common term. + let build = || { + [ + term(5.0, &[(1, 3.0), (2, 1.0), (3, 2.0), (17, 1.0)]), + term(1.5, &[(1, 1.0), (3, 1.0), (5, 1.0), (8, 2.0), (17, 1.0)]), + term( + 0.05, + &(0..40u64).map(|row_id| (row_id, 1.0)).collect::>(), + ), + ] + }; + // Every top-k depth must reproduce the exact scan's top-k scores, so the + // MAXSCORE pruning provably does not change the result. `limit = 20` is + // the depth where this fixture's k-th score ties several candidates' + // ceilings exactly, which is where a non-conservative bound would bite. + for limit in [1usize, 2, 3, 5, 10, 20, 50] { + let expected = exact_topk_scores(&build(), dl_of, limit, false, &scorer); + let (actual, _stats) = maxscore_scores(&mut build(), dl_of, limit, false, &scorer); + assert_eq!( + actual, expected, + "OR top-{limit} scores diverged from exact scan" + ); + } + } + + /// A tie group straddling the top-k cutoff must resolve to the lowest row + /// ids, in ascending order. + /// + /// This is the interaction the candidate prune has to survive: the prune and + /// the collector both reject a candidate that only ties `threshold`, and that + /// is correct precisely because discovery is ascending, so a tied newcomer + /// always loses the row-id tiebreak to the incumbents. + /// + /// `dl_of` depends on `row_id % 4`, so row ids `0, 4, 8, ...` share a blended + /// length; one term with an equal `tf'` at each then scores them all + /// identically, making the whole result one tie. + #[test] + fn test_combined_maxscore_ties_keep_lowest_row_ids() { + let scorer = test_scorer(); + let tied: Vec<(u64, f32)> = (0..6u64).map(|i| (i * 4, 1.0)).collect(); + let build = || [term(5.0, &tied)]; + + for limit in [1usize, 3, 5] { + let (top, stats) = combined_maxscore(&mut build(), dl_of, limit, false, &scorer); + let hits: Vec = top + .into_sorted_vec() + .into_iter() + .map(|Reverse(doc)| doc.row_id.0) + .collect(); + let expected: Vec = tied.iter().take(limit).map(|(row_id, _)| *row_id).collect(); + assert_eq!( + hits, expected, + "top-{limit} over a full tie must be the lowest row ids, ascending" + ); + // Every candidate was reached, so the assertion above is about which + // ties were kept rather than about candidates never being discovered. + assert_eq!( + stats.discovered, + tied.len() as u64, + "top-{limit} did not discover every tied candidate" + ); + } + } + + #[test] + fn test_combined_maxscore_matches_exact_scan_and() { + let scorer = test_scorer(); + let build = || { + [ + term(5.0, &[(1, 3.0), (2, 1.0), (3, 2.0), (17, 1.0)]), + term(1.5, &[(1, 1.0), (3, 1.0), (5, 1.0), (17, 1.0)]), + ] + }; + for limit in [1usize, 2, 3, 10] { + let expected = exact_topk_scores(&build(), dl_of, limit, true, &scorer); + let (actual, _stats) = maxscore_scores(&mut build(), dl_of, limit, true, &scorer); + assert_eq!( + actual, expected, + "AND top-{limit} scores diverged from exact scan" + ); + // AND keeps only docs that have both terms: rows 1, 3, 17. + assert!(actual.len() <= 3); + } + } + + #[test] + fn test_combined_maxscore_no_limit_is_exact_scan() { + let scorer = test_scorer(); + let build = || { + [ + term(5.0, &[(1, 3.0), (2, 1.0), (3, 2.0)]), + term(0.05, &(0..30u64).map(|r| (r, 1.0)).collect::>()), + ] + }; + // usize::MAX limit: the heap never fills, so nothing is pruned and every + // matching doc is scored, exactly like the merged scan. + let expected = exact_topk_scores(&build(), dl_of, usize::MAX, false, &scorer); + let (actual, stats) = maxscore_scores(&mut build(), dl_of, usize::MAX, false, &scorer); + assert_eq!(actual, expected); + assert_eq!(stats.pruned, 0, "no limit must not prune"); + // Union of the two terms is rows 0..30. + assert_eq!(stats.scored, 30); + } + + #[test] + fn test_combined_maxscore_discovery_pruning() { + let scorer = test_scorer(); + // A rare high-idf term whose docs sit early, and a common low-idf term + // over a huge posting list. With a small k the common term goes + // non-essential once the heap fills with the rare docs, so its ~1000 + // rows are never discovered; only the essential rare term drives + // discovery. + let build = || { + [ + term(6.0, &[(1, 3.0), (2, 3.0), (3, 3.0), (4, 3.0), (5, 3.0)]), + term(0.05, &(0..1000u64).map(|r| (r, 1.0)).collect::>()), + ] + }; + let union = 1000u64; // common covers every row + + let (actual, stats) = maxscore_scores(&mut build(), dl_of, 3, false, &scorer); + let expected = exact_topk_scores(&build(), dl_of, 3, false, &scorer); + assert_eq!( + actual, expected, + "pruned run must still match the exact top-k" + ); + + // Discovery examines only a handful of candidates, not the full union. + assert!( + stats.discovered <= 20, + "expected heavy discovery pruning, discovered {} of {union}", + stats.discovered + ); + } + + #[test] + fn test_combined_maxscore_per_candidate_pruning() { + let scorer = test_scorer(); + // Two essential terms. `a` stays essential (large ceiling) but has a + // late doc (row 100) whose tf is low, so its exact contribution plus the + // non-essential ceiling cannot beat the k-th score: that discovered + // candidate is skipped by the per-candidate upper-bound test before any + // non-essential probe. + let build = || { + [ + term(8.0, &[(1, 10.0), (2, 10.0), (100, 1.0)]), + term(0.1, &(0..50u64).map(|r| (r, 1.0)).collect::>()), + ] + }; + + let (actual, stats) = maxscore_scores(&mut build(), dl_of, 2, false, &scorer); + let expected = exact_topk_scores(&build(), dl_of, 2, false, &scorer); + assert_eq!( + actual, expected, + "pruned run must still match the exact top-k" + ); + assert!( + stats.pruned >= 1, + "expected the per-candidate upper-bound test to fire, stats={stats:?}" + ); + } + + /// The per-term ceiling must be conservatively rounded, or MAXSCORE can stop + /// before a strictly higher-scoring document. + /// + /// `doc_weight` saturates at `K1 + 1` in exact arithmetic but can exceed it + /// in f32, so `idf · (K1 + 1)` is not an upper bound. One term and `limit = 1` is enough to lose a document: the + /// first row's score lands exactly on `idf · (K1 + 1)`, so it sets + /// `threshold == ceiling`; the split then makes the only term non-essential, + /// no essential cursor is left to discover a candidate, and the loop exits + /// before the second, one-ULP-higher row is ever scored. + #[test] + fn test_combined_maxscore_ceiling_is_conservative() { + // Valid u32 frequencies and lengths; `better` is exactly one ULP above + // the un-rounded ceiling `idf · (K1 + 1)`. + const FIRST: (u32, u32) = (91_135_840, 3_324_876_276); + const BETTER: (u32, u32) = (1_957_490_862, 2_691_694_489); + let avg_doc_length = ((u64::from(FIRST.1) + u64::from(BETTER.1)) as f64 / 2.0) as f32; + let scorer = CombinedFieldsBM25Scorer::new(2, avg_doc_length, HashMap::new()); + let idf = idf(2, 2); + // Row 0 carries `FIRST` (so it is scored first and sets the threshold), + // row 1 carries `BETTER`. + let dl_prime = |row_id: u64| -> f32 { + if row_id == 0 { + FIRST.1 as f32 + } else { + BETTER.1 as f32 + } + }; + let build = || [term(idf, &[(0, FIRST.0 as f32), (1, BETTER.0 as f32)])]; + + // The fixture is only meaningful while the naive ceiling sits below the + // achievable score and the first row lands exactly on it. + let naive_ceiling = idf * (K1 + 1.0); + let first_score = idf * scorer.doc_weight(FIRST.0 as f32, FIRST.1 as f32); + let better_score = idf * scorer.doc_weight(BETTER.0 as f32, BETTER.1 as f32); + assert_eq!(first_score.to_bits(), naive_ceiling.to_bits()); + assert!( + better_score > naive_ceiling, + "fixture no longer exercises the rounding gap: {better_score:e} vs {naive_ceiling:e}" + ); + + let expected = exact_topk_scores(&build(), dl_prime, 1, false, &scorer); + let (actual, _stats) = maxscore_scores(&mut build(), dl_prime, 1, false, &scorer); + assert_eq!( + actual, expected, + "MAXSCORE stopped before the higher-scoring row" + ); + assert_eq!(actual, vec![better_score]); + // The mechanism: the ceiling dominates every achievable contribution. + assert!(term_upper_bound(idf) >= better_score); + } + + /// `term_upper_bound` must dominate every per-term contribution it is asked + /// to bound, and no `(tf', dl')` may produce a non-finite score, not even the + /// overflowing blends that extreme per-column boosts can create. The MAXSCORE + /// prune is only conservative if both hold, so the scorer establishes them + /// itself rather than relying on the query-level validation of the boosts. + #[test] + fn test_term_upper_bound_dominates_every_doc_weight() { + // A deterministic xorshift walk over the whole u32 range of `tf'`/`dl'`, + // plus the extremes and the values that overflow the blend. + let mut state = 0x9E37_79B9_7F4A_7C15u64; + let mut next = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + let corners = [0.0f32, 1.0, f32::MIN_POSITIVE, f32::MAX, f32::INFINITY]; + // How often a realistic `(tf', dl')` pair pushes `doc_weight` past the + // textbook `K1 + 1` saturation point. Asserted non-zero below so the sweep + // cannot silently stop exercising the rounding boundary that makes the + // naive `idf · (K1 + 1)` ceiling unsafe. + let mut above_naive_saturation = 0u32; + for avg_doc_length in [ + 0.0f32, + 1.0, + 5.0, + 1e9, + f32::MAX, + f32::INFINITY, + f32::NAN, + -1.0, + ] { + let scorer = CombinedFieldsBM25Scorer::new(1000, avg_doc_length, HashMap::new()); + for doc_freq in [1usize, 2, 7, 999, 1000, 4000] { + let idf = idf(doc_freq, 1000); + let bound = term_upper_bound(idf); + let check = |tf: f32, dl: f32| -> f32 { + let weight = scorer.doc_weight(tf, dl); + assert!( + weight.is_finite() && (0.0..=BM25_DOC_WEIGHT_UPPER_BOUND).contains(&weight), + "doc_weight({tf:e}, {dl:e}) = {weight:e} escaped \ + [0, BM25_DOC_WEIGHT_UPPER_BOUND] (avgdl={avg_doc_length:e})" + ); + let contribution = idf.max(0.0) * weight; + assert!( + contribution.is_finite() && contribution <= bound, + "contribution {contribution:e} exceeds ceiling {bound:e} for \ + tf={tf:e} dl={dl:e} avgdl={avg_doc_length:e} df={doc_freq}" + ); + weight + }; + // Frequencies and lengths as they actually arrive: `u32` counts + // widened to f32. + for _ in 0..2_000 { + let tf = (next() % (u64::from(u32::MAX) + 1)) as u32 as f32; + let dl = (next() % (u64::from(u32::MAX) + 1)) as u32 as f32; + if check(tf, dl) > K1 + 1.0 { + above_naive_saturation += 1; + } + } + // Values only reachable once a boost blows the blend up, plus the + // signs and NaNs no validation upstream should be trusted to stop. + for tf in corners { + for dl in corners { + check(tf, dl); + check(-tf, dl); + check(f32::NAN, dl); + check(tf, f32::NAN); + } + } + } + } + assert!( + above_naive_saturation > 0, + "sweep never reached a doc_weight above K1 + 1, so it no longer covers \ + the rounding gap the ceiling exists for" + ); + } +} diff --git a/rust/lance-index/src/scalar/inverted/combined/search.rs b/rust/lance-index/src/scalar/inverted/combined/search.rs index 65e66f2c4c1..5ef15812971 100644 --- a/rust/lance-index/src/scalar/inverted/combined/search.rs +++ b/rust/lance-index/src/scalar/inverted/combined/search.rs @@ -2,11 +2,10 @@ // SPDX-FileCopyrightText: Copyright The Lance Authors //! The indexed `combined_fields` entry point: load every term's postings across -//! the target columns, merge them into the shared row-id space, and score every -//! candidate. +//! the target columns, merge them into the shared row-id space, and rank them +//! with MAXSCORE. use std::cmp::Reverse; -use std::collections::{BTreeSet, BinaryHeap}; use std::sync::Arc; use lance_core::Result; @@ -15,7 +14,8 @@ use lance_core::utils::tokio::spawn_cpu; use super::super::documents::AddressKeyedDocuments; use super::super::query::{FtsSearchParams, Operator, Tokens}; use super::super::scorer::CombinedFieldsBM25Scorer; -use super::cursor::{CombinedTermPostings, LoadedSource, build_term_postings}; +use super::cursor::{LoadedSource, MaterializedTerm, build_materialized_term}; +use super::maxscore::{MaxscoreStats, combined_maxscore}; use super::{CombinedFieldColumn, unique_terms}; use crate::metrics::MetricsCollector; use crate::prefilter::PreFilter; @@ -26,23 +26,24 @@ use crate::vector::graph::OrderedFloat; /// `classify_wand_exactness_certificate`. /// /// [`ScoredDoc`](super::super::builder::ScoredDoc) compares on score alone, which -/// is not enough for a bounded heap: among equal scores it evicts whichever row -/// the heap happens to hold at the bottom, so rows that belong in the top-k are -/// dropped and no later sort can bring them back. A fully covered plan returns -/// this search's output directly, with no `SortExec` above it, so the order and -/// the membership both have to be settled here. +/// is not enough for the bounded heap [`combined_maxscore`] collects into: among +/// equal scores it evicts whichever row the heap happens to hold at the bottom, so +/// rows that belong in the top-k are dropped and no later sort can bring them +/// back. A fully covered plan returns this search's output directly, with no +/// `SortExec` above it, so the order and the membership both have to be settled +/// here. /// /// `row_id` is stored reversed so that the derived lexicographic ordering ranks a /// higher row id lower. The heap's smallest element is then the lowest score with /// the highest row id, which is exactly the candidate a full heap should evict. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -struct RankedDoc { - score: OrderedFloat, - row_id: Reverse, +pub(super) struct RankedDoc { + pub(super) score: OrderedFloat, + pub(super) row_id: Reverse, } impl RankedDoc { - fn new(row_id: u64, score: f32) -> Self { + pub(super) fn new(row_id: u64, score: f32) -> Self { Self { score: OrderedFloat(score), row_id: Reverse(row_id), @@ -53,10 +54,15 @@ impl RankedDoc { /// Exact cross-field BM25F search over the target columns. /// /// Loads each query term's postings across every column and partition, then -/// scores the union of those postings and keeps a bounded top-k. Every candidate -/// is scored; there is no pruning, so the result is exact by construction. +/// ranks them with the term-at-a-time `combined_maxscore`, which skips scoring +/// a candidate whose upper bound cannot reach the running k-th score. That bound +/// only ever drops a candidate the collector would have rejected anyway, so the +/// top-k is the exhaustive scan's top-k. +/// /// Results come back ordered by `score DESC, row_id ASC`, which is a total order, -/// so the same data always yields the same top-k even when scores tie. +/// so the same data always yields the same top-k even when scores tie. Candidates +/// are discovered in ascending row-id order and `RankedDoc` settles ties, so +/// neither the membership nor the order depends on heap internals. /// /// `operator` applies across the virtual field: `And` keeps only docs where /// every query term appears in at least one column; `Or` keeps docs matching @@ -70,10 +76,36 @@ pub async fn combined_fields_search( prefilter: Arc, metrics: &dyn MetricsCollector, ) -> Result<(Vec, Vec)> { + let (row_ids, scores, _stats) = combined_fields_search_with_stats( + columns, tokens, params, operator, scorer, prefilter, metrics, + ) + .await?; + Ok((row_ids, scores)) +} + +/// [`combined_fields_search`] plus the [`MaxscoreStats`] of the scan, for a bench +/// that wants to report how much candidate scoring the pruning saved. +/// +/// This is the whole implementation; [`combined_fields_search`] is the same call +/// with the stats dropped. The stats are three counters the MAXSCORE loop keeps +/// either way, so the default path does no extra work. +/// +/// Reachable outside the crate only under `cfg(test)` or the `test-scan-stats` +/// feature: per-candidate counters are not something the production +/// `MetricsCollector` carries. +pub async fn combined_fields_search_with_stats( + columns: &[CombinedFieldColumn], + tokens: &Tokens, + params: &FtsSearchParams, + operator: Operator, + scorer: &CombinedFieldsBM25Scorer, + prefilter: Arc, + metrics: &dyn MetricsCollector, +) -> Result<(Vec, Vec, MaxscoreStats)> { let terms = unique_terms(tokens); let limit = params.limit.unwrap_or(usize::MAX); if terms.is_empty() || limit == 0 { - return Ok((Vec::new(), Vec::new())); + return Ok((Vec::new(), Vec::new(), MaxscoreStats::default())); } let mask = prefilter.mask(); @@ -111,7 +143,7 @@ pub async fn combined_fields_search( } } // Everything past the loads is uninterruptible CPU work: building and sorting - // a per-term `HashMap`, then the whole scoring loop with no await. Offload it + // a per-term `HashMap`, then the whole MAXSCORE loop with no await. Offload it // so a large query cannot hold a DataFusion // worker past a stream drop or task cancellation, matching how the // single-column `InvertedIndex::bm25_search` dispatches its per-partition @@ -119,63 +151,43 @@ pub async fn combined_fields_search( // scoring loop. The `'static` closure clones the borrowed `scorer` (a handful // of per-term statistics) and moves everything else in. let scorer = Arc::new(scorer.clone()); - let top = spawn_cpu(move || { + let (top, stats) = spawn_cpu(move || { let dl_prime = |row_id: u64| -> f32 { length_sources .iter() .map(|(weight, docs)| weight * docs.doc_length_at(row_id) as f32) .sum() }; - let terms: Vec = terms - .iter() - .zip(loaded) - .map(|(term, sources)| build_term_postings(term, sources, &mask, scorer.as_ref())) - .collect(); - - // Score every candidate: the union of the terms' postings for `Or`, and the - // same union filtered to the documents holding every term for `And`. A row - // absent from a term contributes no `tf'`, so it is skipped rather than - // scored as zero. - // - // Ties are settled by [`RankedDoc`], not left to the heap: it orders on - // `(score, row_id)` as a whole, so both which rows survive the k-th score and - // the order they come back in are fixed by the data alone. - let candidates: BTreeSet = terms - .iter() - .flat_map(|term| term.postings.iter().map(|(row_id, _)| *row_id)) - .collect(); - let mut top: BinaryHeap> = BinaryHeap::new(); - for row_id in candidates { - let dl = dl_prime(row_id); - let mut score = 0.0f32; - let mut missing_term = false; - for term in &terms { - let tf = term.tf_prime(row_id); - if tf <= 0.0 { - missing_term = true; - continue; - } - score += term.idf * scorer.doc_weight(tf, dl); - } - if require_all_terms && missing_term { - continue; - } - top.push(Reverse(RankedDoc::new(row_id, score))); - if top.len() > limit { - top.pop(); - } + // Cursors that are all exhausted need no special case: `combined_maxscore` + // finds no candidate and returns an empty heap, which unzips to no hits. + let mut cursors: Vec = Vec::with_capacity(terms.len()); + for (term, sources) in terms.iter().zip(loaded) { + cursors.push(build_materialized_term( + term, + sources, + &mask, + scorer.as_ref(), + )); } - Result::Ok(top) + let result = combined_maxscore( + &mut cursors, + dl_prime, + limit, + require_all_terms, + scorer.as_ref(), + ); + Result::Ok(result) }) .await?; // Ascending in `Reverse` is descending in `RankedDoc`, i.e. best // first: highest score, and within a score the lowest row id. - Ok(top + let (row_ids, scores) = top .into_sorted_vec() .into_iter() .map(|Reverse(doc)| (doc.row_id.0, doc.score.0)) - .unzip()) + .unzip(); + Ok((row_ids, scores, stats)) } #[cfg(test)] @@ -361,6 +373,77 @@ mod tests { assert_eq!(scores[1].to_bits(), idf(10, 19).to_bits()); } + /// Discovery pruning through the real loading path, not just the + /// `combined_maxscore` unit fixtures: one rare term and one term in every + /// row, so the common term's ceiling drops below the k-th score at once and + /// candidate discovery walks the rare term's single posting alone. + /// + /// Also the coverage for [`combined_fields_search_with_stats`] and its + /// re-export: it is reached here through the gated crate path the bench uses, + /// and its top-k must be what plain [`combined_fields_search`] returns. + #[tokio::test] + async fn test_combined_fields_search_with_stats_prunes_discovery() { + use crate::scalar::inverted::{MaxscoreStats, combined_fields_search_with_stats}; + + const ROWS: usize = 40; + let vocab = ["rare", "common"]; + let rows: ElementRows = (0..ROWS) + .map(|row| { + if row == 0 { + vec![vec!["rare", "common"]] + } else { + vec![vec!["common"]] + } + }) + .collect(); + let (index, _dir) = + element_document_index(InvertedListFormatVersion::V3, &vocab, &rows).await; + let columns = combined_columns(vec![index]); + + let tokens = Tokens::new(vec!["rare".to_owned(), "common".to_owned()], DocType::Text); + let scorer = + build_combined_bm25_scorer(&columns, &tokens, CombinedCorpusStats::IndexOnly, None) + .await + .unwrap(); + let params = FtsSearchParams::new().with_limit(Some(1)); + + let (row_ids, scores, stats): (Vec, Vec, MaxscoreStats) = + combined_fields_search_with_stats( + &columns, + &tokens, + ¶ms, + Operator::Or, + &scorer, + Arc::new(NoFilter), + &NoOpMetricsCollector, + ) + .await + .unwrap(); + assert_eq!(row_ids, vec![0], "the only row holding `rare` must win"); + // Every candidate discovered is either pruned or scored, so the counts + // account for the whole loop. + assert_eq!(stats.discovered, stats.pruned + stats.scored); + assert_eq!( + stats.discovered, 1, + "only `rare`'s single posting drives discovery, not the {ROWS} rows \ + in the candidate union", + ); + + // The delegating entry point must return exactly this, stats aside. + let plain = combined_fields_search( + &columns, + &tokens, + ¶ms, + Operator::Or, + &scorer, + Arc::new(NoFilter), + &NoOpMetricsCollector, + ) + .await + .unwrap(); + assert_eq!(plain, (row_ids, scores)); + } + /// One legacy element-per-document column and one modern row-per-document /// column in the same query. `docCount'` and `docFreq'` are a `max_f` across /// columns, so a column left at element granularity poisons the blend even diff --git a/rust/lance-index/src/scalar/inverted/combined/testing.rs b/rust/lance-index/src/scalar/inverted/combined/testing.rs index c882836ec9b..6edee15738f 100644 --- a/rust/lance-index/src/scalar/inverted/combined/testing.rs +++ b/rust/lance-index/src/scalar/inverted/combined/testing.rs @@ -5,7 +5,8 @@ //! document views, index and flat-scan corpora, and the exact reference scans //! the tests compare against. -use std::collections::HashMap; +use std::cmp::Reverse; +use std::collections::{BTreeSet, HashMap}; use std::sync::Arc; use arrow::array::AsArray; @@ -33,8 +34,11 @@ use super::super::index::{ PostingListBuilder, PostingTailCodec, TOKEN_SET_FORMAT_KEY, TokenSetFormat, }; use super::super::query::{FtsSearchParams, Operator, Tokens}; +use super::super::scorer::CombinedFieldsBM25Scorer; use super::super::tokenizer::document_tokenizer::DocType; use super::super::tokenizer::{InvertedIndexParams, LEGACY_BLOCK_SIZE}; +use super::cursor::{CombinedTermPostings, MaterializedTerm}; +use super::maxscore::{MaxscoreStats, combined_maxscore, term_upper_bound}; use super::{ CombinedCorpusStats, CombinedFieldColumn, build_combined_bm25_scorer, combined_fields_search, }; @@ -43,6 +47,75 @@ use crate::prefilter::NoFilter; use crate::scalar::lance_format::LanceIndexStore; use crate::scalar::{IndexStore, RowIdRemapper}; +pub(super) fn term(idf: f32, entries: &[(u64, f32)]) -> MaterializedTerm { + let mut postings = entries.to_vec(); + postings.sort_unstable_by_key(|(row_id, _)| *row_id); + MaterializedTerm::new(CombinedTermPostings { + idf, + upper_bound: term_upper_bound(idf), + postings, + }) +} + +// A varying blended length so scores are not all equal; the exact reference +// and MAXSCORE must read it identically. +pub(super) fn dl_of(row_id: u64) -> f32 { + 3.0 + (row_id % 4) as f32 +} + +/// Independent exact reference: score every candidate the merged scan would +/// (the union of the terms' postings for OR; all-terms-present for AND) and +/// return the `limit` highest scores, descending. +pub(super) fn exact_topk_scores( + cursors: &[MaterializedTerm], + dl_prime: impl Fn(u64) -> f32, + limit: usize, + require_all_terms: bool, + scorer: &CombinedFieldsBM25Scorer, +) -> Vec { + let union: BTreeSet = cursors + .iter() + .flat_map(|t| t.postings.postings.iter().map(|(row_id, _)| *row_id)) + .collect(); + let mut scores: Vec = union + .into_iter() + .filter_map(|row_id| { + let dl = dl_prime(row_id); + let mut score = 0.0f32; + let mut missing = false; + for t in cursors { + let tf = t.postings.tf_prime(row_id); + if tf <= 0.0 { + missing = true; + continue; + } + score += t.postings.idf * scorer.doc_weight(tf, dl); + } + (!(require_all_terms && missing)).then_some(score) + }) + .collect(); + scores.sort_by(|a, b| b.partial_cmp(a).unwrap()); + scores.truncate(limit); + scores +} + +pub(super) fn maxscore_scores( + cursors: &mut [MaterializedTerm], + dl_prime: impl Fn(u64) -> f32, + limit: usize, + require_all_terms: bool, + scorer: &CombinedFieldsBM25Scorer, +) -> (Vec, MaxscoreStats) { + let (top, stats) = combined_maxscore(cursors, dl_prime, limit, require_all_terms, scorer); + let mut scores: Vec = top.into_iter().map(|Reverse(doc)| doc.score.0).collect(); + scores.sort_by(|a, b| b.partial_cmp(a).unwrap()); + (scores, stats) +} + +pub(super) fn test_scorer() -> CombinedFieldsBM25Scorer { + CombinedFieldsBM25Scorer::new(1000, 5.0, HashMap::new()) +} + pub(super) fn compressed_list(postings: &[(u32, u32)]) -> CompressedPostingList { let doc_ids: Vec = postings.iter().map(|(d, _)| *d).collect(); let freqs: Vec = postings.iter().map(|(_, f)| *f).collect(); diff --git a/rust/lance-index/src/scalar/inverted/wand.rs b/rust/lance-index/src/scalar/inverted/wand.rs index dfde9507a64..b552ae88468 100644 --- a/rust/lance-index/src/scalar/inverted/wand.rs +++ b/rust/lance-index/src/scalar/inverted/wand.rs @@ -250,7 +250,7 @@ static USE_MAXSCORE_SEARCH: LazyLock = LazyLock::new(|| std::env::var("LANCE_FTS_MAXSCORE").as_deref() != Ok("0")); #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -enum CompetitiveFloorMode { +pub(super) enum CompetitiveFloorMode { #[default] Exclusive, Inclusive, @@ -1838,7 +1838,7 @@ pub(super) fn score_sum_upper_bound_factor(num_values: usize) -> f64 { } #[inline] -fn score_sum_cannot_compete( +pub(super) fn score_sum_cannot_compete( partial_score: f32, remaining_upper_bound: f64, floor: f32, From f781d7d853f47af6d3fba35ccc9dea55ae156ca7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B6ren=20Brunk?= Date: Tue, 6 Oct 2026 15:29:44 +0200 Subject: [PATCH 2/2] refactor(fts): trim combined_fields MAXSCORE code and comments Drop the single-impl TermCursor trait and the test-scan-stats feature as they aren't needed here. --- rust/lance-index/Cargo.toml | 4 - rust/lance-index/src/scalar/inverted.rs | 4 - .../src/scalar/inverted/combined.rs | 4 - .../src/scalar/inverted/combined/cursor.rs | 88 ++---- .../src/scalar/inverted/combined/maxscore.rs | 255 ++++++------------ .../src/scalar/inverted/combined/search.rs | 141 ++-------- .../src/scalar/inverted/combined/testing.rs | 17 +- 7 files changed, 129 insertions(+), 384 deletions(-) diff --git a/rust/lance-index/Cargo.toml b/rust/lance-index/Cargo.toml index 4836969e3d5..54d3094fe87 100644 --- a/rust/lance-index/Cargo.toml +++ b/rust/lance-index/Cargo.toml @@ -104,10 +104,6 @@ tokenizer-jieba = ["dep:jieba-rs", "lance-tokenizer/tokenizer-jieba"] # Exposes `scalar::inverted::oracle`, the brute-force scoring reference, to # downstream test and bench targets. Enable it as a dev-dependency feature only. test-oracle = [] -# Exposes `scalar::inverted::combined_fields_search_with_stats` and the -# `MaxscoreStats` it returns, so a bench can report how much candidate scoring -# the MAXSCORE pruning saves. Enable it as a dev-dependency feature only. -test-scan-stats = [] [build-dependencies] prost-build.workspace = true diff --git a/rust/lance-index/src/scalar/inverted.rs b/rust/lance-index/src/scalar/inverted.rs index f2fe3bba9e1..364b8df3251 100644 --- a/rust/lance-index/src/scalar/inverted.rs +++ b/rust/lance-index/src/scalar/inverted.rs @@ -33,10 +33,6 @@ pub use combined::{ CombinedCorpusStats, CombinedFieldColumn, FlatFieldStats, build_combined_bm25_scorer, combined_fields_search, flat_combined_fields_search_stream, validate_combined_tokenizers, }; -/// The `combined_fields` MAXSCORE pruning counters, for tests and benches. Never -/// reachable on a normal build; see the `test-scan-stats` feature. -#[cfg(any(test, feature = "test-scan-stats"))] -pub use combined::{MaxscoreStats, combined_fields_search_with_stats}; pub use compound::{ compound_search, compound_search_prepared_match, compound_search_prepared_match_with_score_floor, compound_search_with_base_scorer, diff --git a/rust/lance-index/src/scalar/inverted/combined.rs b/rust/lance-index/src/scalar/inverted/combined.rs index 7f02c424ba6..a74820431b1 100644 --- a/rust/lance-index/src/scalar/inverted/combined.rs +++ b/rust/lance-index/src/scalar/inverted/combined.rs @@ -40,10 +40,6 @@ use lance_select::RowAddrTreeMap; pub use flat::flat_combined_fields_search_stream; pub use search::combined_fields_search; pub use stats::{CombinedCorpusStats, FlatFieldStats, build_combined_bm25_scorer}; -// The MAXSCORE candidate counters, for test and bench targets only; see the -// `test-scan-stats` feature. -#[cfg(any(test, feature = "test-scan-stats"))] -pub use {maxscore::MaxscoreStats, search::combined_fields_search_with_stats}; use super::index::InvertedIndex; use super::query::Tokens; diff --git a/rust/lance-index/src/scalar/inverted/combined/cursor.rs b/rust/lance-index/src/scalar/inverted/combined/cursor.rs index 49ba4997292..eb28a5ea397 100644 --- a/rust/lance-index/src/scalar/inverted/combined/cursor.rs +++ b/rust/lance-index/src/scalar/inverted/combined/cursor.rs @@ -1,9 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The Lance Authors -//! Per-term cross-column cursors for `combined_fields`: the [`TermCursor`] -//! abstraction, its full-read implementation, and the loaded posting sources it -//! is built from. +//! Per-term cross-column cursors for `combined_fields` and the posting sources +//! they are built from. use std::collections::HashMap; use std::sync::Arc; @@ -15,36 +14,6 @@ use super::super::index::{PostingList, live_posting_rows}; use super::super::scorer::CombinedFieldsBM25Scorer; use super::maxscore::term_upper_bound; -/// The MAXSCORE loop's view of one query term. [`MaterializedTerm`] implements it -/// by reading every posting up front; the trait keeps -/// [`combined_maxscore`](super::maxscore::combined_maxscore) independent of how a -/// `tf'` is fetched, so a lazier cursor can be substituted without touching the -/// algorithm. -/// -/// A term exposes a merged cross-column cursor over the shared row-id space: -/// [`head`](Self::head) is the smallest not-yet-consumed row id, advanced by -/// the essential terms during discovery; [`probe`](Self::probe) reads `tf'` at -/// an arbitrary (non-decreasing) target for the non-essential terms. -pub(super) trait TermCursor { - /// The constant per-term ceiling `idf · MAX_DOC_WEIGHT` (clamped, see - /// [`term_upper_bound`]). - fn upper_bound(&self) -> f32; - /// The blended IDF `idf'(t)`. - fn idf(&self) -> f32; - /// The smallest not-yet-consumed row id across the term's columns, or - /// `None` when the term is exhausted. - fn head(&self) -> Option; - /// `tf'` at [`head`](Self::head) (the weighted sum across the columns that - /// carry the head row id). Only meaningful while `head()` is `Some`. - fn head_tf(&self) -> f32; - /// Consume `row_id`: advance every column cursor currently sitting on it. - /// Called only for `row_id == head()`. - fn consume(&mut self, row_id: u64); - /// `tf'` at `target`, or 0 when the term is absent there. `target` never - /// decreases across calls to one cursor, so the lazy path can skip blocks. - fn probe(&mut self, target: u64) -> f32; -} - /// One query term's postings, merged across every target column/partition into /// the shared row-id space. /// @@ -52,7 +21,6 @@ pub(super) trait TermCursor { /// frequency `tf'(t, d) = Σ_f w_f · freq_f(t, d)`. pub(super) struct CombinedTermPostings { pub(super) idf: f32, - pub(super) upper_bound: f32, pub(super) postings: Vec<(u64, f32)>, } @@ -67,7 +35,11 @@ impl CombinedTermPostings { } } -/// [`TermCursor`] over a [`CombinedTermPostings`] with an owned scan cursor. +/// One query term as seen by +/// [`combined_maxscore`](super::maxscore::combined_maxscore): fully read +/// [`CombinedTermPostings`] plus a cursor. Essential terms are walked with +/// [`head`](Self::head) and [`consume`](Self::consume); non-essential ones are +/// read with [`probe`](Self::probe). pub(super) struct MaterializedTerm { pub(super) postings: CombinedTermPostings, cursor: usize, @@ -80,26 +52,28 @@ impl MaterializedTerm { cursor: 0, } } -} -impl TermCursor for MaterializedTerm { + /// See [`term_upper_bound`]. #[inline] - fn upper_bound(&self) -> f32 { - self.postings.upper_bound + pub(super) fn upper_bound(&self) -> f32 { + term_upper_bound(self.postings.idf) } + /// The blended IDF `idf'(t)`. #[inline] - fn idf(&self) -> f32 { + pub(super) fn idf(&self) -> f32 { self.postings.idf } + /// The smallest unconsumed row id, or `None` when exhausted. #[inline] - fn head(&self) -> Option { + pub(super) fn head(&self) -> Option { self.postings.postings.get(self.cursor).map(|(id, _)| *id) } + /// `tf'` at [`head`](Self::head). #[inline] - fn head_tf(&self) -> f32 { + pub(super) fn head_tf(&self) -> f32 { self.postings .postings .get(self.cursor) @@ -107,15 +81,17 @@ impl TermCursor for MaterializedTerm { .unwrap_or(0.0) } + /// Advance past `row_id`, which must be `head()`. #[inline] - fn consume(&mut self, row_id: u64) { + pub(super) fn consume(&mut self, row_id: u64) { if self.head() == Some(row_id) { self.cursor += 1; } } + /// `tf'` at `target`, or 0 when absent. #[inline] - fn probe(&mut self, target: u64) -> f32 { + pub(super) fn probe(&mut self, target: u64) -> f32 { self.postings.tf_prime(target) } } @@ -128,8 +104,8 @@ pub(super) struct LoadedSource { pub(super) posting: PostingList, } -/// Build the full-read cursor for `term` by merging every source's postings into -/// the shared row-id space, accumulating `tf'` in the canonical order. +/// Merge every source's postings for `term` into the shared row-id space, +/// accumulating `tf'` in the canonical order. pub(super) fn build_materialized_term( term: &str, sources: Vec, @@ -148,11 +124,7 @@ pub(super) fn build_materialized_term( let idf = scorer.query_weight(term); let mut postings: Vec<(u64, f32)> = acc.into_iter().collect(); postings.sort_unstable_by_key(|(row_id, _)| *row_id); - MaterializedTerm::new(CombinedTermPostings { - idf, - upper_bound: term_upper_bound(idf), - postings, - }) + MaterializedTerm::new(CombinedTermPostings { idf, postings }) } #[cfg(test)] @@ -166,7 +138,7 @@ mod tests { #[tokio::test] async fn test_build_materialized_term_merges_legacy_and_compressed() { - // Fallback data path: a legacy (Plain, row-id-keyed, list-multiplicity) + // A legacy (Plain, row-id-keyed, list-multiplicity) // source and a compressed source merge into one ordered `tf'` stream, // masked rows dropped and contributions summed in column order. use super::super::super::index::PlainPostingList; @@ -217,9 +189,7 @@ mod tests { // posting lists stay aligned and answers `TOMBSTONE_ROW` for its address. // Nothing else stops that address: a default mask is an empty block list, // which selects it, and `doc_length_at(TOMBSTONE_ROW) == 0` would give it - // the largest `doc_weight` there is. It stays out of the result today only - // because `TOMBSTONE_ROW == u64::MAX` collides with `combined_maxscore`'s - // exhausted-cursor sentinel, so it must be dropped at the source. + // the largest `doc_weight` there is, so it must be dropped at the source. const DEAD_ROW: u64 = 20; let scorer = CombinedFieldsBM25Scorer::new(1000, 12.0, HashMap::new()); let docs = modern_identity_docs(&[4u32; 40], &[DEAD_ROW]).await; @@ -248,12 +218,8 @@ mod tests { must keep their exact contributions" ); - // Nor may it be collected: the two live rows are the whole top-k, scored - // exactly as if the dead slot's posting did not exist. - // - // `test_scorer` carries no document frequencies, so `query_weight` is 0 for - // every term and both rows score 0. The order is therefore the tiebreak, - // ascending by row id. + // The live rows are the whole top-k, scored as if the dead slot's posting + // did not exist. let mut cursors = vec![term]; let dl_prime = |row_id: u64| -> f32 { 2.0 * docs.doc_length_at(row_id) as f32 }; let (top, _) = combined_maxscore(&mut cursors, dl_prime, 10, false, &scorer); diff --git a/rust/lance-index/src/scalar/inverted/combined/maxscore.rs b/rust/lance-index/src/scalar/inverted/combined/maxscore.rs index b96f35ebaeb..7020f536ce8 100644 --- a/rust/lance-index/src/scalar/inverted/combined/maxscore.rs +++ b/rust/lance-index/src/scalar/inverted/combined/maxscore.rs @@ -1,8 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The Lance Authors -//! The term-at-a-time MAXSCORE loop shared by both `combined_fields` term -//! cursors, its per-term score ceiling, and its candidate-work accounting. +//! Term-at-a-time MAXSCORE for `combined_fields`. use std::cmp::Reverse; use std::collections::BinaryHeap; @@ -11,22 +10,17 @@ use super::super::scorer::{BM25_DOC_WEIGHT_UPPER_BOUND, CombinedFieldsBM25Scorer use super::super::wand::{ CompetitiveFloorMode, score_sum_cannot_compete, score_sum_upper_bound_factor, }; -use super::cursor::TermCursor; +use super::cursor::MaterializedTerm; use super::search::RankedDoc; -/// The constant per-term BM25F score ceiling, clamped to 0 when the term cannot -/// raise a score (`idf <= 0`). +/// The constant per-term score ceiling, or 0 when the term cannot raise a score +/// (`idf <= 0`). /// -/// Lucene's `CombinedFieldQuery::getMaxScore` uses `idf · (K1 + 1)` because BM25 -/// saturates the `tf'` factor at `K1 + 1`. That product is not an upper bound -/// in f32: the evaluated weight can land above it, and a ceiling one ULP short -/// is enough for MAXSCORE to drop a document that outscores the running k-th (a -/// one-term `limit = 1` query suffices; see -/// `test_combined_maxscore_ceiling_is_conservative`). Scaling by -/// [`BM25_DOC_WEIGHT_UPPER_BOUND`] instead keeps -/// `term_upper_bound(idf) >= idf · doc_weight(tf', dl')` for every `tf'` / `dl'`, -/// because `doc_weight` clamps to that ceiling and `x -> fl(idf · x)` is -/// monotone for `idf >= 0`. +/// Lucene's `CombinedFieldQuery` uses `idf · (K1 + 1)`, but in f32 the evaluated +/// weight can land above that, and a ceiling one ULP short is enough to drop a +/// better document (see `test_combined_maxscore_ceiling_is_conservative`). +/// `doc_weight` clamps to [`BM25_DOC_WEIGHT_UPPER_BOUND`], so scaling by it is a +/// true bound. #[inline] pub(super) fn term_upper_bound(idf: f32) -> f32 { if idf > 0.0 { @@ -36,60 +30,42 @@ pub(super) fn term_upper_bound(idf: f32) -> f32 { } } -/// Candidate-work accounting for one MAXSCORE run: the scoring-side work the -/// essential/non-essential split saves. -/// -/// Per-candidate bookkeeping does not belong on the production -/// `MetricsCollector`, so this never leaves the crate on a normal build: the -/// `maxscore` module is private and only `cfg(test)` or the `test-scan-stats` -/// feature re-exports it, alongside `combined_fields_search_with_stats`. The -/// unit tests below are what keep the pruning honest: a gate that never fired -/// would leave every score correct and silently do nothing. +/// Candidate counters for one MAXSCORE run, so tests can check that pruning +/// actually fires. #[derive(Default, Debug, Clone, Copy)] -pub struct MaxscoreStats { +pub(super) struct MaxscoreStats { /// Candidates pulled from the essential terms' cursors. - pub discovered: u64, - /// Discovered candidates skipped by the upper-bound test (no length lookup, - /// no non-essential probe, no full score). - pub pruned: u64, + pub(super) discovered: u64, + /// Discovered candidates rejected by the upper-bound test before probing + /// the non-essential terms. + pub(super) pruned: u64, /// Candidates fully scored. - pub scored: u64, + pub(super) scored: u64, } -/// Term-at-a-time MAXSCORE over the cross-field combined postings. -/// -/// Terms are ordered ascending by their constant ceiling `upper_bound`. Once the -/// heap holds `limit` docs, the leading prefix whose cumulative ceiling cannot -/// beat the k-th score (`threshold`) becomes non-essential: candidate discovery -/// walks the essential terms' cursors alone, and a candidate is skipped whole -/// (no length lookup, no probe) when the essential terms it matches plus every -/// non-essential ceiling still cannot beat `threshold`. `threshold` only rises, -/// so a term never returns to essential once it crosses over. +/// Term-at-a-time MAXSCORE over the cross-field postings. /// -/// Every surviving candidate is scored exactly, summing `idf'(t) · -/// doc_weight(tf', dl')` over the terms in their original order, with `dl_prime` -/// supplying the blended length. Absent terms add `doc_weight(0, ·) == 0`, so the -/// score is bit-identical to the exact scan, which skips them. +/// Terms are sorted by ceiling. Once the heap holds `limit` docs, the longest +/// prefix whose summed ceilings cannot beat the k-th score (`threshold`) is +/// non-essential: only the remaining (essential) terms produce candidates, and a +/// candidate is dropped when its essential score plus the non-essential ceilings +/// still cannot beat `threshold`. Survivors are scored exactly, summed in the +/// original term order so scores are bit-identical to an exhaustive scan. /// -/// Both prunes only ever drop a candidate whose exact `score` is provably -/// `<= threshold`, i.e. one the collector would have rejected anyway, so the top-k -/// is the exact scan's top-k. That rests on two f32 facts, neither of which holds -/// for the textbook `idf · (K1 + 1)` ceiling: the per-term ceiling dominates every -/// per-term contribution ([`term_upper_bound`] over a clamped `doc_weight`), and -/// summing those ceilings is widened enough to dominate the differently-ordered f32 -/// summation that produces `score` ([`score_sum_upper_bound_factor`]). -/// -/// Generic over [`TermCursor`], so the lazy and eager paths share one algorithm. -pub(super) fn combined_maxscore( - cursors: &mut [C], +/// Both prunes only drop candidates scoring `<= threshold`. Candidates arrive in +/// ascending row-id order, so such a candidate would lose the `(score, row_id)` +/// tiebreak to every incumbent anyway, and the top-k equals the exhaustive one. +/// [`score_sum_upper_bound_factor`] widens the summed ceilings enough to cover +/// f32 rounding of the differently ordered sums. +pub(super) fn combined_maxscore( + cursors: &mut [MaterializedTerm], dl_prime: impl Fn(u64) -> f32, limit: usize, require_all_terms: bool, scorer: &CombinedFieldsBM25Scorer, ) -> (BinaryHeap>, MaxscoreStats) { let num_terms = cursors.len(); - // Term indices ordered ascending by ceiling; ties broken by index so the - // essential/non-essential split is deterministic. + // Index tiebreak keeps the essential split deterministic. let mut order: Vec = (0..num_terms).collect(); order.sort_by(|&a, &b| { cursors[a] @@ -103,70 +79,44 @@ pub(super) fn combined_maxscore( let mut top: BinaryHeap> = BinaryHeap::new(); let mut stats = MaxscoreStats::default(); - // The current k-th score; pruning is armed only once the heap is full. + // The k-th score; pruning is armed only once the heap is full. let mut threshold = f32::NEG_INFINITY; - // Per-term score contributions, reused across candidates. Every scored - // candidate overwrites all slots before it is summed. + // Per-term contributions, fully overwritten for every scored candidate. let mut contrib = vec![0.0f32; num_terms]; loop { - // Split `order` into non-essential (a leading prefix whose widened - // cumulative ceiling <= threshold) and essential. Recomputed each step - // because `threshold` may have risen. + // Recomputed every step because `threshold` only rises. let mut nonessential_upper_bound = 0.0f64; - let split = if top.len() < limit { - 0 - } else { - let mut cumulative = 0.0f64; - let mut boundary = 0; - while boundary < num_terms { - let bound = f64::from(cursors[order[boundary]].upper_bound()); - if score_sum_cannot_compete( + let mut split = 0; + if top.len() >= limit { + while split < num_terms { + let bound = f64::from(cursors[order[split]].upper_bound()); + if !score_sum_cannot_compete( 0.0, - cumulative + bound, + nonessential_upper_bound + bound, threshold, bound_factor, CompetitiveFloorMode::Exclusive, ) { - cumulative += bound; - boundary += 1; - } else { break; } - } - nonessential_upper_bound = cumulative; - boundary - }; - - // Next candidate = smallest row id at any essential term's cursor. Docs - // that match only non-essential terms are never discovered: their score is - // at most the widened `nonessential_upper_bound`, hence `<= threshold`, - // which the score-only strict-`<` collector could not admit anyway. - let mut doc = u64::MAX; - for &term in &order[split..] { - if let Some(row_id) = cursors[term].head() { - doc = doc.min(row_id); + nonessential_upper_bound += bound; + split += 1; } } - if doc == u64::MAX { - break; // essential terms exhausted (or all terms non-essential) - } + + // Docs matching only non-essential terms are never discovered: their + // score cannot beat `threshold`. + let Some(doc) = order[split..] + .iter() + .filter_map(|&term| cursors[term].head()) + .min() + else { + break; + }; stats.discovered += 1; let dl = dl_prime(doc); - // Exact contribution of the essential terms, consuming each cursor that - // sits on `doc`. The widened `essential_score + nonessential_upper_bound` - // then dominates the full `score`, so the prune below is safe (see this - // function's doc comment). - // - // The prune stays `Exclusive` (reject on `upper_bound <= threshold`) even - // though the collector now orders on `(score DESC, row_id ASC)`. A - // candidate that merely ties the k-th score cannot belong in the top-k - // here: `doc` only ever increases, so every candidate reaching this point - // has a higher row id than every incumbent, and an incumbent tied at - // `threshold` therefore wins the tiebreak. Rejecting on the tie is what the - // collector below does too, so the prune drops nothing the collector would - // have kept. See `test_combined_maxscore_ties_keep_lowest_row_ids`. let mut essential_score = 0.0f32; let mut missing_term = false; for &term in &order[split..] { @@ -181,6 +131,9 @@ pub(super) fn combined_maxscore( contrib[term] = cursors[term].idf() * scorer.doc_weight(tf, dl); essential_score += contrib[term]; } + if require_all_terms && missing_term { + continue; + } if top.len() >= limit && score_sum_cannot_compete( essential_score, @@ -194,8 +147,6 @@ pub(super) fn combined_maxscore( continue; } - // Probe the non-essential terms on demand to complete the exact score. - // `doc` increases monotonically, so each probe seeks forward. for &term in &order[..split] { let tf = cursors[term].probe(doc); missing_term |= tf <= 0.0; @@ -206,17 +157,8 @@ pub(super) fn combined_maxscore( } stats.scored += 1; - // Sum in original term order so the score is bit-identical to the exact - // scan. let score: f32 = contrib.iter().sum(); - - // The replacement test stays score-only and strict, which is what - // `CompetitiveFloorMode::Exclusive` prunes against: a candidate that only - // ties the k-th score never displaces an incumbent, so pruning one is - // sound. [`RankedDoc`] does not weaken that. `doc` increases - // monotonically, so a tied candidate always carries the higher row id and - // would lose the tiebreak too; ordering the heap on `(score, row_id)` only - // fixes which of the retained ties comes out first. + // Strict `<`: a tie never displaces an incumbent, matching the prune. if top.len() < limit { top.push(Reverse(RankedDoc::new(doc, score))); if top.len() == limit { @@ -253,10 +195,8 @@ mod tests { ), ] }; - // Every top-k depth must reproduce the exact scan's top-k scores, so the - // MAXSCORE pruning provably does not change the result. `limit = 20` is - // the depth where this fixture's k-th score ties several candidates' - // ceilings exactly, which is where a non-conservative bound would bite. + // At `limit = 20` the k-th score ties several candidates' ceilings + // exactly, where a non-conservative bound would bite. for limit in [1usize, 2, 3, 5, 10, 20, 50] { let expected = exact_topk_scores(&build(), dl_of, limit, false, &scorer); let (actual, _stats) = maxscore_scores(&mut build(), dl_of, limit, false, &scorer); @@ -267,17 +207,9 @@ mod tests { } } - /// A tie group straddling the top-k cutoff must resolve to the lowest row - /// ids, in ascending order. - /// - /// This is the interaction the candidate prune has to survive: the prune and - /// the collector both reject a candidate that only ties `threshold`, and that - /// is correct precisely because discovery is ascending, so a tied newcomer - /// always loses the row-id tiebreak to the incumbents. - /// - /// `dl_of` depends on `row_id % 4`, so row ids `0, 4, 8, ...` share a blended - /// length; one term with an equal `tf'` at each then scores them all - /// identically, making the whole result one tie. + /// A tie straddling the top-k cutoff must resolve to the lowest row ids, + /// ascending. Rows `0, 4, 8, ...` share a `dl_of`, so one term with equal + /// `tf'` scores them all the same. #[test] fn test_combined_maxscore_ties_keep_lowest_row_ids() { let scorer = test_scorer(); @@ -296,8 +228,7 @@ mod tests { hits, expected, "top-{limit} over a full tie must be the lowest row ids, ascending" ); - // Every candidate was reached, so the assertion above is about which - // ties were kept rather than about candidates never being discovered. + // Every tie was reached, so the result is the tiebreak, not discovery. assert_eq!( stats.discovered, tied.len() as u64, @@ -336,8 +267,7 @@ mod tests { term(0.05, &(0..30u64).map(|r| (r, 1.0)).collect::>()), ] }; - // usize::MAX limit: the heap never fills, so nothing is pruned and every - // matching doc is scored, exactly like the merged scan. + // The heap never fills, so nothing may be pruned. let expected = exact_topk_scores(&build(), dl_of, usize::MAX, false, &scorer); let (actual, stats) = maxscore_scores(&mut build(), dl_of, usize::MAX, false, &scorer); assert_eq!(actual, expected); @@ -349,11 +279,8 @@ mod tests { #[test] fn test_combined_maxscore_discovery_pruning() { let scorer = test_scorer(); - // A rare high-idf term whose docs sit early, and a common low-idf term - // over a huge posting list. With a small k the common term goes - // non-essential once the heap fills with the rare docs, so its ~1000 - // rows are never discovered; only the essential rare term drives - // discovery. + // Once the rare term's docs fill the heap, the common term goes + // non-essential and its 1000 rows are never discovered. let build = || { [ term(6.0, &[(1, 3.0), (2, 3.0), (3, 3.0), (4, 3.0), (5, 3.0)]), @@ -380,11 +307,8 @@ mod tests { #[test] fn test_combined_maxscore_per_candidate_pruning() { let scorer = test_scorer(); - // Two essential terms. `a` stays essential (large ceiling) but has a - // late doc (row 100) whose tf is low, so its exact contribution plus the - // non-essential ceiling cannot beat the k-th score: that discovered - // candidate is skipped by the per-candidate upper-bound test before any - // non-essential probe. + // The first term stays essential, but its low-tf row 100 plus the + // non-essential ceiling cannot beat the k-th score, so it is pruned. let build = || { [ term(8.0, &[(1, 10.0), (2, 10.0), (100, 1.0)]), @@ -404,26 +328,17 @@ mod tests { ); } - /// The per-term ceiling must be conservatively rounded, or MAXSCORE can stop - /// before a strictly higher-scoring document. - /// - /// `doc_weight` saturates at `K1 + 1` in exact arithmetic but can exceed it - /// in f32, so `idf · (K1 + 1)` is not an upper bound. One term and `limit = 1` is enough to lose a document: the - /// first row's score lands exactly on `idf · (K1 + 1)`, so it sets - /// `threshold == ceiling`; the split then makes the only term non-essential, - /// no essential cursor is left to discover a candidate, and the loop exits - /// before the second, one-ULP-higher row is ever scored. + /// `doc_weight` can exceed `K1 + 1` in f32, so `idf · (K1 + 1)` is not a + /// safe ceiling. Here the first row scores exactly `idf · (K1 + 1)`; with + /// that ceiling the only term would go non-essential and the loop would exit + /// before the one-ULP-higher second row is scored. #[test] fn test_combined_maxscore_ceiling_is_conservative() { - // Valid u32 frequencies and lengths; `better` is exactly one ULP above - // the un-rounded ceiling `idf · (K1 + 1)`. const FIRST: (u32, u32) = (91_135_840, 3_324_876_276); const BETTER: (u32, u32) = (1_957_490_862, 2_691_694_489); let avg_doc_length = ((u64::from(FIRST.1) + u64::from(BETTER.1)) as f64 / 2.0) as f32; let scorer = CombinedFieldsBM25Scorer::new(2, avg_doc_length, HashMap::new()); let idf = idf(2, 2); - // Row 0 carries `FIRST` (so it is scored first and sets the threshold), - // row 1 carries `BETTER`. let dl_prime = |row_id: u64| -> f32 { if row_id == 0 { FIRST.1 as f32 @@ -433,8 +348,7 @@ mod tests { }; let build = || [term(idf, &[(0, FIRST.0 as f32), (1, BETTER.0 as f32)])]; - // The fixture is only meaningful while the naive ceiling sits below the - // achievable score and the first row lands exactly on it. + // Guard that the fixture still hits the rounding gap. let naive_ceiling = idf * (K1 + 1.0); let first_score = idf * scorer.doc_weight(FIRST.0 as f32, FIRST.1 as f32); let better_score = idf * scorer.doc_weight(BETTER.0 as f32, BETTER.1 as f32); @@ -451,19 +365,16 @@ mod tests { "MAXSCORE stopped before the higher-scoring row" ); assert_eq!(actual, vec![better_score]); - // The mechanism: the ceiling dominates every achievable contribution. assert!(term_upper_bound(idf) >= better_score); } - /// `term_upper_bound` must dominate every per-term contribution it is asked - /// to bound, and no `(tf', dl')` may produce a non-finite score, not even the - /// overflowing blends that extreme per-column boosts can create. The MAXSCORE - /// prune is only conservative if both hold, so the scorer establishes them - /// itself rather than relying on the query-level validation of the boosts. + /// `term_upper_bound` must dominate every per-term contribution, and no + /// `(tf', dl')` may give a non-finite score, including the overflowing blends + /// extreme boosts can create. The scorer guarantees this itself instead of + /// relying on query-level boost validation. #[test] fn test_term_upper_bound_dominates_every_doc_weight() { - // A deterministic xorshift walk over the whole u32 range of `tf'`/`dl'`, - // plus the extremes and the values that overflow the blend. + // Deterministic xorshift over the u32 range, plus extreme values. let mut state = 0x9E37_79B9_7F4A_7C15u64; let mut next = move || { state ^= state << 13; @@ -472,10 +383,7 @@ mod tests { state }; let corners = [0.0f32, 1.0, f32::MIN_POSITIVE, f32::MAX, f32::INFINITY]; - // How often a realistic `(tf', dl')` pair pushes `doc_weight` past the - // textbook `K1 + 1` saturation point. Asserted non-zero below so the sweep - // cannot silently stop exercising the rounding boundary that makes the - // naive `idf · (K1 + 1)` ceiling unsafe. + // Must end up non-zero, so the sweep keeps covering the rounding gap. let mut above_naive_saturation = 0u32; for avg_doc_length in [ 0.0f32, @@ -506,8 +414,6 @@ mod tests { ); weight }; - // Frequencies and lengths as they actually arrive: `u32` counts - // widened to f32. for _ in 0..2_000 { let tf = (next() % (u64::from(u32::MAX) + 1)) as u32 as f32; let dl = (next() % (u64::from(u32::MAX) + 1)) as u32 as f32; @@ -515,8 +421,7 @@ mod tests { above_naive_saturation += 1; } } - // Values only reachable once a boost blows the blend up, plus the - // signs and NaNs no validation upstream should be trusted to stop. + // Only reachable through extreme boosts, signs or NaNs. for tf in corners { for dl in corners { check(tf, dl); diff --git a/rust/lance-index/src/scalar/inverted/combined/search.rs b/rust/lance-index/src/scalar/inverted/combined/search.rs index 5ef15812971..0a88e5cce80 100644 --- a/rust/lance-index/src/scalar/inverted/combined/search.rs +++ b/rust/lance-index/src/scalar/inverted/combined/search.rs @@ -15,7 +15,7 @@ use super::super::documents::AddressKeyedDocuments; use super::super::query::{FtsSearchParams, Operator, Tokens}; use super::super::scorer::CombinedFieldsBM25Scorer; use super::cursor::{LoadedSource, MaterializedTerm, build_materialized_term}; -use super::maxscore::{MaxscoreStats, combined_maxscore}; +use super::maxscore::combined_maxscore; use super::{CombinedFieldColumn, unique_terms}; use crate::metrics::MetricsCollector; use crate::prefilter::PreFilter; @@ -54,15 +54,11 @@ impl RankedDoc { /// Exact cross-field BM25F search over the target columns. /// /// Loads each query term's postings across every column and partition, then -/// ranks them with the term-at-a-time `combined_maxscore`, which skips scoring -/// a candidate whose upper bound cannot reach the running k-th score. That bound -/// only ever drops a candidate the collector would have rejected anyway, so the -/// top-k is the exhaustive scan's top-k. +/// ranks them with `combined_maxscore`, which skips candidates that cannot reach +/// the running k-th score. The top-k equals that of an exhaustive scan. /// /// Results come back ordered by `score DESC, row_id ASC`, which is a total order, -/// so the same data always yields the same top-k even when scores tie. Candidates -/// are discovered in ascending row-id order and `RankedDoc` settles ties, so -/// neither the membership nor the order depends on heap internals. +/// so the same data always yields the same top-k even when scores tie. /// /// `operator` applies across the virtual field: `And` keeps only docs where /// every query term appears in at least one column; `Or` keeps docs matching @@ -76,36 +72,10 @@ pub async fn combined_fields_search( prefilter: Arc, metrics: &dyn MetricsCollector, ) -> Result<(Vec, Vec)> { - let (row_ids, scores, _stats) = combined_fields_search_with_stats( - columns, tokens, params, operator, scorer, prefilter, metrics, - ) - .await?; - Ok((row_ids, scores)) -} - -/// [`combined_fields_search`] plus the [`MaxscoreStats`] of the scan, for a bench -/// that wants to report how much candidate scoring the pruning saved. -/// -/// This is the whole implementation; [`combined_fields_search`] is the same call -/// with the stats dropped. The stats are three counters the MAXSCORE loop keeps -/// either way, so the default path does no extra work. -/// -/// Reachable outside the crate only under `cfg(test)` or the `test-scan-stats` -/// feature: per-candidate counters are not something the production -/// `MetricsCollector` carries. -pub async fn combined_fields_search_with_stats( - columns: &[CombinedFieldColumn], - tokens: &Tokens, - params: &FtsSearchParams, - operator: Operator, - scorer: &CombinedFieldsBM25Scorer, - prefilter: Arc, - metrics: &dyn MetricsCollector, -) -> Result<(Vec, Vec, MaxscoreStats)> { let terms = unique_terms(tokens); let limit = params.limit.unwrap_or(usize::MAX); if terms.is_empty() || limit == 0 { - return Ok((Vec::new(), Vec::new(), MaxscoreStats::default())); + return Ok((Vec::new(), Vec::new())); } let mask = prefilter.mask(); @@ -151,43 +121,35 @@ pub async fn combined_fields_search_with_stats( // scoring loop. The `'static` closure clones the borrowed `scorer` (a handful // of per-term statistics) and moves everything else in. let scorer = Arc::new(scorer.clone()); - let (top, stats) = spawn_cpu(move || { + let (top, _stats) = spawn_cpu(move || { let dl_prime = |row_id: u64| -> f32 { length_sources .iter() .map(|(weight, docs)| weight * docs.doc_length_at(row_id) as f32) .sum() }; - // Cursors that are all exhausted need no special case: `combined_maxscore` - // finds no candidate and returns an empty heap, which unzips to no hits. - let mut cursors: Vec = Vec::with_capacity(terms.len()); - for (term, sources) in terms.iter().zip(loaded) { - cursors.push(build_materialized_term( - term, - sources, - &mask, - scorer.as_ref(), - )); - } - let result = combined_maxscore( + let mut cursors: Vec = terms + .iter() + .zip(loaded) + .map(|(term, sources)| build_materialized_term(term, sources, &mask, &scorer)) + .collect(); + Result::Ok(combined_maxscore( &mut cursors, dl_prime, limit, require_all_terms, - scorer.as_ref(), - ); - Result::Ok(result) + &scorer, + )) }) .await?; // Ascending in `Reverse` is descending in `RankedDoc`, i.e. best // first: highest score, and within a score the lowest row id. - let (row_ids, scores) = top + Ok(top .into_sorted_vec() .into_iter() .map(|Reverse(doc)| (doc.row_id.0, doc.score.0)) - .unzip(); - Ok((row_ids, scores, stats)) + .unzip()) } #[cfg(test)] @@ -373,77 +335,6 @@ mod tests { assert_eq!(scores[1].to_bits(), idf(10, 19).to_bits()); } - /// Discovery pruning through the real loading path, not just the - /// `combined_maxscore` unit fixtures: one rare term and one term in every - /// row, so the common term's ceiling drops below the k-th score at once and - /// candidate discovery walks the rare term's single posting alone. - /// - /// Also the coverage for [`combined_fields_search_with_stats`] and its - /// re-export: it is reached here through the gated crate path the bench uses, - /// and its top-k must be what plain [`combined_fields_search`] returns. - #[tokio::test] - async fn test_combined_fields_search_with_stats_prunes_discovery() { - use crate::scalar::inverted::{MaxscoreStats, combined_fields_search_with_stats}; - - const ROWS: usize = 40; - let vocab = ["rare", "common"]; - let rows: ElementRows = (0..ROWS) - .map(|row| { - if row == 0 { - vec![vec!["rare", "common"]] - } else { - vec![vec!["common"]] - } - }) - .collect(); - let (index, _dir) = - element_document_index(InvertedListFormatVersion::V3, &vocab, &rows).await; - let columns = combined_columns(vec![index]); - - let tokens = Tokens::new(vec!["rare".to_owned(), "common".to_owned()], DocType::Text); - let scorer = - build_combined_bm25_scorer(&columns, &tokens, CombinedCorpusStats::IndexOnly, None) - .await - .unwrap(); - let params = FtsSearchParams::new().with_limit(Some(1)); - - let (row_ids, scores, stats): (Vec, Vec, MaxscoreStats) = - combined_fields_search_with_stats( - &columns, - &tokens, - ¶ms, - Operator::Or, - &scorer, - Arc::new(NoFilter), - &NoOpMetricsCollector, - ) - .await - .unwrap(); - assert_eq!(row_ids, vec![0], "the only row holding `rare` must win"); - // Every candidate discovered is either pruned or scored, so the counts - // account for the whole loop. - assert_eq!(stats.discovered, stats.pruned + stats.scored); - assert_eq!( - stats.discovered, 1, - "only `rare`'s single posting drives discovery, not the {ROWS} rows \ - in the candidate union", - ); - - // The delegating entry point must return exactly this, stats aside. - let plain = combined_fields_search( - &columns, - &tokens, - ¶ms, - Operator::Or, - &scorer, - Arc::new(NoFilter), - &NoOpMetricsCollector, - ) - .await - .unwrap(); - assert_eq!(plain, (row_ids, scores)); - } - /// One legacy element-per-document column and one modern row-per-document /// column in the same query. `docCount'` and `docFreq'` are a `max_f` across /// columns, so a column left at element granularity poisons the blend even diff --git a/rust/lance-index/src/scalar/inverted/combined/testing.rs b/rust/lance-index/src/scalar/inverted/combined/testing.rs index 6edee15738f..cb25e33fb6d 100644 --- a/rust/lance-index/src/scalar/inverted/combined/testing.rs +++ b/rust/lance-index/src/scalar/inverted/combined/testing.rs @@ -38,7 +38,7 @@ use super::super::scorer::CombinedFieldsBM25Scorer; use super::super::tokenizer::document_tokenizer::DocType; use super::super::tokenizer::{InvertedIndexParams, LEGACY_BLOCK_SIZE}; use super::cursor::{CombinedTermPostings, MaterializedTerm}; -use super::maxscore::{MaxscoreStats, combined_maxscore, term_upper_bound}; +use super::maxscore::{MaxscoreStats, combined_maxscore}; use super::{ CombinedCorpusStats, CombinedFieldColumn, build_combined_bm25_scorer, combined_fields_search, }; @@ -50,22 +50,17 @@ use crate::scalar::{IndexStore, RowIdRemapper}; pub(super) fn term(idf: f32, entries: &[(u64, f32)]) -> MaterializedTerm { let mut postings = entries.to_vec(); postings.sort_unstable_by_key(|(row_id, _)| *row_id); - MaterializedTerm::new(CombinedTermPostings { - idf, - upper_bound: term_upper_bound(idf), - postings, - }) + MaterializedTerm::new(CombinedTermPostings { idf, postings }) } -// A varying blended length so scores are not all equal; the exact reference -// and MAXSCORE must read it identically. +// A varying blended length so scores are not all equal. pub(super) fn dl_of(row_id: u64) -> f32 { 3.0 + (row_id % 4) as f32 } -/// Independent exact reference: score every candidate the merged scan would -/// (the union of the terms' postings for OR; all-terms-present for AND) and -/// return the `limit` highest scores, descending. +/// Exhaustive reference: score every row in the union of the postings (only +/// rows holding every term for AND) and return the top `limit` scores, +/// descending. pub(super) fn exact_topk_scores( cursors: &[MaterializedTerm], dl_prime: impl Fn(u64) -> f32,