Repository navigation
fix: register Lance SQL functions for RTE filters - #3794
Conversation
There was a problem hiding this comment.
Claude Code Review
This repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.
Tip: disable this comment in your organization's Code Review settings.
…hin-20261027 # Conflicts: # Cargo.lock # Cargo.toml # rust/lancedb/src/query.rs
There was a problem hiding this comment.
❌ Gate recommendation: request changes.
Native-only lowering addresses the earlier remote-query risk. The remaining issues concern safe geo activation and valid regression coverage. Keep the native compatibility rewrite, but defer default Python/Node geo enablement until the upstream predicate fix is incorporated into the Lance dependency. The regression tests also need to compile and preserve the correct plain-scan result set.
Documentation
Add a local ST_DWithin example to QueryBase::only_if, explaining the Rust geo feature, planar coordinate units, and the separate standalone-pylance scope.
|
|
||
| [features] | ||
| default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/metrics-otel"] | ||
| default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/geo", "lancedb/metrics-otel"] |
There was a problem hiding this comment.
Default-enabling geo exposes incorrect spatial write predicates in both SDKs, not just the new radius predicate. The pinned GeoDataFusion 0.5.0 evaluates scalar-first asymmetric relations backwards. I reproduced ST_Contains(region, geometry) returning no matches for an interior point, and delete("NOT ST_Contains(...)") successfully deleting both the interior and exterior points. This silently publishes an incorrect dataset version; retrying does not recover the deleted row.
Keep this feature opt-in for now, including the matching change in nodejs/Cargo.toml, or wait for GeoDataFusion #111 to land, be incorporated into Lance, and then bump the dependency before enabling these defaults. That prerequisite fixes the argument-order mechanism without copying its implementation into this PR.
Executed regression reproducer
Add this integration test and run cargo test --profile ci -p lancedb --no-default-features --features geo,remote --test geo_delete constant_first_delete_with_point_constructor -- --nocapture:
#[tokio::test]
async fn constant_first_delete_with_point_constructor() {
let dir = tempfile::tempdir().unwrap();
let db = lancedb::connect(dir.path().to_str().unwrap())
.execute().await.unwrap();
let batch = arrow_array::record_batch!(
("id", Int32, [1, 2]),
("x", Float64, [1.0, 5.0]),
("y", Float64, [1.0, 5.0])
).unwrap();
let table = db.create_table("points", batch)
.execute().await.unwrap();
let outside = "NOT ST_Contains(ST_GeomFromText('POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0))'), ST_Point(x, y))";
let result = table.delete(outside).await.unwrap();
println!("{result:?}");
assert_eq!(table.count_rows(None).await.unwrap(), 1);
}Observed: DeleteResult { num_deleted_rows: 2, version: 2 }; the assertion fails with actual 0, expected 1. The interior point must survive. The same failure reproduced with a stored GeoArrow extension column.
There was a problem hiding this comment.
Fixed in ef26a9d: the narrowed patch no longer changes either SDK default; it only registers Lance SQL functions for RTE filters and adds a regression test. Default geo enablement is already in the base through #4942, and the pinned Lance registry includes the scalar-first relation and NULL-handling fixes from lance#10080. This earlier default-activation finding no longer applies to the current diff.
| ])); | ||
| let vectors = FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>( | ||
| rows.iter() | ||
| .map(|(_, _, _, vector)| Some(vector.iter().copied().map(Some).collect())), |
There was a problem hiding this comment.
The geo regression fixture does not compile: collect() has no inferable collection type because from_iter_primitive accepts any IntoIterator. This prevents all of the new geo execution tests from running. Give the collection an explicit type, for example collect::<Vec<_>>(), or pass a concrete iterator directly.
Executed on this head:
cargo test --quiet --profile ci -p lancedb --no-default-features --features geo,remote st_dwithin --libThe compiler reports E0283 here: cannot infer type of the type parameter B declared on the method collect. The regression coverage needs to be runnable before this feature can satisfy the repository's test requirement.
There was a problem hiding this comment.
Fixed in a001db6: the explicit Vec<_> collection type makes the Arrow fixture compile. The current-head spatial regression suite passes.
|
|
||
| let batches = table | ||
| .query() | ||
| .nearest_to([0.0, 0.0]) |
There was a problem hiding this comment.
The new vector-query tests pass an owned array, but IntoQueryVector is implemented for borrowed arrays and Vec<f32>, not [f32; 2]. This breaks compilation of the remote test suite even without enabling geo. The two matching calls in query.rs have the same error when geo is enabled.
Use a supported input at all three sites, such as .nearest_to(&[0.0_f32, 0.0]).
Executed cargo test --quiet --profile ci -p lancedb --no-default-features --features geo,remote st_dwithin --lib; it reports E0277: the trait bound [{float}; 2]: IntoQueryVector is not satisfied here and at the two new local vector-query calls.
There was a problem hiding this comment.
Fixed in a001db6: all three vector-query calls now use borrowed arrays. The local and remote spatial regression tests compile and pass on the current head.
| let plain = concat_batches(&plain[0].schema(), &plain).unwrap(); | ||
| let mut plain_ids = plain["id"].as_primitive::<Int32Type>().values().to_vec(); | ||
| plain_ids.sort_unstable(); | ||
| assert_eq!(plain_ids, vec![1, 4]); |
There was a problem hiding this comment.
The plain RTE scan must retain row 2 as well: its point is (1, 1), whose distance from the origin is sqrt(2) < 2. Unlike the vector query below, this scan has no two-row limit. Expect [1, 2, 4] here; keep [1, 4] for the limited nearest-neighbor query.
After correcting only the new test compilation errors, I ran cargo test --quiet --profile ci -p lancedb --no-default-features --features geo,remote st_dwithin --lib. Six tests passed, and this assertion failed with actual [1, 2, 4], expected [1, 4]. The production result is correct; the regression test currently rejects it.
There was a problem hiding this comment.
Fixed in a001db6: the unlimited plain scan now expects [1, 2, 4], while the limited nearest-neighbor query keeps [1, 4]. Both assertions pass with RTE enabled.
| let table = make_geo_query_table(&tmp_dir).await; | ||
| table.set_unenforced_primary_key(["id"]).await.unwrap(); | ||
| table | ||
| .enable_rte(crate::table::RTEWriteSpec::unsharded()) |
There was a problem hiding this comment.
This fixture has no vector index, so its RTE vector query is rejected before it can test the lowered spatial predicate. RTE vector reads require a vector index that the write spec maintains. Create a small index on vector before enabling RTE, for example an IVF-flat index with one partition; the default unsharded spec maintains existing indexes. Keep RTE enabled so the test actually covers both base and active-memtable rows.
After correcting only the new compilation errors and the plain-scan expectation, I ran:
cargo test --quiet --profile ci -p lancedb --no-default-features --features geo,remote test_st_dwithin_filter_on_rte_base_and_active_memtable --libIt reaches the vector query and fails with NotSupported: the MemWAL LSM scanner requires the vector index on 'vector' to be maintained by the write spec. This is a fixture/setup defect, not a reason to weaken the scanner's safety check.
An otherwise identical control with an IVF-flat index passed: plain IDs [1, 2, 4], vector IDs [1, 4].
There was a problem hiding this comment.
Fixed in cfc3ea5: the fixture creates a single-partition IVF-flat index before enabling RTE and explicitly maintains it in the write spec. The base-plus-active-memtable test now passes for both plain and vector queries.
Xuanwo
left a comment
There was a problem hiding this comment.
Thanks for tracking down the RTE filter gap here. Rather than landing the full PR as-is, could we rebase and narrow this PR to the native RTE SQL function registration fix?
- Keep the RTE function registration with a focused regression test: On current
main(85522224, with--features geoand Lancebeta.34), an ordinary scan withST_Distance(...) <= radiussucceeds (returning IDs[1, 2]), while merged RTE planning fails withInvalid function 'st_distance'. Registeringlance_datafusion::udf::register_functionsinrust/lancedb/src/table/query/lsm.rsfixes that path (returning[1, 2, 4, 5]including the boundary row from each source, and all six rows unfiltered). Keeping that fix with a focused base + active MemTable regression for documentedST_Distance <= radiuswould cover the real issue cleanly. - Drop the Python/Node default
geochanges: SDK defaultgeoenablement is already onmainvia #4942. - Drop the LanceDB-only
ST_DWithinalias: As noted in the PR description, a LanceDB-local rewrite cannot satisfy the standalone PyLance caller in #3109. IfST_DWithinis pursued, it belongs in Lance's shared function registry rather than as a LanceDB-only lowering pass.
It would also help to retitle and update the PR description for the narrowed RTE fix (and drop any #3109 fix reference). Happy to review again once rebased.
Integrate main and retain the native RTE function registration from the original PR. Verify an inclusive distance filter across the base table and active MemTable.
There was a problem hiding this comment.
✅ Gate recommendation: approve.
The narrowed patch fixes function resolution at the RTE parsing boundary using the existing Lance registry, matching ordinary Embedded scans without a separate SQL rewrite. The focused regression covers base and active MemTable rows, including the inclusive distance boundary.
The earlier default-activation concern no longer applies: SDK geo defaults were independently merged in #4942, and the pinned Lance registry contains the predicate corrections from lance#10080. The LanceDB-only ST_DWithin alias is gone.
Embedded RTE queries parse SQL filters in a separate DataFusion context. Register Lance's SQL functions in that context so a filter such as
ST_Distance(...) <= radiusresolves as it does in an ordinary Embedded scan.The Rust regression checks an inclusive distance filter against rows in the base table and the active MemTable with the
geofeature enabled.This builds on Gatefixer's original contribution.