From b5f23b7dbfdf0d5bc943f1d3aaa0cd43cb6f81f7 Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Thu, 19 Nov 2026 19:42:02 -0800 Subject: [PATCH] vector: answer a short filtered ANN query by an exact scan (#12802) * vector: answer a short filtered ANN query by an exact scan A prefiltered query through the IVF index sees only the partitions it probes. When those hold fewer than k eligible rows the answer is short (400 matches, topK 500, 63 partitions: about 208 returned), and when at most k rows match Lance appends the ones its probes missed with an infinite distance. Either case is now answered again by an exact scan of the same scope: the listed fragments plus the live coverage of the listed index segments, or the whole table. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * vector: count an explicit probe count as indexed only with an index With nprobes set on a table that has no vector index, the scan was marked indexed, so a filtered query matching fewer than k rows ran the same exact scan a second time. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- seaweed-vector/crates/core/src/index.rs | 77 ++++++++++++++++++++++++ seaweed-vector/crates/core/src/query.rs | 80 +++++++++++++++++++++++-- 2 files changed, 152 insertions(+), 5 deletions(-) diff --git a/seaweed-vector/crates/core/src/index.rs b/seaweed-vector/crates/core/src/index.rs index 4bf9976667..0ceff129c4 100644 --- a/seaweed-vector/crates/core/src/index.rs +++ b/seaweed-vector/crates/core/src/index.rs @@ -198,6 +198,83 @@ mod tests { assert_eq!(filtered.len(), 10); } + /// A filtered query through the index returns every eligible row when + /// fewer than k match, though the probed partitions cannot hold them all: + /// 400 of 4000 rows match, the index has 63 partitions and probes at most + /// 32 of them. + #[tokio::test] + async fn filtered_ann_returns_every_match_below_k() { + let dir = TempDir::new().unwrap(); + let rows = scattered(4000, 8, 0x9E3779B97F4A7C15); + let tags: Vec<&str> = (0..4000) + .map(|i| if i % 10 == 0 { "rare" } else { "common" }) + .collect(); + let mut dataset = testing::write_dataset(&dir, &rows, &tags).await; + let table = VectorTable::resolve(&dataset, None, None).unwrap(); + build( + &mut dataset, + &table.vector_column, + INDEX_NAME, + partitions_for(4000), + false, + ) + .await + .unwrap(); + assert_eq!(partitions_for(4000), 63); + for vector in &scattered(3, 8, 0xD1B54A32D192ED03) { + let q = Query { + filter: Some("tag = 'rare'".to_string()), + ..exact(vector, 500) + }; + let flat = query::flat(&dataset, &table, &q).await.unwrap(); + assert_eq!(flat.len(), 400); + let ann = query::ann(&dataset, &table, &q).await.unwrap(); + assert_eq!(ann.len(), 400, "the index path dropped eligible rows"); + for (f, a) in flat.iter().zip(ann.iter()) { + assert!((f.distance - a.distance).abs() < 1e-5); + } + } + } + + /// When no more than k rows match, every match comes back with its own + /// distance, nearest first — not the rows the probes missed with an + /// infinite distance. Ten fragments of 400 rows, 5 of them matching. + #[tokio::test] + async fn filtered_ann_scores_every_match_at_or_below_k() { + let dir = TempDir::new().unwrap(); + let rows = scattered(4000, 8, 0x9E3779B97F4A7C15); + let tags: Vec<&str> = (0..4000) + .map(|i| if i % 800 == 0 { "rare" } else { "common" }) + .collect(); + let mut dataset = testing::write_dataset(&dir, &rows[..400], &tags[..400]).await; + for chunk in 1..10 { + let r = chunk * 400..(chunk + 1) * 400; + testing::append_dataset(&mut dataset, &rows[r.clone()], &tags[r]).await; + } + let table = VectorTable::resolve(&dataset, None, None).unwrap(); + build(&mut dataset, &table.vector_column, INDEX_NAME, 63, false) + .await + .unwrap(); + for vector in &scattered(3, 8, 0xD1B54A32D192ED03) { + for k in [5, 10] { + let q = Query { + filter: Some("tag = 'rare'".to_string()), + ..exact(vector, k) + }; + let flat = query::flat(&dataset, &table, &q).await.unwrap(); + assert_eq!(flat.len(), 5); + let ann = query::ann(&dataset, &table, &q).await.unwrap(); + assert_eq!(ann.len(), 5); + for (f, a) in flat.iter().zip(ann.iter()) { + assert!( + (f.distance - a.distance).abs() < 1e-5, + "k={k}: {flat:?} vs {ann:?}" + ); + } + } + } + } + #[tokio::test] async fn default_probes_take_the_largest_index() { use lance::index::DatasetIndexExt; diff --git a/seaweed-vector/crates/core/src/query.rs b/seaweed-vector/crates/core/src/query.rs index c8e671851b..320419d04c 100644 --- a/seaweed-vector/crates/core/src/query.rs +++ b/seaweed-vector/crates/core/src/query.rs @@ -53,14 +53,48 @@ pub struct Hit { /// Exact top-K over every fragment, ignoring any index. pub async fn flat(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result> { - run(scanner(dataset, table, query, false).await?, table).await + run(scanner(dataset, table, query, false).await?.0, table).await } /// Top-K with the ANN index where it covers the fragment and a flat pass over /// the rest. Whether the index is used is Lance's decision per fragment, so /// rows written after the last index build are always candidates. +/// +/// A prefiltered search sees only the probed partitions: it can come back +/// short of k, or with unscored rows (infinite distance) when at most k rows +/// match. Either way it is answered again by an exact scan of the same scope. pub async fn ann(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result> { - run(scanner(dataset, table, query, true).await?, table).await + let (scanner, indexed) = scanner(dataset, table, query, true).await?; + let hits = run(scanner, table).await?; + if indexed + && query.filter.is_some() + && !query.postfilter + && (hits.len() < query.k || hits.iter().any(|h| !h.distance.is_finite())) + { + return exact_in_scope(dataset, table, query).await; + } + Ok(hits) +} + +/// [`flat`] over what [`ann`] searches for `query`: the listed fragments plus +/// the live coverage of the listed index segments, or the whole table. +async fn exact_in_scope(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result> { + let fragments = match &query.index_segments { + Some(segments) if !segments.is_empty() => { + let mut ids = query.fragments.clone().unwrap_or_default(); + ids.extend( + crate::segments::covered_fragments(dataset, &table.vector_column, segments).await?, + ); + Some(ids) + } + _ => query.fragments.clone(), + }; + let exact = Query { + index_segments: None, + fragments, + ..query.clone() + }; + run(scanner(dataset, table, &exact, false).await?.0, table).await } /// Fetch rows by key, projected to `columns` (all of them when None). @@ -101,7 +135,7 @@ async fn scanner( table: &VectorTable, query: &Query, use_index: bool, -) -> Result { +) -> Result<(Scanner, bool)> { if query.vector.len() != table.dimension { bail!( "query dim({}) does not match the table's dim({})", @@ -123,12 +157,17 @@ async fn scanner( // An explicitly empty segment list searches no index, so there is // nothing to size probes for. let no_segments = query.index_segments.as_ref().is_some_and(|s| s.is_empty()); + let mut indexed = false; if use_index && !no_segments { let probes = match query.nprobes { - Some(n) => Some(crate::index::Probes { min: n, max: n }), + Some(n) => crate::index::index_names(dataset, &table.vector_column) + .await? + .first() + .map(|_| crate::index::Probes { min: n, max: n }), None => crate::index::default_probes(dataset, &table.vector_column).await?, }; if let Some(probes) = probes { + indexed = true; // Lance searches `min` partitions, and under a prefilter keeps // going up to `max` until it has k rows. An open bound would // make it prepare every partition for that, which costs as much @@ -178,7 +217,7 @@ async fn scanner( columns.push(DISTANCE_COLUMN.to_string()); columns.push(ROW_ID_COLUMN.to_string()); scanner.project(&columns)?; - Ok(scanner) + Ok((scanner, indexed)) } async fn run(scanner: Scanner, table: &VectorTable) -> Result> { @@ -515,4 +554,35 @@ mod tests { exact.iter().map(|h| &h.key).collect::>() ); } + + /// An explicit probe count does not make an unindexed table's scan count + /// as indexed, so a short filtered answer is not scanned a second time. + #[tokio::test] + async fn explicit_probes_need_an_index() { + let dir = TempDir::new().unwrap(); + let rows = crate::testing::vectors(300, DIM); + let mut dataset = write_dataset(&dir, &rows, &["a"; 300]).await; + let table = VectorTable::resolve(&dataset, None, None).unwrap(); + let query = Query { + vector: rows[0].clone(), + k: 10, + filter: Some("tag = 'a'".to_string()), + postfilter: false, + distance: DistanceType::L2, + nprobes: Some(4), + index_segments: None, + fragments: None, + }; + assert!(!scanner(&dataset, &table, &query, true).await.unwrap().1); + crate::index::build( + &mut dataset, + &table.vector_column, + crate::index::INDEX_NAME, + 4, + false, + ) + .await + .unwrap(); + assert!(scanner(&dataset, &table, &query, true).await.unwrap().1); + } }