From ecbe02fcede17ea7c5d2c60922078e58746052f8 Mon Sep 17 00:00:00 2001 From: cyberbeam524 <122214743+cyberbeam524@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:10:34 +0800 Subject: [PATCH 01/10] fix(optimizer): reject incompatible extension types in UNION coercion --- .../optimizer/src/analyzer/type_coercion.rs | 80 ++++++++++++++++++- .../test_files/sql_extension_types.slt | 38 +++++++++ 2 files changed, 115 insertions(+), 3 deletions(-) diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rs index faf7531496291..07ca80c7fde92 100644 --- a/datafusion/optimizer/src/analyzer/type_coercion.rs +++ b/datafusion/optimizer/src/analyzer/type_coercion.rs @@ -1721,11 +1721,53 @@ fn coerce_union_schema_with_schema( .iter() .enumerate() .map(|(i, field)| { + let input_fields: Vec<&Field> = inputs + .iter() + .map(|plan| plan.schema().field(i).as_ref()) + .collect(); + + // Validate extension type compatibility across non-Null inputs. + // Merging extension metadata onto a widened storage type (e.g. + // FixedSizeBinary(16) + Binary -> Binary) produces an + // invalid logical schema that causes internal errors on UNION and + // silently drops the extension type on UNION ALL. + if let Some(ext_field) = input_fields + .iter() + .find(|f| f.extension_type_name().is_some()) + { + let ext_name = ext_field.extension_type_name(); + let ext_meta = ext_field.extension_type_metadata(); + for other in &input_fields { + if matches!(other.data_type(), DataType::Null) { + continue; + } + if other.extension_type_name() != ext_name + || other.extension_type_metadata() != ext_meta + || other.data_type() != ext_field.data_type() + { + return plan_err!( + "UNION types cannot be unified for column '{}': \ + extension type '{}' ({}) is incompatible with {}", + field.name(), + ext_name.unwrap_or_default(), + ext_field.data_type(), + match other.extension_type_name() { + Some(other_ext) => { + format!( + "extension type '{other_ext}' ({})", + other.data_type() + ) + } + None => other.data_type().to_string(), + } + ); + } + } + } + // The stored schema may already contain an inferred common type. Feeding // it back into coercion can change the result, notably for dictionaries. - let datatype = coerce_union_type( - inputs.iter().map(|plan| plan.schema().field(i).as_ref()), - )?; + let datatype = coerce_union_type(input_fields)?; let nullable = field.is_nullable() || inputs .iter() @@ -2012,6 +2054,38 @@ mod test { ) } + #[test] + fn test_coerce_union_incompatible_extension_type() -> Result<()> { + let uuid_field = Field::new("id", DataType::FixedSizeBinary(16), false) + .with_metadata(std::collections::HashMap::from([( + "ARROW:extension:name".to_string(), + "arrow.uuid".to_string(), + )])); + let left_plan = Arc::new(LogicalPlan::EmptyRelation(EmptyRelation { + produce_one_row: false, + schema: Arc::new(DFSchema::from_unqualified_fields( + vec![uuid_field].into(), + std::collections::HashMap::new(), + )?), + })); + 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(), + std::collections::HashMap::new(), + )?), + })); + + let union = LogicalPlan::Union(Union::try_new_with_loose_types(vec![ + left_plan, right_plan, + ])?); + + assert_type_coercion_error( + union, + "UNION types cannot be unified for column 'id': extension type 'arrow.uuid'", + ) + } + #[test] fn merge_into_resolves_and_coerces_target_and_source_columns() -> Result<()> { use datafusion_expr::dml::{ diff --git a/datafusion/sqllogictest/test_files/sql_extension_types.slt b/datafusion/sqllogictest/test_files/sql_extension_types.slt index 957f3dedfc09e..4fcafccea42a2 100644 --- a/datafusion/sqllogictest/test_files/sql_extension_types.slt +++ b/datafusion/sqllogictest/test_files/sql_extension_types.slt @@ -192,3 +192,41 @@ INSERT INTO t1 VALUES (NULL); statement ok DROP TABLE t1; + +statement ok +CREATE TABLE t (id UUID); + +statement ok +INSERT INTO t VALUES + (CAST(arrow_cast(X'00010203040506070809000102030506', 'FixedSizeBinary(16)') AS UUID)); + +# Verify t.id actually has arrow.uuid metadata +query T +SELECT arrow_metadata(id, 'ARROW:extension:name') FROM t; +---- +arrow.uuid + +# UNION and UNION ALL between UUID and a bare Binary literal return a planning error +statement error UNION types cannot be unified for column 'id' +SELECT id FROM t +UNION +SELECT X'00010203040506070809000102030507'; + +statement error UNION types cannot be unified for column 'id' +SELECT id FROM t +UNION ALL +SELECT X'00010203040506070809000102030507'; + +# 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) +); +---- +arrow.uuid +arrow.uuid + +statement ok +DROP TABLE t; \ No newline at end of file From d6fb380b8d83f9159b70a900ca2d37fcb0ce6c72 Mon Sep 17 00:00:00 2001 From: cyberbeam524 <122214743+cyberbeam524@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:25:59 +0800 Subject: [PATCH 02/10] test(sqllogictest): add UNION extension-type mismatch coverage (name, payload, storage, NULL branch) --- .../test_files/sql_extension_types.slt | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/datafusion/sqllogictest/test_files/sql_extension_types.slt b/datafusion/sqllogictest/test_files/sql_extension_types.slt index 4fcafccea42a2..a4e995dd8f2ad 100644 --- a/datafusion/sqllogictest/test_files/sql_extension_types.slt +++ b/datafusion/sqllogictest/test_files/sql_extension_types.slt @@ -217,6 +217,48 @@ SELECT id FROM t UNION ALL SELECT X'00010203040506070809000102030507'; +# Same extension name but different storage type (FixedSizeBinary(16) vs Binary) also fails +statement error UNION types cannot be unified for column 'id' +SELECT id FROM t +UNION +SELECT with_metadata( + X'00010203040506070809000102030507', + 'ARROW:extension:name', + 'arrow.uuid' +); + +# Same extension name and storage type but different extension payload also fails +statement error UNION types cannot be unified for column 'id' +SELECT with_metadata( + with_metadata( + arrow_cast(X'00010203040506070809000102030506', 'FixedSizeBinary(16)'), + 'ARROW:extension:name', + 'arrow.uuid' + ), + 'ARROW:extension:metadata', + '{"shape":"v1"}' +) AS id +UNION +SELECT with_metadata( + with_metadata( + arrow_cast(X'00010203040506070809000102030507', 'FixedSizeBinary(16)'), + 'ARROW:extension:name', + 'arrow.uuid' + ), + 'ARROW:extension:metadata', + '{"shape":"v2"}' +) AS id; + +# NULL branch does not force incompatibility and preserves extension metadata +query T +SELECT arrow_metadata(id, 'ARROW:extension:name') FROM ( + SELECT id FROM t + UNION ALL + SELECT NULL +) LIMIT 1; +---- +arrow.uuid + # UNION between two UUID columns works and preserves arrow.uuid query T SELECT arrow_metadata(id, 'ARROW:extension:name') FROM ( From 43b2d234b706681ded832fd713379d1f72d07e2e Mon Sep 17 00:00:00 2001 From: cyberbeam524 <122214743+cyberbeam524@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:30:03 +0800 Subject: [PATCH 03/10] refactor(optimizer): extract extension_types_equal helper and refine tests --- .../optimizer/src/analyzer/type_coercion.rs | 21 +++++++++++-------- .../test_files/sql_extension_types.slt | 19 +++++++++-------- 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rs index 07ca80c7fde92..463b609e9a847 100644 --- a/datafusion/optimizer/src/analyzer/type_coercion.rs +++ b/datafusion/optimizer/src/analyzer/type_coercion.rs @@ -1649,6 +1649,14 @@ fn coerce_case_expression( Ok(Case::new(case_expr, when_then, else_expr)) } +/// 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() +} + /// Get a common schema that is compatible with all inputs of UNION. /// /// This method presumes that the wildcard expansion is unneeded, or has already @@ -1735,21 +1743,16 @@ fn coerce_union_schema_with_schema( .iter() .find(|f| f.extension_type_name().is_some()) { - let ext_name = ext_field.extension_type_name(); - let ext_meta = ext_field.extension_type_metadata(); for other in &input_fields { if matches!(other.data_type(), DataType::Null) { continue; } - if other.extension_type_name() != ext_name - || other.extension_type_metadata() != ext_meta - || other.data_type() != ext_field.data_type() - { + if !extension_types_equal(ext_field, other) { return plan_err!( "UNION types cannot be unified for column '{}': \ - extension type '{}' ({}) is incompatible with {}", + extension type '{}' ({}) is incompatible with {}", field.name(), - ext_name.unwrap_or_default(), + ext_field.extension_type_name().unwrap_or_default(), ext_field.data_type(), match other.extension_type_name() { Some(other_ext) => { @@ -2071,7 +2074,7 @@ mod test { 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(), + vec![Field::new("id", DataType::FixedSizeBinary(16), false)].into(), std::collections::HashMap::new(), )?), })); diff --git a/datafusion/sqllogictest/test_files/sql_extension_types.slt b/datafusion/sqllogictest/test_files/sql_extension_types.slt index a4e995dd8f2ad..f6f2ec18af469 100644 --- a/datafusion/sqllogictest/test_files/sql_extension_types.slt +++ b/datafusion/sqllogictest/test_files/sql_extension_types.slt @@ -228,26 +228,27 @@ SELECT with_metadata( ); # Same extension name and storage type but different extension payload also fails -statement error UNION types cannot be unified for column 'id' +# (e.g. arrow.fixed_shape_tensor with incompatible shapes [2, 5] vs [5, 2]) +statement error UNION types cannot be unified for column 'tensor' SELECT with_metadata( with_metadata( - arrow_cast(X'00010203040506070809000102030506', 'FixedSizeBinary(16)'), + arrow_cast([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'FixedSizeList(10, Int64)'), 'ARROW:extension:name', - 'arrow.uuid' + 'arrow.fixed_shape_tensor' ), 'ARROW:extension:metadata', - '{"shape":"v1"}' -) AS id + '{"shape":[2,5]}' +) AS tensor UNION SELECT with_metadata( with_metadata( - arrow_cast(X'00010203040506070809000102030507', 'FixedSizeBinary(16)'), + arrow_cast([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'FixedSizeList(10, Int64)'), 'ARROW:extension:name', - 'arrow.uuid' + 'arrow.fixed_shape_tensor' ), 'ARROW:extension:metadata', - '{"shape":"v2"}' -) AS id; + '{"shape":[5,2]}' +) AS tensor; # NULL branch does not force incompatibility and preserves extension metadata query T From 2b189c6ac8511316ecef3ecfede06b3f2a296d1f Mon Sep 17 00:00:00 2001 From: cyberbeam524 <122214743+cyberbeam524@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:06:39 +0800 Subject: [PATCH 04/10] Update datafusion/sqllogictest/test_files/sql_extension_types.slt Co-authored-by: Jay Zhan --- .../test_files/sql_extension_types.slt | 82 ++++++++++++------- 1 file changed, 52 insertions(+), 30 deletions(-) diff --git a/datafusion/sqllogictest/test_files/sql_extension_types.slt b/datafusion/sqllogictest/test_files/sql_extension_types.slt index f6f2ec18af469..6c1778ab96a03 100644 --- a/datafusion/sqllogictest/test_files/sql_extension_types.slt +++ b/datafusion/sqllogictest/test_files/sql_extension_types.slt @@ -217,38 +217,60 @@ SELECT id FROM t UNION ALL SELECT X'00010203040506070809000102030507'; -# Same extension name but different storage type (FixedSizeBinary(16) vs Binary) also fails -statement error UNION types cannot be unified for column 'id' -SELECT id FROM t -UNION -SELECT with_metadata( - X'00010203040506070809000102030507', - 'ARROW:extension:name', - 'arrow.uuid' +# A plain FixedSizeBinary(16) keeps the UUID type, as in 56.0.0 +query ?T +SELECT id, arrow_metadata(id, 'ARROW:extension:name') FROM ( + SELECT id FROM t + UNION ALL + SELECT arrow_cast(X'00010203040506070809000102030507', 'FixedSizeBinary(16)') +) ORDER BY id; +---- +00010203040506070809000102030506 arrow.uuid +00010203040506070809000102030507 arrow.uuid + +# The coerced storage type (Utf8View) already carries arrow.json in one input +query TT +SELECT j, arrow_metadata(j, 'ARROW:extension:name') FROM ( + SELECT with_metadata('{"a":1}', 'ARROW:extension:name', 'arrow.json') AS j + UNION ALL + SELECT with_metadata(arrow_cast('{"b":2}', 'Utf8View'), 'ARROW:extension:name', 'arrow.json') +) ORDER BY j; +---- +{"a":1} arrow.json +{"b":2} arrow.json + +# Extension metadata that differs only in its bytes is not an error (#26810) +query T +SELECT arrow_metadata(j, 'ARROW:extension:name') FROM ( + SELECT with_metadata(with_metadata('{"a":1}', 'ARROW:extension:name', 'arrow.json'), 'ARROW:extension:metadata', '{}') AS j + UNION ALL + SELECT with_metadata(with_metadata('{"b":2}', 'ARROW:extension:name', 'arrow.json'), 'ARROW:extension:metadata', '{ }') ); +---- +arrow.json +arrow.json -# Same extension name and storage type but different extension payload also fails -# (e.g. arrow.fixed_shape_tensor with incompatible shapes [2, 5] vs [5, 2]) -statement error UNION types cannot be unified for column 'tensor' -SELECT with_metadata( - with_metadata( - arrow_cast([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'FixedSizeList(10, Int64)'), - 'ARROW:extension:name', - 'arrow.fixed_shape_tensor' - ), - 'ARROW:extension:metadata', - '{"shape":[2,5]}' -) AS tensor -UNION -SELECT with_metadata( - with_metadata( - arrow_cast([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'FixedSizeList(10, Int64)'), - 'ARROW:extension:name', - 'arrow.fixed_shape_tensor' - ), - 'ARROW:extension:metadata', - '{"shape":[5,2]}' -) AS tensor; +# Utf8View never carried arrow.json in any input, so the result would drop it +statement error UNION types cannot be unified for column 'j' +SELECT with_metadata('{"a":1}', 'ARROW:extension:name', 'arrow.json') AS j +UNION ALL +SELECT arrow_cast('{"b":2}', 'Utf8View'); + +# Different extension names are an error, as in CASE and COALESCE +statement error Cannot merge field metadata with differing values of 'ARROW:extension:name' +SELECT with_metadata('{"a":1}', 'ARROW:extension:name', 'arrow.json') AS j +UNION ALL +SELECT with_metadata('x', 'ARROW:extension:name', 'arrow.opaque'); + +# 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 # NULL branch does not force incompatibility and preserves extension metadata query T From 77389f50ae46ddd740aa0256c651a352358323ad Mon Sep 17 00:00:00 2001 From: cyberbeam524 <122214743+cyberbeam524@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:13:42 +0800 Subject: [PATCH 05/10] refactor(optimizer): narrow UNION extension type check using suggested coerced_fields_metadata and remove extension_types_equal --- .../optimizer/src/analyzer/type_coercion.rs | 82 +++++++++---------- 1 file changed, 37 insertions(+), 45 deletions(-) diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rs index 463b609e9a847..87279a5202306 100644 --- a/datafusion/optimizer/src/analyzer/type_coercion.rs +++ b/datafusion/optimizer/src/analyzer/type_coercion.rs @@ -15,7 +15,7 @@ use crate::utils::{NamePreserver, merge_into_schema}; use arrow::datatypes::{DataType, Field, IntervalUnit, Schema, TimeUnit}; use arrow::temporal_conversions::SECONDS_IN_DAY; use datafusion_common::config::ConfigOptions; -use datafusion_common::metadata::merge_metadata_for_union; +use datafusion_common::metadata::{coerced_fields_metadata, merge_metadata_for_union}; use datafusion_common::tree_node::{ Transformed, TreeNode, TreeNodeRecursion, TreeNodeRewriter, }; @@ -1649,12 +1649,38 @@ fn coerce_case_expression( Ok(Case::new(case_expr, when_then, else_expr)) } -/// 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(()) } /// Get a common schema that is compatible with all inputs of UNION. @@ -1704,6 +1730,7 @@ pub fn coerce_union_schema(inputs: &[Arc]) -> Result { }; coerce_union_schema_with_schema(inputs, first.schema()) } + fn coerce_union_schema_with_schema( inputs: &[Arc], base_schema: &DFSchemaRef, @@ -1734,43 +1761,8 @@ fn coerce_union_schema_with_schema( .map(|plan| plan.schema().field(i).as_ref()) .collect(); - // Validate extension type compatibility across non-Null inputs. - // Merging extension metadata onto a widened storage type (e.g. - // FixedSizeBinary(16) + Binary -> Binary) produces an - // invalid logical schema that causes internal errors on UNION and - // silently drops the extension type on UNION ALL. - if let Some(ext_field) = input_fields - .iter() - .find(|f| f.extension_type_name().is_some()) - { - for other in &input_fields { - if matches!(other.data_type(), DataType::Null) { - continue; - } - if !extension_types_equal(ext_field, other) { - return plan_err!( - "UNION types cannot be unified for column '{}': \ - extension type '{}' ({}) is incompatible with {}", - field.name(), - ext_field.extension_type_name().unwrap_or_default(), - ext_field.data_type(), - match other.extension_type_name() { - Some(other_ext) => { - format!( - "extension type '{other_ext}' ({})", - other.data_type() - ) - } - None => other.data_type().to_string(), - } - ); - } - } - } - - // The stored schema may already contain an inferred common type. Feeding - // it back into coercion can change the result, notably for dictionaries. - 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)?; let nullable = field.is_nullable() || inputs .iter() @@ -2074,7 +2066,7 @@ mod test { let right_plan = Arc::new(LogicalPlan::EmptyRelation(EmptyRelation { produce_one_row: false, schema: Arc::new(DFSchema::from_unqualified_fields( - vec![Field::new("id", DataType::FixedSizeBinary(16), false)].into(), + vec![Field::new("id", DataType::Binary, false)].into(), std::collections::HashMap::new(), )?), })); From b405c0e8a680b7684b892849182d032480617466 Mon Sep 17 00:00:00 2001 From: cyberbeam524 <122214743+cyberbeam524@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:42:13 +0800 Subject: [PATCH 06/10] Update datafusion/optimizer/src/analyzer/type_coercion.rs Co-authored-by: Jay Zhan --- datafusion/optimizer/src/analyzer/type_coercion.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rs index 87279a5202306..82bbdafa04c7d 100644 --- a/datafusion/optimizer/src/analyzer/type_coercion.rs +++ b/datafusion/optimizer/src/analyzer/type_coercion.rs @@ -1756,6 +1756,8 @@ fn coerce_union_schema_with_schema( .iter() .enumerate() .map(|(i, field)| { + // The stored schema may already contain an inferred common type. Feeding + // it back into coercion can change the result, notably for dictionaries. let input_fields: Vec<&Field> = inputs .iter() .map(|plan| plan.schema().field(i).as_ref()) From e76477d355762c3e8ecbedbb6905cad52f093821 Mon Sep 17 00:00:00 2001 From: cyberbeam524 <122214743+cyberbeam524@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:51:42 +0800 Subject: [PATCH 07/10] Update datafusion/sqllogictest/test_files/sql_extension_types.slt Co-authored-by: Jay Zhan --- .../test_files/sql_extension_types.slt | 31 +++++++++++++------ 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/datafusion/sqllogictest/test_files/sql_extension_types.slt b/datafusion/sqllogictest/test_files/sql_extension_types.slt index 6c1778ab96a03..843d4dc273808 100644 --- a/datafusion/sqllogictest/test_files/sql_extension_types.slt +++ b/datafusion/sqllogictest/test_files/sql_extension_types.slt @@ -206,16 +206,27 @@ SELECT arrow_metadata(id, 'ARROW:extension:name') FROM t; ---- arrow.uuid -# UNION and UNION ALL between UUID and a bare Binary literal return a planning error -statement error UNION types cannot be unified for column 'id' -SELECT id FROM t -UNION -SELECT X'00010203040506070809000102030507'; - -statement error UNION types cannot be unified for column 'id' -SELECT id FROM t -UNION ALL -SELECT X'00010203040506070809000102030507'; +# UUID with a bare Binary literal is Binary, as in 56.0.0, until #27383 can +# coerce the literal to UUID; UNION no longer fails with an internal error +query ?TT +SELECT id, arrow_typeof(id), arrow_metadata(id, 'ARROW:extension:name') FROM ( + SELECT id FROM t + UNION + SELECT X'00010203040506070809000102030507' +) ORDER BY id; +---- +00010203040506070809000102030506 Binary NULL +00010203040506070809000102030507 Binary NULL + +query ?TT +SELECT id, arrow_typeof(id), arrow_metadata(id, 'ARROW:extension:name') FROM ( + SELECT id FROM t + UNION ALL + SELECT X'00010203040506070809000102030507' +) ORDER BY id; +---- +00010203040506070809000102030506 Binary NULL +00010203040506070809000102030507 Binary NULL # A plain FixedSizeBinary(16) keeps the UUID type, as in 56.0.0 query ?T From b791e7aaf02f99b1ecbdd7611295b841b2c1c304 Mon Sep 17 00:00:00 2001 From: cyberbeam524 <122214743+cyberbeam524@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:51:57 +0800 Subject: [PATCH 08/10] Update datafusion/sqllogictest/test_files/sql_extension_types.slt Co-authored-by: Jay Zhan --- .../test_files/sql_extension_types.slt | 53 +++++++++++++++---- 1 file changed, 42 insertions(+), 11 deletions(-) diff --git a/datafusion/sqllogictest/test_files/sql_extension_types.slt b/datafusion/sqllogictest/test_files/sql_extension_types.slt index 843d4dc273808..611a0ee793269 100644 --- a/datafusion/sqllogictest/test_files/sql_extension_types.slt +++ b/datafusion/sqllogictest/test_files/sql_extension_types.slt @@ -261,17 +261,48 @@ SELECT arrow_metadata(j, 'ARROW:extension:name') FROM ( arrow.json arrow.json -# Utf8View never carried arrow.json in any input, so the result would drop it -statement error UNION types cannot be unified for column 'j' -SELECT with_metadata('{"a":1}', 'ARROW:extension:name', 'arrow.json') AS j -UNION ALL -SELECT arrow_cast('{"b":2}', 'Utf8View'); - -# Different extension names are an error, as in CASE and COALESCE -statement error Cannot merge field metadata with differing values of 'ARROW:extension:name' -SELECT with_metadata('{"a":1}', 'ARROW:extension:name', 'arrow.json') AS j -UNION ALL -SELECT with_metadata('x', 'ARROW:extension:name', 'arrow.opaque'); +# As in the physical union, the last input's extension metadata wins +query T +SELECT arrow_metadata(j, 'ARROW:extension:metadata') FROM ( + SELECT with_metadata(with_metadata('{"a":1}', 'ARROW:extension:name', 'arrow.json'), 'ARROW:extension:metadata', '{}') AS j + UNION + SELECT with_metadata(with_metadata('{"b":2}', 'ARROW:extension:name', 'arrow.json'), 'ARROW:extension:metadata', '{ }') +); +---- +{ } +{ } + +# Utf8View never carried arrow.json in any input, so the result drops it +query TT +SELECT j, arrow_metadata(j, 'ARROW:extension:name') FROM ( + SELECT with_metadata('{"a":1}', 'ARROW:extension:name', 'arrow.json') AS j + UNION ALL + SELECT arrow_cast('{"b":2}', 'Utf8View') +) ORDER BY j; +---- +{"a":1} NULL +{"b":2} NULL + +# Extension metadata of an input cast to Utf8View is not kept +query TT +SELECT j, arrow_metadata(j, 'ARROW:extension:metadata') FROM ( + SELECT with_metadata(with_metadata('{"a":1}', 'ARROW:extension:name', 'arrow.json'), 'ARROW:extension:metadata', '{}') AS j + UNION + SELECT with_metadata(arrow_cast('{"b":2}', 'Utf8View'), 'ARROW:extension:name', 'arrow.json') +) ORDER BY j; +---- +{"a":1} NULL +{"b":2} NULL + +# NULL inputs keep their extension type when every input is NULL +query T +SELECT arrow_metadata(j, 'ARROW:extension:name') FROM ( + SELECT with_metadata(NULL, 'ARROW:extension:name', 'arrow.opaque') AS j + UNION + SELECT with_metadata(NULL, 'ARROW:extension:name', 'arrow.opaque') +); +---- +arrow.opaque # A NULL input's metadata does not pick the extension type query T From c1c9c89d9b712ae14f5a5031e07d1cdb4e01be8b Mon Sep 17 00:00:00 2001 From: cyberbeam524 <122214743+cyberbeam524@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:44:57 +0800 Subject: [PATCH 09/10] fix(optimizer): align UNION logical extension metadata with physical union --- Cargo.lock | 1 + datafusion/optimizer/Cargo.toml | 1 + .../optimizer/src/analyzer/type_coercion.rs | 122 ++++++++---------- .../test_files/sql_extension_types.slt | 2 +- 4 files changed, 59 insertions(+), 67 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 336d69d12547a..192c0195794af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2465,6 +2465,7 @@ name = "datafusion-optimizer" version = "57.0.0-dev" dependencies = [ "arrow", + "arrow-schema", "async-trait", "chrono", "criterion", diff --git a/datafusion/optimizer/Cargo.toml b/datafusion/optimizer/Cargo.toml index 55b1486a405b4..7df8013cdc9b0 100644 --- a/datafusion/optimizer/Cargo.toml +++ b/datafusion/optimizer/Cargo.toml @@ -40,6 +40,7 @@ recursive_protection = ["dep:recursive"] # traits). [dependencies] arrow = { workspace = true } +arrow-schema = { workspace = true } chrono = { workspace = true } datafusion-common = { workspace = true, default-features = true } datafusion-expr = { workspace = true } diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rs index 82bbdafa04c7d..5920135ef0ea0 100644 --- a/datafusion/optimizer/src/analyzer/type_coercion.rs +++ b/datafusion/optimizer/src/analyzer/type_coercion.rs @@ -14,8 +14,9 @@ use crate::utils::{NamePreserver, merge_into_schema}; use arrow::datatypes::{DataType, Field, IntervalUnit, Schema, TimeUnit}; use arrow::temporal_conversions::SECONDS_IN_DAY; +use arrow_schema::extension::{EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY}; use datafusion_common::config::ConfigOptions; -use datafusion_common::metadata::{coerced_fields_metadata, merge_metadata_for_union}; +use datafusion_common::metadata::merge_metadata_for_union; use datafusion_common::tree_node::{ Transformed, TreeNode, TreeNodeRecursion, TreeNodeRewriter, }; @@ -1649,40 +1650,6 @@ fn coerce_case_expression( Ok(Case::new(case_expr, when_then, else_expr)) } -/// 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(()) -} - /// Get a common schema that is compatible with all inputs of UNION. /// /// This method presumes that the wildcard expansion is unneeded, or has already @@ -1764,15 +1731,29 @@ fn coerce_union_schema_with_schema( .collect(); 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); Ok((None, field.into())) }) .collect::>>()?; @@ -2052,35 +2033,44 @@ mod test { } #[test] - fn test_coerce_union_incompatible_extension_type() -> Result<()> { - let uuid_field = Field::new("id", DataType::FixedSizeBinary(16), false) - .with_metadata(std::collections::HashMap::from([( - "ARROW:extension:name".to_string(), - "arrow.uuid".to_string(), - )])); - let left_plan = Arc::new(LogicalPlan::EmptyRelation(EmptyRelation { - produce_one_row: false, - schema: Arc::new(DFSchema::from_unqualified_fields( - vec![uuid_field].into(), - std::collections::HashMap::new(), - )?), - })); - 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(), + 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(), - )?), - })); - - let union = LogicalPlan::Union(Union::try_new_with_loose_types(vec![ - left_plan, right_plan, - ])?); + ) + .map(|schema| { + Arc::new(LogicalPlan::EmptyRelation(EmptyRelation { + produce_one_row: false, + schema: Arc::new(schema), + })) + }) + }; - assert_type_coercion_error( - union, - "UNION types cannot be unified for column 'id': extension type 'arrow.uuid'", - ) + // 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(()) } #[test] diff --git a/datafusion/sqllogictest/test_files/sql_extension_types.slt b/datafusion/sqllogictest/test_files/sql_extension_types.slt index 611a0ee793269..f774190d1e47f 100644 --- a/datafusion/sqllogictest/test_files/sql_extension_types.slt +++ b/datafusion/sqllogictest/test_files/sql_extension_types.slt @@ -336,4 +336,4 @@ arrow.uuid arrow.uuid statement ok -DROP TABLE t; \ No newline at end of file +DROP TABLE t; From 5af6ff3b7030b67b69c16783a72742539035c68f Mon Sep 17 00:00:00 2001 From: cyberbeam524 <122214743+cyberbeam524@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:53:28 +0800 Subject: [PATCH 10/10] chore(optimizer): address review feedback on UNION extension tests and docs --- .../optimizer/src/analyzer/type_coercion.rs | 16 ++++++++++------ .../test_files/sql_extension_types.slt | 10 ---------- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/datafusion/optimizer/src/analyzer/type_coercion.rs b/datafusion/optimizer/src/analyzer/type_coercion.rs index 5920135ef0ea0..86902765ded90 100644 --- a/datafusion/optimizer/src/analyzer/type_coercion.rs +++ b/datafusion/optimizer/src/analyzer/type_coercion.rs @@ -1662,7 +1662,10 @@ fn coerce_case_expression( /// /// **Schema-level metadata merging**: Later schemas take precedence for duplicate keys. /// -/// **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. /// /// **Type coercion precedence**: The coerced type is determined by iteratively applying /// `type_union_coercion()` between the accumulated type and each new input's type. The @@ -1690,7 +1693,8 @@ fn coerce_case_expression( /// **Precedence Summary**: /// - **Datatypes**: Folded in input order using `type_union_coercion()` /// - **Nullability**: Later inputs can add nullability but cannot remove it (logical OR) -/// - **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 pub fn coerce_union_schema(inputs: &[Arc]) -> Result { let Some(first) = inputs.first() else { return plan_err!("UNION requires at least one input"); @@ -2064,12 +2068,12 @@ mod test { 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 + // Inputs already stored as the coerced type keep their extension type let schema = coerce_union_schema(&[ - input(DataType::Null, Some("arrow.opaque"))?, - input(Utf8, Some("arrow.json"))?, + input(DataType::FixedSizeBinary(16), Some("arrow.uuid"))?, + input(DataType::FixedSizeBinary(16), Some("arrow.uuid"))?, ])?; - assert_eq!(schema.field(0).extension_type_name(), Some("arrow.json")); + assert_eq!(schema.field(0).extension_type_name(), Some("arrow.uuid")); Ok(()) } diff --git a/datafusion/sqllogictest/test_files/sql_extension_types.slt b/datafusion/sqllogictest/test_files/sql_extension_types.slt index f774190d1e47f..2d725d8f1a7c0 100644 --- a/datafusion/sqllogictest/test_files/sql_extension_types.slt +++ b/datafusion/sqllogictest/test_files/sql_extension_types.slt @@ -304,16 +304,6 @@ SELECT arrow_metadata(j, 'ARROW:extension:name') FROM ( ---- arrow.opaque -# 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 - # NULL branch does not force incompatibility and preserves extension metadata query T SELECT arrow_metadata(id, 'ARROW:extension:name') FROM (