Repository navigation
fix: infer UNION output types before analysis - #27139
Conversation
|
I was just about to post a fix too 😭 |
|
Should've taken the issue yesterday |
| /// 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, |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
If we want to document the behavior of how schema resolution works, it should be in the code documentation I think
| .transpose()?; | ||
| // If the branches have no common type, keep the old provisional | ||
| // type. The analyzer reports the error. | ||
| Ok( |
There was a problem hiding this comment.
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"); |
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn union_coercion_preserves_values() -> Result<()> { |
There was a problem hiding this comment.
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
|
Thank you for running with this @kumarUjjawal |
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.
|
Thank you @kumarUjjawal |
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.
## 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.
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?
coerce_union_typehelper.Synthetic nested CASE planning (
ci-bench, SQL through physical planning):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,
xchanges fromDictionary(Int32, Utf8)toUtf8; decoded values remain unchanged. Rustdoc describes UNION and CASE schema inference.