jayzhan211 commented on code in PR #27982:
URL: https://github.com/apache/datafusion/pull/27982#discussion_r4784847211
##########
datafusion/physical-plan/src/union.rs:
##########
@@ -455,6 +456,58 @@ impl ExecutionPlan for UnionExec {
LimitBehavior::CopyToChildren
}
+ /// Pushes `order` into every input. Each output partition is one input
+ /// partition, so the union is `Exact` only when every input is.
+ ///
+ /// A union with several partitions sits below a per-partition sort under a
+ /// [`SortPreservingMergeExec`], or below a [`CoalescePartitionsExec`] that
+ /// downgrades `Exact` to `Inexact`, so the merge across partitions is
+ /// already in place.
+ ///
+ /// [`SortPreservingMergeExec`]:
crate::sorts::sort_preserving_merge::SortPreservingMergeExec
+ /// [`CoalescePartitionsExec`]:
crate::coalesce_partitions::CoalescePartitionsExec
+ fn try_pushdown_sort(
+ &self,
+ order: &[PhysicalSortExpr],
+ ) -> Result<SortOrderPushdownResult<Arc<dyn ExecutionPlan>>> {
+ let mut all_exact = true;
+ let mut any_pushed = false;
+ let mut inputs = Vec::with_capacity(self.inputs.len());
+ for input in &self.inputs {
+ match input.try_pushdown_sort(order)? {
+ SortOrderPushdownResult::Exact { inner } => {
+ any_pushed = true;
+ inputs.push(inner);
+ }
+ SortOrderPushdownResult::Inexact { inner } => {
+ any_pushed = true;
+ all_exact = false;
+ inputs.push(inner);
+ }
+ SortOrderPushdownResult::Unsupported => {
+ all_exact = false;
+ inputs.push(Arc::clone(input));
+ }
+ }
+ }
+
+ if !any_pushed {
+ return Ok(SortOrderPushdownResult::Unsupported);
+ }
+ let inner = UnionExec::try_new(inputs)?;
+ // The merge above checks the union's ordering, so claim `Exact` only
+ // when the union reports it.
+ let exact = all_exact
+ && inner
+ .equivalence_properties()
+ .ordering_satisfy(order.iter().cloned())?;
+ Ok(if exact {
+ SortOrderPushdownResult::Exact { inner }
+ } else {
+ SortOrderPushdownResult::Inexact { inner }
+ })
Review Comment:
@zhuqi-lucas thanks for this! When the inputs are mixed (one `Exact`, one
not), the `Exact` inputs keep their rewrite under the kept TopK, so each
reverse scan buffers a whole decoded row group. With
`enable_exact_reverse_scan` on and `memory_limit = '4M'`, this query fails with
`Resources exhausted ... ParquetReverseRowGroup[0]` here and returns rows on
main:
```sql
SELECT id, length(payload) FROM (SELECT * FROM big UNION ALL SELECT * FROM
small WHERE payload <> 'z')
ORDER BY id DESC LIMIT 3;
```
`FileScanConfig::try_pushdown_sort` already drops the exact rewrite when its
sort stays, for the same reason. The union could keep only `Inexact` rewrites
when it isn't `Exact`. In that mixed case, an input that is `Exact` only
because its files were reordered by statistics then keeps its original file
order, as on main. This changes two of the new snapshots: the first `TestScan`
in `..._inexact_input_keeps_sort` is no longer rewritten, and the plan in
`..._unsupported_input_keeps_sort` stays unchanged.
```suggestion
let results = self
.inputs
.iter()
.map(|input| input.try_pushdown_sort(order))
.collect::<Result<Vec<_>>>()?;
let exact_inputs = results
.iter()
.map(|result| match result {
SortOrderPushdownResult::Exact { inner } =>
Some(Arc::clone(inner)),
_ => None,
})
.collect::<Option<Vec<_>>>();
if let Some(exact_inputs) = exact_inputs {
let inner = UnionExec::try_new(exact_inputs)?;
// The merge above checks the union's ordering, so claim `Exact`
// only when the union reports it.
if inner
.equivalence_properties()
.ordering_satisfy(order.iter().cloned())?
{
return Ok(SortOrderPushdownResult::Exact { inner });
}
}
// The sort stays, so keep only `Inexact` rewrites. An exact rewrite,
// such as a parquet scan that buffers a row group to read it back to
// front, only pays off when it replaces the sort (see
// `FileScanConfig::try_pushdown_sort`).
let mut any_inexact = false;
let inputs = self
.inputs
.iter()
.zip(results)
.map(|(input, result)| match result {
SortOrderPushdownResult::Inexact { inner } => {
any_inexact = true;
inner
}
_ => Arc::clone(input),
})
.collect();
if !any_inexact {
return Ok(SortOrderPushdownResult::Unsupported);
}
Ok(SortOrderPushdownResult::Inexact {
inner: UnionExec::try_new(inputs)?,
})
```
<details>
<summary>Full slt repro (passes on main, fails on this branch)</summary>
```
statement ok
SET datafusion.execution.target_partitions = 1;
statement ok
SET datafusion.execution.parquet.enable_exact_reverse_scan = true;
query I
COPY (SELECT value AS id, repeat('x', 200) AS payload FROM
generate_series(1, 200000) ORDER BY id)
TO 'test_files/scratch/union_mem/big/data.parquet';
----
200000
query I
COPY (SELECT value AS id, repeat('y', 10) AS payload FROM generate_series(1,
10) ORDER BY id)
TO 'test_files/scratch/union_mem/small/data.parquet';
----
10
statement ok
CREATE EXTERNAL TABLE big(id BIGINT, payload VARCHAR) STORED AS PARQUET
LOCATION 'test_files/scratch/union_mem/big/' WITH ORDER (id ASC);
statement ok
CREATE EXTERNAL TABLE small(id BIGINT, payload VARCHAR) STORED AS PARQUET
LOCATION 'test_files/scratch/union_mem/small/';
statement ok
SET datafusion.runtime.memory_limit = '4M';
query II
SELECT id, length(payload) FROM (SELECT * FROM big UNION ALL SELECT * FROM
small WHERE payload <> 'z')
ORDER BY id DESC LIMIT 3;
----
200000 200
199999 200
199998 200
```
</details>
##########
datafusion/core/tests/physical_optimizer/pushdown_sort.rs:
##########
@@ -1555,3 +1555,156 @@ async fn
test_sort_pushdown_exact_partitioned_fetch_through_projection_returns_t
assert_batches_eq!(expected, &batches);
Ok(())
}
+
+// ============================================================================
+// UNION TESTS
+// ============================================================================
+
+#[test]
+fn test_sort_pushdown_through_union_exact() {
+ // Every input of the union is exact, so the per-partition sort is removed
+ // and the merge above the union combines the inputs.
+ let schema = schema();
+ let a = sort_expr("a", &schema);
+ let union = union_exec(vec![
+ Arc::new(TestScan::new(schema.clone(),
vec![]).with_exact_pushdown(true)),
+ Arc::new(TestScan::new(schema.clone(),
vec![]).with_exact_pushdown(true)),
+ ]);
+ let ordering = LexOrdering::new(vec![a.reverse()]).unwrap();
+ let sort =
+ sort_exec_with_fetch_and_preserve_partitioning(ordering.clone(),
Some(10), union);
+ let plan = sort_preserving_merge_exec_with_fetch(ordering, sort, 10);
+
+ insta::assert_snapshot!(
+ OptimizationTest::new(plan, PushdownSort::new(), true),
+ @r"
+ OptimizationTest:
+ input:
+ - SortPreservingMergeExec: [a@0 DESC NULLS LAST], fetch=10
+ - SortExec: TopK(fetch=10), expr=[a@0 DESC NULLS LAST],
preserve_partitioning=[true]
+ - UnionExec
+ - TestScan
+ - TestScan
+ output:
+ Ok:
+ - SortPreservingMergeExec: [a@0 DESC NULLS LAST], fetch=10
+ - BufferExec: capacity=1073741824
+ - UnionExec
+ - GlobalLimitExec: skip=0, fetch=10
+ - TestScan: requested_ordering=[a@0 DESC NULLS LAST]
+ - GlobalLimitExec: skip=0, fetch=10
+ - TestScan: requested_ordering=[a@0 DESC NULLS LAST]
+ "
+ );
+}
+
+#[test]
+fn test_sort_pushdown_through_union_inexact_input_keeps_sort() {
+ // One input is only inexact, so the sort stays, over the rewritten inputs.
+ let schema = schema();
+ let a = sort_expr("a", &schema);
+ let union = union_exec(vec![
+ Arc::new(TestScan::new(schema.clone(),
vec![]).with_exact_pushdown(true)),
+ Arc::new(TestScan::new(schema.clone(), vec![])),
+ ]);
+ let ordering = LexOrdering::new(vec![a.reverse()]).unwrap();
+ let sort =
+ sort_exec_with_fetch_and_preserve_partitioning(ordering.clone(),
Some(10), union);
+ let plan = sort_preserving_merge_exec_with_fetch(ordering, sort, 10);
+
+ insta::assert_snapshot!(
+ OptimizationTest::new(plan, PushdownSort::new(), true),
+ @r"
+ OptimizationTest:
+ input:
+ - SortPreservingMergeExec: [a@0 DESC NULLS LAST], fetch=10
+ - SortExec: TopK(fetch=10), expr=[a@0 DESC NULLS LAST],
preserve_partitioning=[true]
+ - UnionExec
+ - TestScan
+ - TestScan
+ output:
+ Ok:
+ - SortPreservingMergeExec: [a@0 DESC NULLS LAST], fetch=10
+ - SortExec: TopK(fetch=10), expr=[a@0 DESC NULLS LAST],
preserve_partitioning=[true]
+ - UnionExec
+ - TestScan: requested_ordering=[a@0 DESC NULLS LAST]
+ - TestScan: requested_ordering=[a@0 DESC NULLS LAST]
+ "
+ );
+}
+
+#[test]
+fn test_sort_pushdown_through_union_unsupported_input_keeps_sort() {
+ // A `FilterExec` input can't take the ordering, so it is kept as is and
+ // the sort stays.
+ let schema = schema();
+ let a = sort_expr("a", &schema);
+ let union = union_exec(vec![
+ Arc::new(TestScan::new(schema.clone(),
vec![]).with_exact_pushdown(true)),
+ filter_exec(expressions::lit(true), parquet_exec(schema.clone())),
+ ]);
+ let ordering = LexOrdering::new(vec![a.reverse()]).unwrap();
+ let sort =
+ sort_exec_with_fetch_and_preserve_partitioning(ordering.clone(),
Some(10), union);
+ let plan = sort_preserving_merge_exec_with_fetch(ordering, sort, 10);
+
+ insta::assert_snapshot!(
+ OptimizationTest::new(plan, PushdownSort::new(), true),
+ @r"
+ OptimizationTest:
+ input:
+ - SortPreservingMergeExec: [a@0 DESC NULLS LAST], fetch=10
+ - SortExec: TopK(fetch=10), expr=[a@0 DESC NULLS LAST],
preserve_partitioning=[true]
+ - UnionExec
+ - TestScan
+ - FilterExec: true
+ - DataSourceExec: file_groups={1 group: [[x]]}, projection=[a,
b, c, d, e], file_type=parquet
+ output:
+ Ok:
+ - SortPreservingMergeExec: [a@0 DESC NULLS LAST], fetch=10
+ - SortExec: TopK(fetch=10), expr=[a@0 DESC NULLS LAST],
preserve_partitioning=[true]
+ - UnionExec
+ - TestScan: requested_ordering=[a@0 DESC NULLS LAST]
+ - FilterExec: true
+ - DataSourceExec: file_groups={1 group: [[x]]},
projection=[a, b, c, d, e], file_type=parquet
+ "
+ );
+}
+
+#[test]
+fn test_sort_pushdown_through_union_all_unsupported_unchanged() {
Review Comment:
Optional cleanup: this test runs under a `SortPreservingMergeExec`, where
removing the all-`Unsupported` early return in `UnionExec::try_pushdown_sort`
gives the same plan, so nothing covers that return. A standalone TopK covers
it: without the early return, `PushdownSort` adds a `SortPreservingMergeExec`
above it.
```rs
#[test]
fn
test_sort_pushdown_through_union_all_unsupported_standalone_topk_unchanged() {
let schema = schema();
let a = sort_expr("a", &schema);
let union = union_exec(vec![
filter_exec(expressions::lit(true), parquet_exec(schema.clone())),
filter_exec(expressions::lit(true), parquet_exec(schema)),
]);
let ordering = LexOrdering::new(vec![a.reverse()]).unwrap();
let plan = sort_exec_with_fetch_and_preserve_partitioning(ordering,
Some(10), union);
insta::assert_snapshot!(
OptimizationTest::new(plan, PushdownSort::new(), true),
@r"
OptimizationTest:
input:
- SortExec: TopK(fetch=10), expr=[a@0 DESC NULLS LAST],
preserve_partitioning=[true]
- UnionExec
- FilterExec: true
- DataSourceExec: file_groups={1 group: [[x]]}, projection=[a,
b, c, d, e], file_type=parquet
- FilterExec: true
- DataSourceExec: file_groups={1 group: [[x]]}, projection=[a,
b, c, d, e], file_type=parquet
output:
Ok:
- SortExec: TopK(fetch=10), expr=[a@0 DESC NULLS LAST],
preserve_partitioning=[true]
- UnionExec
- FilterExec: true
- DataSourceExec: file_groups={1 group: [[x]]},
projection=[a, b, c, d, e], file_type=parquet
- FilterExec: true
- DataSourceExec: file_groups={1 group: [[x]]},
projection=[a, b, c, d, e], file_type=parquet
"
);
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]