Repository navigation
fix: evaluate constant-first spatial predicates correctly - #10080
Conversation
geodatafusion evaluates a relate predicate whose first argument is a constant as relate(array, constant), so ST_Contains, ST_Within, ST_Covers and ST_CoveredBy answer the converse question when the constant comes first, and a NULL constant geometry panics. Reads return the wrong rows, and delete, update and merge_insert conditions in these forms change the wrong rows. Register Lance wrappers for the ten relate predicates in lance-geo. A constant-first call is evaluated as the converse predicate with the arguments swapped, a NULL constant returns NULL, and simplification rewrites constant-first calls to the column-first converse so the R-tree index can serve them. Closes lance-format#10078 Co-Authored-By: Claude Opus 5.5 <[email protected]>
geruh
left a comment
There was a problem hiding this comment.
Thanks for raising @sarwarbhuiyan!
I compared this with #10079, and I think both approaches look correct. I'm leaning toward this one mostly because of the broader regression coverage, especially the merge_insert case and the additional mutation tests.
One thing I do like about #10079 is that it reuses the existing udf.rs rather than adding another file. Might be worth cleaning that up here too unless I'm missing something.
wdyt?
| import pyarrow as pa | ||
| import pytest | ||
|
|
||
| pytest.importorskip("geoarrow.rust.core") |
There was a problem hiding this comment.
nit: i noticed that this class is skipped in the ci since thegeo extra isn't installed. should we enable it so these python regressions actually run? Or do we intentionally rely on the rust tests for coverage in this submodule?
edit: this existed before and can be done as a followup
There was a problem hiding this comment.
Good catch. Turning it on is one line (add geo to the extras in .github/workflows/run_tests/action.yml; geoarrow-rust-core and geoarrow-rust-io have wheels for every platform and Python version in the matrix). But today it fails test_staged_rtree_after_rewrite_columns, which is a real bug: a staged R-tree segment keeps stale coverage after update_columns, so indexed spatial queries miss rows. Filed #10167. I'd keep this PR scoped and send the CI change as a follow-up, either with that fix or with the test marked xfail until it lands.
rust/lance-geo/src/udf.rs was on main but never compiled, and geodatafusion::register already registers every UDF it listed. Put the relate predicate wrappers there instead of in a new relate.rs, and check that a NULL constant on an empty batch returns an empty array. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks @geruh, good call. Moved the wrappers into |
There was a problem hiding this comment.
✅ Gate recommendation: approve.
Verified the move into udf.rs and added empty-batch NULL coverage. No blocking findings. The focused UDF tests pass, and the existing Rust dataset regressions cover the affected read and mutation paths.
This remains an alternative to #10079, which fixes the same upstream defect; merge one implementation.
geruh
left a comment
There was a problem hiding this comment.
Thanks for addressing the changes @sarwarbhuiyan! LGTM just need maintainer approval and CI run
…main Main bumped rustls 0.23.46 and the trust-store pins (webpki-roots and webpki-root-certs 1.0.10, rustls-webpki 0.103.16) in lance-format#10193 and lance-format#10215; this PR's lockfile predates those changes, so cargo-deny fails on RUSTSEC-2026-0381/0382. Mirror the same root lockfile pins, deny.toml ignores, and dependency-age allowlist entries.
|
Temporarily closing to retrigger CI dispatch for the latest head (test workflows did not start after the dependency-sync push). |
|
@sarwarbhuiyan looks like we got some conflicts again :( |
…t-predicates # Conflicts: # Cargo.lock
Xuanwo
left a comment
There was a problem hiding this comment.
Reviewed the current head. Constant-first spatial predicates now evaluate with the correct operand order, with scan/SQL/update/delete regression coverage. No blocking issues found.
…10251) BREAKING CHANGE: `lance_index::scalar::expression::PlannerIndexExt` is removed. Use the free function `create_filter_plan(expr, index_info, use_scalar_index)`, passing an expression already optimized with `Planner::optimize_expr`. ## Summary lance-index only used DataFusion sub-crate APIs, but it depended on the `datafusion` umbrella crate directly and through lance-datafusion, lance-index-core and lance-geo. So it could not start compiling until the umbrella crate finished. This PR moves what lance-index needs into a new `lance-datafusion-exec` crate built only on the sub-crates, so lance-index compiles in parallel with the umbrella crate. ```diff lance ├── lance-datafusion ── datafusion (umbrella) -├── lance-index ─┬── lance-datafusion ── datafusion -│ ├── lance-index-core ── datafusion -│ └── lance-geo ── geodatafusion ── datafusion +│ └── lance-datafusion-exec ── datafusion-{common,execution,expr,physical-expr,physical-plan,functions} +├── lance-index ─┬── lance-datafusion-exec +│ ├── lance-index-core ── datafusion-{common,execution,expr} +│ └── lance-geo (no DataFusion) ``` - **`lance-datafusion-exec`** holds the moved code: `OneShotExec`, `StrictBatchSizeExec`, `HardCapBatchSizeExec`, `LanceExecutionOptions`, the execution metrics helpers, `chunker`, `utils`, `datagen`, the `contains_tokens` and JSON UDFs, `safe_coerce_scalar` and `column_names_in_expr`. Its `execute_plan` runs under a `TaskContext` built from the options (memory pool, spill dir, batch size) with no registered functions, which is all lance-index's sort and merge plans need. - **lance-datafusion** re-exports the moved modules and items under their old paths. Its `execute_plan` still uses the cached `SessionContext`, so query execution in `lance` is unchanged. Both share `execute_plan_with_context`. - **`PlannerIndexExt`** needed `Planner` (SQL parsing, optimizer), so it is replaced by `create_filter_plan`, and `lance` calls `Planner::optimize_expr` first. - **lance-geo** drops its DataFusion dependency; lance-datafusion registers the `geodatafusion` UDFs itself, and the `st_*` relate-predicate wrappers from #10080 move from `lance-geo/src/udf.rs` to `lance-datafusion/src/udf/geo.rs` unchanged. `lance_geo::register_functions` is gone; `lance_datafusion::udf::register_functions` still registers everything. Splitting lance-geo's features was not enough, because workspace feature unification turned `geo` back on for lance-index's copy. ## Evidence Clean `cargo build --workspace --timings`, dev profile, 16 cores, rustc wrapper cache disabled, one run each. Times in seconds from build start. | | main | this PR | |---|---|---| | `datafusion` umbrella finishes | 98.5 | 96.0 | | lance-index-core starts | 96.9 | 42.6 | | lance-index starts | 102.1 | 49.3 | | lance-index finishes | 132.3 | 79.2 | | `lance` starts | 121.6 | 98.7 | | total | 249.7 | 222.2 | `lance` now starts 2.7s after the umbrella crate finishes instead of 23.1s, so the umbrella crate is the only thing left on its critical path. Part of the 27.5s total difference is run-to-run noise (the shared DataFusion crates finished about 2.5s earlier in the PR run). ## Merge Risk **Door:** Two-way. No format or persisted-state change; the code moves are mechanical and the old lance-datafusion paths still resolve. **Blast Radius:** `public-api` (`PlannerIndexExt` removal in lance-index), index training plans in lance-index now run under a function-less `TaskContext`, and geo UDF registration moved into lance-datafusion. Fixes #10244 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
…d updates Lance 15.0.0-beta.15, which main now pins, includes lance-format/lance#10080: constant-first ST_Contains, ST_Within, ST_Covers and ST_CoveredBy are now evaluated as their column-first converses, so they return the right rows, use the R-tree, and no longer panic on a NULL constant geometry. Replace the strict xfails with regression tests that cover all four asymmetric predicates plus ST_Intersects, with and without an R-tree, in queries, delete() and update(). The old update test passed literal values instead of updates_sql, so it failed for that reason as well; it now uses updates_sql. Drop the "write the column first" warning from the Python and TypeScript docstrings and the docs page. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Part of #4554. Supersedes #4555. This exposes Lance's R-tree index in the Python and TypeScript SDKs. Python gets a `lancedb.index.RTree` config with an optional `page_size`, accepted by `create_index(config=...)` on local, async and remote tables. TypeScript gets `Index.rtree({ pageSize })` and `RTreeOptions`. Both map to the Rust crate's existing `Index::RTree`, so remote tables send `index_type: "RTREE"`. The index accelerates `ST_Intersects`, `ST_Contains`, `ST_Within`, `ST_Touches`, `ST_Crosses`, `ST_Overlaps`, `ST_Covers` and `ST_CoveredBy` filters between a GeoArrow column and a constant geometry, in either argument order, including as a prefilter on vector search. The scalar index docs page gets an R-tree section. `geo` is now a default feature of the Python and Node packages. Without it, a local table can neither build the index nor evaluate `ST_*` filters, and because wheels and npm packages are prebuilt, an opt-in Cargo feature would not reach users. pylance already ships with `geo` on. It adds pure-Rust crates under licenses that `deny.toml` already allows. `Cargo.lock` doesn't change, and the third-party license notices are regenerated. The cost is size: the macOS arm64 release wheel grows from 69.4 MB to 71.7 MB (+2.4 MB, +3.4%). The tests pin the constant-first predicate bug that held up #4555, which lance-format/lance#10080 fixed, in queries, `delete()` and `update()`, with and without the index. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Closes #10078
Motivation
pylance builds with the
geofeature, which is a default feature of thelancecrate, so its spatial predicates run through geodatafusion. When the constant geometry is the first argument, geodatafusion'srelate_implcomputes the DE-9IM matrix for (B, A) but reads it as (A, B). As a result,ST_Contains(<region>, geom)returns false for the points inside the region.delete("NOT ST_Contains(<region>, geom)")deletes every row, including the ones inside the region. A NULL constant geometry panics the scan. lancedb/lancedb#4555 is about to turn ongeoin the LanceDB Python and TypeScript SDKs, so more users will hit this.The bug is in geodatafusion 0.5.0, which
mainpins, and in 0.6.0, which #9979 moves to. The upstream fix, datafusion-contrib/geodatafusion#111, is still open. This PR fixes the bug in Lance, so it works with either version and doesn't wait for a geodatafusion release.What changes
lance-geonow registers its own versions of the ten relate predicates:st_contains,st_within,st_covers,st_coveredby,st_crosses,st_disjoint,st_equals,st_intersects,st_overlapsandst_touches. These replace geodatafusion's registrations of the same names. They live inrust/lance-geo/src/udf.rs. That file was already onmain, but nomod udfdeclaration compiled it, andgeodatafusion::registeralready registers everything it listed, so this PR replaces its contents. Each predicate wraps geodatafusion's implementation and changes three things:ST_Contains(c, x)=ST_Within(x, c)andST_Covers(c, x)=ST_CoveredBy(x, c). The symmetric predicates are their own converse. This uses geodatafusion's (array, scalar) path, which is correct and keeps its prepared-geometry fast path.ScalarUDFImpl::simplifyrewritesf(<literal>, x)toconverse(f)(x, <literal>). The R-tree matcher (visit_scalar_fn) only takes the indexed column from the first argument, so constant-first predicates never used the index before this change; now they do. The rewrite also covers second arguments that are not columns, such asST_Contains(<region>, ST_Point(x, y)).Design
The fix is at the UDF level rather than in the planner, because that is the one place every evaluation path shares. All of these paths resolve the functions by name from a registry that
lance_geo::register_functionsfills:delete,updateandmerge_insertconditionsDataset::sqllance_datafusion::udf::register_functionsornew_session_context, which is how LanceDB sets up its sessionsThe argument-order rewrite is in the UDF's
simplifyhook rather than in a Lance-specific planner pass. DataFusion'sExprSimplifierruns that hook both forPlanner::optimize_exprand for the DataFusion optimizer behindDataset::sql. Constant folding runs first, soST_GeomFromText('...')has already become a literal when the rewrite sees it. The invoke-time swap is still needed for expressions that reach execution without being simplified, such as a rawExprpassed toScanner::filter_expr.There are no
Cargo.tomlorCargo.lockchanges.Affected predicates (verified)
I compared all ten relate predicates, in both argument orders, against
geo::Relate. The test geometries were points, lines and polygons that lie inside a square, on its boundary, or outside it, or that overlap, cross, equal, touch or enclose it: 156 pairs per predicate. This used a temporarygeodev-dependency that is not part of this PR.ST_ContainsST_WithinST_CoversST_CoveredByST_Crosses,ST_Overlaps(including mixed dimensions),ST_Touches,ST_Equals,ST_Intersects,ST_DisjointEvery (array, scalar) result was already correct before this change. The NULL panic affects all ten predicates, with the NULL in either position.
Testing
lance-geounit tests, run with--features geo:geo::Relatein argument order.simplifyrewrite.register_functionsinstalls the wrappers.lancedataset tests indataset_geo.rs. Each runs with and without an R-tree, on a dataset with several fragments that includes a NULL geometry:Dataset::sql, and aSessionContextset up withregister_functionsandLanceTableProvider. The constant-first result must equal the column-first converse and the expected rows. When the column is indexed, the plan for the constant-first form must showScalarIndexQuery.deletewithNOT ST_Contains,ST_Contains,NOT ST_Covers,NOT ST_WithinandNOT ST_CoveredBy, andupdatewithST_Contains,NOT ST_Contains,ST_CoversandNOT ST_Within. Each test asserts exactly which rows survive or change.merge_insertwithWhenNotMatchedBySource::delete_if("ST_Contains(<region>, geom)").delete.Python tests in
test_geo.py: constant-first reads,updateanddelete, each with and without an R-tree, plus the NULL constant.All of the new Rust and Python tests fail when the wrappers are not registered, and pass when they are. With only the
simplifyrewrite disabled, results stay correct but the index-use assertions fail.Commands run:
cargo fmt --all -- --checkcargo clippy --profile ci --locked -p lance-geo --features geo --all-targets -- -D warningscargo clippy --profile ci --locked --all --tests --benches -- -D warningscargo test --profile ci -p lance-geo --features geocargo test --profile ci -p lance --lib -- geo rtree st_intersectscargo test --profile ci -p lance-index --features geo --lib -- rtree geopython/, with thegeoextra installed:uv run make lintanduv run pytest python/tests/test_geo.py. The new tests pass.test_staged_rtree_after_rewrite_columnsfails with the same assertion on a build without this change.CI installs only the
testsandrayextras, so it skipstest_geo.py(importorskip("geoarrow.rust.core")). The Rust tests cover the same behavior.Follow-up
Once Lance pins a geodatafusion release that includes datafusion-contrib/geodatafusion#111, remove the argument swap and NULL handling in
RelateUdf::invoke_with_argsinudf.rs. Thesimplifyrewrite does not depend on the upstream bug and keeps constant-first predicates indexable, so it should stay.🤖 Generated with Claude Code