From fa382ac13126390b030e5a3464eb2e12c5a31ee8 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:20:06 -0800 Subject: [PATCH] fix: declare the input ordering that PartialSortExec requires The operator sorts each run of equal prefix values, so it returns wrong rows if its input is not sorted by the prefix. Without the declaration, the optimizer rules and SanityCheckPlan cannot see that. Co-Authored-By: Claude Opus 5.5 --- .../physical-plan/src/sorts/partial_sort.rs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/datafusion/physical-plan/src/sorts/partial_sort.rs b/datafusion/physical-plan/src/sorts/partial_sort.rs index 86b4b771162c0..5eef56c6926ac 100644 --- a/datafusion/physical-plan/src/sorts/partial_sort.rs +++ b/datafusion/physical-plan/src/sorts/partial_sort.rs @@ -65,6 +65,7 @@ use datafusion_common::tree_node::TreeNodeRecursion; use datafusion_common::utils::evaluate_partition_ranges; use datafusion_execution::{RecordBatchStream, TaskContext}; use datafusion_physical_expr::{LexOrdering, PhysicalExpr}; +use datafusion_physical_expr_common::sort_expr::OrderingRequirements; use futures::{Stream, StreamExt, ready}; use log::trace; @@ -358,6 +359,11 @@ impl ExecutionPlan for PartialSortExec { }) } + fn required_input_ordering(&self) -> Vec> { + let prefix = self.expr[..self.common_prefix_length].to_vec(); + vec![LexOrdering::new(prefix).map(OrderingRequirements::from)] + } + fn benefits_from_input_partitioning(&self) -> Vec { vec![false] } @@ -1188,6 +1194,21 @@ mod tests { .unwrap() as Arc } + #[test] + fn requires_common_prefix_ordering() { + let expr = [("a", 0), ("b", 1)].map(|(name, i)| { + PhysicalSortExpr::new_default(Arc::new(crate::expressions::Column::new( + name, i, + )) as _) + }); + let first = LexOrdering::from([expr[0].clone()]); + let plan = PartialSortExec::new(expr.into(), prepare_partitioned_input(), 1); + assert_eq!( + plan.required_input_ordering(), + vec![Some(OrderingRequirements::from(first))] + ); + } + #[tokio::test] async fn test_partitioned_input_partial_sort() -> Result<()> { let task_ctx = Arc::new(TaskContext::default());