fix(query): apply cosine candidate bounds once per ANN branch (#5330)

An indexed cosine query with an unindexed tail can lose valid rows when
its distance range has a positive lower bound. Lance now translates the
candidate bounds for exact rescoring. Replanning the ANN branch with
doubled inputs can translate them a second time. A public range of
`[0.10, 0.16)` then reaches the index as `[0.40, 0.64)`.

The SDK checks the candidate bounds on each quantized cosine ANN node.
If Lance already supplied the normalized squared-L2 bounds, the SDK uses
that node. Exact fallback and refinement keep their original range, and
returned distances use the public cosine scale.

The regression compares indexed results against a brute-force scan after
appending an out-of-range vector. It exercises modern and legacy IVF_PQ,
single-query refinement, and modern batched queries with and without
refinement. Rust formatting and whitespace checks passed. Project CI
runs the behavioral tests.
This commit is contained in:
Yang Cen
2026-12-01 23:02:29 +08:00
committed by GitHub
parent ec230318f6
commit cf59298934
+95 -34
View File
@@ -598,11 +598,12 @@ async fn create_scanner_plan(
if !normalized_l2_indices.is_empty() {
// Rebuild only the affected ANN nodes with internal normalized squared-L2
// bounds. Exact branches keep the public cosine bounds from `plan`.
let internal_plan = if query.lower_bound.is_some() || query.upper_bound.is_some() {
scanner.distance_range(
query.lower_bound.map(|bound| bound / COSINE_ANN_SCALE),
query.upper_bound.map(|bound| bound / COSINE_ANN_SCALE),
);
let candidate_bounds = (
query.lower_bound.map(|bound| bound / COSINE_ANN_SCALE),
query.upper_bound.map(|bound| bound / COSINE_ANN_SCALE),
);
let internal_plan = if candidate_bounds != (None, None) {
scanner.distance_range(candidate_bounds.0, candidate_bounds.1);
scanner
.create_plan()
.await
@@ -610,7 +611,12 @@ async fn create_scanner_plan(
} else {
plan.clone()
};
plan = normalize_ann_branches(plan, internal_plan, &normalized_l2_indices)?;
plan = normalize_ann_branches(
plan,
internal_plan,
&normalized_l2_indices,
candidate_bounds,
)?;
}
Ok(plan)
@@ -821,7 +827,7 @@ pub(super) async fn normalize_cosine_ann_branches(
if normalized_l2_indices.is_empty() {
return Ok(plan);
}
normalize_ann_branches(plan.clone(), plan, &normalized_l2_indices)
normalize_ann_branches(plan.clone(), plan, &normalized_l2_indices, (None, None))
}
fn find_ann_plans<'a>(plan: &'a dyn ExecutionPlan, ann_plans: &mut Vec<AnnExecRef<'a>>) {
@@ -853,11 +859,16 @@ fn normalize_ann_branches(
public_plan: Arc<dyn ExecutionPlan>,
internal_plan: Arc<dyn ExecutionPlan>,
normalized_l2_indices: &HashSet<uuid::Uuid>,
candidate_bounds: (Option<f32>, Option<f32>),
) -> Result<Arc<dyn ExecutionPlan>> {
let mut internal_ann_plans = VecDeque::new();
collect_ann_plans(&internal_plan, &mut internal_ann_plans);
let normalized =
replace_ann_branches(public_plan, &mut internal_ann_plans, normalized_l2_indices)?;
let normalized = replace_ann_branches(
public_plan,
&mut internal_ann_plans,
normalized_l2_indices,
candidate_bounds,
)?;
if !internal_ann_plans.is_empty() {
return Err(Error::Runtime {
message: "internal and public vector plans contained different ANN branches"
@@ -871,6 +882,7 @@ fn replace_ann_branches(
public_plan: Arc<dyn ExecutionPlan>,
internal_ann_plans: &mut VecDeque<Arc<dyn ExecutionPlan>>,
normalized_l2_indices: &HashSet<uuid::Uuid>,
candidate_bounds: (Option<f32>, Option<f32>),
) -> Result<Arc<dyn ExecutionPlan>> {
if let Some(public_ann) = AnnExecRef::from_plan(public_plan.as_ref()) {
let internal_plan = internal_ann_plans
@@ -913,14 +925,33 @@ fn replace_ann_branches(
.to_string(),
});
}
return scale_distance_column(internal_plan, COSINE_ANN_SCALE);
// Lance can already translate the original bounds for exact rescoring
// (including an unindexed tail). Its sibling flat/exact nodes still
// need the public bounds. Select the candidate node independently.
let query = public_ann.query();
let candidates = if query.lower_bound.map(f32::to_bits)
== candidate_bounds.0.map(f32::to_bits)
&& query.upper_bound.map(f32::to_bits) == candidate_bounds.1.map(f32::to_bits)
{
public_plan
} else {
internal_plan
};
return scale_distance_column(candidates, COSINE_ANN_SCALE);
}
let children = public_plan
.children()
.into_iter()
.cloned()
.map(|child| replace_ann_branches(child, internal_ann_plans, normalized_l2_indices))
.map(|child| {
replace_ann_branches(
child,
internal_ann_plans,
normalized_l2_indices,
candidate_bounds,
)
})
.collect::<Result<Vec<_>>>()?;
Ok(replace_children_if_necessary(public_plan, children)?)
}
@@ -2755,7 +2786,7 @@ mod tests {
}
}
let batched_ranged = table
let ranged_batch = table
.vector_search(query_vector.as_slice())
.unwrap()
.add_query_vector(query_vector.as_slice())
@@ -2763,25 +2794,30 @@ mod tests {
.nprobes(1)
.unwrap()
.limit(1)
.distance_range(None, Some(nearest + 1e-5))
.execute()
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
let batched_ranged_distances = batch_distances_by_query(&batched_ranged, 2);
for (query_index, query_distances) in batched_ranged_distances.into_iter().enumerate() {
assert_eq!(
query_distances.len(),
1,
"public cosine range must return one hit for query {query_index}"
);
assert!(
(query_distances[0] - nearest).abs() < 1e-5,
"ranged batch distance {} for query {query_index} must match {nearest}",
query_distances[0]
);
.distance_range(Some(nearest - 1e-5), Some(nearest + 1e-5));
for query in [ranged_batch.clone(), ranged_batch.refine_factor(1)] {
let batched_ranged = query
.execute()
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
let batched_ranged_distances = batch_distances_by_query(&batched_ranged, 2);
for (query_index, query_distances) in
batched_ranged_distances.into_iter().enumerate()
{
assert_eq!(
query_distances.len(),
1,
"public cosine range must return one hit for query {query_index}"
);
assert!(
(query_distances[0] - nearest).abs() < 1e-5,
"ranged batch distance {} for query {query_index} must match {nearest}",
query_distances[0]
);
}
}
}
@@ -2790,7 +2826,7 @@ mod tests {
.unwrap()
.limit(1)
.refine_factor(1)
.distance_range(None, Some(nearest + 1e-5))
.distance_range(Some(nearest - 1e-5), Some(nearest + 1e-5))
.execute()
.await
.unwrap()
@@ -2849,11 +2885,23 @@ mod tests {
.unwrap();
table.add(appended).execute().await.unwrap();
let mixed = table
let mixed_query = table
.vector_search(query_vector.as_slice())
.unwrap()
.limit(5)
.distance_range(None, Some(nearest + 1e-5))
.distance_range(Some(nearest - 1e-5), Some(nearest + 1e-5));
let exact = mixed_query
.clone()
// Bypassing the index also skips its metric selection.
.distance_type(crate::DistanceType::Cosine)
.bypass_vector_index()
.execute()
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
let mixed = mixed_query
.execute()
.await
.unwrap()
@@ -2863,6 +2911,19 @@ mod tests {
let mixed_distances = distances(&mixed);
assert_eq!(mixed_distances.len(), 1);
assert!((mixed_distances[0] - nearest).abs() < 1e-5);
let ids = |batches: &[RecordBatch]| -> Vec<i32> {
batches
.iter()
.flat_map(|batch| {
batch["id"]
.as_primitive::<Int32Type>()
.values()
.iter()
.copied()
})
.collect()
};
assert_eq!(ids(&mixed), ids(&exact));
}
#[tokio::test]