1use super::super::*;
14use hawdb_executor::bm25::{
15 block_max_wand, idf, term_upper_bound, Bm25Block, Bm25Documents, Bm25Hit, Bm25PostingCursor,
16 Bm25Term,
17};
18use hawdb_storage::relational::{
19 decode_search_sealed_block, search_index_block_bounds_range, search_index_block_fence,
20 search_index_dictionary_key, search_index_length_block_range, search_index_length_block_start,
21 search_index_sealed_block_window, search_index_statistics_key, SearchBlockBounds,
22 SearchDocumentEntry, SearchIndexStatistics, SearchLengthBlock, SearchPosting,
23 SearchTermDictionary, SEARCH_INDEX_LENGTH_BLOCK_DOCUMENTS,
24};
25use std::cell::{Cell, RefCell};
26use std::collections::VecDeque;
27
28const MIN_BLOCK_READAHEAD: usize = 4;
33const MAX_BLOCK_READAHEAD: usize = 64;
34const LENGTHS_WINDOW: u64 = 128;
37
38fn integrity(error: hawdb_storage::relational::RelationalError) -> HawDBError {
39 HawDBError::StorageIntegrity(error.to_string())
40}
41
42fn corrupt(message: &str) -> HawDBError {
43 HawDBError::StorageIntegrity(format!("search index {message}"))
44}
45
46fn data(row: &RelationalReadRow) -> Result<&[u8]> {
47 match row.value(3)? {
48 RelationalValue::Bytea(data) => Ok(data),
49 _ => Err(corrupt("row has an invalid payload")),
50 }
51}
52
53#[derive(Debug, Clone, Default, PartialEq, Eq)]
55pub struct SearchIndexScanEvidence {
56 pub index: String,
57 pub table: String,
58 pub query_terms: usize,
60 pub matched_terms: usize,
61 pub needed: usize,
64 pub limit_pushdown: bool,
65 pub rounds: usize,
68 pub final_k: usize,
71 pub ranked_rows: usize,
72 pub postings_total: u64,
74 pub postings_visited: u64,
76 pub blocks_total: u64,
78 pub blocks_read: u64,
80 pub blocks_decoded: u64,
81 pub blocks_skipped: u64,
83 pub block_skips: u64,
85 pub documents_scored: u64,
86 pub lengths_rows_read: u64,
87 pub candidates_hydrated: usize,
89 pub terminated_early: bool,
91}
92
93pub(super) struct ScanContext<'a> {
95 pub runtime: &'a RelationalRowRuntime<'a>,
96 pub index: &'a str,
97 pub task: Option<&'a hawdb_core::RuntimeTaskContext>,
98 pub max_work: usize,
99 pub work: Cell<usize>,
100 pub memory: RefCell<QueryMemoryLease>,
101 pub evidence: RefCell<SearchIndexScanEvidence>,
102}
103
104impl ScanContext<'_> {
105 pub(super) fn charge(&self, amount: u64) -> Result<()> {
106 let amount = usize::try_from(amount).unwrap_or(usize::MAX);
107 let work = self.work.get().saturating_add(amount);
108 self.work.set(work);
109 if work > self.max_work {
110 return Err(HawDBError::read_budget_exceeded(
111 hawdb_core::ReadBudgetResource::Rows,
112 self.max_work,
113 "text_search exceeds SQL candidate work admission",
114 ));
115 }
116 Ok(())
117 }
118
119 pub(super) fn admit(&self, bytes: usize) -> Result<()> {
120 self.memory.borrow_mut().grow(bytes)
121 }
122
123 fn release(&self, bytes: usize) {
124 self.memory.borrow_mut().shrink(bytes);
125 }
126
127 fn checkpoint(&self) -> Result<()> {
128 hawdb_executor::pipeline::runtime_checkpoint(self.task)
129 }
130
131 pub(super) fn statistics(&self) -> Result<Option<SearchIndexStatistics>> {
132 self.charge(1)?;
133 self.runtime
134 .read_point(self.index, &search_index_statistics_key())?
135 .map(|row| SearchIndexStatistics::decode(data(&row)?).map_err(integrity))
136 .transpose()
137 }
138}
139
140#[derive(Debug, Clone, Copy)]
142struct TermBlock {
143 fence: u64,
144 bounds: SearchBlockBounds,
145 tail: bool,
146}
147
148pub(super) struct TermPostings {
150 term: String,
151 idf: f64,
152 average_length: f64,
153 max_bound: f64,
154 tail: Vec<SearchPosting>,
155 blocks: Vec<TermBlock>,
156 sealed_blocks: u64,
157}
158
159impl TermPostings {
160 pub(super) fn load(
163 context: &ScanContext<'_>,
164 term: &str,
165 statistics: &SearchIndexStatistics,
166 average_length: f64,
167 ) -> Result<Option<Self>> {
168 context.checkpoint()?;
169 context.charge(1)?;
170 let Some(row) = context
171 .runtime
172 .read_point(context.index, &search_index_dictionary_key(term))?
173 else {
174 return Ok(None);
175 };
176 let encoded = data(&row)?;
177 context.admit(encoded.len().saturating_mul(8))?;
179 let dictionary = SearchTermDictionary::decode(encoded).map_err(integrity)?;
180 if dictionary.document_frequency == 0
181 || dictionary.document_frequency > statistics.documents
182 {
183 return Err(corrupt("dictionary disagrees with the corpus statistics"));
184 }
185 let blocks = usize::try_from(dictionary.sealed_blocks)
186 .unwrap_or(usize::MAX)
187 .saturating_add(1);
188 context.admit(blocks.saturating_mul(std::mem::size_of::<TermBlock>()))?;
189 let mut entries = Vec::with_capacity(blocks);
190 let mut postings = 0u64;
191 if dictionary.sealed_blocks > 0 {
192 context.runtime.visit_primary_key_range(
193 context.index,
194 &search_index_block_bounds_range(term).map_err(integrity)?,
195 |row| {
196 context.charge(1)?;
197 let fence = search_index_block_fence(row.value(2)?).map_err(integrity)?;
198 let bounds =
199 SearchBlockBounds::decode(fence, data(&row)?).map_err(integrity)?;
200 if entries.len() as u64 >= dictionary.sealed_blocks
201 || entries.last().is_some_and(|previous: &TermBlock| {
202 previous.bounds.last >= fence || previous.fence >= fence
203 })
204 || bounds.last >= dictionary.tail_start
205 || (entries.is_empty() && fence != 0)
206 {
207 return Err(corrupt("block bounds are out of order"));
208 }
209 postings = postings.saturating_add(bounds.count);
210 entries.push(TermBlock {
211 fence,
212 bounds,
213 tail: false,
214 });
215 Ok(true)
216 },
217 )?;
218 if entries.len() as u64 != dictionary.sealed_blocks {
219 return Err(corrupt("block bounds disagree with their dictionary"));
220 }
221 }
222 if let Some(last) = dictionary.tail.last() {
223 entries.push(TermBlock {
224 fence: dictionary.tail_start,
225 bounds: SearchBlockBounds {
226 last: last.ordinal,
227 count: dictionary.tail.len() as u64,
228 max_frequency: dictionary
229 .tail
230 .iter()
231 .map(|posting| posting.frequency)
232 .max()
233 .unwrap_or(0),
234 min_length: dictionary.tail_min_length,
235 },
236 tail: true,
237 });
238 postings = postings.saturating_add(dictionary.tail.len() as u64);
239 }
240 if postings != dictionary.document_frequency {
241 return Err(corrupt("postings disagree with their document frequency"));
242 }
243 let idf = idf(statistics.documents, dictionary.document_frequency);
244 let max_bound =
245 entries
246 .iter()
247 .filter(|block| block.bounds.count > 0)
248 .fold(0.0f64, |bound, block| {
249 bound.max(term_upper_bound(
250 idf,
251 block.bounds.max_frequency,
252 block.bounds.min_length,
253 average_length,
254 ))
255 });
256 Ok(Some(Self {
257 term: term.to_owned(),
258 idf,
259 average_length,
260 max_bound,
261 tail: dictionary.tail,
262 blocks: entries,
263 sealed_blocks: dictionary.sealed_blocks,
264 }))
265 }
266
267 pub(super) fn document_frequency(&self) -> u64 {
268 self.blocks.iter().map(|block| block.bounds.count).sum()
269 }
270
271 pub(super) fn sealed_blocks(&self) -> u64 {
272 self.sealed_blocks
273 }
274}
275
276pub(super) struct IndexCursor<'a> {
279 context: &'a ScanContext<'a>,
280 postings: &'a TermPostings,
281 hint: usize,
282 position: Option<u64>,
283 exact: Option<(usize, usize)>,
285 loaded: Option<usize>,
286 decoded: Vec<SearchPosting>,
287 decoded_bytes: usize,
288 ahead: VecDeque<(usize, Vec<u8>)>,
290 ahead_bytes: usize,
291 window: usize,
292 threshold: f64,
294}
295
296impl<'a> IndexCursor<'a> {
297 pub(super) fn new(context: &'a ScanContext<'a>, postings: &'a TermPostings) -> Self {
298 let mut cursor = Self {
299 context,
300 postings,
301 hint: 0,
302 position: Some(0),
303 exact: None,
304 loaded: None,
305 decoded: Vec::new(),
306 decoded_bytes: 0,
307 ahead: VecDeque::new(),
308 ahead_bytes: 0,
309 window: 1,
310 threshold: f64::NEG_INFINITY,
311 };
312 if cursor.block_index(0).is_none() {
313 cursor.position = None;
314 }
315 cursor
316 }
317
318 fn block_index(&mut self, target: u64) -> Option<usize> {
319 let blocks = &self.postings.blocks;
320 while self.hint < blocks.len()
321 && (blocks[self.hint].bounds.count == 0 || blocks[self.hint].bounds.last < target)
322 {
323 self.hint += 1;
324 }
325 (self.hint < blocks.len()).then_some(self.hint)
326 }
327
328 fn payload(&mut self, index: usize) -> Result<Vec<u8>> {
332 while self.ahead.front().is_some_and(|(ahead, _)| *ahead < index) {
333 let (_, skipped) = self.ahead.pop_front().expect("front exists");
334 self.ahead_bytes -= skipped.len();
335 self.context.release(skipped.len());
336 }
337 if let Some((ahead, _)) = self.ahead.front()
338 && *ahead == index
339 {
340 let (_, payload) = self.ahead.pop_front().expect("front exists");
341 self.ahead_bytes -= payload.len();
342 return Ok(payload);
343 }
344 for (_, stale) in self.ahead.drain(..) {
345 self.context.release(stale.len());
346 }
347 self.ahead_bytes = 0;
348 self.window = if self.loaded.is_some_and(|loaded| loaded + 1 == index) {
351 (self.window * 2).min(MAX_BLOCK_READAHEAD)
352 } else {
353 MIN_BLOCK_READAHEAD
354 };
355 let blocks = &self.postings.blocks;
356 let threshold = self.threshold;
357 let competitive = |block: &TermBlock| {
358 term_upper_bound(
359 self.postings.idf,
360 block.bounds.max_frequency,
361 block.bounds.min_length,
362 self.postings.average_length,
363 ) >= threshold
364 };
365 let last = index
366 + blocks[index + 1..]
367 .iter()
368 .take(self.window.saturating_sub(1))
369 .take_while(|block| !block.tail && block.bounds.count > 0 && competitive(block))
370 .count();
371 let mut found = None;
372 let mut expected = index;
373 let context = self.context;
374 let mut ahead = Vec::new();
375 context.runtime.visit_primary_key_range(
376 context.index,
377 &search_index_sealed_block_window(
378 &self.postings.term,
379 blocks[index].fence,
380 blocks[last].fence,
381 )
382 .map_err(integrity)?,
383 |row| {
384 let fence = search_index_block_fence(row.value(2)?).map_err(integrity)?;
385 if expected > last || blocks[expected].fence != fence {
386 return Err(corrupt("sealed blocks disagree with their bounds"));
387 }
388 context.charge(blocks[expected].bounds.count.max(1))?;
389 let payload = data(&row)?;
390 context.admit(payload.len())?;
391 let mut evidence = context.evidence.borrow_mut();
392 evidence.blocks_read = evidence.blocks_read.saturating_add(1);
393 if expected == index {
394 found = Some(payload.to_vec());
395 } else {
396 ahead.push((expected, payload.to_vec()));
397 }
398 expected += 1;
399 Ok(true)
400 },
401 )?;
402 if expected != last + 1 {
403 return Err(corrupt("sealed block is missing"));
404 }
405 for (block, payload) in ahead {
406 self.ahead_bytes += payload.len();
407 self.ahead.push_back((block, payload));
408 }
409 found.ok_or_else(|| corrupt("sealed block is missing"))
410 }
411
412 fn load(&mut self, index: usize) -> Result<()> {
413 if self.loaded == Some(index) {
414 return Ok(());
415 }
416 self.context.checkpoint()?;
417 let block = self.postings.blocks[index];
418 let count = usize::try_from(block.bounds.count).unwrap_or(usize::MAX);
419 let bytes = count.saturating_mul(std::mem::size_of::<SearchPosting>());
420 self.context.admit(bytes)?;
421 self.context.release(self.decoded_bytes);
422 self.decoded_bytes = bytes;
423 self.decoded.clear();
424 if block.tail {
425 self.decoded.extend_from_slice(&self.postings.tail);
426 } else {
427 let payload = self.payload(index)?;
428 let decoded = decode_search_sealed_block(block.fence, &payload, &mut self.decoded);
429 self.context.release(payload.len());
430 decoded.map_err(integrity)?;
431 if !block.bounds.describes(block.fence, &self.decoded) {
432 return Err(corrupt("block disagrees with its bounds"));
433 }
434 let mut evidence = self.context.evidence.borrow_mut();
435 evidence.blocks_decoded = evidence.blocks_decoded.saturating_add(1);
436 }
437 let mut evidence = self.context.evidence.borrow_mut();
438 evidence.postings_visited = evidence
439 .postings_visited
440 .saturating_add(self.decoded.len() as u64);
441 self.loaded = Some(index);
442 Ok(())
443 }
444}
445
446impl Drop for IndexCursor<'_> {
447 fn drop(&mut self) {
448 self.context
449 .release(self.decoded_bytes.saturating_add(self.ahead_bytes));
450 }
451}
452
453fn kernel_block(bounds: SearchBlockBounds) -> Bm25Block {
454 Bm25Block {
455 last: bounds.last,
456 max_frequency: bounds.max_frequency,
457 min_length: bounds.min_length,
458 }
459}
460
461impl Bm25PostingCursor for IndexCursor<'_> {
462 fn position(&self) -> Option<u64> {
463 self.position
464 }
465
466 fn is_exact(&self) -> bool {
467 self.exact.is_some()
468 }
469
470 fn block_at(&mut self, target: u64) -> Result<Option<Bm25Block>> {
471 Ok(self
472 .block_index(target)
473 .map(|index| kernel_block(self.postings.blocks[index].bounds)))
474 }
475
476 fn skip_to(&mut self, target: u64) -> Result<()> {
477 let Some(position) = self.position else {
478 return Ok(());
479 };
480 if target <= position {
481 return Ok(());
482 }
483 self.exact = None;
484 self.position = self.block_index(target).map(|_| target);
485 Ok(())
486 }
487
488 fn materialize(&mut self) -> Result<()> {
489 let Some(position) = self.position else {
490 return Ok(());
491 };
492 let Some(index) = self.block_index(position) else {
493 self.position = None;
494 return Ok(());
495 };
496 self.load(index)?;
497 let offset = self
498 .decoded
499 .partition_point(|posting| posting.ordinal < position);
500 let posting = self
501 .decoded
502 .get(offset)
503 .ok_or_else(|| corrupt("block bounds overstate its last posting"))?;
504 self.position = Some(posting.ordinal);
505 self.exact = Some((index, offset));
506 Ok(())
507 }
508
509 fn competitive_threshold(&mut self, threshold: f64) {
510 self.threshold = threshold;
511 }
512
513 fn current(&self) -> Result<(u64, Bm25Block)> {
514 let (index, offset) = self
515 .exact
516 .ok_or_else(|| HawDBError::Execution("BM25 cursor is not positioned".into()))?;
517 Ok((
518 self.decoded[offset].frequency,
519 kernel_block(self.postings.blocks[index].bounds),
520 ))
521 }
522}
523
524pub(super) struct IndexDocuments<'a> {
526 context: &'a ScanContext<'a>,
527 rows: Vec<(u64, SearchLengthBlock, usize)>,
528 rows_bytes: usize,
529}
530
531impl<'a> IndexDocuments<'a> {
532 pub(super) fn new(context: &'a ScanContext<'a>) -> Result<Self> {
533 let capacity = LENGTHS_WINDOW as usize;
534 let rows_bytes = capacity * std::mem::size_of::<(u64, SearchLengthBlock, usize)>();
535 context.admit(rows_bytes)?;
536 Ok(Self {
537 context,
538 rows: Vec::with_capacity(capacity),
539 rows_bytes,
540 })
541 }
542
543 fn entry(&mut self, ordinal: u64) -> Result<&hawdb_storage::relational::SearchDocumentEntry> {
544 let row = ordinal / SEARCH_INDEX_LENGTH_BLOCK_DOCUMENTS;
545 if self
546 .rows
547 .binary_search_by_key(&row, |entry| entry.0)
548 .is_err()
549 {
550 for (_, _, bytes) in self.rows.drain(..) {
553 self.context.release(bytes);
554 }
555 let last = row.saturating_add(LENGTHS_WINDOW - 1);
556 let context = self.context;
557 let rows = &mut self.rows;
558 context.runtime.visit_primary_key_range(
559 context.index,
560 &search_index_length_block_range(
561 row * SEARCH_INDEX_LENGTH_BLOCK_DOCUMENTS,
562 last.saturating_mul(SEARCH_INDEX_LENGTH_BLOCK_DOCUMENTS),
563 )
564 .map_err(integrity)?,
565 |read| {
566 context.charge(1)?;
567 let start =
568 search_index_length_block_start(read.value(2)?).map_err(integrity)?;
569 let row = start / SEARCH_INDEX_LENGTH_BLOCK_DOCUMENTS;
570 if rows.len() == LENGTHS_WINDOW as usize
571 || rows.last().is_some_and(|entry| entry.0 >= row)
572 {
573 return Err(corrupt(
574 "lengths window is out of order or exceeds its bound",
575 ));
576 }
577 let data = data(&read)?;
578 let bytes = (SEARCH_INDEX_LENGTH_BLOCK_DOCUMENTS as usize)
582 .saturating_mul(std::mem::size_of::<Option<SearchDocumentEntry>>())
583 .saturating_add(data.len());
584 context.admit(bytes)?;
585 let block = SearchLengthBlock::decode(data).map_err(integrity)?;
586 rows.push((row, block, bytes));
587 let mut evidence = context.evidence.borrow_mut();
588 evidence.lengths_rows_read = evidence.lengths_rows_read.saturating_add(1);
589 Ok(true)
590 },
591 )?;
592 }
593 self.rows
594 .binary_search_by_key(&row, |entry| entry.0)
595 .ok()
596 .and_then(|index| self.rows[index].1.get(ordinal))
597 .ok_or_else(|| corrupt("posting names an absent document"))
598 }
599}
600
601impl Drop for IndexDocuments<'_> {
602 fn drop(&mut self) {
603 for (_, _, bytes) in self.rows.drain(..) {
604 self.context.release(bytes);
605 }
606 self.context.release(self.rows_bytes);
607 }
608}
609
610impl Bm25Documents for IndexDocuments<'_> {
611 fn length(&mut self, ordinal: u64) -> Result<u64> {
612 Ok(self.entry(ordinal)?.length)
613 }
614
615 fn key(&mut self, ordinal: u64) -> Result<&[u8]> {
616 Ok(&self.entry(ordinal)?.key)
617 }
618
619 fn checkpoint(&mut self) -> Result<()> {
620 self.context.checkpoint()
621 }
622
623 fn admit(&mut self, bytes: usize) -> Result<()> {
624 self.context.admit(bytes)
625 }
626
627 fn release(&mut self, bytes: usize) {
628 self.context.release(bytes);
629 }
630}
631
632pub(super) fn rank_top_k(
635 context: &ScanContext<'_>,
636 terms: &[TermPostings],
637 average_length: f64,
638 k: usize,
639) -> Result<Vec<Bm25Hit>> {
640 let mut cursors = terms
641 .iter()
642 .map(|postings| Bm25Term {
643 cursor: IndexCursor::new(context, postings),
644 idf: postings.idf,
645 max_bound: postings.max_bound,
646 })
647 .collect::<Vec<_>>();
648 let mut documents = IndexDocuments::new(context)?;
649 let top = block_max_wand(&mut cursors, average_length, k, &mut documents)?;
650 let mut evidence = context.evidence.borrow_mut();
651 evidence.rounds += 1;
652 evidence.final_k = k;
653 evidence.ranked_rows = top.hits.len();
654 evidence.blocks_total = terms.iter().map(TermPostings::sealed_blocks).sum();
655 evidence.documents_scored = evidence
656 .documents_scored
657 .saturating_add(top.stats.documents_scored);
658 evidence.block_skips = evidence.block_skips.saturating_add(top.stats.block_skips);
659 evidence.terminated_early |= top.stats.terminated_early;
660 evidence.blocks_skipped = (evidence.blocks_total.saturating_mul(evidence.rounds as u64))
661 .saturating_sub(evidence.blocks_read);
662 Ok(top.hits)
663}