Skip to main content

hawdb_executor/
bm25.rs

1// Copyright 2026 Nowledge
2// SPDX-License-Identifier: Apache-2.0
3
4//! Okapi BM25 scoring and exact Block-Max WAND top-k retrieval.
5//!
6//! This is the one BM25 scorer shared by the graph-side lexical projection
7//! and the SQL search index access path: the same constants, the same IDF and
8//! the same floating-point operations in the same order, so a score computed
9//! by either path is bit-identical to a brute-force evaluation that sums
10//! per-term contributions in query-term order.
11//!
12//! [`block_max_wand`] finds the exact top-k of a disjunctive query over
13//! posting cursors that expose per-block upper bounds (Ding and Suel, "Faster
14//! top-k document retrieval using block-max indexes", SIGIR 2011). The
15//! posting format stays behind [`Bm25PostingCursor`]: the kernel never sees
16//! storage rows, only ordinals, frequencies and block bounds. Documents are
17//! ranked by score descending, ties broken by ascending encoded key, which
18//! is a total order; the result is therefore exactly the first `k` entries of
19//! a full ranking, whatever was pruned.
20
21use hawdb_core::{HawDBError, Result};
22use std::collections::BinaryHeap;
23
24/// Term-frequency saturation.
25pub const BM25_K1: f64 = 1.2;
26/// Document-length normalization.
27pub const BM25_B: f64 = 0.75;
28
29/// Relative margin added to every block upper bound. Bounds and scores are
30/// each a handful of correctly rounded operations, so their rounding error is
31/// a few units in the last place (about 1e-15 relative); a bound inflated by
32/// this margin is never below the score of a document it covers, whatever
33/// the summation order. The cost is pruning nothing within 1e-12 of the floor.
34pub const BM25_UPPER_BOUND_MARGIN: f64 = 1e-12;
35
36/// Lucene's non-negative IDF, `ln(1 + (N - n + 0.5) / (n + 0.5))`.
37pub fn idf(documents: u64, document_frequency: u64) -> f64 {
38    (1.0 + (documents as f64 - document_frequency as f64 + 0.5) / (document_frequency as f64 + 0.5))
39        .ln()
40}
41
42/// One term's contribution to a document's score.
43pub fn term_score(idf: f64, frequency: f64, document_length: f64, average_length: f64) -> f64 {
44    let denominator =
45        frequency + BM25_K1 * (1.0 - BM25_B + BM25_B * document_length / average_length.max(1.0));
46    idf * (frequency * (BM25_K1 + 1.0)) / denominator
47}
48
49/// An upper bound on [`term_score`] for every posting with a frequency of at
50/// most `max_frequency` in a document of at least `min_length` tokens. BM25
51/// grows with frequency and falls with length, so the corner is the bound.
52pub fn term_upper_bound(idf: f64, max_frequency: u64, min_length: u64, average_length: f64) -> f64 {
53    term_score(idf, max_frequency as f64, min_length as f64, average_length)
54        * (1.0 + BM25_UPPER_BOUND_MARGIN)
55}
56
57/// The skip entry of the block that serves a cursor's next posting.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub struct Bm25Block {
60    /// The block's last posting ordinal.
61    pub last: u64,
62    /// No posting in the block has a higher frequency.
63    pub max_frequency: u64,
64    /// No document in the block is shorter.
65    pub min_length: u64,
66}
67
68/// An ordinal-ordered posting list read block by block.
69///
70/// `position` is a lower bound on the next posting's ordinal; it becomes
71/// exact after [`Self::materialize`]. [`Self::skip_to`] and
72/// [`Self::block_at`] must not decode blocks: skipping a block whose bound
73/// cannot reach the top-k is the point of the algorithm.
74pub trait Bm25PostingCursor {
75    /// Lower bound on the next posting's ordinal; `None` when exhausted.
76    fn position(&self) -> Option<u64>;
77    /// Whether `position` is the ordinal of an actual posting.
78    fn is_exact(&self) -> bool;
79    /// The block holding the first posting at or after `target` (at least
80    /// `position`), without decoding it; `None` past the last block.
81    fn block_at(&mut self, target: u64) -> Result<Option<Bm25Block>>;
82    /// Raises `position` to `target` without decoding.
83    fn skip_to(&mut self, target: u64) -> Result<()>;
84    /// Decodes as needed so that `position` is the next posting's exact
85    /// ordinal (or `None`).
86    fn materialize(&mut self) -> Result<()>;
87    /// The exact current posting's term frequency and its block's bounds.
88    fn current(&self) -> Result<(u64, Bm25Block)>;
89    /// A block of this term whose upper bound is below `threshold` cannot
90    /// hold a top-k document, whatever the other terms contribute. Cursors
91    /// may use it to avoid reading such blocks ahead; it never changes the
92    /// result. Called whenever the floor rises.
93    fn competitive_threshold(&mut self, _threshold: f64) {}
94}
95
96/// One query term: its cursor, IDF and the bound over all its blocks.
97pub struct Bm25Term<C> {
98    pub cursor: C,
99    pub idf: f64,
100    /// At least [`term_upper_bound`] of every block of the term.
101    pub max_bound: f64,
102}
103
104/// Per-document state and the scan's admission hooks.
105pub trait Bm25Documents {
106    /// The token count of a document that has postings.
107    fn length(&mut self, ordinal: u64) -> Result<u64>;
108    /// The document's encoded key, borrowed until heap admission succeeds.
109    fn key(&mut self, ordinal: u64) -> Result<&[u8]>;
110    /// Cancellation and work admission, called once per loop iteration.
111    fn checkpoint(&mut self) -> Result<()>;
112    /// Admits `bytes` of retained heap state before it is allocated.
113    fn admit(&mut self, bytes: usize) -> Result<()>;
114    /// Returns bytes of an evicted heap entry.
115    fn release(&mut self, bytes: usize);
116}
117
118/// One ranked document.
119#[derive(Debug, Clone, PartialEq)]
120pub struct Bm25Hit {
121    pub ordinal: u64,
122    pub key: Vec<u8>,
123    pub score: f64,
124}
125
126impl Bm25Hit {
127    /// Retained bytes of a heap entry, admitted before it is allocated.
128    pub fn retained_bytes(key_len: usize) -> usize {
129        std::mem::size_of::<Self>().saturating_add(key_len)
130    }
131
132    fn worse_than(&self, score: f64, key: &[u8]) -> bool {
133        self.score
134            .total_cmp(&score)
135            .then_with(|| key.cmp(&self.key))
136            .is_lt()
137    }
138}
139
140/// Heap order: the worst retained hit (lowest score, then greatest key) on top.
141struct Worst(Bm25Hit);
142
143impl PartialEq for Worst {
144    fn eq(&self, other: &Self) -> bool {
145        self.cmp(other).is_eq()
146    }
147}
148
149impl Eq for Worst {}
150
151impl PartialOrd for Worst {
152    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
153        Some(self.cmp(other))
154    }
155}
156
157impl Ord for Worst {
158    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
159        other
160            .0
161            .score
162            .total_cmp(&self.0.score)
163            .then_with(|| self.0.key.cmp(&other.0.key))
164    }
165}
166
167/// Work the kernel did, for query reports and EXPLAIN ANALYZE.
168#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
169pub struct Bm25KernelStats {
170    /// Documents whose exact score was computed.
171    pub documents_scored: u64,
172    /// Candidate documents whose block bounds fell below the floor, so the
173    /// cursors jumped past the blocks without decoding them.
174    pub block_skips: u64,
175    /// Hits that entered the k-sized heap (including later evictions).
176    pub heap_insertions: u64,
177    /// The scan ended because no remaining document could reach the floor.
178    pub terminated_early: bool,
179}
180
181/// The exact top-k and the work it took.
182#[derive(Debug, Clone, PartialEq)]
183pub struct Bm25TopK {
184    /// Best first: score descending, then key ascending.
185    pub hits: Vec<Bm25Hit>,
186    pub stats: Bm25KernelStats,
187}
188
189/// Exact top-`k` of the disjunction of `terms` by BM25, with Block-Max WAND
190/// pruning once `k` documents are retained. `terms` are in query-term order,
191/// which is the order a document's contributions are summed in.
192pub fn block_max_wand<C: Bm25PostingCursor, D: Bm25Documents>(
193    terms: &mut [Bm25Term<C>],
194    average_length: f64,
195    k: usize,
196    documents: &mut D,
197) -> Result<Bm25TopK> {
198    let mut stats = Bm25KernelStats::default();
199    if k == 0 {
200        return Ok(Bm25TopK {
201            hits: Vec::new(),
202            stats,
203        });
204    }
205    let capacity = k.min(1 << 20);
206    documents.admit(capacity.saturating_mul(std::mem::size_of::<Worst>()))?;
207    let mut heap = BinaryHeap::<Worst>::with_capacity(capacity);
208    let mut order: Vec<usize> = Vec::with_capacity(terms.len());
209    let mut in_group = vec![false; terms.len()];
210    let total_bound = terms.iter().fold(0.0, |sum, term| sum + term.max_bound);
211    loop {
212        documents.checkpoint()?;
213        order.clear();
214        order.extend((0..terms.len()).filter(|&term| terms[term].cursor.position().is_some()));
215        if order.is_empty() {
216            break;
217        }
218        let position = |terms: &[Bm25Term<C>], term: usize| {
219            terms[term]
220                .cursor
221                .position()
222                .expect("active cursors have a position")
223        };
224        order.sort_by_key(|&term| (position(terms, term), term));
225        let floor = (heap.len() >= k).then(|| heap.peek().map(|worst| worst.0.score));
226        let floor = floor.flatten();
227        let pivot = match floor {
228            None => position(terms, order[0]),
229            Some(floor) => {
230                // WAND pivot: the first candidate whose cursors (all those at
231                // or before it) can together reach the floor. Every document
232                // before it scores below the floor. Bounds are summed in term
233                // order, like scores.
234                let reach = |candidate: u64| {
235                    terms
236                        .iter()
237                        .fold(0.0, |sum, term| match term.cursor.position() {
238                            Some(position) if position <= candidate => sum + term.max_bound,
239                            _ => sum,
240                        })
241                };
242                let pivot_index =
243                    order.partition_point(|&term| reach(position(terms, term)) < floor);
244                let Some(&pivot_term) = order.get(pivot_index) else {
245                    stats.terminated_early = true;
246                    break;
247                };
248                position(terms, pivot_term)
249            }
250        };
251        // The pivot group: every cursor at or before the pivot.
252        let group_len = order.partition_point(|&term| position(terms, term) <= pivot);
253        if let Some(floor) = floor {
254            // Block-max check: the blocks that hold the group's postings at
255            // the pivot bound every document from the pivot up to the end of
256            // the first of those blocks.
257            let mut bound = 0.0;
258            let mut boundary = u64::MAX;
259            for flag in in_group.iter_mut() {
260                *flag = false;
261            }
262            for &term in &order[..group_len] {
263                in_group[term] = true;
264            }
265            for (term, &member) in terms.iter_mut().zip(&in_group) {
266                if !member {
267                    continue;
268                }
269                if let Some(block) = term.cursor.block_at(pivot)? {
270                    bound += term_upper_bound(
271                        term.idf,
272                        block.max_frequency,
273                        block.min_length,
274                        average_length,
275                    );
276                    boundary = boundary.min(block.last.saturating_add(1));
277                }
278            }
279            if bound < floor {
280                // No document in [pivot, boundary) can reach the floor, nor
281                // any before the next cursor outside the group.
282                let target = order
283                    .get(group_len)
284                    .map_or(boundary, |&next| boundary.min(position(terms, next)));
285                if target <= pivot {
286                    return Err(HawDBError::StorageIntegrity(
287                        "BM25 block bounds do not advance past their pivot".into(),
288                    ));
289                }
290                for &term in &order[..group_len] {
291                    terms[term].cursor.skip_to(target)?;
292                }
293                stats.block_skips = stats.block_skips.saturating_add(1);
294                continue;
295            }
296        }
297        if position(terms, order[0]) < pivot {
298            // Documents before the pivot cannot reach the floor.
299            for &term in &order[..group_len] {
300                if position(terms, term) < pivot {
301                    terms[term].cursor.skip_to(pivot)?;
302                }
303            }
304            continue;
305        }
306        // Every group cursor is at the pivot; make that exact before scoring.
307        let mut moved = false;
308        for &term in &order[..group_len] {
309            let cursor = &mut terms[term].cursor;
310            if !cursor.is_exact() {
311                cursor.materialize()?;
312                moved |= cursor.position() != Some(pivot);
313            }
314        }
315        if moved {
316            continue;
317        }
318        let length = documents.length(pivot)?;
319        let mut score = 0.0;
320        for flag in in_group.iter_mut() {
321            *flag = false;
322        }
323        for &term in &order[..group_len] {
324            in_group[term] = true;
325        }
326        for (term, &member) in terms.iter().zip(&in_group) {
327            if !member {
328                continue;
329            }
330            let (frequency, block) = term.cursor.current()?;
331            if frequency > block.max_frequency || length < block.min_length {
332                return Err(HawDBError::StorageIntegrity(
333                    "BM25 posting exceeds its block bounds".into(),
334                ));
335            }
336            score += term_score(term.idf, frequency as f64, length as f64, average_length);
337        }
338        stats.documents_scored = stats.documents_scored.saturating_add(1);
339        if !score.is_finite() || score <= 0.0 {
340            return Err(HawDBError::StorageIntegrity(
341                "BM25 score is not a positive finite number".into(),
342            ));
343        }
344        let full = heap.len() >= k;
345        let competitive = match heap.peek() {
346            Some(worst) if full => worst.0.score <= score,
347            _ => true,
348        };
349        if competitive {
350            let retained_key = {
351                let key = documents.key(pivot)?;
352                let enters = match heap.peek() {
353                    Some(worst) if full => worst.0.worse_than(score, key),
354                    _ => true,
355                };
356                enters.then_some(key.len())
357            };
358            if let Some(key_len) = retained_key {
359                documents.admit(Bm25Hit::retained_bytes(key_len))?;
360                let key = documents.key(pivot)?.to_vec();
361                if full && let Some(evicted) = heap.pop() {
362                    documents.release(Bm25Hit::retained_bytes(evicted.0.key.len()));
363                }
364                heap.push(Worst(Bm25Hit {
365                    ordinal: pivot,
366                    key,
367                    score,
368                }));
369                stats.heap_insertions = stats.heap_insertions.saturating_add(1);
370                if heap.len() >= k
371                    && let Some(worst) = heap.peek()
372                {
373                    let floor = worst.0.score;
374                    for term in terms.iter_mut() {
375                        let others = total_bound - term.max_bound;
376                        term.cursor.competitive_threshold(floor - others);
377                    }
378                }
379            }
380        }
381        let next = pivot
382            .checked_add(1)
383            .ok_or_else(|| HawDBError::StorageIntegrity("BM25 ordinal overflow".into()))?;
384        for &term in &order[..group_len] {
385            terms[term].cursor.skip_to(next)?;
386        }
387    }
388    let mut hits = heap.into_iter().map(|worst| worst.0).collect::<Vec<_>>();
389    hits.sort_by(|left, right| {
390        right
391            .score
392            .total_cmp(&left.score)
393            .then_with(|| left.key.cmp(&right.key))
394    });
395    Ok(Bm25TopK { hits, stats })
396}
397
398#[cfg(test)]
399mod tests;