diff --git a/rust/lance-index/protos-cache/cache.proto b/rust/lance-index/protos-cache/cache.proto index e92da05815f..a861e2ef652 100644 --- a/rust/lance-index/protos-cache/cache.proto +++ b/rust/lance-index/protos-cache/cache.proto @@ -31,6 +31,8 @@ message CompressedPostingHeader { // Number of documents in each compressed posting block. Older cache entries // omit this field and decode as the legacy 128-doc block size. uint32 block_size = 6; + // Whether an impact IPC section follows the posting/position sections. + bool has_impacts = 7; } // Header for a serialized `PlainPostingList` cache entry. Followed by an Arrow diff --git a/rust/lance-index/src/scalar/inverted.rs b/rust/lance-index/src/scalar/inverted.rs index 55e2b2abce5..c7a3cdade51 100644 --- a/rust/lance-index/src/scalar/inverted.rs +++ b/rust/lance-index/src/scalar/inverted.rs @@ -4,6 +4,7 @@ pub mod builder; mod cache_codec; mod encoding; +mod impact; mod index; mod iter; pub mod json; diff --git a/rust/lance-index/src/scalar/inverted/builder.rs b/rust/lance-index/src/scalar/inverted/builder.rs index 0276bc0dc3a..7f91fe768f5 100644 --- a/rust/lance-index/src/scalar/inverted/builder.rs +++ b/rust/lance-index/src/scalar/inverted/builder.rs @@ -1734,11 +1734,27 @@ pub fn inverted_list_schema_for_version_with_block_size( with_position: bool, format_version: InvertedListFormatVersion, block_size: usize, +) -> SchemaRef { + inverted_list_schema_for_version_with_block_size_and_impacts( + with_position, + format_version, + block_size, + true, + ) +} + +pub(crate) fn inverted_list_schema_for_version_with_block_size_and_impacts( + with_position: bool, + format_version: InvertedListFormatVersion, + block_size: usize, + with_impacts: bool, ) -> SchemaRef { validate_format_version_block_size(format_version, block_size) .expect("invalid FTS format version for posting block size"); match format_version { - InvertedListFormatVersion::V1 => inverted_list_schema_v1(with_position, block_size), + InvertedListFormatVersion::V1 => { + inverted_list_schema_v1(with_position, block_size, with_impacts) + } InvertedListFormatVersion::V2 | InvertedListFormatVersion::V3 => { inverted_list_schema_with_tail_codec_and_position_codec( with_position, @@ -1746,12 +1762,17 @@ pub fn inverted_list_schema_for_version_with_block_size( PostingTailCodec::VarintDelta, Some(PositionStreamCodec::PackedDelta), block_size, + with_impacts, ) } } } -fn inverted_list_schema_v1(with_position: bool, block_size: usize) -> SchemaRef { +fn inverted_list_schema_v1( + with_position: bool, + block_size: usize, + with_impacts: bool, +) -> SchemaRef { let mut fields = vec![ arrow_schema::Field::new( POSTING_COL, @@ -1765,6 +1786,17 @@ fn inverted_list_schema_v1(with_position: bool, block_size: usize) -> SchemaRef arrow_schema::Field::new(MAX_SCORE_COL, datatypes::DataType::Float32, false), arrow_schema::Field::new(LENGTH_COL, datatypes::DataType::UInt32, false), ]; + if with_impacts { + fields.push(arrow_schema::Field::new( + IMPACT_COL, + datatypes::DataType::List(Arc::new(Field::new( + "item", + datatypes::DataType::LargeBinary, + true, + ))), + false, + )); + } if with_position { fields.push(arrow_schema::Field::new( POSITION_COL, @@ -1807,6 +1839,7 @@ pub fn inverted_list_schema_with_tail_codec( posting_tail_codec, Some(PositionStreamCodec::PackedDelta), LEGACY_BLOCK_SIZE, + false, ) } @@ -1816,6 +1849,7 @@ fn inverted_list_schema_with_tail_codec_and_position_codec( posting_tail_codec: PostingTailCodec, position_codec: Option, block_size: usize, + with_impacts: bool, ) -> SchemaRef { let mut fields = vec![ // we compress the posting lists (including row ids and frequencies), @@ -1832,6 +1866,17 @@ fn inverted_list_schema_with_tail_codec_and_position_codec( arrow_schema::Field::new(MAX_SCORE_COL, datatypes::DataType::Float32, false), arrow_schema::Field::new(LENGTH_COL, datatypes::DataType::UInt32, false), ]; + if with_impacts { + fields.push(arrow_schema::Field::new( + IMPACT_COL, + datatypes::DataType::List(Arc::new(Field::new( + "item", + datatypes::DataType::LargeBinary, + true, + ))), + false, + )); + } if with_position { fields.push(arrow_schema::Field::new( COMPRESSED_POSITION_COL, diff --git a/rust/lance-index/src/scalar/inverted/cache_codec.rs b/rust/lance-index/src/scalar/inverted/cache_codec.rs index fffb080bda1..bf36209d449 100644 --- a/rust/lance-index/src/scalar/inverted/cache_codec.rs +++ b/rust/lance-index/src/scalar/inverted/cache_codec.rs @@ -39,6 +39,7 @@ use crate::cache_pb::{ PostingTailCodec as PbPostingTailCodec, }; +use super::impact::ImpactSkipData; use super::index::{ CompressedPositionStorage, CompressedPostingList, PlainPostingList, PositionStreamCodec, Positions, PostingList, PostingListGroup, PostingTailCodec, SharedPositionStream, @@ -96,6 +97,7 @@ const BLOCK_OFFSETS_COLUMN: &str = "block_offsets"; const ROW_IDS_COLUMN: &str = "row_ids"; const FREQUENCIES_COLUMN: &str = "frequencies"; const BLOCKS_COLUMN: &str = "blocks"; +const IMPACTS_COLUMN: &str = "impacts"; fn legacy_positions_batch(list: &ListArray) -> Result { let schema = Arc::new(Schema::new(vec![Field::new( @@ -179,7 +181,7 @@ fn read_position_sections( impl CacheCodecImpl for PostingList { const TYPE_ID: &'static str = "lance.fts.PostingList"; - const CURRENT_VERSION: u32 = 1; + const CURRENT_VERSION: u32 = 2; fn serialize(&self, w: &mut CacheEntryWriter<'_>) -> Result<()> { match self { @@ -293,6 +295,7 @@ fn serialize_compressed( position_storage: position_storage as i32, position_stream_codec: position_stream_codec as i32, block_size: posting.block_size as u32, + has_impacts: posting.impacts.is_some(), }; w.write_header(&header)?; @@ -307,6 +310,15 @@ fn serialize_compressed( if let Some(storage) = &posting.positions { write_position_sections(w, storage)?; } + if let Some(impacts) = &posting.impacts { + let schema = Arc::new(Schema::new(vec![Field::new( + IMPACTS_COLUMN, + DataType::LargeBinary, + false, + )])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(impacts.entries().clone())])?; + w.write_ipc(&batch)?; + } Ok(()) } @@ -329,6 +341,22 @@ fn deserialize_compressed(r: &mut CacheEntryReader<'_>) -> Result= 2 && header.has_impacts { + let batch = r.read_ipc()?; + let entries = batch + .column(0) + .as_any() + .downcast_ref::() + .ok_or_else(|| Error::io("impacts column is not a LargeBinaryArray".to_string()))? + .clone(); + Some(ImpactSkipData::new( + entries, + blocks.len(), + super::impact::ImpactFormat::for_block_size(block_size), + )?) + } else { + None + }; Ok(CompressedPostingList::new( blocks, @@ -337,6 +365,7 @@ fn deserialize_compressed(r: &mut CacheEntryReader<'_>) -> Result) -> Result) -> Result<()> { let count = u32::try_from(self.posting_lists.len()) @@ -418,12 +447,13 @@ impl CacheCodecImpl for Positions { #[cfg(test)] mod tests { use arrow::buffer::ScalarBuffer; - use arrow_array::LargeBinaryArray; - use arrow_array::builder::{Int32Builder, ListBuilder}; + use arrow_array::builder::{Int32Builder, LargeBinaryBuilder, ListBuilder}; + use arrow_array::{Array, LargeBinaryArray}; use bytes::Bytes; use lance_core::Result; use lance_core::cache::{CacheCodecImpl, CacheEntryReader, CacheEntryWriter}; + use super::super::impact::ImpactSkipData; use super::super::index::{ CompressedPositionStorage, CompressedPostingList, PlainPostingList, PositionStreamCodec, Positions, PostingList, PostingListGroup, PostingTailCodec, SharedPositionStream, @@ -469,6 +499,44 @@ mod tests { } } + fn impact_entry(doc_up_to: u32, pairs: &[(u32, u32)]) -> Vec { + let mut bytes = Vec::with_capacity(8 + pairs.len() * 8); + bytes.extend_from_slice(&doc_up_to.to_le_bytes()); + bytes.extend_from_slice(&(pairs.len() as u32).to_le_bytes()); + for (freq, doc_len) in pairs { + bytes.extend_from_slice(&freq.to_le_bytes()); + bytes.extend_from_slice(&doc_len.to_le_bytes()); + } + bytes + } + + fn impact_skip_data(level0_len: usize) -> ImpactSkipData { + let mut entries = Vec::with_capacity(level0_len + level0_len.div_ceil(32)); + for block_idx in 0..level0_len { + entries.push(impact_entry( + (block_idx as u32 + 1) * 10 - 1, + &[(block_idx as u32 + 1, 10)], + )); + } + let num_level1 = level0_len.div_ceil(32); + for group_idx in 0..num_level1 { + let group_end = ((group_idx + 1) * 32).min(level0_len); + let doc_up_to = group_end as u32 * 10 - 1; + entries.push(impact_entry(doc_up_to, &[(1, 10), (2, 8)])); + } + let mut builder = LargeBinaryBuilder::with_capacity(entries.len(), 0); + for entry in entries { + builder.append_value(entry); + } + let array = builder.finish(); + ImpactSkipData::new( + array, + level0_len, + super::super::impact::ImpactFormat::FixedU32, + ) + .unwrap() + } + /// Serialize a codec body (no envelope) into a standalone buffer. fn body_bytes(entry: &T) -> Bytes { let mut buf = Vec::new(); @@ -483,6 +551,11 @@ mod tests { T::deserialize(&mut r) } + fn from_body_version(data: &Bytes, version: u32) -> Result { + let mut r = CacheEntryReader::new(data, 0, version); + T::deserialize(&mut r) + } + fn roundtrip_posting_list(entry: &PostingList) -> PostingList { from_body::(&body_bytes(entry)).unwrap() } @@ -540,8 +613,15 @@ mod tests { Some(&[1u8, 2, 3, 4, 5][..]), Some(&[6, 7, 8, 9, 10][..]), ]); - let posting = - CompressedPostingList::new(blocks, 3.5, 42, PostingTailCodec::VarintDelta, 256, None); + let posting = CompressedPostingList::new( + blocks, + 3.5, + 42, + PostingTailCodec::VarintDelta, + 256, + None, + None, + ); let entry = PostingList::Compressed(posting.clone()); match roundtrip_posting_list(&entry) { PostingList::Compressed(restored) => { @@ -556,6 +636,53 @@ mod tests { } } + #[test] + fn compressed_posting_list_impacts_roundtrip() { + let blocks = LargeBinaryArray::from_opt_vec(vec![ + Some(&[1u8, 2, 3, 4, 5][..]), + Some(&[6, 7, 8, 9, 10][..]), + ]); + let impacts = impact_skip_data(blocks.len()); + let posting = CompressedPostingList::new( + blocks, + 3.5, + 42, + PostingTailCodec::VarintDelta, + 256, + None, + Some(impacts.clone()), + ); + let entry = PostingList::Compressed(posting); + match roundtrip_posting_list(&entry) { + PostingList::Compressed(restored) => { + let restored = restored.impacts.expect("impacts should roundtrip"); + assert_eq!(restored.level0_len(), impacts.level0_len()); + assert_eq!(restored.level1_len(), impacts.level1_len()); + assert_eq!(restored.entries(), impacts.entries()); + } + PostingList::Plain(_) => panic!("expected Compressed variant"), + } + } + + #[test] + fn compressed_posting_list_v1_cache_without_impacts_decodes() { + let posting = CompressedPostingList::new( + LargeBinaryArray::from_opt_vec(vec![Some(&[1u8, 2, 3][..])]), + 1.25, + 5, + PostingTailCodec::Fixed32, + crate::scalar::inverted::LEGACY_BLOCK_SIZE, + None, + None, + ); + let data = body_bytes(&PostingList::Compressed(posting)); + let restored = from_body_version::(&data, 1).unwrap(); + let PostingList::Compressed(restored) = restored else { + panic!("expected Compressed variant"); + }; + assert!(restored.impacts.is_none()); + } + #[test] fn compressed_posting_list_legacy_positions_roundtrip() { let blocks = LargeBinaryArray::from_opt_vec(vec![Some(&[1u8, 2, 3][..])]); @@ -568,6 +695,7 @@ mod tests { Some(CompressedPositionStorage::LegacyPerDoc(legacy_positions( &[&[0, 4, 8]], ))), + None, ); let entry = PostingList::Compressed(posting.clone()); match roundtrip_posting_list(&entry) { @@ -601,6 +729,7 @@ mod tests { PostingTailCodec::VarintDelta, 256, Some(CompressedPositionStorage::SharedStream(stream)), + None, ); let entry = PostingList::Compressed(posting.clone()); match roundtrip_posting_list(&entry) { @@ -632,6 +761,7 @@ mod tests { Some(CompressedPositionStorage::SharedStream( expected_stream.clone(), )), + None, ); let serialized = body_bytes(&PostingList::Compressed(posting)); @@ -665,6 +795,7 @@ mod tests { PostingTailCodec::VarintDelta, 256, None, + None, )); for members in [ @@ -689,6 +820,64 @@ mod tests { } } + #[test] + fn posting_list_group_impacted_compressed_members_roundtrip() { + let first = CompressedPostingList::new( + LargeBinaryArray::from_opt_vec(vec![Some(&[1u8, 2, 3][..]), Some(&[4u8, 5, 6][..])]), + 3.0, + 256, + PostingTailCodec::VarintDelta, + crate::scalar::inverted::LEGACY_BLOCK_SIZE, + None, + Some(impact_skip_data(2)), + ); + let second = CompressedPostingList::new( + LargeBinaryArray::from_opt_vec(vec![Some(&[7u8, 8, 9][..])]), + 5.0, + 128, + PostingTailCodec::Fixed32, + 256, + Some(CompressedPositionStorage::SharedStream( + SharedPositionStream::new( + PositionStreamCodec::PackedDelta, + vec![0u32, 12], + Bytes::from(vec![0xABu8; 32]), + ), + )), + Some(impact_skip_data(1)), + ); + let members = vec![ + PostingList::Compressed(first.clone()), + PostingList::Compressed(second.clone()), + ]; + let group = PostingListGroup::new(members); + let restored = from_body::(&body_bytes(&group)).unwrap(); + assert_eq!(restored.posting_lists.len(), 2); + + let expected = [&first, &second]; + for (expected, restored) in expected.iter().zip(restored.posting_lists.iter()) { + let PostingList::Compressed(restored) = restored else { + panic!("expected compressed member"); + }; + assert_eq!(restored.blocks, expected.blocks); + assert_eq!(restored.length, expected.length); + assert_eq!(restored.max_score, expected.max_score); + assert_eq!(restored.posting_tail_codec, expected.posting_tail_codec); + assert_eq!(restored.block_size, expected.block_size); + assert_eq!( + restored.impacts.as_ref().unwrap().entries(), + expected.impacts.as_ref().unwrap().entries() + ); + match (&expected.positions, &restored.positions) { + (Some(expected), Some(restored)) => { + assert_position_storage_eq(expected, restored); + } + (None, None) => {} + _ => panic!("position storage mismatch"), + } + } + } + #[test] fn positions_legacy_roundtrip() { let positions = Positions(CompressedPositionStorage::LegacyPerDoc(legacy_positions( @@ -775,6 +964,7 @@ mod tests { PostingTailCodec::VarintDelta, 256, Some(CompressedPositionStorage::SharedStream(stream)), + None, )) } @@ -826,6 +1016,7 @@ mod tests { PostingTailCodec::VarintDelta, 256, None, + None, )) }; let group = PostingListGroup::new(vec![make_member(9), make_member(1)]); diff --git a/rust/lance-index/src/scalar/inverted/impact.rs b/rust/lance-index/src/scalar/inverted/impact.rs new file mode 100644 index 00000000000..b465d0e7cfe --- /dev/null +++ b/rust/lance-index/src/scalar/inverted/impact.rs @@ -0,0 +1,765 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The Lance Authors + +use std::sync::{Arc, OnceLock}; + +use arrow_array::builder::LargeBinaryBuilder; +use arrow_array::{Array, LargeBinaryArray}; +use lance_core::{Error, Result}; + +use super::scorer::Scorer; + +pub const IMPACT_LEVEL1_BLOCKS: usize = 32; +const SMALL_FRONTIER_FREQ_LIMIT: usize = 256; + +/// On-disk encoding of one impact entry. +/// +/// `FixedU32` (128-doc blocks): [doc_up_to u32][pair_count u32][(freq u32, +/// doc_len u32)...]. `Varint` (256-doc blocks, format V3): [doc_up_to varint] +/// [pair_count varint][(freq delta varint, doc_len varint)...] with the +/// frontier's freqs delta-encoded in ascending order — pairs shrink from 8 +/// bytes to ~2-3. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ImpactFormat { + FixedU32, + Varint, +} + +impl ImpactFormat { + pub fn for_block_size(block_size: usize) -> Self { + if block_size == 256 { + Self::Varint + } else { + Self::FixedU32 + } + } +} + +#[derive(Debug, Clone)] +pub struct ImpactSkipData { + entries: LargeBinaryArray, + level0_len: usize, + format: ImpactFormat, + // Last doc id covered by each entry (level0 entries then level1 entries), + // decoded once at construction; u32::MAX marks malformed entries. + entry_doc_up_tos: Arc<[u32]>, + // Per-entry max doc weight plus the list-wide max, baked on first use and + // shared across the per-query clones of a cached list. Doc weights depend + // only on (freq, doc_len) and index-wide stats (e.g. BM25 avgdl), not the + // query. Malformed entries bake to INFINITY so pruning stays safe. + doc_weight_bounds: Arc, f32)>>, +} + +impl PartialEq for ImpactSkipData { + fn eq(&self, other: &Self) -> bool { + self.entries == other.entries && self.level0_len == other.level0_len + } +} + +#[derive(Debug, Clone, Copy)] +pub struct ImpactScore { + pub score: f32, + pub entries_scanned: usize, +} + +#[derive(Debug, Default, Clone)] +pub struct ImpactScoreCache {} + +impl ImpactScoreCache { + fn entry_score( + &mut self, + impacts: &ImpactSkipData, + entry_idx: usize, + query_weight: f32, + scorer: &S, + ) -> f32 { + if query_weight <= 0.0 { + return 0.0; + } + query_weight * impacts.doc_weight_bounds(scorer)[entry_idx] + } +} + +#[derive(Debug, Clone, Copy)] +struct ImpactEntryHeader { + doc_up_to: u32, + pair_count: usize, +} + +impl ImpactSkipData { + pub fn new(entries: LargeBinaryArray, level0_len: usize, format: ImpactFormat) -> Result { + let expected_len = level0_len + level1_len(level0_len); + if entries.len() != expected_len { + return Err(Error::index(format!( + "impact entry count mismatch: got {}, expected {} for {} level0 blocks", + entries.len(), + expected_len, + level0_len + ))); + } + let entry_doc_up_tos = (0..entries.len()) + .map(|entry_idx| { + if entries.is_null(entry_idx) { + return u32::MAX; + } + decode_entry_doc_up_to(entries.value(entry_idx), format).unwrap_or(u32::MAX) + }) + .collect::>(); + Ok(Self { + entries, + level0_len, + format, + entry_doc_up_tos, + doc_weight_bounds: Arc::new(OnceLock::new()), + }) + } + + fn baked_bounds(&self, scorer: &S) -> &(Box<[f32]>, f32) { + self.doc_weight_bounds.get_or_init(|| { + // V3 (Varint impacts <=> 256-doc blocks) scores with quantized doc + // lengths, so bake the bounds against the same quantized lengths. + // Quantization is monotone, so pareto dominance among the stored + // (freq, doc_len) frontier pairs is preserved and the frontier max + // still bounds every doc in the range. + let quantized = self.format == ImpactFormat::Varint; + let per_entry = (0..self.entries.len()) + .map(|entry_idx| { + let bytes = self.entries.value(entry_idx); + let mut max_doc_weight = 0.0_f32; + match for_each_entry_pair(bytes, self.format, |freq, doc_len| { + let doc_len = if quantized { + super::index::dequantize_doc_length(super::index::quantize_doc_length( + doc_len, + )) + } else { + doc_len + }; + max_doc_weight = max_doc_weight.max(scorer.doc_weight(freq, doc_len)); + }) { + Ok(()) => max_doc_weight, + Err(_) => f32::INFINITY, + } + }) + .collect::>(); + // The level1 entries cover every block, so their max is the + // list-wide max doc weight; fall back to level0 entries for lists + // too short to have a level1 entry. + let global = if per_entry.len() > self.level0_len { + per_entry[self.level0_len..] + .iter() + .copied() + .fold(0.0_f32, f32::max) + } else { + per_entry.iter().copied().fold(0.0_f32, f32::max) + }; + (per_entry, global) + }) + } + + fn doc_weight_bounds(&self, scorer: &S) -> &[f32] { + &self.baked_bounds(scorer).0 + } + + /// List-wide max doc weight, from the baked bounds. The tightest valid + /// global score bound for this list is `query_weight * this`, matching + /// what the non-impact format stores as `max_score` at build time — but + /// computed against the current index stats. + pub fn global_max_doc_weight(&self, scorer: &S) -> f32 { + self.baked_bounds(scorer).1 + } + + pub fn entries(&self) -> &LargeBinaryArray { + &self.entries + } + + #[cfg(test)] + pub fn level0_len(&self) -> usize { + self.level0_len + } + + #[cfg(test)] + pub fn level1_len(&self) -> usize { + level1_len(self.level0_len) + } + + pub(crate) fn level1_doc_up_to(&self, group_idx: usize) -> Option { + if group_idx >= level1_len(self.level0_len) { + return None; + } + match self.entry_doc_up_tos[self.level0_len + group_idx] { + u32::MAX => None, + doc_up_to => Some(doc_up_to), + } + } + + /// Max score of the docs covered by the level0 entry of `block_idx`, + /// answered from the baked bounds slab. + // Only tests exercise the uncached form until the maxscore rework + // (stacked follow-up) anchors its block-max caches on it. + #[cfg_attr(not(test), allow(dead_code))] + pub fn level0_score( + &self, + block_idx: usize, + query_weight: f32, + scorer: &S, + ) -> f32 { + if block_idx >= self.level0_len || query_weight <= 0.0 { + return 0.0; + } + query_weight * self.doc_weight_bounds(scorer)[block_idx] + } + + pub fn level0_score_cached( + &self, + block_idx: usize, + query_weight: f32, + scorer: &S, + cache: &mut ImpactScoreCache, + ) -> f32 { + if block_idx >= self.level0_len { + return 0.0; + } + cache.entry_score(self, block_idx, query_weight, scorer) + } + + #[cfg(test)] + pub fn max_score_up_to( + &self, + start_block_idx: usize, + up_to: u64, + _block_least_doc_id: F, + query_weight: f32, + scorer: &S, + ) -> ImpactScore + where + S: Scorer + ?Sized, + F: FnMut(usize) -> u32, + { + self.max_score_up_to_with(start_block_idx, up_to, |impacts, entry_idx| { + impacts.entry_score(entry_idx, query_weight, scorer) + }) + } + + pub fn max_score_up_to_cached( + &self, + start_block_idx: usize, + up_to: u64, + query_weight: f32, + scorer: &S, + cache: &mut ImpactScoreCache, + ) -> ImpactScore + where + S: Scorer + ?Sized, + { + self.max_score_up_to_with(start_block_idx, up_to, |impacts, entry_idx| { + cache.entry_score(impacts, entry_idx, query_weight, scorer) + }) + } + + fn max_score_up_to_with( + &self, + start_block_idx: usize, + up_to: u64, + mut entry_score: E, + ) -> ImpactScore + where + E: FnMut(&Self, usize) -> f32, + { + let mut block_idx = start_block_idx; + let mut max_score = 0.0_f32; + let mut entries_scanned = 0usize; + + while block_idx < self.level0_len { + let group_idx = block_idx / IMPACT_LEVEL1_BLOCKS; + let group_start = group_idx * IMPACT_LEVEL1_BLOCKS; + let group_end = ((group_idx + 1) * IMPACT_LEVEL1_BLOCKS).min(self.level0_len); + if block_idx == group_start { + let level1_entry_idx = self.level0_len + group_idx; + match self.entry_doc_up_tos[level1_entry_idx] { + u32::MAX => { + return ImpactScore { + score: f32::INFINITY, + entries_scanned: entries_scanned + 1, + }; + } + doc_up_to if u64::from(doc_up_to) <= up_to => { + max_score = max_score.max(entry_score(self, level1_entry_idx)); + entries_scanned += 1; + block_idx = group_end; + continue; + } + _ => {} + } + } + + max_score = max_score.max(entry_score(self, block_idx)); + entries_scanned += 1; + match self.entry_doc_up_tos[block_idx] { + u32::MAX => { + return ImpactScore { + score: f32::INFINITY, + entries_scanned, + }; + } + doc_up_to if u64::from(doc_up_to) >= up_to => break, + _ => {} + } + block_idx += 1; + } + + ImpactScore { + score: max_score, + entries_scanned, + } + } + + #[cfg(test)] + fn entry_score( + &self, + entry_idx: usize, + query_weight: f32, + scorer: &S, + ) -> f32 { + if query_weight <= 0.0 { + return 0.0; + } + let bytes = self.entries.value(entry_idx); + let mut max_doc_weight = 0.0_f32; + if for_each_entry_pair(bytes, self.format, |freq, doc_len| { + max_doc_weight = max_doc_weight.max(scorer.doc_weight(freq, doc_len)); + }) + .is_err() + { + return f32::INFINITY; + } + query_weight * max_doc_weight + } +} + +pub struct ImpactSkipDataBuilder { + entries: LargeBinaryBuilder, + level0_len: usize, + level1_entries: Vec>, + level1_docs: Vec<(u32, u32, u32)>, + format: ImpactFormat, +} + +impl ImpactSkipDataBuilder { + pub fn with_capacity(level0_blocks: usize, block_size: usize) -> Self { + Self { + entries: LargeBinaryBuilder::with_capacity( + level0_blocks + level1_len(level0_blocks), + 0, + ), + level0_len: 0, + level1_entries: Vec::with_capacity(level1_len(level0_blocks)), + level1_docs: Vec::with_capacity(IMPACT_LEVEL1_BLOCKS * block_size), + format: ImpactFormat::for_block_size(block_size), + } + } + + pub fn append_block(&mut self, docs: &[(u32, u32, u32)]) -> Result<()> { + let bytes = encode_impact_entry(docs, self.format)?; + self.entries.append_value(bytes.as_slice()); + self.level0_len += 1; + self.level1_docs.extend_from_slice(docs); + if self.level0_len.is_multiple_of(IMPACT_LEVEL1_BLOCKS) { + self.flush_level1()?; + } + Ok(()) + } + + pub fn finish(mut self) -> Result { + if !self.level1_docs.is_empty() { + self.flush_level1()?; + } + for entry in self.level1_entries { + self.entries.append_value(entry.as_slice()); + } + ImpactSkipData::new(self.entries.finish(), self.level0_len, self.format) + } + + fn flush_level1(&mut self) -> Result<()> { + let bytes = encode_impact_entry(self.level1_docs.as_slice(), self.format)?; + self.level1_entries.push(bytes); + self.level1_docs.clear(); + Ok(()) + } +} + +#[cfg(test)] +pub fn build_impact_skip_data(blocks: &[Vec<(u32, u32, u32)>]) -> Result { + let block_size = blocks.iter().map(Vec::len).max().unwrap_or(0).max(1); + let mut builder = ImpactSkipDataBuilder::with_capacity(blocks.len(), block_size); + for block in blocks { + builder.append_block(block)?; + } + builder.finish() +} + +fn encode_impact_entry(docs: &[(u32, u32, u32)], format: ImpactFormat) -> Result> { + let doc_up_to = docs + .last() + .map(|(doc_id, _, _)| *doc_id) + .unwrap_or_default(); + let frontier = impact_frontier(docs); + let pair_count = u32::try_from(frontier.len()).map_err(|_| { + Error::index("impact frontier too large to encode as u32 pair count".to_string()) + })?; + let mut bytes = Vec::with_capacity(8 + frontier.len() * 8); + match format { + ImpactFormat::FixedU32 => { + bytes.extend_from_slice(&doc_up_to.to_le_bytes()); + bytes.extend_from_slice(&pair_count.to_le_bytes()); + for (freq, doc_len) in frontier { + bytes.extend_from_slice(&freq.to_le_bytes()); + bytes.extend_from_slice(&doc_len.to_le_bytes()); + } + } + ImpactFormat::Varint => { + super::encoding::encode_varint_u32(&mut bytes, doc_up_to); + super::encoding::encode_varint_u32(&mut bytes, pair_count); + let mut previous_freq = 0u32; + for (freq, doc_len) in frontier { + super::encoding::encode_varint_u32(&mut bytes, freq - previous_freq); + super::encoding::encode_varint_u32(&mut bytes, doc_len); + previous_freq = freq; + } + } + } + Ok(bytes) +} + +fn decode_entry_doc_up_to(bytes: &[u8], format: ImpactFormat) -> Result { + match format { + ImpactFormat::FixedU32 => decode_header(bytes).map(|header| header.doc_up_to), + ImpactFormat::Varint => { + let mut offset = 0usize; + super::encoding::decode_varint_u32(bytes, &mut offset) + } + } +} + +/// Walk an entry's (freq, doc_len) frontier pairs, validating the layout. +fn for_each_entry_pair( + bytes: &[u8], + format: ImpactFormat, + mut visit: impl FnMut(u32, u32), +) -> Result<()> { + match format { + ImpactFormat::FixedU32 => { + let header = decode_header(bytes)?; + let mut offset = 8usize; + for _ in 0..header.pair_count { + visit(read_u32_le(bytes, offset), read_u32_le(bytes, offset + 4)); + offset += 8; + } + } + ImpactFormat::Varint => { + let mut offset = 0usize; + let _doc_up_to = super::encoding::decode_varint_u32(bytes, &mut offset)?; + let pair_count = super::encoding::decode_varint_u32(bytes, &mut offset)?; + let mut freq = 0u32; + for _ in 0..pair_count { + freq = freq + .checked_add(super::encoding::decode_varint_u32(bytes, &mut offset)?) + .ok_or_else(|| Error::index("impact freq delta overflow".to_owned()))?; + let doc_len = super::encoding::decode_varint_u32(bytes, &mut offset)?; + visit(freq, doc_len); + } + if offset != bytes.len() { + return Err(Error::index(format!( + "impact varint entry has {} trailing bytes", + bytes.len() - offset + ))); + } + } + } + Ok(()) +} + +fn impact_frontier(docs: &[(u32, u32, u32)]) -> Vec<(u32, u32)> { + let max_freq = docs.iter().map(|(_, freq, _)| *freq).max().unwrap_or(0) as usize; + if max_freq <= SMALL_FRONTIER_FREQ_LIMIT { + return impact_frontier_small_freq(docs, max_freq); + } + + impact_frontier_sparse_freq(docs) +} + +fn impact_frontier_small_freq(docs: &[(u32, u32, u32)], max_freq: usize) -> Vec<(u32, u32)> { + let mut min_doc_len_by_freq = [u32::MAX; SMALL_FRONTIER_FREQ_LIMIT + 1]; + for (_, freq, doc_len) in docs { + min_doc_len_by_freq[*freq as usize] = min_doc_len_by_freq[*freq as usize].min(*doc_len); + } + + let min_doc_lens = min_doc_len_by_freq[..=max_freq] + .iter() + .enumerate() + .filter_map(|(freq, doc_len)| (*doc_len != u32::MAX).then_some((freq as u32, *doc_len))) + .collect::>(); + frontier_from_min_doc_lens(min_doc_lens) +} + +fn impact_frontier_sparse_freq(docs: &[(u32, u32, u32)]) -> Vec<(u32, u32)> { + let mut pairs = docs + .iter() + .map(|(_, freq, doc_len)| (*freq, *doc_len)) + .collect::>(); + pairs.sort_unstable_by_key(|(freq, _)| *freq); + + let mut min_doc_lens: Vec<(u32, u32)> = Vec::with_capacity(pairs.len()); + for (freq, doc_len) in pairs { + match min_doc_lens.last_mut() { + Some((last_freq, last_doc_len)) if *last_freq == freq => { + *last_doc_len = (*last_doc_len).min(doc_len); + } + _ => min_doc_lens.push((freq, doc_len)), + } + } + + frontier_from_min_doc_lens(min_doc_lens) +} + +fn frontier_from_min_doc_lens(min_doc_lens: Vec<(u32, u32)>) -> Vec<(u32, u32)> { + let mut best_doc_len = u32::MAX; + let mut frontier = Vec::with_capacity(min_doc_lens.len()); + for (freq, doc_len) in min_doc_lens.into_iter().rev() { + if doc_len < best_doc_len { + frontier.push((freq, doc_len)); + best_doc_len = doc_len; + } + } + frontier.reverse(); + frontier +} + +fn decode_header(bytes: &[u8]) -> Result { + if bytes.len() < 8 { + return Err(Error::index(format!( + "impact entry too short: {} bytes", + bytes.len() + ))); + } + let pair_count = read_u32_le(bytes, 4) as usize; + let expected_len = 8 + pair_count * 8; + if bytes.len() != expected_len { + return Err(Error::index(format!( + "impact entry length mismatch: got {} bytes, expected {} for {} pairs", + bytes.len(), + expected_len, + pair_count + ))); + } + Ok(ImpactEntryHeader { + doc_up_to: read_u32_le(bytes, 0), + pair_count, + }) +} + +#[inline] +fn read_u32_le(bytes: &[u8], offset: usize) -> u32 { + let mut value = [0u8; 4]; + value.copy_from_slice(&bytes[offset..offset + 4]); + u32::from_le_bytes(value) +} + +fn level1_len(level0_len: usize) -> usize { + level0_len.div_ceil(IMPACT_LEVEL1_BLOCKS) +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use super::*; + use crate::scalar::inverted::scorer::{MemBM25Scorer, Scorer}; + + #[test] + fn impact_entry_frontier_drops_dominated_pairs() { + let docs = vec![(0, 1, 10), (1, 1, 8), (2, 2, 9), (3, 3, 20)]; + assert_eq!(impact_frontier(&docs), vec![(1, 8), (2, 9), (3, 20)]); + } + + #[test] + fn impact_entry_frontier_handles_sparse_large_frequencies() { + let docs = vec![ + (0, 1, 100), + (1, 1, 80), + (2, 512, 90), + (3, 1_000, 120), + (4, 1_000, 110), + ]; + assert_eq!( + impact_frontier(&docs), + vec![(1, 80), (512, 90), (1_000, 110)] + ); + } + + #[test] + fn impact_max_score_can_use_level1_entry() { + let blocks = (0..40) + .map(|block| vec![(block as u32, 1 + block as u32 % 3, 10)]) + .collect::>(); + let impacts = build_impact_skip_data(&blocks).unwrap(); + assert_eq!(impacts.level0_len(), 40); + assert_eq!(impacts.level1_len(), 2); + let scorer = MemBM25Scorer::new(400, 40, HashMap::from([(String::from("token"), 40usize)])); + let score = impacts.max_score_up_to(0, 31, |idx| idx as u32, 1.0, &scorer); + assert!(score.entries_scanned < IMPACT_LEVEL1_BLOCKS); + assert!(score.score > 0.0); + } + + #[test] + fn impact_level1_doc_up_to_reports_full_and_partial_groups() { + let blocks = (0..40) + .map(|block| vec![(block as u32, 1, 10)]) + .collect::>(); + let impacts = build_impact_skip_data(&blocks).unwrap(); + + assert_eq!( + impacts.level1_doc_up_to(0), + Some((IMPACT_LEVEL1_BLOCKS - 1) as u32) + ); + assert_eq!(impacts.level1_doc_up_to(1), Some(39)); + assert_eq!(impacts.level1_doc_up_to(2), None); + } + + #[test] + fn impact_level1_doc_up_to_returns_none_for_malformed_entry() { + let level0 = encode_impact_entry(&[(0, 1, 10)], ImpactFormat::FixedU32).unwrap(); + let malformed_level1 = vec![1, 2, 3]; + let entries = LargeBinaryArray::from_opt_vec(vec![ + Some(level0.as_slice()), + Some(malformed_level1.as_slice()), + ]); + let impacts = ImpactSkipData::new(entries, 1, ImpactFormat::FixedU32).unwrap(); + + assert_eq!(impacts.level1_doc_up_to(0), None); + } + + #[test] + fn impact_score_cache_matches_uncached_scores() { + let blocks = (0..40) + .map(|block| vec![(block as u32, 1 + block as u32 % 3, 10)]) + .collect::>(); + let impacts = build_impact_skip_data(&blocks).unwrap(); + let scorer = MemBM25Scorer::new(400, 40, HashMap::from([(String::from("token"), 40usize)])); + let mut cache = ImpactScoreCache::default(); + + let uncached_level0 = impacts.level0_score(3, 1.0, &scorer); + let cached_level0 = impacts.level0_score_cached(3, 1.0, &scorer, &mut cache); + assert_eq!(cached_level0, uncached_level0); + + let uncached = impacts.max_score_up_to(0, 31, |idx| idx as u32, 1.0, &scorer); + let cached = impacts.max_score_up_to_cached(0, 31, 1.0, &scorer, &mut cache); + assert_eq!(cached.score, uncached.score); + assert_eq!(cached.entries_scanned, uncached.entries_scanned); + } + + #[test] + fn impact_entries_are_decoded_lazily() { + let level0_0 = encode_impact_entry(&[(0, 1, 10)], ImpactFormat::FixedU32).unwrap(); + let malformed_level0_1 = vec![1, 2, 3]; + let level1 = + encode_impact_entry(&[(0, 1, 10), (1, 1, 10)], ImpactFormat::FixedU32).unwrap(); + let entries = LargeBinaryArray::from_opt_vec(vec![ + Some(level0_0.as_slice()), + Some(malformed_level0_1.as_slice()), + Some(level1.as_slice()), + ]); + let impacts = ImpactSkipData::new(entries, 2, ImpactFormat::FixedU32).unwrap(); + let scorer = MemBM25Scorer::new(10, 10, HashMap::from([(String::from("token"), 2usize)])); + + let score = impacts.max_score_up_to(0, 0, |_| 0, 1.0, &scorer); + assert!(score.score.is_finite()); + assert_eq!(score.entries_scanned, 1); + + let mut cache = ImpactScoreCache::default(); + assert_eq!( + impacts.level0_score_cached(1, 1.0, &scorer, &mut cache), + f32::INFINITY + ); + } + + #[test] + fn impact_varint_entries_roundtrip_and_match_fixed() { + let docs = vec![(3, 1, 100), (9, 2, 40), (200, 7, 80), (4095, 130, 900)]; + let fixed = encode_impact_entry(&docs, ImpactFormat::FixedU32).unwrap(); + let varint = encode_impact_entry(&docs, ImpactFormat::Varint).unwrap(); + assert!(varint.len() < fixed.len()); + assert_eq!( + decode_entry_doc_up_to(&fixed, ImpactFormat::FixedU32).unwrap(), + decode_entry_doc_up_to(&varint, ImpactFormat::Varint).unwrap() + ); + let mut fixed_pairs = Vec::new(); + for_each_entry_pair(&fixed, ImpactFormat::FixedU32, |f, l| { + fixed_pairs.push((f, l)) + }) + .unwrap(); + let mut varint_pairs = Vec::new(); + for_each_entry_pair(&varint, ImpactFormat::Varint, |f, l| { + varint_pairs.push((f, l)) + }) + .unwrap(); + assert_eq!(fixed_pairs, varint_pairs); + assert!(!fixed_pairs.is_empty()); + + // a 256-doc-block skip data goes through the varint path end to end + let blocks: Vec> = (0..3) + .map(|b| (0..256).map(|i| (b * 256 + i, 1 + i % 5, 10)).collect()) + .collect(); + let impacts = build_impact_skip_data(&blocks).unwrap(); + assert_eq!(impacts.level1_doc_up_to(0), Some(767)); + let scorer = MemBM25Scorer::new(400, 768, HashMap::from([(String::from("t"), 768usize)])); + assert!(impacts.level0_score(0, 1.0, &scorer).is_finite()); + let level1 = impacts.max_score_up_to(0, 767, |idx| (idx * 256) as u32, 1.0, &scorer); + assert!(level1.score.is_finite() && level1.score > 0.0); + } + + #[test] + fn impact_upper_bound_covers_real_scores() { + let blocks = vec![ + vec![(0, 1, 100), (3, 2, 40), (7, 4, 80)], + vec![(9, 3, 15), (10, 1, 5), (12, 5, 30)], + vec![(16, 2, 10), (18, 6, 70), (21, 3, 12)], + vec![(24, 1, 4), (28, 7, 100), (30, 2, 8)], + ]; + let impacts = build_impact_skip_data(&blocks).unwrap(); + let scorer = MemBM25Scorer::new(474, 31, HashMap::from([(String::from("token"), 4usize)])); + let query_weight = scorer.query_weight("token"); + + for start_block_idx in 0..blocks.len() { + let up_to = blocks + .iter() + .skip(start_block_idx) + .take(2) + .flatten() + .map(|(doc_id, _, _)| *doc_id) + .max() + .unwrap(); + let upper_bound = impacts.max_score_up_to( + start_block_idx, + u64::from(up_to), + |idx| blocks[idx][0].0, + query_weight, + &scorer, + ); + let exact_max = blocks + .iter() + .skip(start_block_idx) + .flatten() + .take_while(|(doc_id, _, _)| *doc_id <= up_to) + .map(|(_, freq, doc_len)| query_weight * scorer.doc_weight(*freq, *doc_len)) + .fold(0.0_f32, f32::max); + assert!( + upper_bound.score + 1e-6 >= exact_max, + "upper bound {} should cover exact max {} from block {} up to doc {}", + upper_bound.score, + exact_max, + start_block_idx, + up_to + ); + } + } +} diff --git a/rust/lance-index/src/scalar/inverted/index.rs b/rust/lance-index/src/scalar/inverted/index.rs index f4298c817d7..5850de39fb8 100644 --- a/rust/lance-index/src/scalar/inverted/index.rs +++ b/rust/lance-index/src/scalar/inverted/index.rs @@ -54,6 +54,7 @@ use tokio::{sync::OnceCell, task::spawn_blocking}; use tracing::{info, instrument}; use super::encoding::{MAX_POSTING_BLOCK_SIZE, PositionBlockBuilder, decode_group_starts}; +use super::impact::{ImpactSkipData, ImpactSkipDataBuilder}; use super::iter::PostingListIterator; use super::lazy_docset::LazyDocSet; use super::tokenizer::{LEGACY_BLOCK_SIZE, validate_block_size}; @@ -61,7 +62,8 @@ use super::{InvertedIndexBuilder, InvertedIndexParams, wand::*}; use super::{ builder::{ BLOCK_SIZE, PostingGroupAccumulator, PostingGroupConfig, ScoredDoc, doc_file_path, - inverted_list_schema_for_version_with_block_size, posting_file_path, token_file_path, + inverted_list_schema_for_version_with_block_size_and_impacts, posting_file_path, + token_file_path, }, iter::PlainPostingListIterator, query::*, @@ -106,6 +108,7 @@ pub const POSITION_COL: &str = "_position"; pub const COMPRESSED_POSITION_COL: &str = "_compressed_position"; pub const POSITION_BLOCK_OFFSET_COL: &str = "_position_block_offset"; pub const POSTING_COL: &str = "_posting"; +pub const IMPACT_COL: &str = "_impacts"; pub const MAX_SCORE_COL: &str = "_max_score"; pub const LENGTH_COL: &str = "_length"; pub const BLOCK_MAX_SCORE_COL: &str = "_block_max_score"; @@ -292,6 +295,7 @@ impl PartitionCandidates { struct LoadedPostings { postings: Vec, grouped_expansions: Vec, + impact_safe: bool, } impl LoadedPostings { @@ -299,6 +303,7 @@ impl LoadedPostings { Self { postings: Vec::new(), grouped_expansions: Vec::new(), + impact_safe: false, } } } @@ -855,7 +860,7 @@ impl InvertedIndex { // hits per-token `posting_len`; building a `MemBM25Scorer` with // precomputed per-term IDFs avoids the v2 bulk metadata pull. let local_scorer; - let scorer: &dyn Scorer = if let Some(base_scorer) = base_scorer { + let scorer: &MemBM25Scorer = if let Some(base_scorer) = base_scorer { base_scorer } else { local_scorer = self @@ -863,6 +868,7 @@ impl InvertedIndex { .await?; &local_scorer }; + let impact_scorer = Arc::new(scorer.clone()); let limit = params.limit.unwrap_or(usize::MAX); if limit == 0 { @@ -901,8 +907,9 @@ impl InvertedIndex { // Shared top-k floor across this query's partitions. Seeded to -inf so // the first real score wins; each partition publishes its local k-th // and prunes against the running global k-th (a lower bound on the true - // global k-th — see `Wand::shared_threshold`). - let shared_threshold = Arc::new(AtomicU32::new(f32::NEG_INFINITY.to_bits())); + // global k-th - see `Wand::shared_threshold`). + let impact_shared_threshold = Arc::new(AtomicU32::new(f32::NEG_INFINITY.to_bits())); + let legacy_shared_threshold = Arc::new(AtomicU32::new(f32::NEG_INFINITY.to_bits())); let parts = self .partitions .iter() @@ -912,19 +919,23 @@ impl InvertedIndex { let params = params.clone(); let mask = mask.clone(); let metrics = metrics.clone(); - let shared_threshold = shared_threshold.clone(); + let impact_scorer = impact_scorer.clone(); + let impact_shared_threshold = impact_shared_threshold.clone(); + let legacy_shared_threshold = legacy_shared_threshold.clone(); async move { let loaded_postings = part .load_posting_lists( tokens.as_ref(), params.as_ref(), operator, + Some(impact_scorer.as_ref()), metrics.as_ref(), ) .await?; let LoadedPostings { postings, grouped_expansions, + impact_safe, } = loaded_postings; if postings.is_empty() { // No hits in this partition; its DocSet stays @@ -948,6 +959,7 @@ impl InvertedIndex { let metrics = metrics.clone(); let part_for_wand = part.clone(); let has_grouped_expansions = !grouped_expansions.is_empty(); + let use_impact_path = impact_safe && !has_grouped_expansions; let wand_params = if has_grouped_expansions { let mut rescoring_params = params.as_ref().clone(); rescoring_params.limit = @@ -958,9 +970,12 @@ impl InvertedIndex { }; let partition_threshold = if has_grouped_expansions { Arc::new(AtomicU32::new(f32::NEG_INFINITY.to_bits())) + } else if use_impact_path { + impact_shared_threshold } else { - shared_threshold + legacy_shared_threshold }; + let wand_scorer = use_impact_path.then(|| impact_scorer.clone()); let candidates = spawn_cpu(move || { let candidates = part_for_wand.bm25_search( docs_for_wand.as_ref(), @@ -968,6 +983,7 @@ impl InvertedIndex { operator, mask, postings, + wand_scorer, metrics.as_ref(), partition_threshold, )?; @@ -1742,6 +1758,7 @@ impl InvertedPartition { tokens: &Tokens, params: &FtsSearchParams, operator: Operator, + impact_scorer: Option<&MemBM25Scorer>, metrics: &dyn MetricsCollector, ) -> Result { let is_fuzzy = matches!(params.fuzziness, Some(n) if n != 0); @@ -1819,11 +1836,18 @@ impl InvertedPartition { } if !is_fuzzy_and_query { + let impact_safe = impact_scorer.is_some() + && loaded_postings + .iter() + .all(|(_, _, _, posting)| posting.has_impacts()); return Ok(LoadedPostings { postings: loaded_postings .into_iter() .map(|(token_id, token, position, posting)| { - let query_weight = idf(posting.len(), num_docs); + let query_weight = impact_scorer + .filter(|_| impact_safe) + .map(|scorer| scorer.query_weight(&token)) + .unwrap_or_else(|| idf(posting.len(), num_docs)); PostingIterator::with_query_weight( token, token_id, @@ -1835,6 +1859,7 @@ impl InvertedPartition { }) .collect(), grouped_expansions: Vec::new(), + impact_safe, }); } @@ -1902,6 +1927,7 @@ impl InvertedPartition { Ok(LoadedPostings { postings: grouped_postings, grouped_expansions, + impact_safe: false, }) } @@ -1917,6 +1943,7 @@ impl InvertedPartition { operator: Operator, mask: Arc, postings: Vec, + impact_scorer: Option>, metrics: &dyn MetricsCollector, shared_threshold: Arc, ) -> Result> { @@ -1927,10 +1954,16 @@ impl InvertedPartition { // Caller selects the DocSet shape via `LazyDocSet::docs_for_wand` // and passes it in here; wand uses `docs.has_row_ids()` to // handle the num_tokens-only case. - let scorer = IndexBM25Scorer::new(std::iter::once(self)); - let mut wand = Wand::new(operator, postings.into_iter(), docs, scorer) - .with_shared_threshold(shared_threshold); - let hits = wand.search(params, mask, metrics)?; + let hits = if let Some(scorer) = impact_scorer { + let mut wand = Wand::new(operator, postings.into_iter(), docs, scorer) + .with_shared_threshold(shared_threshold); + wand.search(params, mask, metrics)? + } else { + let scorer = IndexBM25Scorer::new(std::iter::once(self)); + let mut wand = Wand::new(operator, postings.into_iter(), docs, scorer) + .with_shared_threshold(shared_threshold); + wand.search(params, mask, metrics)? + }; Ok(hits) } @@ -2349,6 +2382,7 @@ pub struct PostingListReader { metadata: PostingMetadata, has_position: bool, + has_impacts: bool, posting_tail_codec: PostingTailCodec, block_size: usize, positions_layout: PositionsLayout, @@ -2451,6 +2485,7 @@ impl PostingListReader { let posting_tail_codec = parse_posting_tail_codec(&reader.schema().metadata)?; let block_size = parse_posting_block_size(&reader.schema().metadata)?; let has_position = positions_layout != PositionsLayout::None; + let has_impacts = reader.schema().field(IMPACT_COL).is_some(); let metadata = if reader.schema().field(POSTING_COL).is_none() { let (offsets, max_scores) = Self::load_metadata(reader.schema())?; PostingMetadata::LegacyV1 { @@ -2469,6 +2504,7 @@ impl PostingListReader { reader, metadata, has_position, + has_impacts, posting_tail_codec, block_size, positions_layout, @@ -2665,7 +2701,7 @@ impl PostingListReader { self.posting_batch_legacy(token_id, with_position).await } else { let token_id = token_id as usize; - let columns = if with_position { + let mut columns = if with_position { match self.positions_layout { PositionsLayout::SharedStream(_) => { vec![ @@ -2680,6 +2716,9 @@ impl PostingListReader { } else { vec![POSTING_COL] }; + if self.has_impacts { + columns.push(IMPACT_COL); + } let batch = self .reader .read_range(token_id..token_id + 1, Some(&columns)) @@ -2724,11 +2763,18 @@ impl PostingListReader { Some((start, end)) => { let group = self .index_cache - .get_or_insert_with_key(PostingListGroupKey { start, end }, || async move { - metrics.record_part_load(); - info!(target: TRACE_IO_EVENTS, r#type=IO_TYPE_LOAD_SCALAR_PART, index_type="inverted", part_id=start); - self.load_posting_list_group(start, end).await - }) + .get_or_insert_with_key( + PostingListGroupKey { + start, + end, + has_impacts: self.has_impacts, + }, + || async move { + metrics.record_part_load(); + info!(target: TRACE_IO_EVENTS, r#type=IO_TYPE_LOAD_SCALAR_PART, index_type="inverted", part_id=start); + self.load_posting_list_group(start, end).await + }, + ) .await?; let slot = (token_id - start) as usize; group @@ -2744,19 +2790,25 @@ impl PostingListReader { // per token. None => self .index_cache - .get_or_insert_with_key(PostingListKey { token_id }, || async move { - metrics.record_part_load(); - info!(target: TRACE_IO_EVENTS, r#type=IO_TYPE_LOAD_SCALAR_PART, index_type="inverted", part_id=token_id); - // Fetch the posting batch and this token's (max_score, - // length) in parallel; for cold v2 partitions this is one - // single-row metadata read plus one posting-row read, - // instead of pulling the full per-token metadata table. - let (batch, (max_score, length)) = futures::try_join!( - self.posting_batch(token_id, false), - self.posting_metadata_for_token(token_id), - )?; - self.posting_list_from_batch(&batch, max_score, length) - }) + .get_or_insert_with_key( + PostingListKey { + token_id, + has_impacts: self.has_impacts, + }, + || async move { + metrics.record_part_load(); + info!(target: TRACE_IO_EVENTS, r#type=IO_TYPE_LOAD_SCALAR_PART, index_type="inverted", part_id=token_id); + // Fetch the posting batch and this token's (max_score, + // length) in parallel; for cold v2 partitions this is one + // single-row metadata read plus one posting-row read, + // instead of pulling the full per-token metadata table. + let (batch, (max_score, length)) = futures::try_join!( + self.posting_batch(token_id, false), + self.posting_metadata_for_token(token_id), + )?; + self.posting_list_from_batch(&batch, max_score, length) + }, + ) .await? .as_ref() .clone(), @@ -2801,12 +2853,13 @@ impl PostingListReader { /// [`PostingListGroup`] cache value (issue #7040). Positions are excluded; /// phrase queries load them on demand via [`Self::read_positions`]. async fn load_posting_list_group(&self, start: u32, end: u32) -> Result { + let mut columns = vec![POSTING_COL, MAX_SCORE_COL, LENGTH_COL]; + if self.has_impacts { + columns.push(IMPACT_COL); + } let batch = self .reader - .read_range( - start as usize..end as usize, - Some(&[POSTING_COL, MAX_SCORE_COL, LENGTH_COL]), - ) + .read_range(start as usize..end as usize, Some(&columns)) .await?; let max_scores = batch[MAX_SCORE_COL].as_primitive::(); let lengths = batch[LENGTH_COL].as_primitive::(); @@ -3129,7 +3182,14 @@ impl PostingListReader { let hi = end as usize - tok_start; let group = PostingListGroup::new(chunk_postings[lo..hi].to_vec()); self.index_cache - .insert_with_key(&PostingListGroupKey { start, end }, Arc::new(group)) + .insert_with_key( + &PostingListGroupKey { + start, + end, + has_impacts: self.has_impacts, + }, + Arc::new(group), + ) .await; } } @@ -3138,7 +3198,13 @@ impl PostingListReader { self.cache_positions(&mut posting_list, token_id, with_position) .await; self.index_cache - .insert_with_key(&PostingListKey { token_id }, Arc::new(posting_list)) + .insert_with_key( + &PostingListKey { + token_id, + has_impacts: self.has_impacts, + }, + Arc::new(posting_list), + ) .await; } } @@ -3308,6 +3374,9 @@ impl PostingListReader { } } } + if self.has_impacts { + base_columns.push(IMPACT_COL); + } base_columns } } @@ -3404,13 +3473,18 @@ impl DeepSizeOf for Positions { #[derive(Debug, Clone)] pub struct PostingListKey { pub token_id: u32, + pub has_impacts: bool, } impl CacheKey for PostingListKey { type ValueType = PostingList; fn key(&self) -> std::borrow::Cow<'_, str> { - format!("postings-{}", self.token_id).into() + if self.has_impacts { + format!("postings-{}-impacts", self.token_id).into() + } else { + format!("postings-{}", self.token_id).into() + } } fn type_name() -> &'static str { @@ -3430,13 +3504,18 @@ impl CacheKey for PostingListKey { pub struct PostingListGroupKey { pub start: u32, pub end: u32, + pub has_impacts: bool, } impl CacheKey for PostingListGroupKey { type ValueType = PostingListGroup; fn key(&self) -> std::borrow::Cow<'_, str> { - format!("postings-{}-{}", self.start, self.end).into() + if self.has_impacts { + format!("postings-{}-{}-impacts", self.start, self.end).into() + } else { + format!("postings-{}-{}", self.start, self.end).into() + } } fn type_name() -> &'static str { @@ -3582,6 +3661,7 @@ impl PostingListGroup { } #[derive(Debug, Clone, DeepSizeOf)] +#[allow(clippy::large_enum_variant)] pub enum PostingList { Plain(PlainPostingList), Compressed(CompressedPostingList), @@ -3646,7 +3726,7 @@ impl PostingList { posting_tail_codec, block_size, shared_position_codec, - ); + )?; Ok(Self::Compressed(posting)) } None => { @@ -3667,6 +3747,13 @@ impl PostingList { } } + pub fn has_impacts(&self) -> bool { + match self { + Self::Plain(_) => false, + Self::Compressed(posting) => posting.impacts.is_some(), + } + } + pub fn set_positions(&mut self, positions: CompressedPositionStorage) { match self { Self::Plain(posting) => match positions { @@ -3887,6 +3974,7 @@ pub struct CompressedPostingList { pub posting_tail_codec: PostingTailCodec, pub block_size: usize, pub positions: Option, + pub(crate) impacts: Option, // First doc id per block, baked lazily and shared across per-query clones // of the cached list. See `block_first_docs`. first_docs: Arc>>, @@ -3900,6 +3988,7 @@ impl PartialEq for CompressedPostingList { && self.posting_tail_codec == other.posting_tail_codec && self.block_size == other.block_size && self.positions == other.positions + && self.impacts == other.impacts } } @@ -3911,17 +4000,23 @@ impl DeepSizeOf for CompressedPostingList { .as_ref() .map(|positions| positions.deep_size_of_children(context)) .unwrap_or(0) + + self + .impacts + .as_ref() + .map(|impacts| sliced_cache_bytes(impacts.entries())) + .unwrap_or(0) } } impl CompressedPostingList { - pub fn new( + pub(crate) fn new( blocks: LargeBinaryArray, max_score: f32, length: u32, posting_tail_codec: PostingTailCodec, block_size: usize, positions: Option, + impacts: Option, ) -> Self { debug_assert!(block_size.is_power_of_two()); Self { @@ -3931,23 +4026,11 @@ impl CompressedPostingList { posting_tail_codec, block_size, positions, + impacts, first_docs: Arc::new(OnceLock::new()), } } - /// Block sizes are validated powers of two, so per-doc hot loops derive - /// block indices with shift/mask instead of runtime division, which is - /// measurably slower in the iterator advance path. - #[inline] - pub(crate) fn block_shift(&self) -> u32 { - self.block_size.trailing_zeros() - } - - #[inline] - pub(crate) fn block_mask(&self) -> usize { - self.block_size - 1 - } - pub fn from_batch( batch: &RecordBatch, max_score: f32, @@ -3955,7 +4038,7 @@ impl CompressedPostingList { posting_tail_codec: PostingTailCodec, block_size: usize, shared_position_codec: Option, - ) -> Self { + ) -> Result { debug_assert_eq!(batch.num_rows(), 1); let blocks = batch[POSTING_COL] .as_list::() @@ -3984,16 +4067,28 @@ impl CompressedPostingList { ) }) }; + let impacts = batch + .column_by_name(IMPACT_COL) + .map(|col| { + let entries = col.as_list::().value(0).as_binary::().clone(); + ImpactSkipData::new( + entries, + blocks.len(), + super::impact::ImpactFormat::for_block_size(block_size), + ) + }) + .transpose()?; - Self { + Ok(Self { max_score, length, blocks, posting_tail_codec, block_size, positions, + impacts, first_docs: Arc::new(OnceLock::new()), - } + }) } pub fn iter(&self) -> CompressedPostingListIterator { @@ -4181,6 +4276,7 @@ pub struct PostingListBuilder { pub(super) struct PostingListBatchBuilder { schema: SchemaRef, postings: ListBuilder, + impacts: Option>, max_scores: Float32Builder, lengths: UInt32Builder, positions: BatchPositionsBuilder, @@ -4232,9 +4328,14 @@ impl PostingListBatchBuilder { capacity, )) }; + let impacts = schema + .field_with_name(IMPACT_COL) + .ok() + .map(|_| ListBuilder::with_capacity(LargeBinaryBuilder::new(), capacity)); Self { schema, postings: ListBuilder::with_capacity(LargeBinaryBuilder::new(), capacity), + impacts, max_scores: Float32Builder::with_capacity(capacity), lengths: UInt32Builder::with_capacity(capacity), positions, @@ -4254,11 +4355,19 @@ impl PostingListBatchBuilder { fn append( &mut self, compressed: LargeBinaryArray, + impacts: Option<&ImpactSkipData>, max_score: f32, length: u32, positions: Option<&CompressedPositionStorage>, ) -> Result<()> { - let posting_bytes = compressed.value_data().len(); + let impact_bytes = if self.impacts.is_some() { + impacts + .map(|impacts| impacts.entries().value_data().len()) + .unwrap_or(0) + } else { + 0 + }; + let posting_bytes = compressed.value_data().len() + impact_bytes; { let values = self.postings.values(); for index in 0..compressed.len() { @@ -4266,6 +4375,19 @@ impl PostingListBatchBuilder { } } self.postings.append(true); + if let Some(impacts_builder) = &mut self.impacts { + let impacts = impacts.ok_or_else(|| { + Error::index(format!( + "impacts builder missing impact data for posting length {}", + length + )) + })?; + let values = impacts_builder.values(); + for index in 0..impacts.entries().len() { + values.append_value(impacts.entries().value(index)); + } + impacts_builder.append(true); + } self.group_accumulator.push(posting_bytes); self.max_scores.append_value(max_score); self.lengths.append_value(length); @@ -4331,6 +4453,9 @@ impl PostingListBatchBuilder { Arc::new(self.max_scores.finish()) as ArrayRef, Arc::new(self.lengths.finish()) as ArrayRef, ]; + if let Some(impacts) = &mut self.impacts { + columns.push(Arc::new(impacts.finish()) as ArrayRef); + } match &mut self.positions { BatchPositionsBuilder::None => {} BatchPositionsBuilder::Legacy(position_lists) => { @@ -4748,6 +4873,7 @@ impl PostingListBuilder { fn build_batch( self, compressed: LargeBinaryArray, + impacts: Option, max_score: f32, schema: SchemaRef, positions: Option, @@ -4766,6 +4892,22 @@ impl PostingListBuilder { length as u32, ))) as ArrayRef, ]; + if schema.field_with_name(IMPACT_COL).is_ok() { + let impacts = impacts.ok_or_else(|| { + Error::index(format!( + "impact column requested without impact data for posting length {}", + length + )) + })?; + let impact_offsets = + OffsetBuffer::new(ScalarBuffer::from(vec![0, impacts.entries().len() as i32])); + columns.push(Arc::new(ListArray::try_new( + Arc::new(Field::new("item", datatypes::DataType::LargeBinary, true)), + impact_offsets, + Arc::new(impacts.entries().clone()), + None, + )?) as ArrayRef); + } columns.extend(Self::build_position_columns(positions)?); let batch = RecordBatch::try_new(schema, columns)?; @@ -4836,13 +4978,19 @@ impl PostingListBuilder { tail_entries: tail_entries.as_slice(), tail_position_block: with_positions.then(|| tail_positions.finish()), }; - let (compressed, shared_positions, max_score) = + let (compressed, shared_positions, max_score, impacts) = Self::build_compressed_with_scores_from_parts(parts, docs)?; let positions = match legacy_positions { Some(positions) => Some(CompressedPositionStorage::LegacyPerDoc(positions)), None => shared_positions.map(CompressedPositionStorage::SharedStream), }; - batch_builder.append(compressed, max_score, len, positions.as_ref()) + batch_builder.append( + compressed, + Some(&impacts), + max_score, + len, + positions.as_ref(), + ) } fn extend_tail_components( @@ -4859,7 +5007,12 @@ impl PostingListBuilder { fn build_compressed_with_scores_from_parts( parts: PostingListParts<'_>, docs: &DocSet, - ) -> Result<(LargeBinaryArray, Option, f32)> { + ) -> Result<( + LargeBinaryArray, + Option, + f32, + ImpactSkipData, + )> { let PostingListParts { with_positions, posting_tail_codec, @@ -4875,6 +5028,9 @@ impl PostingListBuilder { let mut max_score = f32::MIN; let mut doc_ids = Vec::with_capacity(block_size); let mut frequencies = Vec::with_capacity(block_size); + let mut impact_block = Vec::with_capacity(block_size); + let mut impact_builder = + ImpactSkipDataBuilder::with_capacity(length.div_ceil(block_size), block_size); for index in 0..encoded_blocks.len() { let block = encoded_blocks.block(index); @@ -4886,13 +5042,15 @@ impl PostingListBuilder { &mut frequencies, block_size, ); - let block_score = compute_block_score( + let block_score = compute_block_score_and_impact_block( docs, avgdl, idf_scale, doc_ids.iter().copied(), frequencies.iter().copied(), + &mut impact_block, ); + impact_builder.append_block(impact_block.as_slice())?; max_score = max_score.max(block_score); if super::encoding::posting_block_score_prefix_len(block_size) > 0 { encoded_blocks.set_block_score(index, block_score); @@ -4901,13 +5059,15 @@ impl PostingListBuilder { if !tail_entries.is_empty() { Self::extend_tail_components(tail_entries, &mut doc_ids, &mut frequencies); - let block_score = compute_block_score( + let block_score = compute_block_score_and_impact_block( docs, avgdl, idf_scale, doc_ids.iter().copied(), frequencies.iter().copied(), + &mut impact_block, ); + impact_builder.append_block(impact_block.as_slice())?; max_score = max_score.max(block_score); encoded_blocks.append_remainder_block_with_codec( doc_ids.as_slice(), @@ -4927,10 +5087,12 @@ impl PostingListBuilder { } } + let impacts = impact_builder.finish()?; Ok(( encoded_blocks.into_array(), with_positions.then(|| encoded_position_blocks.into_stream()), max_score, + impacts, )) } @@ -4996,10 +5158,11 @@ impl PostingListBuilder { self.posting_tail_codec, self.block_size, )?; - let schema = inverted_list_schema_for_version_with_block_size( + let schema = inverted_list_schema_for_version_with_block_size_and_impacts( self.has_positions(), format_version, self.block_size, + false, ); let legacy_positions = if self.with_positions && !format_version.uses_shared_position_stream() { @@ -5057,7 +5220,7 @@ impl PostingListBuilder { Some(positions) => Some(CompressedPositionStorage::LegacyPerDoc(positions)), None => shared_positions.map(CompressedPositionStorage::SharedStream), }; - builder.build_batch(compressed, max_score, schema, positions) + builder.build_batch(compressed, None, max_score, schema, positions) } pub fn to_batch_with_docs(self, docs: &DocSet, schema: SchemaRef) -> Result { @@ -5099,7 +5262,7 @@ impl PostingListBuilder { tail_entries: tail_entries.as_slice(), tail_position_block: with_positions.then(|| tail_positions.finish()), }; - let (compressed, shared_positions, max_score) = + let (compressed, shared_positions, max_score, impacts) = Self::build_compressed_with_scores_from_parts(parts, docs)?; let builder = Self { with_positions, @@ -5119,7 +5282,7 @@ impl PostingListBuilder { Some(positions) => Some(CompressedPositionStorage::LegacyPerDoc(positions)), None => shared_positions.map(CompressedPositionStorage::SharedStream), }; - builder.build_batch(compressed, max_score, schema, positions) + builder.build_batch(compressed, Some(impacts), max_score, schema, positions) } pub fn remap(&mut self, removed: &[u32]) { @@ -5147,19 +5310,23 @@ impl PostingListBuilder { } } -fn compute_block_score( +fn compute_block_score_and_impact_block( docs: &DocSet, avgdl: f32, idf_scale: f32, doc_ids: impl Iterator, frequencies: impl Iterator, + impact_block: &mut Vec<(u32, u32, u32)>, ) -> f32 { + impact_block.clear(); let mut block_max_score = f32::MIN; for (doc_id, freq) in doc_ids.zip(frequencies) { - let doc_norm = K1 * (1.0 - B + B * docs.num_tokens(doc_id) as f32 / avgdl); - let freq = freq as f32; - let score = freq / (freq + doc_norm); + let doc_len = docs.num_tokens(doc_id); + let doc_norm = K1 * (1.0 - B + B * doc_len as f32 / avgdl); + let freq_f32 = freq as f32; + let score = freq_f32 / (freq_f32 + doc_norm); block_max_score = block_max_score.max(score); + impact_block.push((doc_id, freq, doc_len)); } block_max_score * idf_scale } @@ -6125,7 +6292,10 @@ mod tests { use crate::prefilter::NoFilter; use crate::scalar::ScalarIndex; use crate::scalar::inverted::builder::{ - InnerBuilder, InvertedIndexBuilder, PositionRecorder, inverted_list_schema, + InnerBuilder, InvertedIndexBuilder, PositionRecorder, doc_file_path, inverted_list_schema, + inverted_list_schema_for_version_with_block_size, + inverted_list_schema_for_version_with_block_size_and_impacts, posting_file_path, + token_file_path, }; use crate::scalar::inverted::encoding::{ compress_positions, compress_posting_list_with_tail_codec, @@ -6225,6 +6395,57 @@ mod tests { assert!(err.to_string().contains("block_size")); } + #[test] + fn test_posting_builder_writes_impacts_for_supported_block_sizes() { + for block_size in [128, 256] { + let format_version = default_fts_format_version_for_block_size(block_size).unwrap(); + let num_docs = block_size * 33 + 1; + let mut docs = DocSet::default(); + let mut posting = PostingListBuilder::new_with_posting_tail_codec_and_block_size( + false, + format_version.posting_tail_codec(), + block_size, + ); + for doc_id in 0..num_docs { + docs.append(doc_id as u64, (doc_id % 5 + 1) as u32); + posting.add( + doc_id as u32, + PositionRecorder::Count((doc_id % 3 + 1) as u32), + ); + } + let schema = + inverted_list_schema_for_version_with_block_size(false, format_version, block_size); + let batch = posting.to_batch_with_docs(&docs, schema).unwrap(); + assert!(batch.column_by_name(IMPACT_COL).is_some()); + let max_score = batch[MAX_SCORE_COL].as_primitive::().value(0); + let length = batch[LENGTH_COL].as_primitive::().value(0); + let posting = PostingList::from_batch(&batch, Some(max_score), Some(length)).unwrap(); + let PostingList::Compressed(posting) = posting else { + panic!("expected compressed posting list"); + }; + let impacts = posting.impacts.expect("posting should include impacts"); + assert_eq!(impacts.level0_len(), posting.blocks.len()); + assert_eq!(impacts.level1_len(), posting.blocks.len().div_ceil(32)); + assert_eq!( + impacts.entries().len(), + impacts.level0_len() + impacts.level1_len() + ); + } + } + + #[test] + fn test_posting_builder_without_impact_column_roundtrips_without_impacts() { + let mut posting = PostingListBuilder::new(false); + for doc_id in 0..BLOCK_SIZE + 3 { + posting.add(doc_id as u32, PositionRecorder::Count(1)); + } + let batch = posting.to_batch(vec![1.0, 1.0]).unwrap(); + assert!(batch.column_by_name(IMPACT_COL).is_none()); + let posting = + PostingList::from_batch(&batch, Some(1.0), Some((BLOCK_SIZE + 3) as u32)).unwrap(); + assert!(!posting.has_impacts()); + } + #[tokio::test] async fn test_build_search_uses_configured_posting_block_size() { let tmpdir = TempObjDir::default(); @@ -6276,6 +6497,16 @@ mod tests { }; assert_eq!(posting.block_size, block_size); assert_eq!(posting.blocks.len(), num_docs.div_ceil(block_size)); + let impacts = posting + .impacts + .as_ref() + .expect("newly written posting list should include impacts"); + assert_eq!(impacts.level0_len(), posting.blocks.len()); + assert_eq!(impacts.level1_len(), posting.blocks.len().div_ceil(32)); + assert_eq!( + impacts.entries().len(), + impacts.level0_len() + impacts.level1_len() + ); let tokens = Arc::new(Tokens::new(vec!["needle".to_owned()], DocType::Text)); let params = Arc::new(FtsSearchParams::new().with_limit(Some(10))); @@ -7027,7 +7258,11 @@ mod tests { let (start, end) = inverted_list.group_range_for_token(0).unwrap(); let group = inverted_list .index_cache - .get_with_key(&PostingListGroupKey { start, end }) + .get_with_key(&PostingListGroupKey { + start, + end, + has_impacts: inverted_list.has_impacts, + }) .await .unwrap(); @@ -7339,7 +7574,11 @@ mod tests { let (start, end) = inverted_list.group_range_for_token(token_id).unwrap(); let group = inverted_list .index_cache - .get_with_key(&PostingListGroupKey { start, end }) + .get_with_key(&PostingListGroupKey { + start, + end, + has_impacts: inverted_list.has_impacts, + }) .await .unwrap(); let slot = (token_id - start) as usize; @@ -7814,7 +8053,11 @@ mod tests { let (start, end) = inverted_list.group_range_for_token(0).unwrap(); let group = inverted_list .index_cache - .get_with_key(&PostingListGroupKey { start, end }) + .get_with_key(&PostingListGroupKey { + start, + end, + has_impacts: inverted_list.has_impacts, + }) .await .unwrap(); @@ -7903,6 +8146,7 @@ mod tests { PostingTailCodec::Fixed32, LEGACY_BLOCK_SIZE, None, + None, ); let full_backing = full.get_buffer_memory_size(); @@ -8049,7 +8293,11 @@ mod tests { let (start, end) = inverted_list.group_range_for_token(0).unwrap(); let group = inverted_list .index_cache - .get_with_key(&PostingListGroupKey { start, end }) + .get_with_key(&PostingListGroupKey { + start, + end, + has_impacts: inverted_list.has_impacts, + }) .await .unwrap(); assert!( @@ -8293,6 +8541,178 @@ mod tests { writer.finish_with_metadata(metadata).await.unwrap(); } + async fn write_test_partition_with_optional_impacts( + store: &Arc, + partition_id: u64, + mut builder: InnerBuilder, + token_set_format: TokenSetFormat, + with_impacts: bool, + ) { + let format_version = InvertedListFormatVersion::V1; + let block_size = LEGACY_BLOCK_SIZE; + let docs = std::mem::take(&mut builder.docs); + let schema = inverted_list_schema_for_version_with_block_size_and_impacts( + false, + format_version, + block_size, + with_impacts, + ); + + let mut posting_writer = store + .new_index_file(&posting_file_path(partition_id), schema.clone()) + .await + .unwrap(); + for posting_list in std::mem::take(&mut builder.posting_lists) { + let batch = posting_list + .to_batch_with_docs(&docs, schema.clone()) + .unwrap(); + posting_writer.write_record_batch(batch).await.unwrap(); + } + posting_writer.finish().await.unwrap(); + + let token_batch = std::mem::take(&mut builder.tokens) + .to_batch(token_set_format) + .unwrap(); + let mut token_writer = store + .new_index_file(&token_file_path(partition_id), token_batch.schema()) + .await + .unwrap(); + token_writer.write_record_batch(token_batch).await.unwrap(); + token_writer.finish().await.unwrap(); + + let doc_batch = docs.to_batch().unwrap(); + let mut doc_writer = store + .new_index_file(&doc_file_path(partition_id), doc_batch.schema()) + .await + .unwrap(); + doc_writer.write_record_batch(doc_batch).await.unwrap(); + doc_writer.finish().await.unwrap(); + } + + #[tokio::test] + async fn test_mixed_impact_and_legacy_partitions_use_global_final_scores() { + let tmpdir = TempObjDir::default(); + let store = Arc::new(LanceIndexStore::new( + ObjectStore::local().into(), + tmpdir.clone(), + Arc::new(LanceCache::no_cache()), + )); + + let mut impact_builder = InnerBuilder::new_with_format_version( + 0, + false, + TokenSetFormat::default(), + InvertedListFormatVersion::V1, + ); + impact_builder.tokens.add("alpha".to_owned()); + impact_builder + .posting_lists + .push(PostingListBuilder::new_with_posting_tail_codec( + false, + InvertedListFormatVersion::V1.posting_tail_codec(), + )); + impact_builder.posting_lists[0].add(0, PositionRecorder::Count(1)); + impact_builder.docs.append(100, 5_000); + for row_id in 101..111 { + impact_builder.docs.append(row_id, 5_000); + } + write_test_partition_with_optional_impacts( + &store, + 0, + impact_builder, + TokenSetFormat::default(), + true, + ) + .await; + + let mut legacy_builder = InnerBuilder::new_with_format_version( + 1, + false, + TokenSetFormat::default(), + InvertedListFormatVersion::V1, + ); + legacy_builder.tokens.add("alpha".to_owned()); + legacy_builder + .posting_lists + .push(PostingListBuilder::new_with_posting_tail_codec( + false, + InvertedListFormatVersion::V1.posting_tail_codec(), + )); + legacy_builder.posting_lists[0].add(0, PositionRecorder::Count(1)); + legacy_builder.docs.append(200, 1_000); + for row_id in 201..301 { + legacy_builder.docs.append(row_id, 1); + } + write_test_partition_with_optional_impacts( + &store, + 1, + legacy_builder, + TokenSetFormat::default(), + false, + ) + .await; + + write_test_metadata(&store, vec![0, 1], InvertedIndexParams::default()).await; + let cache = Arc::new(LanceCache::with_capacity(4096)); + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + .await + .unwrap(); + + let impact_partition = index + .partitions + .iter() + .find(|partition| partition.id() == 0) + .unwrap(); + let legacy_partition = index + .partitions + .iter() + .find(|partition| partition.id() == 1) + .unwrap(); + + let impact_posting = impact_partition + .inverted_list + .posting_list(0, false, &NoOpMetricsCollector) + .await + .unwrap(); + assert!(impact_posting.has_impacts()); + + let legacy_posting = legacy_partition + .inverted_list + .posting_list(0, false, &NoOpMetricsCollector) + .await + .unwrap(); + assert!(!legacy_posting.has_impacts()); + + let tokens = Arc::new(Tokens::new(vec!["alpha".to_string()], DocType::Text)); + let params = Arc::new(FtsSearchParams::new().with_limit(Some(1))); + let (row_ids, scores) = index + .bm25_search( + tokens.clone(), + params.clone(), + Operator::Or, + Arc::new(NoFilter), + Arc::new(NoOpMetricsCollector), + None, + ) + .await + .unwrap(); + + assert_eq!(row_ids, vec![200]); + assert_eq!(row_ids.len(), scores.len()); + + let scorer = index + .bm25_base_scorer(tokens.as_ref(), params.as_ref()) + .await + .unwrap(); + let expected_score = scorer.query_weight("alpha") * scorer.doc_weight(1, 1_000); + assert!( + (scores[0] - expected_score).abs() < 1e-6, + "score: {}, expected: {}", + scores[0], + expected_score + ); + } + #[tokio::test] async fn test_and_query_returns_empty_when_exact_term_missing() { let tmpdir = TempObjDir::default(); @@ -9478,7 +9898,11 @@ mod tests { assert!( posting_reader .index_cache - .get_with_key(&PostingListGroupKey { start, end }) + .get_with_key(&PostingListGroupKey { + start, + end, + has_impacts: posting_reader.has_impacts, + }) .await .is_some(), "prewarm did not populate group [{start}, {end}) that the read \ @@ -9625,7 +10049,10 @@ mod tests { assert!( posting_reader .index_cache - .get_with_key(&PostingListKey { token_id }) + .get_with_key(&PostingListKey { + token_id, + has_impacts: posting_reader.has_impacts, + }) .await .is_some(), "fallback prewarm should populate per-token entry {token_id}", diff --git a/rust/lance-index/src/scalar/inverted/scorer.rs b/rust/lance-index/src/scalar/inverted/scorer.rs index eb7d78ff397..b6b48ce4149 100644 --- a/rust/lance-index/src/scalar/inverted/scorer.rs +++ b/rust/lance-index/src/scalar/inverted/scorer.rs @@ -3,6 +3,7 @@ use super::InvertedPartition; use std::collections::HashMap; +use std::sync::Arc; // the Scorer trait is used to calculate the score of a token in a document // in general, the score is calculated as: @@ -12,6 +13,16 @@ pub trait Scorer: Send + Sync { fn doc_weight(&self, freq: u32, doc_tokens: u32) -> f32; } +impl Scorer for Arc { + fn query_weight(&self, token: &str) -> f32 { + self.as_ref().query_weight(token) + } + + fn doc_weight(&self, freq: u32, doc_tokens: u32) -> f32 { + self.as_ref().doc_weight(freq, doc_tokens) + } +} + // BM25 parameters pub const K1: f32 = 1.2; pub const B: f32 = 0.75; diff --git a/rust/lance-index/src/scalar/inverted/wand.rs b/rust/lance-index/src/scalar/inverted/wand.rs index 1e0a87c7ad4..467ada26e4f 100644 --- a/rust/lance-index/src/scalar/inverted/wand.rs +++ b/rust/lance-index/src/scalar/inverted/wand.rs @@ -22,6 +22,7 @@ use crate::metrics::MetricsCollector; use super::{ CompressedPositionStorage, + impact::{IMPACT_LEVEL1_BLOCKS, ImpactScoreCache, ImpactSkipData}, query::Operator, scorer::{K1, idf}, }; @@ -38,6 +39,7 @@ use super::{ use super::{DocInfo, builder::BLOCK_SIZE}; const TERMINATED_DOC_ID: u64 = u64::MAX; +const LINEAR_BLOCK_SKIP_LIMIT: usize = 8; pub static FLAT_SEARCH_PERCENT_THRESHOLD: LazyLock = LazyLock::new(|| { std::env::var("LANCE_FLAT_SEARCH_PERCENT_THRESHOLD") .unwrap_or_else(|_| "10".to_string()) @@ -45,6 +47,33 @@ pub static FLAT_SEARCH_PERCENT_THRESHOLD: LazyLock = LazyLock::new(|| { .unwrap_or(10) }); +#[inline] +fn posting_block_idx(index: usize, block_size: usize) -> usize { + match block_size { + 128 => index >> 7, + 256 => index >> 8, + _ => index / block_size, + } +} + +#[inline] +fn posting_block_offset(index: usize, block_size: usize) -> usize { + match block_size { + 128 => index & 127, + 256 => index & 255, + _ => index % block_size, + } +} + +#[inline] +fn posting_block_start(block_idx: usize, block_size: usize) -> usize { + match block_size { + 128 => block_idx << 7, + 256 => block_idx << 8, + _ => block_idx * block_size, + } +} + pub struct PostingIterator { token: String, token_id: u32, @@ -55,6 +84,7 @@ pub struct PostingIterator { index: usize, // the index of current block, this can be changed by `next() and shallow_next()` block_idx: usize, + current_doc: Option, approximate_upper_bound: f32, // for compressed posting list @@ -71,6 +101,8 @@ struct CompressedState { position_values: Vec, position_offsets: Vec, block_max_window: BlockMaxWindow, + current_block_max_score: Option<(usize, f32)>, + block_least_doc_ids: Vec>, } impl CompressedState { @@ -84,6 +116,8 @@ impl CompressedState { position_values: Vec::new(), position_offsets: Vec::new(), block_max_window: BlockMaxWindow::new(), + current_block_max_score: None, + block_least_doc_ids: Vec::new(), } } @@ -100,7 +134,7 @@ impl CompressedState { self.doc_ids.clear(); self.freqs.clear(); - let remainder = length as usize % block_size; + let remainder = posting_block_offset(length as usize, block_size); if block_idx + 1 == num_blocks && remainder != 0 { decompress_posting_remainder( block, @@ -133,6 +167,7 @@ struct BlockMaxWindow { start_block_idx: usize, next_block_idx: usize, max_scores: VecDeque<(usize, f32)>, + impact_score_cache: ImpactScoreCache, } struct BlockMaxScore { @@ -146,6 +181,7 @@ impl BlockMaxWindow { start_block_idx: 0, next_block_idx: 0, max_scores: VecDeque::new(), + impact_score_cache: ImpactScoreCache::default(), } } @@ -155,12 +191,28 @@ impl BlockMaxWindow { self.max_scores.clear(); } - fn max_score_up_to( + fn max_score_up_to( &mut self, list: &CompressedPostingList, start_block_idx: usize, up_to: u64, + query_weight: f32, + scorer: &S, ) -> BlockMaxScore { + if let Some(impacts) = &list.impacts { + let score = impacts.max_score_up_to_cached( + start_block_idx, + up_to, + query_weight, + scorer, + &mut self.impact_score_cache, + ); + return BlockMaxScore { + score: score.score, + blocks_scanned: score.entries_scanned, + }; + } + if start_block_idx >= list.blocks.len() { self.reset(start_block_idx); return BlockMaxScore { @@ -264,6 +316,96 @@ impl Ord for PostingIterator { } impl PostingIterator { + #[inline] + fn block_least_doc_id(&self, list: &CompressedPostingList, block_idx: usize) -> u32 { + let compressed = unsafe { &mut *self.compressed_state_ptr() }; + if compressed.block_least_doc_ids.len() < list.blocks.len() { + compressed + .block_least_doc_ids + .resize(list.blocks.len(), None); + } + if let Some(doc_id) = compressed.block_least_doc_ids[block_idx] { + return doc_id; + } + let doc_id = list.block_least_doc_id(block_idx); + compressed.block_least_doc_ids[block_idx] = Some(doc_id); + doc_id + } + + fn block_idx_for_doc( + &self, + list: &CompressedPostingList, + mut block_idx: usize, + least_id: u32, + ) -> usize { + let mut linear_skips = 0; + while block_idx + 1 < list.blocks.len() && linear_skips < LINEAR_BLOCK_SKIP_LIMIT { + if self.block_least_doc_id(list, block_idx + 1) > least_id { + return block_idx; + } + block_idx += 1; + linear_skips += 1; + } + + if block_idx + 1 >= list.blocks.len() { + return block_idx; + } + + if let Some(impacts) = list.impacts.as_ref() + && let Some(block_idx) = + self.block_idx_for_doc_with_impacts(list, impacts, block_idx, least_id) + { + return block_idx; + } + + self.block_idx_for_doc_by_least_doc_id(list, block_idx, least_id, list.blocks.len()) + } + + fn block_idx_for_doc_with_impacts( + &self, + list: &CompressedPostingList, + impacts: &ImpactSkipData, + mut block_idx: usize, + least_id: u32, + ) -> Option { + while block_idx + 1 < list.blocks.len() { + let group_idx = (block_idx + 1) / IMPACT_LEVEL1_BLOCKS; + let group_end = ((group_idx + 1) * IMPACT_LEVEL1_BLOCKS).min(list.blocks.len()); + let group_doc_up_to = impacts.level1_doc_up_to(group_idx)?; + if group_doc_up_to < least_id { + block_idx = group_end - 1; + continue; + } + if group_doc_up_to == least_id { + return Some(group_end - 1); + } + return Some( + self.block_idx_for_doc_by_least_doc_id(list, block_idx, least_id, group_end), + ); + } + Some(block_idx) + } + + fn block_idx_for_doc_by_least_doc_id( + &self, + list: &CompressedPostingList, + block_idx: usize, + least_id: u32, + right: usize, + ) -> usize { + let mut left = block_idx + 1; + let mut right = right; + while left < right { + let mid = left + (right - left) / 2; + if self.block_least_doc_id(list, mid) <= least_id { + left = mid + 1; + } else { + right = mid; + } + } + left - 1 + } + #[inline] fn compressed_state_ptr(&self) -> *mut CompressedState { debug_assert!(self.compressed.is_some()); @@ -312,9 +454,12 @@ impl PostingIterator { list: PostingList, num_doc: usize, ) -> Self { - let approximate_upper_bound = match list.max_score() { - Some(max_score) => max_score, - None => idf(list.len(), num_doc) * (K1 + 1.0), + let approximate_upper_bound = match &list { + PostingList::Compressed(posting) if posting.impacts.is_some() => f32::INFINITY, + _ => match list.max_score() { + Some(max_score) => max_score, + None => idf(list.len(), num_doc) * (K1 + 1.0), + }, }; let compressed = match &list { PostingList::Compressed(list) => { @@ -323,7 +468,7 @@ impl PostingIterator { PostingList::Plain(_) => None, }; - Self { + let mut posting = Self { token, token_id, position, @@ -331,9 +476,12 @@ impl PostingIterator { list, index: 0, block_idx: 0, + current_doc: None, approximate_upper_bound, compressed, - } + }; + posting.refresh_current_doc(); + posting } #[inline] @@ -351,8 +499,24 @@ impl PostingIterator { self.approximate_upper_bound } + /// Tightest known list-wide score bound. Impact lists answer from the + /// baked doc-weight slab (the data-driven equivalent of the max_score the + /// non-impact format bakes at build time); everything else falls back to + /// `approximate_upper_bound`. A finite, tight global bound is what lets + /// lagging iterators park in the WAND tail instead of being force-advanced + /// on every candidate. + #[inline] + fn global_upper_bound(&self, scorer: &S) -> f32 { + if let PostingList::Compressed(ref list) = self.list + && let Some(impacts) = list.impacts.as_ref() + { + return self.query_weight * impacts.global_max_doc_weight(scorer); + } + self.approximate_upper_bound + } + #[inline] - fn score(&self, scorer: &S, freq: u32, doc_length: u32) -> f32 { + fn score(&self, scorer: &S, freq: u32, doc_length: u32) -> f32 { self.query_weight * scorer.doc_weight(freq, doc_length) } @@ -368,14 +532,19 @@ impl PostingIterator { #[inline] fn doc(&self) -> Option { + self.current_doc + } + + fn refresh_current_doc(&mut self) { if self.empty() { - return None; + self.current_doc = None; + return; } - match self.list { + let current_doc = match self.list { PostingList::Compressed(ref list) => { - let block_idx = self.index >> list.block_shift(); - let block_offset = self.index & list.block_mask(); + let block_idx = posting_block_idx(self.index, list.block_size); + let block_offset = posting_block_offset(self.index, list.block_size); let compressed = unsafe { &mut *self.ensure_compressed_block_ptr(list, block_idx) }; // Read from the decompressed block @@ -385,7 +554,8 @@ impl PostingIterator { Some(doc) } PostingList::Plain(ref list) => Some(DocInfo::Located(list.doc(self.index))), - } + }; + self.current_doc = current_doc; } fn position_cursor(&self) -> Option> { @@ -413,8 +583,8 @@ impl PostingIterator { )) } CompressedPositionStorage::SharedStream(stream) => { - let block_idx = self.index >> list.block_shift(); - let block_offset = self.index & list.block_mask(); + let block_idx = posting_block_idx(self.index, list.block_size); + let block_offset = posting_block_offset(self.index, list.block_size); let compressed = unsafe { &mut *self.ensure_compressed_block_ptr(list, block_idx) }; if compressed.position_block_idx != Some(block_idx) { @@ -454,37 +624,46 @@ impl PostingIterator { PostingList::Compressed(ref list) => { debug_assert!(least_id <= u32::MAX as u64); let least_id = least_id as u32; - let shift = list.block_shift(); - let mut block_idx = self.index >> shift; - while block_idx + 1 < list.blocks.len() - && list.block_least_doc_id(block_idx + 1) <= least_id - { - block_idx += 1; - } - self.index = self.index.max(block_idx << shift); + let block_idx = self.block_idx_for_doc( + list, + posting_block_idx(self.index, list.block_size), + least_id, + ); + self.index = self + .index + .max(posting_block_start(block_idx, list.block_size)); let length = list.length as usize; while self.index < length { - let block_idx = self.index >> shift; - let block_offset = self.index & list.block_mask(); + let block_idx = posting_block_idx(self.index, list.block_size); + let block_offset = posting_block_offset(self.index, list.block_size); let compressed = unsafe { &mut *self.ensure_compressed_block_ptr(list, block_idx) }; let in_block = &compressed.doc_ids[block_offset..]; let offset_in_block = in_block.partition_point(|&doc_id| doc_id < least_id); let new_offset = block_offset + offset_in_block; if new_offset < compressed.doc_ids.len() { - self.index = (block_idx << shift) + new_offset; - break; + self.index = posting_block_start(block_idx, list.block_size) + new_offset; + self.block_idx = block_idx; + self.current_doc = Some(DocInfo::Raw(RawDocInfo { + doc_id: compressed.doc_ids[new_offset], + frequency: compressed.freqs[new_offset], + })); + return; } if block_idx + 1 >= list.blocks.len() { self.index = length; + self.block_idx = posting_block_idx(self.index, list.block_size); + self.current_doc = None; break; } - self.index = (block_idx + 1) << shift; + self.index = posting_block_start(block_idx + 1, list.block_size); } - self.block_idx = self.index >> shift; + self.block_idx = posting_block_idx(self.index, list.block_size); + self.current_doc = None; } PostingList::Plain(ref list) => { self.index += list.row_ids[self.index..].partition_point(|&id| id < least_id); + self.current_doc = (!self.empty()).then(|| DocInfo::Located(list.doc(self.index))); } } } @@ -494,11 +673,7 @@ impl PostingIterator { PostingList::Compressed(ref list) => { debug_assert!(least_id <= u32::MAX as u64); let least_id = least_id as u32; - while self.block_idx + 1 < list.blocks.len() - && list.block_least_doc_id(self.block_idx + 1) <= least_id - { - self.block_idx += 1; - } + self.block_idx = self.block_idx_for_doc(list, self.block_idx, least_id); } PostingList::Plain(_) => { // we don't have block max score for legacy index, @@ -508,21 +683,48 @@ impl PostingIterator { } #[inline] - fn block_max_score(&self) -> f32 { + fn block_max_score(&self, scorer: &S) -> f32 { match self.list { - PostingList::Compressed(ref list) => list.block_max_score(self.block_idx), + PostingList::Compressed(ref list) => { + if let Some(impacts) = list.impacts.as_ref() { + let compressed = unsafe { &mut *self.compressed_state_ptr() }; + if let Some((block_idx, score)) = compressed.current_block_max_score + && block_idx == self.block_idx + { + return score; + } + + let score = impacts.level0_score_cached( + self.block_idx, + self.query_weight, + scorer, + &mut compressed.block_max_window.impact_score_cache, + ); + compressed.current_block_max_score = Some((self.block_idx, score)); + return score; + } + list.block_max_score(self.block_idx) + } PostingList::Plain(_) => self.approximate_upper_bound, } } #[inline] - fn block_max_score_up_to_with_stats(&mut self, up_to: u64) -> BlockMaxScore { + fn block_max_score_up_to_with_stats( + &mut self, + up_to: u64, + scorer: &S, + ) -> BlockMaxScore { match self.list { PostingList::Compressed(ref list) => { let compressed = unsafe { &mut *self.compressed_state_ptr() }; - compressed - .block_max_window - .max_score_up_to(list, self.block_idx, up_to) + compressed.block_max_window.max_score_up_to( + list, + self.block_idx, + up_to, + self.query_weight, + scorer, + ) } PostingList::Plain(_) => BlockMaxScore { score: self.approximate_upper_bound, @@ -547,7 +749,7 @@ impl PostingIterator { fn block_first_doc(&self) -> Option { match self.list { PostingList::Compressed(ref list) => { - Some(list.block_least_doc_id(self.block_idx) as u64) + Some(self.block_least_doc_id(list, self.block_idx) as u64) } PostingList::Plain(ref plain) => plain.row_ids.get(self.index).cloned(), } @@ -560,7 +762,7 @@ impl PostingIterator { if self.block_idx + 1 >= list.blocks.len() { return None; } - Some(list.block_least_doc_id(self.block_idx + 1) as u64) + Some(self.block_least_doc_id(list, self.block_idx + 1) as u64) } PostingList::Plain(ref plain) => plain.row_ids.get(self.index + 1).cloned(), } @@ -1188,7 +1390,7 @@ impl<'a, S: Scorer> Wand<'a, S> { let remaining_upper_bound = remaining .iter() - .map(|posting| posting.block_max_score()) + .map(|posting| posting.block_max_score(&self.scorer)) .sum::(); first.score(&self.scorer, doc.frequency(), doc_length) + remaining_upper_bound <= self.threshold @@ -1375,7 +1577,7 @@ impl<'a, S: Scorer> Wand<'a, S> { let narrow_max_score = self .lead .iter() - .map(|posting| posting.block_max_score()) + .map(|posting| posting.block_max_score(&self.scorer)) .sum::(); if narrow_max_score >= self.threshold { @@ -1398,7 +1600,7 @@ impl<'a, S: Scorer> Wand<'a, S> { let mut wide_max_score = 0.0; let mut range_blocks_scanned = 0; for posting in &mut self.lead { - let block_max = posting.block_max_score_up_to_with_stats(lead_up_to); + let block_max = posting.block_max_score_up_to_with_stats(lead_up_to, &self.scorer); wide_max_score += block_max.score; range_blocks_scanned += block_max.blocks_scanned; } @@ -1462,7 +1664,7 @@ impl<'a, S: Scorer> Wand<'a, S> { fn move_head_before_target_to_tail(&mut self, target: u64) { while matches!(self.head_doc(), Some(doc_id) if doc_id < target) { if let Some(posting) = self.head.pop() { - let upper_bound = posting.posting.approximate_upper_bound(); + let upper_bound = posting.posting.global_upper_bound(&self.scorer); if let Some(mut evicted) = self.insert_tail_with_overflow(posting.posting, upper_bound) { @@ -1481,12 +1683,12 @@ impl<'a, S: Scorer> Wand<'a, S> { let lead: f32 = self .lead .iter() - .map(|posting| posting.block_max_score()) + .map(|posting| posting.block_max_score(&self.scorer)) .sum(); let head: f32 = self .head .iter() - .map(|posting| posting.posting.block_max_score()) + .map(|posting| posting.posting.block_max_score(&self.scorer)) .sum(); lead + head + self.tail_max_score } @@ -1499,12 +1701,12 @@ impl<'a, S: Scorer> Wand<'a, S> { let mut sum = self .lead .iter() - .map(|posting| posting.block_max_score()) + .map(|posting| posting.block_max_score(&self.scorer)) .sum::(); let mut possible_matches = self.lead.len(); for posting in &self.tail { if matches!(posting.posting.block_first_doc(), Some(block_doc) if block_doc <= target) { - sum += posting.posting.block_max_score(); + sum += posting.posting.block_max_score(&self.scorer); possible_matches += 1; } } @@ -1570,7 +1772,7 @@ impl<'a, S: Scorer> Wand<'a, S> { Some(block_doc) if block_doc <= target => { tail_posting .posting - .block_max_score_up_to_with_stats(up_to) + .block_max_score_up_to_with_stats(up_to, &self.scorer) .score } _ => 0.0, @@ -1707,9 +1909,9 @@ impl<'a, S: Scorer> Wand<'a, S> { && posting.is_compressed() && self.up_to.is_some_and(|up_to| target <= up_to) { - posting.block_max_score() + posting.block_max_score(&self.scorer) } else { - posting.approximate_upper_bound() + posting.global_upper_bound(&self.scorer) } } @@ -1991,13 +2193,17 @@ mod tests { use std::sync::atomic::{AtomicUsize, Ordering}; + use super::super::impact::build_impact_skip_data; use super::*; use crate::scalar::inverted::scorer::IndexBM25Scorer; use crate::{ metrics::{MetricsCollector, NoOpMetricsCollector}, scalar::inverted::{ - CompressedPostingList, PlainPostingList, PostingListBuilder, builder::PositionRecorder, - encoding::compress_posting_list, + CompressedPostingList, PlainPostingList, PostingListBuilder, + builder::PositionRecorder, + encoding::{ + compress_posting_list, compress_posting_list_with_tail_codec_and_block_size, + }, }, }; @@ -2162,6 +2368,7 @@ mod tests { crate::scalar::inverted::PostingTailCodec::VarintDelta, crate::scalar::inverted::LEGACY_BLOCK_SIZE, None, + None, )) } else { PostingList::Plain(PlainPostingList::new( @@ -2173,6 +2380,75 @@ mod tests { } } + fn generate_impact_posting_list_with_freqs( + doc_ids: Vec, + freqs: Vec, + doc_lengths: Vec, + ) -> PostingList { + generate_impact_posting_list_with_freqs_and_block_size( + doc_ids, + freqs, + doc_lengths, + crate::scalar::inverted::LEGACY_BLOCK_SIZE, + ) + } + + fn generate_impact_posting_list_with_freqs_and_block_size( + doc_ids: Vec, + freqs: Vec, + doc_lengths: Vec, + block_size: usize, + ) -> PostingList { + assert_eq!(doc_ids.len(), freqs.len()); + assert_eq!(doc_ids.len(), doc_lengths.len()); + let block_max_scores = vec![0.0; doc_ids.len().div_ceil(block_size)]; + let blocks = compress_posting_list_with_tail_codec_and_block_size( + doc_ids.len(), + doc_ids.iter(), + freqs.iter(), + block_max_scores.into_iter(), + crate::scalar::inverted::PostingTailCodec::VarintDelta, + block_size, + ) + .unwrap(); + let impact_blocks = doc_ids + .chunks(block_size) + .zip(freqs.chunks(block_size)) + .zip(doc_lengths.chunks(block_size)) + .map(|((doc_ids, freqs), doc_lengths)| { + doc_ids + .iter() + .copied() + .zip(freqs.iter().copied()) + .zip(doc_lengths.iter().copied()) + .map(|((doc_id, freq), doc_length)| (doc_id, freq, doc_length)) + .collect::>() + }) + .collect::>(); + let impacts = build_impact_skip_data(impact_blocks.as_slice()).unwrap(); + PostingList::Compressed(CompressedPostingList::new( + blocks, + 0.0, + doc_ids.len() as u32, + crate::scalar::inverted::PostingTailCodec::VarintDelta, + block_size, + None, + Some(impacts), + )) + } + + fn generate_contiguous_impact_posting_list_with_block_size( + total: usize, + block_size: usize, + ) -> PostingList { + generate_impact_posting_list_with_freqs_and_block_size( + (0..total as u32).collect(), + vec![1; total], + vec![1; total], + block_size, + ) + } + fn generate_posting_list_with_positions( doc_ids: Vec, positions_by_doc: Vec>, @@ -2997,7 +3273,7 @@ mod tests { posting.shallow_next(0); assert_eq!( posting - .block_max_score_up_to_with_stats((3 * BLOCK_SIZE - 1) as u64) + .block_max_score_up_to_with_stats((3 * BLOCK_SIZE - 1) as u64, &UnitScorer) .score, 4.0 ); @@ -3005,7 +3281,7 @@ mod tests { posting.shallow_next((2 * BLOCK_SIZE) as u64); assert_eq!( posting - .block_max_score_up_to_with_stats((4 * BLOCK_SIZE - 1) as u64) + .block_max_score_up_to_with_stats((4 * BLOCK_SIZE - 1) as u64, &UnitScorer) .score, 5.0 ); @@ -3013,12 +3289,127 @@ mod tests { posting.shallow_next((4 * BLOCK_SIZE) as u64); assert_eq!( posting - .block_max_score_up_to_with_stats((5 * BLOCK_SIZE - 1) as u64) + .block_max_score_up_to_with_stats((5 * BLOCK_SIZE - 1) as u64, &UnitScorer) .score, 3.0 ); } + #[test] + fn test_impact_level1_skip_keeps_boundary_equality_in_group() { + for block_size in [crate::scalar::inverted::LEGACY_BLOCK_SIZE, 256] { + let total = (IMPACT_LEVEL1_BLOCKS + 1) * block_size; + let mut posting = PostingIterator::new( + String::from("term"), + 0, + 0, + generate_contiguous_impact_posting_list_with_block_size(total, block_size), + total, + ); + let target = (IMPACT_LEVEL1_BLOCKS * block_size - 1) as u64; + + posting.shallow_next(target); + assert_eq!(posting.block_idx, IMPACT_LEVEL1_BLOCKS - 1); + + posting.next(target); + assert_eq!(posting.block_idx, IMPACT_LEVEL1_BLOCKS - 1); + assert_eq!(posting.doc().map(|doc| doc.doc_id()), Some(target)); + } + } + + #[test] + fn test_impact_level1_skip_handles_partial_final_group() { + for block_size in [crate::scalar::inverted::LEGACY_BLOCK_SIZE, 256] { + let total = (IMPACT_LEVEL1_BLOCKS + 3) * block_size + 17; + let mut posting = PostingIterator::new( + String::from("term"), + 0, + 0, + generate_contiguous_impact_posting_list_with_block_size(total, block_size), + total, + ); + let target = (total - 1) as u64; + let expected_block = total.div_ceil(block_size) - 1; + + posting.shallow_next(target); + assert_eq!(posting.block_idx, expected_block); + + posting.next(target); + assert_eq!(posting.block_idx, expected_block); + assert_eq!(posting.doc().map(|doc| doc.doc_id()), Some(target)); + } + } + + #[test] + fn test_impact_level1_skip_reaches_far_target_doc() { + for block_size in [crate::scalar::inverted::LEGACY_BLOCK_SIZE, 256] { + let total = (IMPACT_LEVEL1_BLOCKS * 3 + 5) * block_size; + let target_block = IMPACT_LEVEL1_BLOCKS * 2 + 2; + let target = (target_block * block_size + 17) as u64; + let mut posting = PostingIterator::new( + String::from("term"), + 0, + 0, + generate_contiguous_impact_posting_list_with_block_size(total, block_size), + total, + ); + + posting.shallow_next(target); + assert_eq!(posting.block_idx, target_block); + + posting.next(target); + assert_eq!(posting.block_idx, target_block); + assert_eq!(posting.doc().map(|doc| doc.doc_id()), Some(target)); + } + } + + #[test] + fn test_compressed_impact_block_max_score_memoizes_current_block() { + let total = 2 * BLOCK_SIZE as u32; + let doc_ids = (0..total).collect::>(); + let freqs = doc_ids + .iter() + .map(|doc_id| if *doc_id < BLOCK_SIZE as u32 { 1 } else { 2 }) + .collect::>(); + let doc_lengths = vec![1; total as usize]; + let posting_list = generate_impact_posting_list_with_freqs(doc_ids, freqs, doc_lengths); + let mut posting = + PostingIterator::new(String::from("term"), 0, 0, posting_list, total as usize); + let scored = Arc::new(AtomicUsize::new(0)); + let scorer = CountingScorer { + scored: scored.clone(), + }; + + let first_score = posting.block_max_score(&scorer); + assert_eq!(first_score, 1.0); + // Baking the shared doc-weight bounds visits every frontier pair once + // (two level0 entries plus one level1 entry for this list). + let baked = scored.load(Ordering::Relaxed); + assert!(baked >= 2); + { + let compressed = unsafe { &mut *posting.compressed_state_ptr() }; + assert_eq!(compressed.current_block_max_score, Some((0, first_score))); + compressed.block_max_window.impact_score_cache = ImpactScoreCache::default(); + } + + let second_score = posting.block_max_score(&scorer); + assert_eq!(second_score, first_score); + assert_eq!( + scored.load(Ordering::Relaxed), + baked, + "repeated block max scores must not recompute doc weights" + ); + + posting.shallow_next(BLOCK_SIZE as u64); + let next_block_score = posting.block_max_score(&scorer); + assert_eq!(next_block_score, 2.0); + assert_eq!( + scored.load(Ordering::Relaxed), + baked, + "other blocks answer from the baked bounds without rescoring" + ); + } + #[test] fn test_and_candidate_prune_scores_first_term_before_full_score() { let total_docs = 2 * BLOCK_SIZE as u32 + 1; @@ -3355,7 +3746,7 @@ mod tests { let posting = PostingIterator::new(String::from("test"), 0, 0, posting_list, 1); - let actual = posting.block_max_score(); + let actual = posting.block_max_score(&UnitScorer); assert!( (actual - expected).abs() < 1e-6, "block max score should match stored value"