Skip to content

Commit a348975

Browse files
Merge pull request #225 from cherry-pick/apache-pr-26790-20261124
Cherry-pick apache#26790
2 parents b516542 + e46e643 commit a348975

2 files changed

Lines changed: 110 additions & 30 deletions

File tree

‎datafusion/physical-plan/benches/union_schema.rs‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@
2525
//! the scan runs, fails on the final child, then the full merge runs anyway.
2626
//! - `names_differ`: the first field is renamed in every child but the first,
2727
//! the common real-world unequal union where equality fails immediately.
28+
//!
29+
//! The non-nullable cases also require scanning all children to determine
30+
//! output nullability, rather than stopping at the first nullable field.
2831
2932
use std::collections::HashMap;
3033
use std::sync::Arc;
@@ -45,10 +48,10 @@ fn metadata(tag: &str, i: usize) -> HashMap<String, String> {
4548
.collect()
4649
}
4750

48-
fn flat_schema() -> Schema {
51+
fn flat_schema(nullable: bool) -> Schema {
4952
let fields: Vec<Field> = (0..NUM_FIELDS)
5053
.map(|i| {
51-
Field::new(format!("col_{i}"), DataType::Int64, true)
54+
Field::new(format!("col_{i}"), DataType::Int64, nullable)
5255
.with_metadata(metadata("f", i))
5356
})
5457
.collect();
@@ -120,8 +123,9 @@ fn children_last_differs(schema: &Schema, n: usize) -> Vec<Arc<dyn ExecutionPlan
120123

121124
fn bench_union_construction(c: &mut Criterion) {
122125
for (suffix, schema, sizes) in [
123-
("", flat_schema(), &[100usize, 1000, 4000][..]),
126+
("", flat_schema(true), &[100usize, 1000, 4000][..]),
124127
("_nested", nested_schema(), &[1000, 4000][..]),
128+
("_non_nullable", flat_schema(false), &[10, 100, 1000][..]),
125129
] {
126130
let mut group = c.benchmark_group(format!("union_exec_try_new{suffix}"));
127131
for &n in sizes {

‎datafusion/physical-plan/src/union.rs‎

Lines changed: 103 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ use crate::statistics::{ChildStats, StatisticsArgs};
4646
use crate::stream::ObservedStream;
4747
use crate::{ChildrenPropertiesMode, ReplaceChildrenOptions, validate_child_count};
4848

49-
use arrow::datatypes::{Field, Schema, SchemaRef};
49+
use arrow::datatypes::{Schema, SchemaRef};
5050
use arrow::record_batch::RecordBatch;
5151
use datafusion_common::config::ConfigOptions;
5252
use datafusion_common::stats::NdvFallback;
@@ -918,8 +918,8 @@ fn union_schema(inputs: &[Arc<dyn ExecutionPlan>]) -> Result<SchemaRef> {
918918
let first_schema = inputs[0].schema();
919919

920920
// Fast path: when every input already shares the first input's schema, the
921-
// field-by-field metadata/nullability merge below is redundant work that
922-
// scales as O(n^2 * fields). This is common in practice: unions built from
921+
// field-by-field metadata/nullability merge below is redundant work.
922+
// This is common in practice: unions built from
923923
// repartitioned copies of the same plan (e.g. observed in InfluxDB) hand us
924924
// children that all carry the exact same schema. A pointer-equality check
925925
// catches the shared-`Arc` case for free, and a content `==` comparison
@@ -951,31 +951,29 @@ fn union_schema(inputs: &[Arc<dyn ExecutionPlan>]) -> Result<SchemaRef> {
951951
// which also uses the left side names.
952952
let base_field = first_schema.field(i).clone();
953953

954-
// Coerce metadata and nullability across all inputs
955-
956-
inputs
954+
// Select the first nullable field, or the first field if none are
955+
// nullable, before merging metadata. Otherwise, each non-nullable
956+
// candidate would repeat the full metadata merge.
957+
let (input_idx, input) = inputs
957958
.iter()
958959
.enumerate()
959-
.map(|(input_idx, input)| {
960-
let field = input.schema().field(i).clone();
961-
let mut metadata = field.metadata().clone();
962-
963-
let other_metadatas = inputs
964-
.iter()
965-
.enumerate()
966-
.filter(|(other_idx, _)| *other_idx != input_idx)
967-
.flat_map(|(_, other_input)| {
968-
other_input.schema().field(i).metadata().clone().into_iter()
969-
});
970-
971-
metadata.extend(other_metadatas);
972-
field.with_metadata(metadata)
973-
})
974-
.find_or_first(Field::is_nullable)
975-
// We can unwrap this because if inputs was empty, this would've already panic'ed when we
976-
// indexed into inputs[0].
977-
.unwrap()
978-
.with_name(base_field.name())
960+
.find_or_first(|(_, input)| input.schema().field(i).is_nullable())
961+
// Empty inputs are rejected above.
962+
.unwrap();
963+
let field = input.schema().field(i).clone();
964+
let mut metadata = field.metadata().clone();
965+
966+
// Preserve precedence: the selected field's metadata comes first,
967+
// followed by the other inputs in their original order.
968+
let other_metadatas = inputs
969+
.iter()
970+
.enumerate()
971+
.filter(|(other_idx, _)| *other_idx != input_idx)
972+
.flat_map(|(_, other_input)| {
973+
other_input.schema().field(i).metadata().clone().into_iter()
974+
});
975+
metadata.extend(other_metadatas);
976+
field.with_metadata(metadata).with_name(base_field.name())
979977
})
980978
.collect::<Vec<_>>();
981979

@@ -1067,7 +1065,7 @@ mod tests {
10671065
use crate::test::{self, TestMemoryExec};
10681066

10691067
use arrow::compute::SortOptions;
1070-
use arrow::datatypes::DataType;
1068+
use arrow::datatypes::{DataType, Field};
10711069
use datafusion_common::SplitPoint;
10721070
use datafusion_common::stats::Precision;
10731071
use datafusion_common::{ColumnStatistics, ScalarValue};
@@ -1741,6 +1739,84 @@ mod tests {
17411739
Ok(())
17421740
}
17431741

1742+
#[tokio::test]
1743+
async fn test_union_schema_metadata_and_nullability() -> Result<()> {
1744+
use arrow::array::Int32Array;
1745+
1746+
// Field metadata from the selected field is merged first, followed by
1747+
// the other inputs in order. Schema metadata always follows input order.
1748+
for (nullability, expected_field_value) in [
1749+
([false, false, false], "input2"),
1750+
([true, false, false], "input2"),
1751+
([false, true, false], "input2"),
1752+
([false, false, true], "input1"),
1753+
([true, true, true], "input2"),
1754+
] {
1755+
let inputs = nullability
1756+
.iter()
1757+
.enumerate()
1758+
.map(|(i, &nullable)| {
1759+
let metadata = std::collections::HashMap::from([
1760+
("shared".to_owned(), format!("input{i}")),
1761+
(format!("only{i}"), "kept".to_owned()),
1762+
]);
1763+
let field =
1764+
Field::new(format!("value{i}"), DataType::Int32, nullable)
1765+
.with_metadata(metadata.clone());
1766+
let schema =
1767+
Arc::new(Schema::new_with_metadata(vec![field], metadata));
1768+
let batch = RecordBatch::try_new(
1769+
Arc::clone(&schema),
1770+
vec![Arc::new(Int32Array::from(vec![i as i32]))],
1771+
)?;
1772+
let input: Arc<dyn ExecutionPlan> =
1773+
TestMemoryExec::try_new_exec(&[vec![batch]], schema, None)?;
1774+
Ok(input)
1775+
})
1776+
.collect::<Result<Vec<_>>>()?;
1777+
1778+
let expected_metadata = std::collections::HashMap::from([
1779+
("shared".to_owned(), expected_field_value.to_owned()),
1780+
("only0".to_owned(), "kept".to_owned()),
1781+
("only1".to_owned(), "kept".to_owned()),
1782+
("only2".to_owned(), "kept".to_owned()),
1783+
]);
1784+
let mut expected_schema_metadata = expected_metadata.clone();
1785+
expected_schema_metadata.insert("shared".to_owned(), "input2".to_owned());
1786+
let expected_schema = Arc::new(Schema::new_with_metadata(
1787+
vec![
1788+
Field::new("value0", DataType::Int32, nullability.contains(&true))
1789+
.with_metadata(expected_metadata),
1790+
],
1791+
expected_schema_metadata,
1792+
));
1793+
1794+
let union = UnionExec::try_new(inputs)?;
1795+
assert_eq!(union.schema(), expected_schema, "{nullability:?}");
1796+
let batches = collect(union, Arc::new(TaskContext::default())).await?;
1797+
datafusion_common::assert_batches_sorted_eq!(
1798+
[
1799+
"+--------+",
1800+
"| value0 |",
1801+
"+--------+",
1802+
"| 0 |",
1803+
"| 1 |",
1804+
"| 2 |",
1805+
"+--------+"
1806+
],
1807+
&batches
1808+
);
1809+
for batch in batches {
1810+
assert_eq!(
1811+
batch.schema().fields(),
1812+
expected_schema.fields(),
1813+
"{nullability:?}"
1814+
);
1815+
}
1816+
}
1817+
Ok(())
1818+
}
1819+
17441820
#[test]
17451821
fn test_union_schema_mismatch() {
17461822
// Test that UnionExec properly rejects inputs with different field counts

0 commit comments

Comments
 (0)