Skip to content

chore: upgrade DataFusion to 55 and Arrow to 59 - #9979

Closed
timsaucer wants to merge 6 commits into
lance-format:mainfrom
rerun-io:chore/datafusion-55
Closed

timsaucer wants to merge 6 commits into
lance-format:mainfrom
rerun-io:chore/datafusion-55

Conversation

@timsaucer

@timsaucer timsaucer commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Closes #9647.

DataFusion 55.0.0 is now released upstream, both for Rust and Python so this PR upgrades Lance. There are corresponding updates to other dependencies like Arrow included.

The PR has two parts: the mechanical upgrade, then fixes for behaviour changes the upgrade surfaced in tests.

Migration for DataFusion 55 breaking changes

Most of these are purely mechanical:

  • Implemented the now-required ExecutionPlan::apply_expressions on every Lance node. Nodes that own physical expressions (FilteredReadExec, LanceFilterExec, CountFromMaskExec, the memtable scan nodes) report them; the rest report none.
  • Migrated statistics from the deprecated partition_statistics to child_stats_requests + statistics_from_inputs, and callers/tests to StatisticsContext::compute.
  • Replaced deprecated with_new_children calls with replace_children_if_necessary (tests that deliberately rebuild a node use replace_children with Recompute).
  • The execution batch size is now a ConfigNonZeroUsize, so a zero LanceExecutionOptions::batch_size is rejected with an invalid-input error instead of panicking inside DataFusion. This overlaps with fix(datafusion): reject a zero batch_size in LanceExecutionOptions #9641.

Behavior changes addressed

I have gone through and added in-line comments for the sections that I think require more careful review. The list of all behavior changes generated by the LLM are:

  • Physical optimizer (option B from feature: upgrade to Arrow 59 and DataFusion 55 #9647). DataFusion 55 removed EnforceDistribution in favour of EnsureRequirements, which also enforces sorting and drops sorts no parent declares it needs. Because TakeExec (and most Lance nodes) don't declare maintains_input_order, it removed the _score sort under legacy-format full-text search. optimizer.rs now composes the still-public pieces of the old rule into a Lance EnforceDistribution, so plans are unchanged. Adopting EnsureRequirements after an ordering audit is left as follow-up.
  • UnionExec relabelling. project() now builds its output with the requested schema's metadata (ProjectionExec::try_new_with_schema_metadata), so DataFusion 55's UnionExec no longer inserts a no-op relabelling projection over the scalar-index arm.
  • Signed zero in merge-insert keys. DataFusion 55's hash join matches -0.0 and +0.0 per IEEE 754 (perf: stop redoing per-chunk setup on the hash join probe path apache/datafusion#25658). The indexed lookup (MapIndexExec) now probes both zero encodings so the indexed and unindexed paths agree, consistent with Lance filters since fix: make float filters treat -0.0 and 0.0 as the same value #6236. test_merge_insert_on_float_zero_key now expects both zero rows to match.
  • Spec-violating maps when adding blank rows. Arrow 59's take rebuilds maps via the validating MapArray::try_new, which rejects exactly the maps (nullable entries field, or nulls in the entries) that the BlankPlan::Take fallback from fix: choose cheapest blanks when restoring deleted rows #8946 exists for. Those columns are now copied with MutableArrayData, matching Arrow 58's result.
  • MemWAL index filter test. DataFusion 55 no longer casts a list column whose nested field metadata differs from a list literal's, so the test builds the relabelling cast explicitly; the production code that sees through such casts is unchanged.

Verification

  • cargo clippy --all --tests --benches --all-features -- -D warnings clean for the workspace, python/ and java/lance-jni/; all three lockfiles and python/uv.lock refreshed.
  • cargo test -p lance -p lance-datafusion --all-features: all pass except the DynamoDB/S3 commit tests, which need localstack and were not run locally.
  • Python: test_table_provider.py passes against datafusion-python 55, and uv run make lint is clean. The full Python suite was not run locally.

🤖 Generated with Claude Code but edited by a human 🧑.

timsaucer and others added 2 commits October 13, 2026 12:18
Bump DataFusion 54 -> 55 and Arrow 58 -> 59.2 across the Rust workspace,
the Python bindings and the Java JNI crate, along with the dependencies
that must move in lockstep: geodatafusion 0.6, geoarrow 0.9, pyo3 0.29
and pythonize 0.29. The Python `datafusion` requirement moves to
`>=55,<56` so the datafusion-python major version matches the
datafusion-ffi version pylance is built against.

Migration for DataFusion 55 breaking changes:

- Implement the now-required `ExecutionPlan::apply_expressions`. Nodes
  that own physical expressions (FilteredReadExec, LanceFilterExec,
  CountFromMaskExec and the memtable scan nodes) report them.
- Migrate statistics from the deprecated `partition_statistics` to
  `child_stats_requests` + `statistics_from_inputs`, and compute stats
  through `StatisticsContext` in callers and tests.
- Replace deprecated `with_new_children` calls with
  `replace_children_if_necessary` (or `replace_children` in tests that
  deliberately rebuild a node).
- Pass a `PhysicalPlanningContext` to `create_physical_expr` and
  `LoweredAggregateBuilder`, and update `ExtensionPlanner::plan_extension`.
- Build `AnalyzeExec` through its builder.
- `EnforceDistribution` was removed; use `EnsureRequirements`.
- The execution batch size is now a `ConfigNonZeroUsize`, so a zero
  `LanceExecutionOptions::batch_size` is rejected with an invalid-input
  error instead of panicking inside DataFusion.

Arrow 59 / pyo3 0.29 follow-ups: `MutableArrayData::try_extend` and
`PyCapsule::new_with_value`. The arrow-scalar and arrow-stats crate
versions track the Arrow major version.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Follow-up to the DataFusion 55 / Arrow 59 upgrade, fixing the test
regressions it introduced.

- Keep distribution-only physical optimization. DataFusion 55 folded
  `EnforceDistribution` into `EnsureRequirements`, which also enforces
  sort requirements and drops sorts that no parent declares it needs.
  Many Lance nodes (e.g. `TakeExec`) do not declare whether they
  maintain input order, so that rule removed the score sort under
  full-text search results. Rebuild the old rule from DataFusion's
  public pieces until those nodes declare their ordering (lance-format#9647).
- Build `project()` with the requested schema's metadata. DataFusion 55's
  `UnionExec` relabels any input whose schema metadata differs from the
  union's, which added a no-op projection over scalar-index union arms.
- Treat `-0.0` and `+0.0` as the same merge-insert key. DataFusion 55's
  hash join now matches float keys per IEEE 754, so the indexed lookup
  probes both zero encodings to agree with it (and with Lance filters).
- Copy rows of maps whose entries break the Arrow spec without
  validation. Arrow 59's `take` rebuilds maps through the validating
  `MapArray::try_new`, which rejected exactly the maps the blank-row
  `Take` fallback exists for.
- Build the relabelling cast explicitly in the MemWAL index filter test,
  since DataFusion 55 no longer casts a column whose nested field
  metadata differs from a list literal's.

Co-Authored-By: Claude Opus 5.5 (1M context) <[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 A-index Vector index, linalg, tokenizer A-java Java bindings + JNI A-deps Dependency updates A-encoding Encoding, IO, file reader/writer chore labels Oct 14, 2026
Comment on lines +255 to +267
// DataFusion 55 no longer casts the column when only nested field
// metadata differs, so add the relabelling cast that older planners
// produced.
let relabelled = DataType::List(Arc::new(Field::new("item", DataType::Utf8, true)));
let filter = filter
.transform_up(|expr| match expr {
Expr::Column(column) if column.name == "tags" => Ok(Transformed::yes(
datafusion::logical_expr::cast(Expr::Column(column), relabelled.clone()),
)),
expr => Ok(Transformed::no(expr)),
})
.unwrap()
.data;

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.

This is one of the non-trivial changes needed, so worth reviewing.

Comment on lines +751 to +758
/// Copy the rows at `indices` out of `array` without validating the result.
///
/// A map only takes the [`BlankPlan::Take`] fallback when its entries break the
/// Arrow spec (see [`blank_plan`]), and arrow's `take` rebuilds maps through the
/// validating `MapArray::try_new`, which rejects exactly those maps. Copying the
/// buffers keeps the source's shape, which is what `take` produced before arrow
/// 59 added that validation.
fn copy_rows_unvalidated(

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.

This section and all changes in this file are non-trivial and worth careful review.

/// raw bits. Both settings of `use_index` are exercised; which one the planner
/// picks for a one-row source is not asserted.
/// merge_insert matches float keys per IEEE 754, like filters do, so a source
/// key of `+0.0` matches both the `-0.0` and the `+0.0` row. Both settings of

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.

This is a potentially important change upstream

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.

I doubt it's too important. Hardly anyone is going to be matching on float values.

Comment on lines +214 to +223
/// Rule that inserts exchange nodes (`RepartitionExec`, `CoalescePartitionsExec`)
/// where needed to satisfy each node's input distribution requirements.
///
/// This is DataFusion's former `EnforceDistribution` rule. DataFusion 55 folded it
/// into `EnsureRequirements`, which also enforces sort requirements and removes
/// any sort a node above it does not declare it needs. Many Lance nodes do not
/// declare whether they maintain their input order (e.g. `TakeExec`), so that
/// rule drops sorts Lance relies on, such as the score ordering of full-text
/// search results. Until those nodes declare their ordering, only enforce
/// distribution. See <https://github.com/lance-format/lance/issues/9647>.

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.

See the linked issue in the comments here for why this code was added. We may want a follow up to change the behavior, but this is purely an upgrade PR so I'm trying to keep the prior behavior as in the discussion of the issue.

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.

This seems fine. We can follow up and fix this in a more proper way.

Comment on lines +691 to +700
let encodings = match zero_encodings(&value) {
Some((negative, positive)) => vec![negative, positive],
None => vec![value],
};
for value in encodings {
if dedupe {
if seen.contains(&value) {
continue;
}
seen.insert(value.clone());

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.

One of the non-trivial changes due to the -0.0 / +0.0 change upstream.

@timsaucer

Copy link
Copy Markdown
Contributor Author

FYI @slachiewicz if you're available to review.

Copilot AI 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.

🟡 Changes recommended

Deferred blank restoration still invokes Arrow’s validating take path for spec-violating maps.

1 open finding
What changed in this PR

Upgrades Lance to DataFusion 55 and Arrow 59 while adapting execution plans, statistics, bindings, and changed runtime behavior.

Changes:

  • Migrates DataFusion execution-plan, statistics, optimizer, and planning APIs.
  • Handles signed-zero joins, map copying, projection metadata, and batch-size validation.
  • Refreshes Rust, Python, and Java dependencies and lockfiles.
File Description
rust/​lance/​tests/​topk_late_materialization/​mod.rs Adapts optimizer tests and execution plans.
rust/​lance/​tests/​count_pushdown/​mod.rs Updates count-pushdown test plans.
rust/​lance/​src/​io/​exec/​utils.rs Implements expression traversal requirements.
rust/​lance/​src/​io/​exec/​topk_late_materialization.rs Migrates child replacement APIs.
rust/​lance/​src/​io/​exec/​testing.rs Updates test execution plan implementation.
rust/​lance/​src/​io/​exec/​take.rs Migrates statistics and child replacement APIs.
rust/​lance/​src/​io/​exec/​scan.rs Updates expression traversal and statistics tests.
rust/​lance/​src/​io/​exec/​scalar_index.rs Adds signed-zero probing and API migration.
rust/​lance/​src/​io/​exec/​rowids.rs Migrates row-ID statistics handling.
rust/​lance/​src/​io/​exec/​row_addr_mask.rs Implements expression traversal.
rust/​lance/​src/​io/​exec/​pushdown_scan.rs Implements expression traversal.
rust/​lance/​src/​io/​exec/​projection.rs Preserves requested schema metadata.
rust/​lance/​src/​io/​exec/​optimizer.rs Restores distribution-only optimization behavior.
rust/​lance/​src/​io/​exec/​minhash.rs Updates minhash execution plans.
rust/​lance/​src/​io/​exec/​knn.rs Migrates KNN plans and statistics.
rust/​lance/​src/​io/​exec/​fts.rs Migrates FTS execution-plan APIs.
rust/​lance/​src/​io/​exec/​filtered_read.rs Migrates statistics and expression reporting.
rust/​lance/​src/​io/​exec/​filter.rs Delegates new filter-plan APIs.
rust/​lance/​src/​io/​exec/​count_from_mask.rs Reports aggregate physical expressions.
rust/​lance/​src/​dataset/​write/​merge_insert/​logical_plan.rs Updates extension planner signature.
rust/​lance/​src/​dataset/​write/​merge_insert/​exec/​write.rs Updates merge-write execution plan.
rust/​lance/​src/​dataset/​write/​merge_insert/​exec/​in_place.rs Updates in-place execution plan.
rust/​lance/​src/​dataset/​write/​merge_insert/​exec/​delete.rs Updates delete execution plan.
rust/​lance/​src/​dataset/​write/​merge_insert.rs Migrates APIs and signed-zero expectations.
rust/​lance/​src/​dataset/​updater/​blanks.rs Adds unvalidated copying for invalid maps.
rust/​lance/​src/​dataset/​scanner.rs Supplies physical planning contexts.
rust/​lance/​src/​dataset/​mem_wal/​scanner/​generation_read.rs Updates physical expression planning.
rust/​lance/​src/​dataset/​mem_wal/​scanner/​exec/​schema_relabel.rs Updates schema-relabel execution plan.
rust/​lance/​src/​dataset/​mem_wal/​scanner/​exec/​reconcile.rs Updates reconciliation execution plan.
rust/​lance/​src/​dataset/​mem_wal/​scanner/​exec/​pk_block_filter.rs Updates PK-filter execution plan.
rust/​lance/​src/​dataset/​mem_wal/​scanner/​exec/​generation_tag.rs Updates generation-tag execution plan.
rust/​lance/​src/​dataset/​mem_wal/​scanner/​exec/​first_by_pk.rs Updates first-by-PK execution plan.
rust/​lance/​src/​dataset/​mem_wal/​scanner/​exec/​coalesce_first.rs Updates coalescing execution plan.
rust/​lance/​src/​dataset/​mem_wal/​scanner/​exec/​bloom_guard.rs Updates bloom-guard execution plan.
rust/​lance/​src/​dataset/​mem_wal/​memtable/​scanner/​exec/​vector.rs Updates vector-index execution plan.
rust/​lance/​src/​dataset/​mem_wal/​memtable/​scanner/​exec/​scan.rs Reports memtable scan expressions.
rust/​lance/​src/​dataset/​mem_wal/​memtable/​scanner/​exec/​scalar_index.rs Reports scalar-index expressions.
rust/​lance/​src/​dataset/​mem_wal/​memtable/​scanner/​exec/​fts.rs Reports memtable FTS expressions.
rust/​lance/​src/​dataset/​mem_wal/​memtable/​scanner/​exec/​dedup_scan.rs Reports dedup-scan expressions.
rust/​lance/​src/​dataset/​mem_wal/​memtable/​scanner/​exec/​brute_force_vector.rs Reports vector-filter expressions.
rust/​lance/​src/​dataset/​mem_wal/​index/​filter.rs Updates cast-specific test construction.
rust/​lance-index/​src/​scalar/​btree/​flat.rs Supplies physical planning contexts.
rust/​lance-index/​src/​scalar/​btree.rs Supplies physical planning context.
rust/​lance-encoding/​src/​testing.rs Migrates fallible mutable-array extension.
rust/​lance-datafusion/​src/​signed_zero.rs Exposes signed-zero encodings.
rust/​lance-datafusion/​src/​projection.rs Updates expression planning.
rust/​lance-datafusion/​src/​planner.rs Updates expression planning.
rust/​lance-datafusion/​src/​lib.rs Exposes signed-zero utilities.
rust/​lance-datafusion/​src/​exec.rs Migrates plans and validates batch size.
rust/​lance-arrow/​src/​deepcopy.rs Handles fallible mutable-array copying.
rust/​arrow-stats/​Cargo.toml Bumps crate version for Arrow 59.
rust/​arrow-scalar/​src/​lib.rs Handles fallible scalar copying.
rust/​arrow-scalar/​Cargo.toml Bumps crate version for Arrow 59.
python/​uv.lock Refreshes Python dependency resolution.
python/​src/​object_store.rs Migrates PyO3 capsule construction.
python/​src/​lib.rs Migrates DataFusion FFI capsule creation.
python/​pyproject.toml Requires DataFusion Python 55.
python/​Cargo.toml Upgrades Arrow, DataFusion, and PyO3.
java/​lance-jni/​Cargo.toml Upgrades JNI Rust dependencies.
java/​lance-jni/​Cargo.lock Refreshes JNI dependency resolution.
Cargo.toml Upgrades workspace dependencies.
Cargo.lock Refreshes workspace dependency resolution.

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +758 to +761
fn copy_rows_unvalidated(
array: &ArrayRef,
indices: &UInt32Array,
) -> std::result::Result<ArrayRef, ArrowError> {

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.

compact_blank_source takes its row from storage, and the map decoder already builds maps with the validating MapArray::try_new, so a spec-violating map can't reach this take. d20d1c9 adds a comment there saying so.

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

Keeping distribution-only optimization is reasonable for this upgrade; adopting EnsureRequirements can follow the ordering audit discussed in #9647.

The deferred-map finding reproduces with deliberately invalid arrays, but the existing storage decoder already rejects these entry shapes before updates. It does not establish a newly failing supported dataset path.

Please mark this PR with the breaking-change label.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 14, 2026

@slachiewicz slachiewicz 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 the careful write-up. The migration looks right to me (apply_expressions on every node that owns physical expressions, child_stats_requests where children's stats are needed, replace_children_if_necessary), and the geo bump to geoarrow 0.9 / geodatafusion 0.6 keeps geo in the defaults.

  • Signed zero in merge_insert: +1 on the breaking-change label. Besides one +0.0 key now matching both zero rows, a source containing both -0.0 and +0.0 is now one key twice, so the default SourceDedupeBehavior::Fail rejects it as an ambiguous merge where it used to succeed. Worth a release-note line, and a test pinning that case.
  • blanks.rs: agreed with the gate that compact_blank_source only fails on maps the decoder already rejects. A comment there saying so would save the next reader the same trip.
  • optimizer.rs: fine for this upgrade; the functions it borrows are documented in DataFusion 55 as internals of ensure_requirements, so the EnsureRequirements follow-up from #9647 should land before DataFusion 56.

This supersedes my #9641, which I'll close once it lands, and I'll rebase #9643 after it.

@wjones127 wjones127 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 working on this. I have a couple blocking questions, but happy to merge once those are addressed and this is rebased.

if dedupe {
if seen.contains(&value) {
continue;
let encodings = match zero_encodings(&value) {

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.

question (blocking): With dedupe=false, a zero row now yields two values, so the output no longer lines up 1:1 with input rows. Does any non-dedupe caller zip these back to rows by position? Cleared when you either confirm that no caller does (with call-site references) or keep one entry per row on that path, plus a test that covers it.

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.

From reading the call sites, nothing lines these values up with rows. key_values is private and has one caller, map_batch (scalar_index.rs:752). Its values go into a SargableQuery::IsIn (built at :715), which is a set, and their count only orders probes when there are several keys (:749, :771), where dedupe is true. The operator's output is a single _rowid column (INDEX_LOOKUP_SCHEMA, :397) built from the index result, so a second encoding of zero only widens the IsIn set. The one side effect is the comparison metric in bitmap.rs:1020, which counts that zero twice.

key_values_probes_both_zero_encodings in rerun-io#86 pins it: the zero row yields both encodings, so four rows give five values without dedupe and four with it, and an integer zero or NaN is not expanded.

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.

No caller lines these values up with rows. As @slachiewicz traced above, key_values has one caller, map_batch, which feeds a set (SargableQuery::IsIn), and the operator's output is built from the index result, not from the input rows. bb0eaaa/d20d1c98e add key_values_probes_both_zero_encodings, which pins this: four rows give five values without dedupe and four with it, and integer zero and NaN are not expanded.

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 adding the test. I'm satisfied with that.

Comment thread rust/lance-datafusion/src/lib.rs Resolved
Comment thread rust/lance/src/io/exec/take.rs Outdated
@@ -709,6 +713,13 @@ impl ExecutionPlan for TakeExec {
}

/// This preserves the output schema.

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.

nitpick: The existing /// This preserves the output schema. doc comment now sits on apply_expressions instead of with_new_children. Move apply_expressions above it.

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.

Fixed in bf1f739.

None,
),
})?;
if contains_map(array.data_type()) {

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.

question: what are we doing with maps that isn't compliant? Can we fix that instead of making this workaround?

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.

The maps that need this are ones storage can't produce. Field::try_from checks that a map key is non-nullable (rust/lance-core/src/datatypes/field.rs:1269) but not the entries field, which the Arrow spec also requires to be non-nullable, so lance accepts such a schema. Arrow 59's take rebuilds maps with MapArray::try_new and rejects them, while the map decoder already builds with MapArray::try_new (rust/lance-encoding/src/encodings/logical/map.rs:229), so they only reach apply_blank_plan as in-memory arrays.

Fixing it at the source would mean rejecting a nullable entries field in Field::try_from and dropping copy_rows_unvalidated (blanks.rs:758). That turns a schema lance accepts today into an error, so it may fit better as a follow-up than in this upgrade.

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.

They're maps that storage can't produce: Field::try_from doesn't reject a nullable entries field, so such a schema can exist in memory, but the map decoder already rejects these arrays. Fixing it at the source means rejecting that schema in Field::try_from, which turns something accepted today into an error, so I'd rather do it as a follow-up than in this upgrade. Happy to open an issue for it.

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.

Yeah, let's open an issue for that.

/// raw bits. Both settings of `use_index` are exercised; which one the planner
/// picks for a one-row source is not asserted.
/// merge_insert matches float keys per IEEE 754, like filters do, so a source
/// key of `+0.0` matches both the `-0.0` and the `+0.0` row. Both settings of

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.

I doubt it's too important. Hardly anyone is going to be matching on float values.

Comment on lines +214 to +223
/// Rule that inserts exchange nodes (`RepartitionExec`, `CoalescePartitionsExec`)
/// where needed to satisfy each node's input distribution requirements.
///
/// This is DataFusion's former `EnforceDistribution` rule. DataFusion 55 folded it
/// into `EnsureRequirements`, which also enforces sort requirements and removes
/// any sort a node above it does not declare it needs. Many Lance nodes do not
/// declare whether they maintain their input order (e.g. `TakeExec`), so that
/// rule drops sorts Lance relies on, such as the score ordering of full-text
/// search results. Until those nodes declare their ordering, only enforce
/// distribution. See <https://github.com/lance-format/lance/issues/9647>.

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.

This seems fine. We can follow up and fix this in a more proper way.

timsaucer and others added 4 commits October 20, 2026 11:12
Resolve conflicts with main and port its new code to DataFusion 55 and
Arrow 59: MergeConditionExec now takes a `&dyn Session` and reports its
conditions via apply_expressions, OrderedConcatExec gains
apply_expressions, the row-offset statistics fix moves into
statistics_from_inputs, and planar sparse pages use try_extend.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
-0.0 and +0.0 are one key now, so a source holding both matches each zero
target row twice: Fail rejects it as ambiguous, FirstSeen updates each once.
Also note in compact_blank_source why its validating take is safe.
Hide the signed_zero module from docs since it is public only for
internal reuse, and keep the with_new_children doc comment on
TakeExec::with_new_children.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@timsaucer

Copy link
Copy Markdown
Contributor Author

Merged main in (no force push, so the review threads still point at the original commits) and addressed the review:

  • Pulled in @slachiewicz's tests from test: pin merge_insert of a source holding both float zeros rerun-io/lance#86: test_merge_insert_source_with_both_float_zeros (a source holding both -0.0 and +0.0 is rejected under the default SourceDedupeBehavior::Fail) and key_values_probes_both_zero_encodings, plus the comment in compact_blank_source.
  • Applied the nitpicks (#[doc(hidden)] on signed_zero, doc comment placement in take.rs).
  • The merge commit also ports code that landed on main since the last push (MergeConditionExec, OrderedConcatExec, row-offset statistics, sparse planar pages) to DataFusion 55 / Arrow 59.

@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 20, 2026

@wjones127 wjones127 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 working on this, @timsaucer

@wjones127

Copy link
Copy Markdown
Contributor

Looks like we need to:

  1. Bump the version of lance-arrow-stats to 59.0.0
  2. Bump MSRV to 1.95

Should be good after that.

Xuanwo added a commit that referenced this pull request Oct 23, 2026
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](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Xuanwo <[email protected]>
@Xuanwo

Xuanwo commented Oct 27, 2026

Copy link
Copy Markdown
Member

I'm working on merging this.

@Xuanwo

Xuanwo commented Oct 28, 2026

Copy link
Copy Markdown
Member

seems I can't push to this branch directly since it's a fork from org. I will duplicate one with all commits preserved.

Xuanwo added a commit that referenced this pull request Oct 28, 2026
Closes #9647.

DataFusion 55 and Arrow 59 require a coordinated upgrade across the Rust
workspace, Python bindings, and Java JNI crate. This PR carries the
original implementation forward, resolves its conflicts with the current
`main`, and adapts the remaining execution-plan, spill, and binding APIs
to DataFusion 55.

This replaces #9979 because that branch is owned by an organization
where the maintainer cannot push. The original commit authors are
preserved in the branch history; the trailers at the end of this
description also retain their credit if the PR is squash-merged.

### Behavior changes

- Migrate execution-plan expression reporting, statistics, planning
contexts, optimizer composition, and `AnalyzeExec` construction to
DataFusion 55.
- Preserve full-text-search ordering during the `EnforceDistribution`
removal, align indexed and hash-join signed-zero matching, and keep
Arrow 59 map copying behavior compatible with existing data.
- Use DataFusion 55's public `SpillFile` API and refresh the Rust,
Python, Java, and Python dependency lockfiles.
- Package the local Arrow helper crates in CI while their `59.0.0`
versions are not yet on crates.io.

### Verification

- `cargo fmt --all -- --check`
- `cargo clippy --all --tests --benches -- -D warnings`
- `cargo check --workspace --tests --benches`, including
`--all-features`
- `cargo package --workspace --no-verify --all-features`
- Targeted Rust tests for DataFusion, spill handling, merge-insert
behavior, Arrow ordering, count pushdown, top-k late materialization,
full-text search, and execution plans
- Python `make install`, `uv run make lint`, and
`test_table_provider.py`
- Java JNI clippy, Spotless, and `./mvnw test`

Thanks to @timsaucer for the original implementation and careful
behavior analysis, and to @slachiewicz, @wjones127 for the review,
signed-zero discussion, and follow-up coverage. Their contributions and
review history made this upgrade possible.

Co-authored-by: Sylwester Lachiewicz <[email protected]>
Co-authored-by: Tim Saucer <[email protected]>

---------

Co-authored-by: Tim Saucer <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Sylwester Lachiewicz <[email protected]>
@Xuanwo

Xuanwo commented Oct 28, 2026

Copy link
Copy Markdown
Member

merged in #10397.

Thank you @timsaucer, @slachiewicz and @wjones127!

@Xuanwo Xuanwo closed this Oct 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-deps Dependency updates A-encoding Encoding, IO, file reader/writer A-index Vector index, linalg, tokenizer A-java Java bindings + JNI A-python Python bindings chore

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feature: upgrade to Arrow 59 and DataFusion 55

5 participants