Skip to content

Commit 0c03aae

Browse files
kumarUjjawalPerseus
authored andcommitted
perf: avoid quadratic metadata merging in union schemas (apache#26790)
Related to apache#17261. Complements the fast path for equal schemas added in Benchmark coverage is reviewed in apache#26791. This PR is stacked on its benchmark-only commit `cfc6594b5`; the [optimization-only diff](apache/datafusion@cfc6594...c5f9d3e) contains the schema change and regression test. Constructing a union with unequal input schemas can take quadratic time in the number of children. The fallback merges every input's field metadata before checking whether that candidate field is nullable. With non-nullable fields, the same full merge is repeated for every child. Select the first nullable field (or the first field when none are nullable) before merging metadata. This makes the fallback linear in child count for a fixed number of fields and metadata entries per input. The shared helper also serves `InterleaveExec`. - Merge metadata once per output field, preserving the selected field, leftmost name, and existing metadata conflict precedence. - Add a test that constructs and executes unions with non-nullable inputs, first/middle/last nullable inputs, conflicting and distinct metadata keys, and checks output rows. Benchmarks use upstream `c18e5d974` plus the benchmark extension, Rust 1.99.1, `release-nonlto`, and an Apple M5 Pro. The table averages two interleaved runs per binary, with 20 Criterion samples per run. Schemas have 10 fields and two metadata entries per field. | Non-nullable schema case | Children | Upstream | Patched | Speedup | | --- | ---: | ---: | ---: | ---: | | Last child's metadata differs | 10 | 141 µs | 62 µs | 2.3× | | Last child's metadata differs | 100 | 9.24 ms | 0.66 ms | 14.1× | | Last child's metadata differs | 1,000 | 877 ms | 7.40 ms | 118.6× | | Field names differ | 10 | 140 µs | 60 µs | 2.3× | | Field names differ | 100 | 9.38 ms | 0.66 ms | 14.3× | | Field names differ | 1,000 | 866 ms | 7.36 ms | 117.6× | The controls with nullable fields or equal schemas at 4,000 children varied from -0.8% to +6.3% on this shared machine. Background builds affected some measurements, so the larger SQL cases with sorted unions were also checked in a tighter alternating sequence, with four runs per binary: | SQL planning case | Upstream | Patched | Change | | --- | ---: | ---: | ---: | | 50 columns, Int64 | 38.61 ms | 38.40 ms | -0.5% | | 50 columns, UInt64 | 139.48 ms | 139.63 ms | +0.1% | These results establish the constructor improvement independently of workloads. The original extended logical-planning benchmark only calls logical optimization and does not exercise this physical schema helper. To run the benchmark cases from apache#26791: ```sh cargo bench --profile release-nonlto -p datafusion-physical-plan --bench union_schema -- union_exec_try_new_non_nullable ``` Faster construction of unions and interleaves with unequal schemas and non-nullable fields. Schema behavior and public APIs are preserved. AI assistance: OpenAI Codex. (cherry picked from commit 7ca68cf) Ported to branch-55 (arrow 59): arrow::datatypes::Metadata does not exist there, so the new test builds field metadata as a HashMap<String, String>, and the unused Field import is dropped.
1 parent ca920a7 commit 0c03aae

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};
@@ -1673,6 +1671,84 @@ mod tests {
16731671
Ok(())
16741672
}
16751673

1674+
#[tokio::test]
1675+
async fn test_union_schema_metadata_and_nullability() -> Result<()> {
1676+
use arrow::array::Int32Array;
1677+
1678+
// Field metadata from the selected field is merged first, followed by
1679+
// the other inputs in order. Schema metadata always follows input order.
1680+
for (nullability, expected_field_value) in [
1681+
([false, false, false], "input2"),
1682+
([true, false, false], "input2"),
1683+
([false, true, false], "input2"),
1684+
([false, false, true], "input1"),
1685+
([true, true, true], "input2"),
1686+
] {
1687+
let inputs = nullability
1688+
.iter()
1689+
.enumerate()
1690+
.map(|(i, &nullable)| {
1691+
let metadata = std::collections::HashMap::from([
1692+
("shared".to_owned(), format!("input{i}")),
1693+
(format!("only{i}"), "kept".to_owned()),
1694+
]);
1695+
let field =
1696+
Field::new(format!("value{i}"), DataType::Int32, nullable)
1697+
.with_metadata(metadata.clone());
1698+
let schema =
1699+
Arc::new(Schema::new_with_metadata(vec![field], metadata));
1700+
let batch = RecordBatch::try_new(
1701+
Arc::clone(&schema),
1702+
vec![Arc::new(Int32Array::from(vec![i as i32]))],
1703+
)?;
1704+
let input: Arc<dyn ExecutionPlan> =
1705+
TestMemoryExec::try_new_exec(&[vec![batch]], schema, None)?;
1706+
Ok(input)
1707+
})
1708+
.collect::<Result<Vec<_>>>()?;
1709+
1710+
let expected_metadata = std::collections::HashMap::from([
1711+
("shared".to_owned(), expected_field_value.to_owned()),
1712+
("only0".to_owned(), "kept".to_owned()),
1713+
("only1".to_owned(), "kept".to_owned()),
1714+
("only2".to_owned(), "kept".to_owned()),
1715+
]);
1716+
let mut expected_schema_metadata = expected_metadata.clone();
1717+
expected_schema_metadata.insert("shared".to_owned(), "input2".to_owned());
1718+
let expected_schema = Arc::new(Schema::new_with_metadata(
1719+
vec![
1720+
Field::new("value0", DataType::Int32, nullability.contains(&true))
1721+
.with_metadata(expected_metadata),
1722+
],
1723+
expected_schema_metadata,
1724+
));
1725+
1726+
let union = UnionExec::try_new(inputs)?;
1727+
assert_eq!(union.schema(), expected_schema, "{nullability:?}");
1728+
let batches = collect(union, Arc::new(TaskContext::default())).await?;
1729+
datafusion_common::assert_batches_sorted_eq!(
1730+
[
1731+
"+--------+",
1732+
"| value0 |",
1733+
"+--------+",
1734+
"| 0 |",
1735+
"| 1 |",
1736+
"| 2 |",
1737+
"+--------+"
1738+
],
1739+
&batches
1740+
);
1741+
for batch in batches {
1742+
assert_eq!(
1743+
batch.schema().fields(),
1744+
expected_schema.fields(),
1745+
"{nullability:?}"
1746+
);
1747+
}
1748+
}
1749+
Ok(())
1750+
}
1751+
16761752
#[test]
16771753
fn test_union_schema_mismatch() {
16781754
// Test that UnionExec properly rejects inputs with different field counts

0 commit comments

Comments
 (0)