Skip to content

fix(optimizer): take UNION extension metadata only from inputs that are not cast - #27788

Open
cyberbeam524 wants to merge 10 commits into
apache:mainfrom
cyberbeam524:fix/union-extension-types
Open

cyberbeam524 wants to merge 10 commits into
apache:mainfrom
cyberbeam524:fix/union-extension-types

Conversation

@cyberbeam524

@cyberbeam524 cyberbeam524 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

Currently, running a UNION between an extension-typed column and an input with a different storage type (such as UUID UNION a bare Binary literal X'...', or arrow.json with metadata {} on Utf8 UNION arrow.json on Utf8View) fails with an internal error.

This happens because type coercion casts any input whose storage type differs from the coerced type—which drops its ARROW:extension:* metadata in the physical union—while the logical UNION schema still kept extension metadata merged from all inputs. Aligning the logical schema with the physical union fixes the internal error without introducing new planning errors or breaking existing 56.0.0 queries (such as count(*) or INSERT over UNION ALL).

Per-query results: 56.0.0 vs. after
Query 56.0.0 After
count(*) over UUID UNION ALL X'..' 2 2
INSERT INTO <UUID or BYTEA table> from UUID UNION ALL X'..' rows stored rows stored
UUID UNION X'..' internal error rows, Binary
UUID UNION ALL BY NAME X'..'; Dictionary(Int32, FixedSizeBinary(16)) input; arrow.json + plain LargeUtf8 rows rows
count(*) over arrow.json UNION ALL arrow.opaque 2 2
arrow.json with metadata {} on Utf8 UNION arrow.json on Utf8View internal error rows
all-NULL inputs with an extension, UNION rows rows

What changes are included in this PR?

  • Updated coerce_union_schema_with_schema in datafusion/optimizer/src/analyzer/type_coercion.rs to take ARROW:extension:name and ARROW:extension:metadata only from inputs already stored as the coerced DataType (using last-input-wins semantics to match the physical union).
  • Added arrow-schema = { workspace = true } to datafusion/optimizer/Cargo.toml for the extension metadata key constants.
  • Added a unit test in type_coercion.rs (coerce_union_schema_extension_type).
  • Added end-to-end SQLLogicTests in datafusion/sqllogictest/test_files/sql_extension_types.slt covering UNION / UNION ALL with UUID + Binary literals, last-wins extension metadata, cast inputs, and all-NULL extension inputs. (Note: the tests use CREATE TABLE + INSERT because CREATE TABLE ... AS with explicit column definitions currently drops extension metadata. Filed a separate issue for that at CREATE TABLE ... AS (CTAS) with explicit column definitions drops Arrow extension type metadata #27791)

What is the testing strategy for this PR?

Unit tests in datafusion-optimizer (coerce_union_schema_extension_type) and SQLLogicTests (including sql_extension_types.slt) pass locally.

Are there any user-facing changes?

UNION between an extension-typed column and an input with a different storage type no longer fails with an internal error; it now returns the coerced storage type (matching UNION ALL and 56.0.0 behavior) until #27383 adds extension-aware common-type coercion.

@cyberbeam524
cyberbeam524 marked this pull request as draft November 27, 2026 08:20
@github-actions github-actions Bot added optimizer Optimizer rules sqllogictest SQL Logic Tests (.slt) labels Nov 27, 2026
@cyberbeam524
cyberbeam524 marked this pull request as ready for review November 27, 2026 09:26
@cyberbeam524

Copy link
Copy Markdown
Contributor Author

Thanks again @adriangb @paleolimbot @tschwarzinger @sdf-jkl for your help getting #21714 landed! This is a followup to a bug found on that issue. This PR addresses UNION/UNION ALL behavior for extension-typed columns when inputs are not extension-compatible.

Regression coverage added:

  • UUID vs bare Binary literal -> planning error (UNION and UNION ALL)
  • Same extension name but different storage type -> planning error
  • Same extension name+storage but different payload -> planning error
  • NULL branch with UUID -> remains compatible and preserves extension metadata

Would appreciate your view on this to make sure this is what you had in mind!

@tschwarzinger tschwarzinger 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 looks already good to me, thanks!

I think the current semantics are also a good choice for now and the SLT tests document that well. The only thing I'd like to change is the use of the arrow.uuid metadata and maybe looking for an existing implementation of the compatibility check.

Before approving, someone more familiar with the casting ecosystem should take a look at it.

let right_plan = Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
produce_one_row: false,
schema: Arc::new(DFSchema::from_unqualified_fields(
vec![Field::new("id", DataType::Binary, false)].into(),

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.

Maybe we can use FixedSizeBinary(16) here to make sure that the extension type is the cause of the error.

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.

But I think the slt tests cover everything fine, so this is just a remark.

'ARROW:extension:name',
'arrow.uuid'
),
'ARROW:extension:metadata',

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 guess it could be that this might be rejected in the future because arrow.uuid has no specified extension type metadata. I think if with_metadata will check whether the actual extension name and metadata are compatible, this could become an error. Maybe the spec also leaves this open for implementations, at least now we're not checking the metadata in Uuid::try_new.

Maybe we can use a different type here? Detecting different layouts of an arrow.fixed_shape_tensor could be a nice use case. For example, the tensor { "shape": [2, 5] } should not be merged with the tensor { "shape": [5, 2] }.

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.

Updated! Switched the metadata test to arrow.fixed_shape_tensor ([2, 5] vs [5, 2])

if matches!(other.data_type(), DataType::Null) {
continue;
}
if other.extension_type_name() != ext_name

@tschwarzinger tschwarzinger Nov 27, 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.

Do we have somewhere a helper function to check whether two fields with extension types are "equivalent". Starting now with extracting this check into a single place might make it easier in the future to make this behavior more lenient (e.g., #26810).

Even if we stay strict with the comparison, it would be good to have that in a single place. Could also be a follow-up if it does not yet exist where we search for existing usages in the code.

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.

Checked check_metadata_with_storage_equal, which compares the entire metadata map (which is very strict) rather than just ARROW:extension:*, so keeping a dedicated extension helper avoids breaking non-extension metadata merging in UNION. Extracted extension_types_equal into a helper function.

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

While I think this is in general a good idea, I am hesitant to special case/add one off validation rules because if they're wrong, planning the query fails. Downstream engines can enforce stricter rules with analyzer/optimizer rules and insert casts, but this doesn't work if validation fails.

A true solution here is a registry of

  • Functions that takes two types (e.g., Binary, and UUID) and returns the type to which they should be cast (UUID)
  • Functions that override the cast behaviour between two arbitrary types (#27383)

This has been used for 6ish years in R to implement dplyr::bind_rows() in a generic/extensible way (vec_ptype2() and vec_cast() are the two generics).

I'm happy to implement this but we need the CastExtension first.

@cyberbeam524

Copy link
Copy Markdown
Contributor Author

Thank you for taking a look @paleolimbot @tschwarzinger! @tschwarzinger Addressed the comments you raised. @paleolimbot Makes sense, I looked through #27383 and agree that CastExtension + a vec_ptype2-style common-type registry is the right long-term design so downstream engines aren't blocked from intercepting UNION with their own rules.

Since #27383 and the common-type registry are still in progress, would you prefer we close this PR and wait for that work to resolve #26915, or merge this as an interim guard against the UNION internal error? Once #27383's registry prototype lands on main, I'd also be happy to help with the UNION or canonical UUID/JSON follow-up.

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

@cyberbeam524 thanks for working on this! On your question to @paleolimbot: an interim error looks fine to me if it covers only shapes that fail today, so that downstream rules lose nothing that works in 56.0.0. As written, it also rejects 5 shapes that run correctly in 56.0.0. The inline comments have the per-query results and a narrower check that I tested locally.

.map(|plan| plan.schema().field(i).as_ref())
.collect();

// Validate extension type compatibility across non-Null inputs.

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.

@cyberbeam524 thanks for picking this up! This check also rejects 5 UNION shapes that run correctly in 56.0.0, for example UUID with a plain FixedSizeBinary(16) column, or extension metadata that differs only in its bytes (#26810, the GeoArrow CRS case). Every broken shape coerces to a storage type that no input carried the extension on (FixedSizeBinary(16)<arrow.uuid> + Binary → Binary), so the error can be limited to that. The diff below does this. For differing names it reuses coerced_fields_metadata (the existing helper @tschwarzinger asked about), so UNION follows the same rule as CASE and COALESCE.

Per-query results: 56.0.0, this PR, and the diff below
Query (UNION ALL unless noted) 56.0.0 this PR diff below
UUID + plain FixedSizeBinary(16) (also UNION, and a table column) rows, arrow.uuid kept error rows, arrow.uuid kept
arrow.json on Utf8 + arrow.json on Utf8View rows, kept error rows, kept
arrow.json with metadata {} + { } rows, kept error rows, kept
UUID + X'..' (UNION) internal error error error
UUID + X'..'; UUID + NULL + X'..' arrow.uuid dropped error error
arrow.json on Utf8 + plain Utf8View arrow.json dropped error error
arrow.json + arrow.opaque relabeled arrow.opaque error error
tensor {"shape":[2,5]} + {"shape":[5,2]} last shape wins error last shape wins
-use datafusion_common::metadata::merge_metadata_for_union;
+use datafusion_common::metadata::{coerced_fields_metadata, merge_metadata_for_union};
@@
-/// Returns `true` if two fields have the same extension type (name, metadata,
-/// and underlying storage type).
-fn extension_types_equal(left: &Field, right: &Field) -> bool {
-    left.extension_type_name() == right.extension_type_name()
-        && left.extension_type_metadata() == right.extension_type_metadata()
-        && left.data_type() == right.data_type()
+/// Rejects UNION inputs whose extension type cannot be kept on the coerced
+/// storage type `coerced`.
+///
+/// TODO(#27383): replace with an extension-aware common type rule.
+fn check_union_extension_type(
+    name: &str,
+    fields: &[&Field],
+    coerced: &DataType,
+) -> Result<()> {
+    // Same rule as CASE and COALESCE: differing extension names are an error,
+    // differing extension metadata bytes are not (#26810).
+    coerced_fields_metadata(fields.iter().copied())?;
+    // NULL inputs are skipped, as in `coerced_fields_metadata`.
+    let Some(extension) = fields
+        .iter()
+        .filter(|f| !f.data_type().is_null())
+        .find_map(|f| f.extension_type_name())
+    else {
+        return Ok(());
+    };
+    // The merged metadata is only valid on a storage type that an input
+    // already carried this extension type on.
+    let keeps_storage = fields
+        .iter()
+        .any(|f| f.extension_type_name() == Some(extension) && f.data_type() == coerced);
+    if !keeps_storage {
+        return plan_err!(
+            "UNION types cannot be unified for column '{name}': extension type \
+            '{extension}' cannot be stored as {coerced}"
+        );
+    }
+    Ok(())
 }
@@ fn coerce_union_schema_with_schema(
-            // Validate extension type compatibility across non-Null inputs.
-            // ... (the whole `if let Some(ext_field) = ...` block)
-            let datatype = coerce_union_type(input_fields)?;
+            let datatype = coerce_union_type(input_fields.iter().copied())?;
+            check_union_extension_type(field.name(), &input_fields, &datatype)?;
@@ fn test_coerce_union_incompatible_extension_type
-                vec![Field::new("id", DataType::FixedSizeBinary(16), false)].into(),
+                vec![Field::new("id", DataType::Binary, false)].into(),

With this applied, cargo test -p datafusion-optimizer and sql_extension_types.slt (with the test change suggested on the .slt file) pass, and clippy is clean.

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.

Thanks @jayzhan211 for the thorough analysis and diff!

I've applied the narrower check_union_extension_type check suggestion using coerced_fields_metadata (that reuses the same rule as CASE and COALESCE), removed the previous extension_types_equal and updated both the unit test and sql_extension_types.slt so all 56.0.0 working shapes stay intact. Local datafusion-optimizer tests, sql_extension_types.slt, and clippy are all passing.

Ready for another look!

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

@cyberbeam524 thanks for the quick update! I have to correct my last review: the errors I suggested also reject queries that return correct rows in 56.0.0, like count(*) or an INSERT from a UUID UNION ALL X'..'. The inline comments have a version with no error that fixes the UNION internal error by making the logical schema match the physical union, with per-query results against 56.0.0.

/// storage type `coerced`.
///
/// TODO(#27383): replace with an extension-aware common type rule.
fn check_union_extension_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.

@cyberbeam524 thanks for applying the change, and sorry: I missed this in my last review. Both errors in this check reject queries that return correct rows in 56.0.0. For example, SELECT count(*) FROM (SELECT id FROM t UNION ALL SELECT X'0001') returns 2 there, and INSERT INTO t SELECT id FROM t UNION ALL SELECT X'..' stores the right rows; this PR errors on both. The internal error comes from the logical UNION schema keeping extension keys that the physical union doesn't have, because coercion casts every input whose type differs and the cast drops them. Taking those keys only from inputs already stored as the coerced type fixes it with no new error. The diff below does that, and the two .slt suggestions update the tests. Since UNION ALL still returns Binary until #27383 can coerce the literal to UUID, could the description say Part of #26915 instead of Closes?

Per-query results: 56.0.0, this PR, and the diff below
Query 56.0.0 this PR diff below
count(*) over UUID UNION ALL X'..' 2 error 2
INSERT INTO <UUID or BYTEA table> from UUID UNION ALL X'..' rows stored error rows stored
UUID UNION X'..' internal error error rows, Binary
UUID UNION ALL BY NAME X'..'; Dictionary(Int32, FixedSizeBinary(16)) input; arrow.json + plain LargeUtf8 rows error rows
count(*) over arrow.json UNION ALL arrow.opaque 2 error 2
arrow.json with metadata {} on Utf8 UNION arrow.json on Utf8View internal error internal error rows
all-NULL inputs with an extension, UNION rows rows rows

With the diff, the full sqllogictest suite (309 files) and cargo test -p datafusion-optimizer pass, and clippy and cargo doc are clean.

Diff (also adds `arrow-schema = { workspace = true }` to datafusion/optimizer/Cargo.toml)
+use arrow_schema::extension::{EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY};
-use datafusion_common::metadata::{coerced_fields_metadata, merge_metadata_for_union};
+use datafusion_common::metadata::merge_metadata_for_union;
@@
-/// Rejects UNION inputs whose extension type cannot be kept on the coerced
-/// ... (remove `check_union_extension_type` entirely)
@@ pub fn coerce_union_schema
 /// - **Metadata**: Later inputs take precedence for same keys (HashMap::extend semantics)
+/// - **Extension type**: Taken only from inputs already stored as the coerced type,
+///   since coercion casts the others and a cast drops the extension type
@@ fn coerce_union_schema_with_schema(
             let datatype = coerce_union_type(input_fields.iter().copied())?;
-            check_union_extension_type(field.name(), &input_fields, &datatype)?;
             let nullable = field.is_nullable()
                 || inputs
                     .iter()
                     .any(|plan| plan.schema().field(i).is_nullable());
-            let mut field = Field::new(field.name().clone(), datatype, nullable);
-            field.set_metadata(merge_metadata_for_union(
+            let mut metadata = merge_metadata_for_union(
                 all_schemas.iter().map(|schema| schema.field(i).metadata()),
-            ));
+            );
+            // Coercion casts each input not stored as `datatype`, and the cast
+            // drops its extension type, so only the other inputs can supply it.
+            // Anything else differs from the physical union's schema (#26915).
+            for key in [EXTENSION_TYPE_NAME_KEY, EXTENSION_TYPE_METADATA_KEY] {
+                metadata.remove(key);
+                if let Some(value) = input_fields
+                    .iter()
+                    .rev()
+                    .filter(|f| f.data_type() == &datatype)
+                    .find_map(|f| f.metadata().get(key))
+                {
+                    metadata.insert(key, value.clone());
+                }
+            }
+            let mut field = Field::new(field.name().clone(), datatype, nullable);
+            field.set_metadata(metadata);

The test below replaces test_coerce_union_incompatible_extension_type. It checks the NULL-input filter, which the .slt tests can't see because optimizer rules recompute the UNION schema after type coercion:

#[test]
fn coerce_union_schema_extension_type() -> Result<()> {
    use super::coerce_union_schema;
    use arrow_schema::extension::EXTENSION_TYPE_NAME_KEY;
    let input = |data_type: DataType, extension: Option<&str>| {
        let mut field = Field::new("c", data_type, true);
        if let Some(extension) = extension {
            field = field.with_metadata(std::collections::HashMap::from([(
                EXTENSION_TYPE_NAME_KEY.to_string(),
                extension.to_string(),
            )]));
        }
        DFSchema::from_unqualified_fields(
            vec![field].into(),
            std::collections::HashMap::new(),
        )
        .map(|schema| {
            Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
                produce_one_row: false,
                schema: Arc::new(schema),
            }))
        })
    };

    // No input stores arrow.uuid as Binary, so the result drops it
    let schema = coerce_union_schema(&[
        input(DataType::FixedSizeBinary(16), Some("arrow.uuid"))?,
        input(DataType::Binary, None)?,
    ])?;
    assert_eq!(schema.field(0).data_type(), &DataType::Binary);
    assert_eq!(schema.field(0).extension_type_name(), None);

    // A NULL input's extension type does not decide the result
    let schema = coerce_union_schema(&[
        input(DataType::Null, Some("arrow.opaque"))?,
        input(Utf8, Some("arrow.json"))?,
    ])?;
    assert_eq!(schema.field(0).extension_type_name(), Some("arrow.json"));
    Ok(())
}

@cyberbeam524 cyberbeam524 Nov 30, 2026 •

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.

@jayzhan211 Good catch on the count(*) and INSERT regressions in 56.0.0, aligning the logical schema with the physical union instead of erroring is much cleaner. I've applied the diff (including arrow-schema in Cargo.toml & Cargo.lock), updated the tests, and changed the PR description. Local datafusion-optimizer tests, sql_extension_types.slt, clippy, and cargo doc are all passing. Ready for another look!

arrow.uuid

statement ok
DROP TABLE t; No newline at end of file

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.

Optional cleanup: the file is missing its trailing newline.

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.

Added the trailing newline!

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

I think this works for all of us: your ptype2 here is extension + anything else -> anything else, which is sufficiently lax that a downstream engine's rules can be stricter.

You may want to retitle this PR, since we are no longer rejecting anything here as far as I can tell, but stripping metadata when extension types don't agree to prevent potentially invalid extension types that may be rejected by extension aware consumers (feel free to correct my understanding here).

Comment on lines +2067 to +2072
// A NULL input's extension type does not decide the result
let schema = coerce_union_schema(&[
input(DataType::Null, Some("arrow.opaque"))?,
input(Utf8, Some("arrow.json"))?,
])?;
assert_eq!(schema.field(0).extension_type_name(), Some("arrow.json"));

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.

Can we remove this portion of the test?

I am not sure this is behaviour we actually want, although it's definitely fine to live with if the rest of the approach works (a null valued extension type has probably never happened in the real world).

I mostly just don't want a future PR that improves handling of extension types to run into this and add complexity trying to keep this test passing.

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.

+1 to removing it. One thing to keep: this block is the only unit assertion that fails when the extension key isn't put back, so the UUID + UUID case you asked for should take its place. This version passes on this head and fails with that line removed:

        // Inputs already stored as the coerced type keep their extension type
        let schema = coerce_union_schema(&[
            input(DataType::FixedSizeBinary(16), Some("arrow.uuid"))?,
            input(DataType::FixedSizeBinary(16), Some("arrow.uuid"))?,
        ])?;
        assert_eq!(schema.field(0).extension_type_name(), Some("arrow.uuid"));

Comment on lines +2059 to +2065
// No input stores arrow.uuid as Binary, so the result drops it
let schema = coerce_union_schema(&[
input(DataType::FixedSizeBinary(16), Some("arrow.uuid"))?,
input(DataType::Binary, None)?,
])?;
assert_eq!(schema.field(0).data_type(), &DataType::Binary);
assert_eq!(schema.field(0).extension_type_name(), None);

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.

Can we also add a test here that UUID + UUID -> UUID?

Comment on lines +307 to +315
# A NULL input's metadata does not pick the extension type
query T
SELECT arrow_metadata(j, 'ARROW:extension:name') FROM (
SELECT with_metadata(NULL, 'ARROW:extension:name', 'arrow.opaque') AS j
UNION ALL
SELECT with_metadata('x', 'ARROW:extension:name', 'arrow.json')
) WHERE j IS NOT NULL;
----
arrow.json

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.

Again, perhaps just remove this since it's a fine side-effect but not behaviour I personally would like to lock in

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.

+1. Removing it loses no coverage: it still passes with each of the four conditions in the new loop removed (the clearing, .rev(), the type filter, and the re-insert), and other tests in this file catch all four.

Comment on lines +327 to +333
# UNION between two UUID columns works and preserves arrow.uuid
query T
SELECT arrow_metadata(id, 'ARROW:extension:name') FROM (
SELECT id FROM t
UNION
SELECT CAST(arrow_cast(X'00010203040506070809000102030507', 'FixedSizeBinary(16)') AS UUID)
);

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.

🎉

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

@cyberbeam524 thanks for the update! I ran 25 UNION shapes (aggregate, window, join, filter, INSERT, UNION BY NAME, dictionary, nested unions) on this head and on the merge-base: 16 that hit the internal error on the merge-base now return rows, the rest are unchanged, and the full sqllogictest suite passes. Two optional cleanups before merge:

  • The title is the squashed commit message and still says "reject", as @paleolimbot noted. Something like fix(optimizer): take UNION extension metadata only from inputs that are not cast describes what merges.
  • In type_coercion.rs around lines 1664 and 1693, the rustdoc of the public coerce_union_schema still says later inputs win for every metadata key, so a caller reading it would expect arrow.uuid to survive a UUID + Binary union:
-/// **Field-level metadata merging**: Later fields take precedence for duplicate metadata keys.
+/// **Field-level metadata merging**: Later fields take precedence for duplicate metadata keys,
+/// except the extension type keys (`ARROW:extension:name` and `ARROW:extension:metadata`):
+/// those come only from inputs whose type already equals the coerced type, because
+/// coercion casts the other inputs and the cast drops their extension type.
-/// - **Metadata**: Later inputs take precedence for same keys (HashMap::extend semantics)
+/// - **Metadata**: Later inputs take precedence for same keys (HashMap::extend semantics),
+///   except extension type keys, which come only from inputs already of the coerced type

@cyberbeam524
cyberbeam524 force-pushed the fix/union-extension-types branch from fc18a3d to c1c9c89 Compare December 3, 2026 08:27
@cyberbeam524 cyberbeam524 changed the title fix(optimizer): reject incompatible extension types in UNION coercion fix(optimizer): take UNION extension metadata only from inputs that are not cast Dec 3, 2026
@cyberbeam524
cyberbeam524 force-pushed the fix/union-extension-types branch 2 times, most recently from c340bdd to c1c9c89 Compare December 3, 2026 10:48
@cyberbeam524

Copy link
Copy Markdown
Contributor Author

Thanks @paleolimbot @jayzhan211! I've retitled the PR, switched the NULL extension unit test for the UUID + UUID case, removed the NULL extension .slt test, and updated the coerce_union_schema docs. Ready to merge once CI is green!

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.

4 participants