Skip to content

fix: evaluate constant-first spatial predicates correctly - #10080

Merged
Xuanwo merged 5 commits into
lance-format:mainfrom
sarwarbhuiyan:fix/geo-constant-first-predicates
Oct 23, 2026
Merged

Xuanwo merged 5 commits into
lance-format:mainfrom
sarwarbhuiyan:fix/geo-constant-first-predicates

Conversation

@sarwarbhuiyan

@sarwarbhuiyan sarwarbhuiyan commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Closes #10078

Motivation

pylance builds with the geo feature, which is a default feature of the lance crate, so its spatial predicates run through geodatafusion. When the constant geometry is the first argument, geodatafusion's relate_impl computes 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 on geo in the LanceDB Python and TypeScript SDKs, so more users will hit this.

The bug is in geodatafusion 0.5.0, which main pins, 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-geo now 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_overlaps and st_touches. These replace geodatafusion's registrations of the same names. They live in rust/lance-geo/src/udf.rs. That file was already on main, but no mod udf declaration compiled it, and geodatafusion::register already registers everything it listed, so this PR replaces its contents. Each predicate wraps geodatafusion's implementation and changes three things:

  • Scalar first, array second. The call is evaluated as the converse predicate with the arguments swapped: ST_Contains(c, x) = ST_Within(x, c) and ST_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.
  • NULL geometry. A NULL scalar geometry in either position returns NULL instead of panicking.
  • Index use. ScalarUDFImpl::simplify rewrites f(<literal>, x) to converse(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 as ST_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_functions fills:

  • the scanner filter
  • delete, update and merge_insert conditions
  • Substrait filters
  • Dataset::sql
  • downstream sessions built with lance_datafusion::udf::register_functions or new_session_context, which is how LanceDB sets up its sessions

The argument-order rewrite is in the UDF's simplify hook rather than in a Lance-specific planner pass. DataFusion's ExprSimplifier runs that hook both for Planner::optimize_expr and for the DataFusion optimizer behind Dataset::sql. Constant folding runs first, so ST_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 raw Expr passed to Scanner::filter_expr.

There are no Cargo.toml or Cargo.lock changes.

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 temporary geo dev-dependency that is not part of this PR.

Predicate geodatafusion 0.5.0, scalar first With this PR
ST_Contains 30 of 156 pairs wrong all correct
ST_Within 30 of 156 pairs wrong all correct
ST_Covers 44 of 156 pairs wrong all correct
ST_CoveredBy 44 of 156 pairs wrong all correct
ST_Crosses, ST_Overlaps (including mixed dimensions), ST_Touches, ST_Equals, ST_Intersects, ST_Disjoint all correct all correct

Every (array, scalar) result was already correct before this change. The NULL panic affects all ten predicates, with the NULL in either position.

Testing

lance-geo unit tests, run with --features geo:

  • Every predicate, with the constant in either position, against geodatafusion's (array, array) evaluation. That path relates each pair of rows with geo::Relate in argument order.
  • The constant-first result against the column-first converse.
  • Known answers for the asymmetric predicates.
  • NULL constants, typed and untyped, in both positions, on both a non-empty and an empty batch.
  • The simplify rewrite.
  • That register_functions installs the wrappers.

lance dataset tests in dataset_geo.rs. Each runs with and without an R-tree, on a dataset with several fragments that includes a NULL geometry:

  • Reads, through the scanner filter, Dataset::sql, and a SessionContext set up with register_functions and LanceTableProvider. 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 show ScalarIndexQuery.
  • Wrong-row mutation regressions. delete with NOT ST_Contains, ST_Contains, NOT ST_Covers, NOT ST_Within and NOT ST_CoveredBy, and update with ST_Contains, NOT ST_Contains, ST_Covers and NOT ST_Within. Each test asserts exactly which rows survive or change.
  • merge_insert with WhenNotMatchedBySource::delete_if("ST_Contains(<region>, geom)").
  • NULL constant geometry, in reads and in delete.

Python tests in test_geo.py: constant-first reads, update and delete, 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 simplify rewrite disabled, results stay correct but the index-use assertions fail.

Commands run:

  • cargo fmt --all -- --check
  • cargo clippy --profile ci --locked -p lance-geo --features geo --all-targets -- -D warnings
  • cargo clippy --profile ci --locked --all --tests --benches -- -D warnings
  • cargo test --profile ci -p lance-geo --features geo
  • cargo test --profile ci -p lance --lib -- geo rtree st_intersects
  • cargo test --profile ci -p lance-index --features geo --lib -- rtree geo
  • From python/, with the geo extra installed: uv run make lint and uv run pytest python/tests/test_geo.py. The new tests pass. test_staged_rtree_after_rewrite_columns fails with the same assertion on a build without this change.

CI installs only the tests and ray extras, so it skips test_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_args in udf.rs. The simplify rewrite does not depend on the upstream bug and keeps constant-first predicates indexable, so it should stay.

🤖 Generated with Claude Code

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

@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 pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@github-actions github-actions Bot added A-python Python bindings bug Something isn't working labels Oct 16, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 16, 2026
@wjones127 wjones127 added the critical-fix Bugs that cause crashes, security vulnerabilities, or incorrect data. label Oct 19, 2026

@geruh geruh left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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")

@geruh geruh Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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]>
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 20, 2026
@sarwarbhuiyan

Copy link
Copy Markdown
Contributor Author

Thanks @geruh, good call. Moved the wrappers into udf.rs and dropped relate.rs (963d9d9). udf.rs wasn't actually compiled on main (no mod udf), and geodatafusion::register already covers everything it registered, so replacing its contents is safe. I also pulled in #10079's empty-batch NULL check. Otherwise the two fixes behave the same, so #10079 can be closed if you go with this one.

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ 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 geruh left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.
@github-actions github-actions Bot added the A-deps Dependency updates label Oct 22, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 22, 2026
@Xuanwo

Xuanwo commented Oct 22, 2026

Copy link
Copy Markdown
Member

Temporarily closing to retrigger CI dispatch for the latest head (test workflows did not start after the dependency-sync push).

@Xuanwo Xuanwo closed this Oct 22, 2026
@Xuanwo Xuanwo reopened this Oct 22, 2026
@geruh

geruh commented Oct 22, 2026

Copy link
Copy Markdown
Contributor

@sarwarbhuiyan looks like we got some conflicts again :(

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

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.

@Xuanwo
Xuanwo merged commit 251079e into lance-format:main Oct 23, 2026
5 checks passed
wjones127 added a commit that referenced this pull request Oct 26, 2026
…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]>
sarwarbhuiyan added a commit to lancedb/lancedb that referenced this pull request Nov 18, 2026
…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]>
wjones127 pushed a commit to lancedb/lancedb that referenced this pull request Nov 19, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-deps Dependency updates A-python Python bindings bug Something isn't working critical-fix Bugs that cause crashes, security vulnerabilities, or incorrect data.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: ST_Contains, ST_Within, ST_Covers and ST_CoveredBy return wrong rows when the constant geometry comes first

5 participants