Skip to content

fix: register Lance SQL functions for RTE filters - #3794

Merged
Xuanwo merged 9 commits into
mainfrom
gatekeeper/fix-3109-1
Dec 2, 2026
Merged

Xuanwo merged 9 commits into
mainfrom
gatekeeper/fix-3109-1

Conversation

@lancedb-gatefixer

@lancedb-gatefixer lancedb-gatefixer Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

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(...) <= radius resolves 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 geo feature enabled.

This builds on Gatefixer's original contribution.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@github-actions github-actions Bot added bug Something isn't working Rust Rust related issues labels Aug 5, 2026
lancedb-gatekeeper[bot]

This comment was marked as outdated.

@lancedb-gatekeeper lancedb-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Sep 17, 2026
@lancedb-gatekeeper lancedb-gatekeeper Bot removed K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Oct 27, 2026
lancedb-gatekeeper[bot]

This comment was marked as outdated.

@lancedb-gatekeeper lancedb-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Oct 27, 2026
@github-actions github-actions Bot added the Python Python SDK label Oct 27, 2026
@lancedb-gatekeeper lancedb-gatekeeper Bot removed K-risk Latest Gatekeeper recommendation includes a non-blocking risk. K-approved Latest Gatekeeper recommendation permits acceptance. labels Oct 27, 2026

@lancedb-gatekeeper lancedb-gatekeeper Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ 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.

Comment thread python/Cargo.toml Outdated

[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"]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread rust/lancedb/src/query.rs Outdated
]));
let vectors = FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>(
rows.iter()
.map(|(_, _, _, vector)| Some(vector.iter().copied().map(Some).collect())),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 --lib

The 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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a001db6: the explicit Vec<_> collection type makes the Arrow fixture compile. The current-head spatial regression suite passes.

Comment thread rust/lancedb/src/remote/table.rs Outdated

let batches = table
.query()
.nearest_to([0.0, 0.0])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread rust/lancedb/src/query.rs Outdated
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]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread rust/lancedb/src/query.rs Outdated
let table = make_geo_query_table(&tmp_dir).await;
table.set_unenforced_primary_key(["id"]).await.unwrap();
table
.enable_rte(crate::table::RTEWriteSpec::unsharded())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 --lib

It 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].

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@lancedb-gatekeeper lancedb-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Oct 27, 2026
@lancedb-gatekeeper lancedb-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Oct 27, 2026
lancedb-gatekeeper[bot]

This comment was marked as outdated.

@lancedb-gatekeeper lancedb-gatekeeper Bot added K-changes Latest Gatekeeper recommendation requests changes. and removed K-changes Latest Gatekeeper recommendation requests changes. labels Oct 27, 2026

@Xuanwo Xuanwo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

  1. Keep the RTE function registration with a focused regression test: On current main (85522224, with --features geo and Lance beta.34), an ordinary scan with ST_Distance(...) <= radius succeeds (returning IDs [1, 2]), while merged RTE planning fails with Invalid function 'st_distance'. Registering lance_datafusion::udf::register_functions in rust/lancedb/src/table/query/lsm.rs fixes 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 documented ST_Distance <= radius would cover the real issue cleanly.
  2. Drop the Python/Node default geo changes: SDK default geo enablement is already on main via #4942.
  3. Drop the LanceDB-only ST_DWithin alias: As noted in the PR description, a LanceDB-local rewrite cannot satisfy the standalone PyLance caller in #3109. If ST_DWithin is 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.
@Xuanwo Xuanwo changed the title fix: support ST_DWithin filters fix: register Lance SQL functions for RTE filters Dec 2, 2026
@lancedb-gatekeeper lancedb-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Dec 2, 2026

@lancedb-gatekeeper lancedb-gatekeeper Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.

@lancedb-gatekeeper lancedb-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Dec 2, 2026
@Xuanwo
Xuanwo merged commit 8c9ba71 into main Dec 2, 2026
61 of 64 checks passed
@Xuanwo
Xuanwo deleted the gatekeeper/fix-3109-1 branch December 2, 2026 07:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working K-approved Latest Gatekeeper recommendation permits acceptance. Python Python SDK Rust Rust related issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant