Skip to content

fix: infer UNION output types before analysis - #27139

Merged
alamb merged 2 commits into
apache:mainfrom
kumarUjjawal:kumarUjjawal/datafusion-27023-fix
Nov 6, 2026
Merged

alamb merged 2 commits into
apache:mainfrom
kumarUjjawal:kumarUjjawal/datafusion-27023-fix

Conversation

@kumarUjjawal

@kumarUjjawal kumarUjjawal commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

DataFrame::schema() previously reported the first UNION input's type while execution used the common type. UNION construction now infers the common output type.

What changes are included in this PR?

  • Infer UNION and CASE result types before analysis, with cast insertion deferred to the analyzer.
  • Derive final UNION types from actual inputs with the shared coerce_union_type helper.
  • A branch-56 backport remains a maintainer decision because public inference behavior and one executed Arrow type change.

Synthetic nested CASE planning (ci-bench, SQL through physical planning):

Depth Main (µs) Patch (µs) Extra (µs)
8 101.2 105.5 +4.3
32 270.1 317.6 +47.5
64 502.8 684.0 +181.2

These three points suggest roughly quadratic extra work. Extrapolating that trend to depth 1,000 gives about 45 ms of extra planning. The benchmark did not measure depth 1,000.

What is the testing strategy for this PR?

Focused core and expression tests (316), 64 doctests, five SLT files, all-features Clippy, Rustdoc, and formatting pass.

Are there any user-facing changes?

In this query, x changes from Dictionary(Int32, Utf8) to Utf8; decoded values remain unchanged. Rustdoc describes UNION and CASE schema inference.

SELECT 1 AS y
UNION ALL BY NAME
SELECT arrow_cast('a', 'Dictionary(Int32, Utf8)') AS x;

@kumarUjjawal kumarUjjawal added api change Changes the API exposed to users of the crate bug Something isn't working labels Nov 5, 2026
@kumarUjjawal
kumarUjjawal requested a review from alamb November 5, 2026 17:14
@sdf-jkl

sdf-jkl commented Nov 5, 2026

Copy link
Copy Markdown
Member

I was just about to post a fix too 😭

@sdf-jkl

sdf-jkl commented Nov 5, 2026

Copy link
Copy Markdown
Member

Should've taken the issue yesterday

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

This is definitely a patch, but I think it is ok for now.

It seems like to fix this for real, we should do what @findepi told us (namely build correct Union plans in the first place)

/// alone is not enough here -- it reflects the raw, pre-`Analyzer` plan (see
/// `SessionState::create_logical_plan`), which for a `UNION` still has the
/// first leg's un-coerced type.
/// This test checks the schema after the Analyzer and Optimizer run,

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.

thank you for trimming the AI verbosity

in this section pertains to features and changes that have already been merged
to the main branch and are awaiting release in this version.

### UNION and CASE infer common output types before analysis

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 is a bug fix. Why does it need a upgrade guide entry?

`datafusion_expr::type_coercion::other::coerce_union_type` is a new helper
that infers one UNION column type from input fields.

For `UNION BY NAME`, missing columns participate as `NULL` during 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.

If we want to document the behavior of how schema resolution works, it should be in the code documentation I think

Comment thread datafusion/expr/src/expr_schema.rs Outdated
.transpose()?;
// If the branches have no common type, keep the old provisional
// type. The analyzer reports the error.
Ok(

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.

we could probably make this more concse / less indented with some intermediate variables

pub fn coerce_union_schema(inputs: &[Arc<LogicalPlan>]) -> Result<DFSchema> {
coerce_union_schema_with_schema(&inputs[1..], inputs[0].schema())
let Some(first) = inputs.first() else {
return plan_err!("UNION requires at least one input");

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 is a nice cleanup

}

#[tokio::test]
async fn union_coercion_preserves_values() -> Result<()> {

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 feel like most of these tests can be written as .slt tests (but better). I recommend leaving some tests here that cover the expected schema case but don't run the query -- instead run the queries as a .slt tests

@alamb

alamb commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Thank you for running with this @kumarUjjawal

sdf-jkl added a commit to sdf-jkl/datafusion that referenced this pull request Nov 5, 2026
Incorporate deferred CASE/UNION coercion errors, dictionary coercion from
actual inputs, and an empty-input guard, informed by:
apache#27139

Keep regression coverage in SQL and document the dictionary output-type
change for UNION BY NAME.
@alamb
alamb added this pull request to the merge queue Nov 6, 2026
@alamb

alamb commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

Thank you @kumarUjjawal

Merged via the queue into apache:main with commit 13bd9d1 Nov 6, 2026
44 of 45 checks passed
mbutrovich pushed a commit that referenced this pull request Nov 6, 2026
…27139) (#27178)

## Which issue does this PR close?

- Backport of #27139 to
`branch-56`
- Part of #24461
- Closes #27023

Co-authored-by: Kumar Ujjawal <ujjawalpathak6@gmail.com>
james-willis added a commit to james-willis/datafusion that referenced this pull request Nov 17, 2026
Since apache#27139, get_type gives a CASE the common type of its THEN and ELSE
types. to_field took the first non-NULL branch type, so a CASE field could
have a different type than get_type before analysis. Both now share
case_result_type, and to_field computes it from the branch fields it already
has.
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

api change Changes the API exposed to users of the crate bug Something isn't working v57.0.0

Projects

None yet

Development

Successfully merging this pull request may close these issues.

REGRESSION: UNION: DataFrame::schema() reports the first input's type, but execution returns the coerced type

3 participants