1use hawdb_core::{HawDBError, Result};
22use std::collections::BinaryHeap;
23
24pub const BM25_K1: f64 = 1.2;
26pub const BM25_B: f64 = 0.75;
28
29pub const BM25_UPPER_BOUND_MARGIN: f64 = 1e-12;
35
36pub 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
42pub 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
49pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub struct Bm25Block {
60 pub last: u64,
62 pub max_frequency: u64,
64 pub min_length: u64,
66}
67
68pub trait Bm25PostingCursor {
75 fn position(&self) -> Option<u64>;
77 fn is_exact(&self) -> bool;
79 fn block_at(&mut self, target: u64) -> Result<Option<Bm25Block>>;
82 fn skip_to(&mut self, target: u64) -> Result<()>;
84 fn materialize(&mut self) -> Result<()>;
87 fn current(&self) -> Result<(u64, Bm25Block)>;
89 fn competitive_threshold(&mut self, _threshold: f64) {}
94}
95
96pub struct Bm25Term<C> {
98 pub cursor: C,
99 pub idf: f64,
100 pub max_bound: f64,
102}
103
104pub trait Bm25Documents {
106 fn length(&mut self, ordinal: u64) -> Result<u64>;
108 fn key(&mut self, ordinal: u64) -> Result<&[u8]>;
110 fn checkpoint(&mut self) -> Result<()>;
112 fn admit(&mut self, bytes: usize) -> Result<()>;
114 fn release(&mut self, bytes: usize);
116}
117
118#[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 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
140struct 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
169pub struct Bm25KernelStats {
170 pub documents_scored: u64,
172 pub block_skips: u64,
175 pub heap_insertions: u64,
177 pub terminated_early: bool,
179}
180
181#[derive(Debug, Clone, PartialEq)]
183pub struct Bm25TopK {
184 pub hits: Vec<Bm25Hit>,
186 pub stats: Bm25KernelStats,
187}
188
189pub 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 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 let group_len = order.partition_point(|&term| position(terms, term) <= pivot);
253 if let Some(floor) = floor {
254 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 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 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 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;