Skip to content

Commit d185ed5

Browse files
vadimpivenclaudealamb
authored
Fix ordering for UNION ALL over heterogeneous constants (#23528)
## Which issue does this PR close? <!-- We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123. --> - Closes #. ## Rationale for this change <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. --> `add_sort_above` and `add_sort_above_with_distribution` in physical-optimizer prune every expression that `EquivalenceProperties::is_expr_constant` reports as constant. This treats `AcrossPartitions::Heterogeneous` the same as `AcrossPartitions::Uniform`, which is incorrect. Check an example: ```sql SELECT 2 AS sample, c FROM t UNION ALL SELECT 1 AS sample, c FROM t ORDER BY sample, c ``` The union reports sample as a `Heterogeneous` constant and so it gets pruned, which breaks `ORDER BY`. ## What changes are included in this PR? <!-- There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR. --> Helper that activates pruning only for `AcrossPartitions::Uniform`, use it at both prune sites (`add_sort_above` and `add_sort_above_with_distribution`) so `Heterogeneous` constants are retained. ## Are these changes tested? <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 2. Serve as another way to document the expected behavior of the code If tests are not included in your PR, please explain why (for example, are they covered by existing tests)? --> Yes, a new unit-test added. ## Are there any user-facing changes? <!-- If there are user-facing changes then we may require documentation to be updated before approving the PR. --> <!-- If there are any breaking changes to public APIs, please add the `api change` label. --> No API changes, just an internal logic bug-fix. --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: Andrew Lamb <andrew@nerdnetworks.org>
1 parent 620262b commit d185ed5

2 files changed

Lines changed: 82 additions & 2 deletions

File tree

datafusion/physical-expr/src/equivalence/class.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -551,7 +551,19 @@ impl EquivalenceGroup {
551551
sort_exprs
552552
.into_iter()
553553
.map(|sort_expr| self.normalize_sort_expr(sort_expr))
554-
.filter(|sort_expr| self.is_expr_constant(&sort_expr.expr).is_none())
554+
.filter(|sort_expr| !self.is_uniform_constant(&sort_expr.expr))
555+
}
556+
557+
/// Returns `true` when `expr` is a *globally* constant column, safe to drop
558+
/// from a required ordering. Only [`AcrossPartitions::Uniform`] qualifies; a
559+
/// [`AcrossPartitions::Heterogeneous`] value is constant within a partition
560+
/// but varies across partitions, so it still discriminates the order once
561+
/// partitions are merged and must be kept.
562+
fn is_uniform_constant(&self, expr: &Arc<dyn PhysicalExpr>) -> bool {
563+
matches!(
564+
self.is_expr_constant(expr),
565+
Some(AcrossPartitions::Uniform(_))
566+
)
555567
}
556568

557569
/// Normalizes the given sort requirement according to this group. The
@@ -582,7 +594,7 @@ impl EquivalenceGroup {
582594
sort_reqs
583595
.into_iter()
584596
.map(|req| self.normalize_sort_requirement(req))
585-
.filter(|req| self.is_expr_constant(&req.expr).is_none())
597+
.filter(|req| !self.is_uniform_constant(&req.expr))
586598
}
587599

588600
/// Perform an indirect projection of `expr` by consulting the equivalence

datafusion/sqllogictest/test_files/order.slt

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1770,3 +1770,71 @@ reset datafusion.sql_parser.default_null_ordering;
17701770

17711771
statement ok
17721772
reset datafusion.sql_parser.dialect;
1773+
1774+
# A global sort feeding a sink (CopyTo) must keep a leading key that is constant
1775+
# within each partition but differs across them ("a" is 2 on one union branch,
1776+
# 1 on the other). The merge above the union has to reorder rows across branches,
1777+
# so the physical plan must keep "a" in its ordering; dropping it (leaving only
1778+
# [b@1 ASC]) silently loses the global order under the sink.
1779+
statement ok
1780+
CREATE TABLE t2(b INT) AS VALUES (10), (20);
1781+
1782+
query TT
1783+
EXPLAIN COPY (
1784+
SELECT 2 AS a, b FROM t2
1785+
UNION ALL
1786+
SELECT 1 AS a, b FROM t2
1787+
ORDER BY a, b
1788+
) TO 'test_files/scratch/order/sort_key_sink.parquet';
1789+
----
1790+
logical_plan
1791+
01)CopyTo: format=parquet output_url=test_files/scratch/order/sort_key_sink.parquet options: ()
1792+
02)--Sort: a ASC NULLS LAST, b ASC NULLS LAST
1793+
03)----Union
1794+
04)------Projection: Int64(2) AS a, t2.b
1795+
05)--------TableScan: t2 projection=[b]
1796+
06)------Projection: Int64(1) AS a, t2.b
1797+
07)--------TableScan: t2 projection=[b]
1798+
physical_plan
1799+
01)DataSinkExec: sink=ParquetSink(file_groups=[])
1800+
02)--SortPreservingMergeExec: [a@0 ASC NULLS LAST, b@1 ASC NULLS LAST]
1801+
03)----UnionExec
1802+
04)------SortExec: expr=[b@1 ASC NULLS LAST], preserve_partitioning=[false]
1803+
05)--------ProjectionExec: expr=[2 as a, b@0 as b]
1804+
06)----------DataSourceExec: partitions=1, partition_sizes=[1]
1805+
07)------SortExec: expr=[b@1 ASC NULLS LAST], preserve_partitioning=[false]
1806+
08)--------ProjectionExec: expr=[1 as a, b@0 as b]
1807+
09)----------DataSourceExec: partitions=1, partition_sizes=[1]
1808+
1809+
# Actually execute the COPY and verify the rows written to the file are in
1810+
# global (a, b) order, interleaving the two union branches. If "a" were
1811+
# dropped from the sort, the file would instead contain rows ordered only
1812+
# by "b" within each branch.
1813+
query I
1814+
COPY (
1815+
SELECT 2 AS a, b FROM t2
1816+
UNION ALL
1817+
SELECT 1 AS a, b FROM t2
1818+
ORDER BY a, b
1819+
) TO 'test_files/scratch/order/sort_key_sink.parquet';
1820+
----
1821+
4
1822+
1823+
statement ok
1824+
CREATE EXTERNAL TABLE sort_key_sink STORED AS PARQUET
1825+
LOCATION 'test_files/scratch/order/sort_key_sink.parquet';
1826+
1827+
# Note: no ORDER BY here, so this checks the order rows were written in
1828+
query II
1829+
SELECT * FROM sort_key_sink;
1830+
----
1831+
1 10
1832+
1 20
1833+
2 10
1834+
2 20
1835+
1836+
statement ok
1837+
DROP TABLE sort_key_sink;
1838+
1839+
statement ok
1840+
DROP TABLE t2;

0 commit comments

Comments
 (0)