Skip to content

fix: keep field metadata when CASE WHEN false simplifies to NULL - #26951

Closed
james-willis wants to merge 1 commit into
apache:mainfrom
james-willis:case-false-fold-metadata
Closed

james-willis wants to merge 1 commit into
apache:mainfrom
james-willis:case-false-fold-metadata

Conversation

@james-willis

@james-willis james-willis commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Depends on #26145. This PR makes the simplifier copy the CASE's field metadata onto the NULL it folds to. On main, a CASE's field has no metadata yet (#26145 fixes that), so this change has no effect there, and the new tests fail until #26145 merges. They pass with this commit applied on top of #26145.

Rationale for this change

CASE WHEN false THEN x END (including forms that constant-fold to false, such as WHEN 1 = 0) loses the Arrow extension type of x. Planning sees the CASE's field, but the simplifier then replaces the CASE with a bare NULL literal without metadata, so a function that checks its argument's extension type sees a different type after optimization than during planning.

With #26145 and #26158 applied, this is the only remaining place where the following query loses the extension type:

select arrow_metadata(
  case when 1 = 0 then with_metadata(name, 'ARROW:extension:name', 'a.type') end,
  'ARROW:extension:name')
from table_with_metadata;
-- a.type with this PR + #26145; NULL without this PR

EXPLAIN shows the CASE has already become Utf8(NULL) before physical planning, so the physical CASE fix in #26158 does not reach it.

What changes are included in this PR?

  • CASE WHEN false THEN A END --> NULL (every WHEN is false and there is no ELSE) now builds the NULL from the CASE's own field: its type and its metadata. The merge policy stays in Expr::Case's to_field (fix: preserve CASE result field metadata #26145); the simplifier does not compute it separately.
  • The other folds in the same rule are unchanged. CASE WHEN false THEN A ELSE B END --> B and CASE WHEN true THEN A ... END --> A already return the surviving branch, which carries its own metadata.

What is the testing strategy for this PR?

  • metadata.slt: the query above, checking the extension type at execution after the fold.
  • expr_simplifier.rs: simplify_expr_case_when_false_keeps_field_metadata, checking the folded literal carries the metadata of the column it replaced.
  • The existing CASE simplifier tests still pass.
  • Run locally: on main, only the two new tests fail (the literal has no metadata). With this commit on top of fix: preserve CASE result field metadata #26145, all datafusion-optimizer lib tests and metadata.slt pass.

Are there any user-facing changes?

A CASE that is folded to NULL keeps its field metadata.

@github-actions github-actions Bot added optimizer Optimizer rules sqllogictest SQL Logic Tests (.slt) labels Oct 30, 2026
@james-willis james-willis changed the title fix: keep field metadata when CASE WHEN false simplifies to NULL fix: keep field metadata when CASE WHEN false simplifies to NULL [WIP] Nov 5, 2026
@james-willis
james-willis force-pushed the case-false-fold-metadata branch from 72c47ae to 528b7fa Compare November 5, 2026 19:44
@james-willis james-willis changed the title fix: keep field metadata when CASE WHEN false simplifies to NULL [WIP] fix: keep field metadata when CASE WHEN false simplifies to NULL Nov 5, 2026
@james-willis
james-willis marked this pull request as ready for review November 5, 2026 19:52
@james-willis

Copy link
Copy Markdown
Contributor Author

@paleolimbot this winds up being its own case to handle

@paleolimbot

Copy link
Copy Markdown
Member

Would it make sense to fold this in to #1566? It may make it easier to see how the two relate and the other PR is quite small.

@james-willis

Copy link
Copy Markdown
Contributor Author

Would it make sense to fold this in to #1566?

Sure sounds good. I raised this before I was going to raise that originally.

bvolpato pushed a commit to bvolpato/datafusion that referenced this pull request Nov 21, 2026
## Which issue does this PR close?

- Closes apache#24860.

This is a smaller alternative to apache#26145 + apache#26158, following the
suggestion on apache#24865 to look for a simpler way to reach the same goal.
It also includes the simplifier fix from apache#26951, which depends on the
CASE fix here.

## Rationale for this change

`CASE` drops the field metadata of its branches, so Arrow extension
types are lost. That breaks functions that check the extension type of
their argument when the argument is a `CASE`, or a `COALESCE`, `NVL`,
`IFNULL` or `NVL2`, since those are rewritten to `CASE` before
execution. Examples are `variant_get` over a Parquet Variant column,
reported on apache#26145, and geometry and raster functions in SedonaDB.

The metadata is dropped in the logical `Expr::Case` field, in the
physical `CaseExpr`, which has no `return_field` override, and in
simplifier rewrites that drop the branch carrying it.

## What changes are included in this PR?

- **Logical `Expr::Case::to_field`** merges the fields of its THEN and
ELSE branches with `coerced_fields_metadata`, the helper
`COALESCE`/`NVL2` use since apache#24865. It takes the type and nullability
from the same fields, so it reads each branch once. The type rule from
apache#27139 moves into a helper that `get_type` also uses.
- **Physical `CaseExpr::return_field`** does the same with its branches'
`return_field`.
- **A typed NULL ELSE that carries metadata** is no longer dropped by
`CaseExpr::try_new`. It is still evaluated like no ELSE.
- **CASE simplifications keep the metadata.** A literal left by a
constant WHEN, such as the NULL from `CASE WHEN false THEN x END`, takes
the CASE's metadata. A CASE is not simplified when that would change its
metadata, and a Boolean CASE with metadata on a branch is not rewritten
to AND/OR.

So CASE follows the same rules as `COALESCE`: the earlier branch wins
for each key, an extension name is kept together with its parameters,
differing extension names are a planning error, and a branch without
metadata or an untyped `NULL` does not block another branch's metadata.
The operand of a simple `CASE` and the WHEN conditions do not
contribute.

<details>
<summary>Differences from apache#26145 + apache#26158</summary>

About 290 lines of non-test code, against about 700 there. That includes
the simplifier changes and about 70 lines that move the existing CASE
type and nullability logic into helpers.

- **No stored copy of the logical field, and no protobuf change.** The
physical CASE derives its field from its physical branches, so it
matches the logical field whenever each branch's field does. A unit test
checks that for column, literal, cast and nested CASE branches. apache#26158
instead carries the logical field into the physical CASE.
- **A branch whose logical and physical fields differ therefore shows
through the CASE.** Physical `NOT` passes its input's metadata through
while logical `NOT` drops it (apache#27155), and an alias's metadata can be
lost when the physical expression is created (apache#27156). With `NOT`, this
can be a planning error that `main` doesn't raise, when the other branch
has a different extension name. Those mismatches are in `NOT` and
`Alias` and are not addressed here.

</details>

<details>
<summary>Performance</summary>

Local runs on a laptop against `main`, so treat them as indicative:
Criterion runs of the benchmarks from apache#26145/apache#26158, and `EXPLAIN`
timings with a debug build of `datafusion-cli` for planning.

- **CASE evaluation and physical planning** are unchanged.
- **`return_field` rebuilds the merged metadata on every call:** 954 ns
vs 274 ns for a column CASE with 4 metadata keys. A function asks its
CASE argument for its field once per batch; field plus evaluation for
8,192 rows took 13.6 µs vs 13.1 µs.
- **Logical `to_field`** for a wide CASE without any metadata took 2–3x
as long.

Both were measured before the nesting changes below, which only remove
work.
- **Nested CASE.** `to_field`, `return_field` and the constant-WHEN
simplification visit each branch once. I timed 18 nesting shapes up to
22 levels: the CASE in the THEN, the ELSE or a WHEN; nested directly, in
a function call, in `||` or under a cast; with a nullable or
non-nullable other branch; a simple CASE; and COALESCE nested in either
argument. The plans are the same as on `main`.
  - 10 take the same time as on `main`.
- 7 are exponential on `main` and linear here. With the CASE in a
function call, 6 shapes take 16–22 s on `main` at 18 levels and 0.05 s
here. With a cast between levels (found by @jayzhan211), `main` takes
13.2 s at 16 levels and this PR 0.06 s.
- COALESCE nested in its first argument is exponential on both, because
the simplifier rewrites it to a CASE that repeats that argument: 4.05 s
vs 3.82 s at 18 levels.

Fast paths can come later: reuse the metadata when only one branch has
any, and return early when none has.

</details>

## What is the testing strategy for this PR?

- **New `metadata.slt` cases** check the metadata at execution with
`arrow_metadata`, mostly with the built-in `JSON` extension type. They
cover precedence, simple CASE, conflicting extension names, a branch
without metadata, no ELSE, an untyped and a typed NULL ELSE, coercion to
a common type, nested CASE, the CASE rewrites of `coalesce`, `nvl`,
`ifnull` and `nvl2`, constant-WHEN simplification, and a Boolean CASE.
Each check fails without this change. Each query uses a given CASE only
once, because a repeated expression is computed in a lower projection
whose field comes from the logical plan.
- **Unit tests** check that the physical CASE field matches the logical
one in metadata, type and nullability, and cover the CASE
simplifications. That includes the rewrite of a Boolean CASE to
`NOT(CASE ...)`, which SQL can't observe because physical `NOT` passes
the metadata through (apache#27155).
- **Existing tests:** the `datafusion-expr`, `datafusion-physical-expr`
and `datafusion-optimizer` lib tests pass. The full sqllogictest suite
and the `core_integration` `sql` tests show no new failures; my checkout
doesn't have the test-data submodules, so the files that need that data
fail the same way on `main`.
- **The `metadata.slt` from apache#26158**, which includes the cases from
apache#26895, also passes with this change, checked locally with the current
head of apache#26158.

## Are there any user-facing changes?

- `CASE` results keep their field metadata, including extension types,
also when the optimizer simplifies the CASE. So do `COALESCE`, `NVL`,
`IFNULL` and `NVL2` at execution.
- `CASE` branches with differing extension names are now a planning
error, as they already are for `COALESCE`.

No public API changes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

optimizer Optimizer rules sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants