You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "geoffreyclaude (via GitHub)" <gi...@apache.org> on 2025/04/03 14:59:46 UTC
[PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input [datafusion]
geoffreyclaude opened a new pull request, #15563:
URL: https://github.com/apache/datafusion/pull/15563
## Which issue does this PR close?
- Closes #15529.
## 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.
-->
## 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.
-->
## 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)?
-->
## 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.
-->
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2029892886
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -681,4 +793,98 @@ mod tests {
record_batch_store.unuse(0);
assert_eq!(record_batch_store.batches_size, 0);
}
+
+ /// This test validates that the `try_finish` method marks the TopK operator as finished
+ /// when the prefix (on column "a") of the last row in the current batch is strictly greater
+ /// than the worst topβk row.
+ /// The full sort expression is defined on both columns ("a", "b"), but the input ordering is only on "a".
+ #[tokio::test]
+ async fn test_try_finish_marks_finished_with_prefix() -> Result<()> {
+ // Create a schema with two columns.
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("a", DataType::Int32, false),
+ Field::new("b", DataType::Float64, false),
+ ]));
+
+ // Create sort expressions.
+ // Full sort: first by "a", then by "b".
+ let sort_expr_a = PhysicalSortExpr {
+ expr: col("a", schema.as_ref())?,
+ options: SortOptions::default(),
+ };
+ let sort_expr_b = PhysicalSortExpr {
+ expr: col("b", schema.as_ref())?,
+ options: SortOptions::default(),
+ };
+
+ // Input ordering uses only column "a" (a prefix of the full sort).
+ let input_ordering = LexOrdering::from(vec![sort_expr_a.clone()]);
+ let full_expr = LexOrdering::from(vec![sort_expr_a, sort_expr_b]);
+
+ // Create a dummy runtime environment and metrics.
+ let runtime = Arc::new(RuntimeEnv::default());
+ let metrics = ExecutionPlanMetricsSet::new();
+
+ // Create a TopK instance with k = 3 and batch_size = 2.
+ let mut topk = TopK::try_new(
+ 0,
+ Arc::clone(&schema),
+ input_ordering,
+ full_expr,
+ 3,
+ 2,
+ runtime,
+ &metrics,
+ )?;
+
+ // Create the first batch with two columns:
+ // Column "a": [1, 1, 2], Column "b": [10.0, 20.0, 10.0].
Review Comment:
Nice catch, I had updated the `b` in the comment but not in the code... I think what we really want is the "comment" data:
```
First batch:
a | b
---+---
1 | 10.0
1 | 20.0
2 | 10.0
Second batch:
a | b
---+---
2 | 30.0
3 | 10.0
```
Like that in the top3 we get the first two rows from the first batch and the third row from the second batch. wdyt?
I can also swap the first two rows of the first batch to enforce sorting as you suggested: `(1,20.0), (1, 10.0), (2, 10.0)`
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2033192038
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -1066,22 +1071,33 @@ impl SortExec {
}
/// This function creates the cache object that stores the plan properties such as schema, equivalence properties, ordering, partitioning, etc.
+ /// It also returns the common sort prefix between the input and the sort expressions.
fn compute_properties(
input: &Arc<dyn ExecutionPlan>,
sort_exprs: LexOrdering,
preserve_partitioning: bool,
- ) -> PlanProperties {
+ ) -> (PlanProperties, LexOrdering) {
// Determine execution mode:
let requirement = LexRequirement::from(sort_exprs);
- let sort_satisfied = input
+
+ let (sort_prefix, sort_satisfied) = input
.equivalence_properties()
- .ordering_satisfy_requirement(&requirement);
+ .extract_matching_prefix(&requirement);
+
+ let sort_partially_satisfied = sort_satisfied || !sort_prefix.is_empty();
// The emission type depends on whether the input is already sorted:
- // - If already sorted, we can emit results in the same way as the input
+ // - If already fully sorted, we can emit results in the same way as the input
+ // - If partially sorted, we might be able to emit results incrementally, but it is not guaranteed (Both)
// - If not sorted, we must wait until all data is processed to emit results (Final)
let emission_type = if sort_satisfied {
input.pipeline_behavior()
+ } else if sort_partially_satisfied {
+ if input.pipeline_behavior() == EmissionType::Incremental {
+ EmissionType::Both
Review Comment:
That risk is always there. For example aggregation groups might never close, but we don't mark it as "Both".
Both is currently used for Joins, when there is an exact accumulation inside of the operator, and that accumulated data can only be output when the input is consumed
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2033193030
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -1066,22 +1071,33 @@ impl SortExec {
}
/// This function creates the cache object that stores the plan properties such as schema, equivalence properties, ordering, partitioning, etc.
+ /// It also returns the common sort prefix between the input and the sort expressions.
fn compute_properties(
input: &Arc<dyn ExecutionPlan>,
sort_exprs: LexOrdering,
preserve_partitioning: bool,
- ) -> PlanProperties {
+ ) -> (PlanProperties, LexOrdering) {
// Determine execution mode:
let requirement = LexRequirement::from(sort_exprs);
- let sort_satisfied = input
+
+ let (sort_prefix, sort_satisfied) = input
.equivalence_properties()
- .ordering_satisfy_requirement(&requirement);
+ .extract_matching_prefix(&requirement);
+
+ let sort_partially_satisfied = sort_satisfied || !sort_prefix.is_empty();
// The emission type depends on whether the input is already sorted:
- // - If already sorted, we can emit results in the same way as the input
+ // - If already fully sorted, we can emit results in the same way as the input
+ // - If partially sorted, we might be able to emit results incrementally, but it is not guaranteed (Both)
// - If not sorted, we must wait until all data is processed to emit results (Final)
let emission_type = if sort_satisfied {
input.pipeline_behavior()
+ } else if sort_partially_satisfied {
+ if input.pipeline_behavior() == EmissionType::Incremental {
+ EmissionType::Both
Review Comment:
But maybe those should be Both as well. Let me think on that a bit π
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2033512360
##########
datafusion/physical-expr/src/equivalence/properties/mod.rs:
##########
@@ -575,10 +576,35 @@ impl EquivalenceProperties {
// From the analysis above, we know that `[a ASC]` is satisfied. Then,
// we add column `a` as constant to the algorithm state. This enables us
// to deduce that `(b + c) ASC` is satisfied, given `a` is constant.
- eq_properties = eq_properties
- .with_constants(std::iter::once(ConstExpr::from(normalized_req.expr)));
+ eq_properties = eq_properties.with_constants(std::iter::once(
+ ConstExpr::from(Arc::clone(&normalized_req.expr)),
+ ));
}
- true
+
+ // All requirements are satisfied.
+ normalized_reqs.len()
+ }
+
+ /// Determines the longest prefix of `reqs` that is satisfied by the existing ordering.
+ /// Returns that prefix as a new `LexRequirement`, and a boolean indicating if all the requirements are satisfied.
+ pub fn extract_matching_prefix(
+ &self,
+ reqs: &LexRequirement,
+ ) -> (LexRequirement, bool) {
Review Comment:
```
SortExec: [expr: [a,b]]
--FilterExec: [a=x] // x normalizes to a
----ScanExec: [... output_ordering: [x,c]]
```
While SortExec deciding its common_prefix_count, it has an input equivalence properties:
equivalent column: [a,x]
ordering: [x,c]
So, the normalization is not lost actually, but we need to make a reverse requirement-satisfy check.
I don't think this is a blocker for this PR, I'm just keeping on to achieve a flawless structure. Because keeping more input dependent fields in an operator brings more trouble while keeping things in-sync as I've experienced so far.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "gabotechs (via GitHub)" <gi...@apache.org>.
gabotechs commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2030623674
##########
datafusion/physical-expr/src/equivalence/properties/mod.rs:
##########
@@ -575,10 +576,35 @@ impl EquivalenceProperties {
// From the analysis above, we know that `[a ASC]` is satisfied. Then,
// we add column `a` as constant to the algorithm state. This enables us
// to deduce that `(b + c) ASC` is satisfied, given `a` is constant.
- eq_properties = eq_properties
- .with_constants(std::iter::once(ConstExpr::from(normalized_req.expr)));
+ eq_properties = eq_properties.with_constants(std::iter::once(
+ ConstExpr::from(Arc::clone(&normalized_req.expr)),
+ ));
}
- true
+
+ // All requirements are satisfied.
+ normalized_reqs.len()
+ }
+
+ /// Determines the longest prefix of `reqs` that is satisfied by the existing ordering.
+ /// Returns that prefix as a new `LexRequirement`, and a boolean indicating if all the requirements are satisfied.
+ pub fn extract_matching_prefix(
+ &self,
+ reqs: &LexRequirement,
+ ) -> (LexRequirement, bool) {
+ // First, standardize the given requirement:
+ let normalized_reqs = self.normalize_sort_requirements(reqs);
Review Comment:
I imagine that this will normalize cases where columns get aliased, duplicate sort expressions, etc. But would this normalize cases where expressions that do not alter the order are applied to columns? For example, would `[int_column+1 DESC, int_column DESC]` be normalized to `[int_column DESC]`? if that's the case, maybe adding a sql logic test that verifies that the common sort prefix takes this into account?
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "NGA-TRAN (via GitHub)" <gi...@apache.org>.
NGA-TRAN commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2031191811
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -681,4 +797,98 @@ mod tests {
record_batch_store.unuse(0);
assert_eq!(record_batch_store.batches_size, 0);
}
+
+ /// This test validates that the `try_finish` method marks the TopK operator as finished
+ /// when the prefix (on column "a") of the last row in the current batch is strictly greater
+ /// than the worst topβk row.
+ /// The full sort expression is defined on both columns ("a", "b"), but the input ordering is only on "a".
+ #[tokio::test]
+ async fn test_try_finish_marks_finished_with_prefix() -> Result<()> {
+ // Create a schema with two columns.
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("a", DataType::Int32, false),
+ Field::new("b", DataType::Float64, false),
+ ]));
+
+ // Create sort expressions.
+ // Full sort: first by "a", then by "b".
+ let sort_expr_a = PhysicalSortExpr {
+ expr: col("a", schema.as_ref())?,
+ options: SortOptions::default(),
+ };
+ let sort_expr_b = PhysicalSortExpr {
+ expr: col("b", schema.as_ref())?,
+ options: SortOptions::default(),
+ };
+
+ // Input ordering uses only column "a" (a prefix of the full sort).
+ let input_ordering = LexOrdering::from(vec![sort_expr_a.clone()]);
+ let full_expr = LexOrdering::from(vec![sort_expr_a, sort_expr_b]);
+
+ // Create a dummy runtime environment and metrics.
+ let runtime = Arc::new(RuntimeEnv::default());
+ let metrics = ExecutionPlanMetricsSet::new();
+
+ // Create a TopK instance with k = 3 and batch_size = 2.
+ let mut topk = TopK::try_new(
+ 0,
+ Arc::clone(&schema),
+ input_ordering,
+ full_expr,
+ 3,
+ 2,
+ runtime,
+ &metrics,
+ )?;
+
+ // Create the first batch with two columns:
+ // Column "a": [1, 1, 2], Column "b": [20.0, 15.0, 30.0].
+ let array_a1: ArrayRef =
+ Arc::new(Int32Array::from(vec![Some(1), Some(1), Some(2)]));
+ let array_b1: ArrayRef = Arc::new(Float64Array::from(vec![20.0, 15.0, 30.0]));
+ let batch1 = RecordBatch::try_new(Arc::clone(&schema), vec![array_a1, array_b1])?;
+
+ // Insert the first batch.
+ // At this point the heap is not yet βfinishedβ because the prefix of the last row of the batch
+ // is not strictly greater than the prefix of the worst topβk row (both being `2`).
+ topk.insert_batch(batch1)?;
+ assert!(
+ !topk.finished,
+ "Expected 'finished' to be false after the first batch."
+ );
+
+ // Create the second batch with two columns:
+ // Column "a": [2, 3], Column "b": [10.0, 20.0].
+ let array_a2: ArrayRef = Arc::new(Int32Array::from(vec![Some(2), Some(3)]));
+ let array_b2: ArrayRef = Arc::new(Float64Array::from(vec![10.0, 20.0]));
+ let batch2 = RecordBatch::try_new(Arc::clone(&schema), vec![array_a2, array_b2])?;
+
+ // Insert the second batch.
+ // The last row in this batch has a prefix value of `3`,
+ // which is strictly greater than the worst topβk row (with value `2`),
+ // so try_finish should mark the TopK as finished.
+ topk.insert_batch(batch2)?;
+ assert!(
+ topk.finished,
+ "Expected 'finished' to be true after the second batch."
+ );
+
+ // Verify the TopK correctly emits the top k rows from both batches
+ // (the value 10.0 for b is from the second batch).
+ let results: Vec<_> = topk.emit()?.try_collect().await?;
+ assert_batches_eq!(
+ &[
+ "+---+------+",
+ "| a | b |",
+ "+---+------+",
+ "| 1 | 15.0 |",
+ "| 1 | 20.0 |",
+ "| 2 | 10.0 |",
+ "+---+------+",
Review Comment:
π
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -681,4 +797,98 @@ mod tests {
record_batch_store.unuse(0);
assert_eq!(record_batch_store.batches_size, 0);
}
+
+ /// This test validates that the `try_finish` method marks the TopK operator as finished
+ /// when the prefix (on column "a") of the last row in the current batch is strictly greater
+ /// than the worst topβk row.
+ /// The full sort expression is defined on both columns ("a", "b"), but the input ordering is only on "a".
+ #[tokio::test]
+ async fn test_try_finish_marks_finished_with_prefix() -> Result<()> {
+ // Create a schema with two columns.
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("a", DataType::Int32, false),
+ Field::new("b", DataType::Float64, false),
+ ]));
+
+ // Create sort expressions.
+ // Full sort: first by "a", then by "b".
+ let sort_expr_a = PhysicalSortExpr {
+ expr: col("a", schema.as_ref())?,
+ options: SortOptions::default(),
+ };
+ let sort_expr_b = PhysicalSortExpr {
+ expr: col("b", schema.as_ref())?,
+ options: SortOptions::default(),
+ };
+
+ // Input ordering uses only column "a" (a prefix of the full sort).
+ let input_ordering = LexOrdering::from(vec![sort_expr_a.clone()]);
+ let full_expr = LexOrdering::from(vec![sort_expr_a, sort_expr_b]);
+
+ // Create a dummy runtime environment and metrics.
+ let runtime = Arc::new(RuntimeEnv::default());
+ let metrics = ExecutionPlanMetricsSet::new();
+
+ // Create a TopK instance with k = 3 and batch_size = 2.
+ let mut topk = TopK::try_new(
+ 0,
+ Arc::clone(&schema),
+ input_ordering,
+ full_expr,
+ 3,
+ 2,
+ runtime,
+ &metrics,
+ )?;
+
+ // Create the first batch with two columns:
+ // Column "a": [1, 1, 2], Column "b": [20.0, 15.0, 30.0].
+ let array_a1: ArrayRef =
+ Arc::new(Int32Array::from(vec![Some(1), Some(1), Some(2)]));
+ let array_b1: ArrayRef = Arc::new(Float64Array::from(vec![20.0, 15.0, 30.0]));
Review Comment:
Nice test to cover both general and corner cases
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -681,4 +797,98 @@ mod tests {
record_batch_store.unuse(0);
assert_eq!(record_batch_store.batches_size, 0);
}
+
+ /// This test validates that the `try_finish` method marks the TopK operator as finished
+ /// when the prefix (on column "a") of the last row in the current batch is strictly greater
+ /// than the worst topβk row.
+ /// The full sort expression is defined on both columns ("a", "b"), but the input ordering is only on "a".
+ #[tokio::test]
+ async fn test_try_finish_marks_finished_with_prefix() -> Result<()> {
+ // Create a schema with two columns.
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("a", DataType::Int32, false),
+ Field::new("b", DataType::Float64, false),
+ ]));
+
+ // Create sort expressions.
+ // Full sort: first by "a", then by "b".
+ let sort_expr_a = PhysicalSortExpr {
+ expr: col("a", schema.as_ref())?,
+ options: SortOptions::default(),
+ };
+ let sort_expr_b = PhysicalSortExpr {
+ expr: col("b", schema.as_ref())?,
+ options: SortOptions::default(),
+ };
+
+ // Input ordering uses only column "a" (a prefix of the full sort).
+ let input_ordering = LexOrdering::from(vec![sort_expr_a.clone()]);
+ let full_expr = LexOrdering::from(vec![sort_expr_a, sort_expr_b]);
+
+ // Create a dummy runtime environment and metrics.
+ let runtime = Arc::new(RuntimeEnv::default());
+ let metrics = ExecutionPlanMetricsSet::new();
+
+ // Create a TopK instance with k = 3 and batch_size = 2.
+ let mut topk = TopK::try_new(
+ 0,
+ Arc::clone(&schema),
+ input_ordering,
+ full_expr,
+ 3,
+ 2,
+ runtime,
+ &metrics,
+ )?;
+
+ // Create the first batch with two columns:
+ // Column "a": [1, 1, 2], Column "b": [20.0, 15.0, 30.0].
+ let array_a1: ArrayRef =
+ Arc::new(Int32Array::from(vec![Some(1), Some(1), Some(2)]));
+ let array_b1: ArrayRef = Arc::new(Float64Array::from(vec![20.0, 15.0, 30.0]));
+ let batch1 = RecordBatch::try_new(Arc::clone(&schema), vec![array_a1, array_b1])?;
+
+ // Insert the first batch.
+ // At this point the heap is not yet βfinishedβ because the prefix of the last row of the batch
+ // is not strictly greater than the prefix of the worst topβk row (both being `2`).
+ topk.insert_batch(batch1)?;
+ assert!(
+ !topk.finished,
+ "Expected 'finished' to be false after the first batch."
+ );
+
+ // Create the second batch with two columns:
+ // Column "a": [2, 3], Column "b": [10.0, 20.0].
+ let array_a2: ArrayRef = Arc::new(Int32Array::from(vec![Some(2), Some(3)]));
+ let array_b2: ArrayRef = Arc::new(Float64Array::from(vec![10.0, 20.0]));
Review Comment:
π
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2031201913
##########
datafusion/sqllogictest/test_files/topk.slt:
##########
@@ -233,3 +233,104 @@ d 1 -98 y7C453hRWd4E7ImjNDWlpexB8nUqjh y7C453hRWd4E7ImjNDWlpexB8nUqjh
e 2 52 xipQ93429ksjNcXPX5326VSg1xJZcW xipQ93429ksjNcXPX5326VSg1xJZcW
d 1 -72 wwXqSGKLyBQyPkonlzBNYUJTCo4LRS wwXqSGKLyBQyPkonlzBNYUJTCo4LRS
a 1 -5 waIGbOGl1PM6gnzZ4uuZt4E2yDWRHs waIGbOGl1PM6gnzZ4uuZt4E2yDWRHs
+
+#####################################
+## Test TopK with Partially Sorted Inputs
+#####################################
+
+
+# Create an external table where data is pre-sorted by (column1 DESC, column2 ASC) only.
+statement ok
+CREATE EXTERNAL TABLE partial_sorted (
+ column1 VARCHAR,
+ column2 INT,
+ column3 INT
+)
+STORED AS parquet
+LOCATION 'test_files/scratch/topk/partial_sorted/1.parquet'
+WITH ORDER (column1 DESC, column2 ASC);
+
+# Insert test data into the external table.
+query I
+COPY (VALUES
Review Comment:
I've set the batch size to 2 and am now inserting from a `ORDER BY` query:
```sql
# Insert test data into the external table.
query I
COPY (
SELECT *
FROM (
VALUES
(1, 'F', 100),
(1, 'B', 50),
(2, 'C', 70),
(2, 'D', 80),
(3, 'A', 60),
(3, 'E', 90)
) AS t(number, letter, age)
ORDER BY number DESC, letter ASC
)
TO 'test_files/scratch/topk/partial_sorted/1.parquet';
----
6
```
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2033541557
##########
datafusion/physical-expr/src/equivalence/properties/mod.rs:
##########
@@ -575,10 +576,35 @@ impl EquivalenceProperties {
// From the analysis above, we know that `[a ASC]` is satisfied. Then,
// we add column `a` as constant to the algorithm state. This enables us
// to deduce that `(b + c) ASC` is satisfied, given `a` is constant.
- eq_properties = eq_properties
- .with_constants(std::iter::once(ConstExpr::from(normalized_req.expr)));
+ eq_properties = eq_properties.with_constants(std::iter::once(
+ ConstExpr::from(Arc::clone(&normalized_req.expr)),
+ ));
}
- true
+
+ // All requirements are satisfied.
+ normalized_reqs.len()
+ }
+
+ /// Determines the longest prefix of `reqs` that is satisfied by the existing ordering.
+ /// Returns that prefix as a new `LexRequirement`, and a boolean indicating if all the requirements are satisfied.
+ pub fn extract_matching_prefix(
+ &self,
+ reqs: &LexRequirement,
+ ) -> (LexRequirement, bool) {
Review Comment:
Are you suggesting recomputing the normalized prefix for each pass inside `attempt_early_completion`? Or using the un-normalized prefix instead (which might result in longer bytes arrays to compare, if there were redundant columns in the sort expression)?
I totally agree that storing only the count of common sort expressions would be cleaner, but I don't see how to do that without additional compute cost...
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#issuecomment-2788680550
> @geoffreyclaude I'm going to merge if you're done with this?
@berkaysynnada: Fine by me! We resolved the (unfortunately, necessary) semi-redundant common prefix field.
Only remaining question is the Emission type: if it makes sense to leave it as `Both` you can merge, but if you think `Incremental` makes more sense I can do a quick new commit to change it.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#issuecomment-2789196357
> I think it's ready to go now?
All ready :) I need to look at PartialSortExec, I wasn't aware of it and it seems like there could be some code duplication?
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2030903888
##########
datafusion/physical-expr/src/equivalence/properties/mod.rs:
##########
@@ -575,10 +576,35 @@ impl EquivalenceProperties {
// From the analysis above, we know that `[a ASC]` is satisfied. Then,
// we add column `a` as constant to the algorithm state. This enables us
// to deduce that `(b + c) ASC` is satisfied, given `a` is constant.
- eq_properties = eq_properties
- .with_constants(std::iter::once(ConstExpr::from(normalized_req.expr)));
+ eq_properties = eq_properties.with_constants(std::iter::once(
+ ConstExpr::from(Arc::clone(&normalized_req.expr)),
+ ));
}
- true
+
+ // All requirements are satisfied.
+ normalized_reqs.len()
+ }
+
+ /// Determines the longest prefix of `reqs` that is satisfied by the existing ordering.
+ /// Returns that prefix as a new `LexRequirement`, and a boolean indicating if all the requirements are satisfied.
+ pub fn extract_matching_prefix(
+ &self,
+ reqs: &LexRequirement,
+ ) -> (LexRequirement, bool) {
Review Comment:
Same comment as above, I'm afraid we lose the normalization work if we do this.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2031142700
##########
datafusion/physical-expr/src/equivalence/properties/mod.rs:
##########
@@ -575,10 +576,35 @@ impl EquivalenceProperties {
// From the analysis above, we know that `[a ASC]` is satisfied. Then,
// we add column `a` as constant to the algorithm state. This enables us
// to deduce that `(b + c) ASC` is satisfied, given `a` is constant.
- eq_properties = eq_properties
- .with_constants(std::iter::once(ConstExpr::from(normalized_req.expr)));
+ eq_properties = eq_properties.with_constants(std::iter::once(
+ ConstExpr::from(Arc::clone(&normalized_req.expr)),
+ ));
}
- true
+
+ // All requirements are satisfied.
+ normalized_reqs.len()
+ }
+
+ /// Determines the longest prefix of `reqs` that is satisfied by the existing ordering.
+ /// Returns that prefix as a new `LexRequirement`, and a boolean indicating if all the requirements are satisfied.
+ pub fn extract_matching_prefix(
+ &self,
+ reqs: &LexRequirement,
+ ) -> (LexRequirement, bool) {
+ // First, standardize the given requirement:
+ let normalized_reqs = self.normalize_sort_requirements(reqs);
Review Comment:
=> new test added:
```sql
explain select column1 + 1 as column1_plus, column1, column1 + 1 as other_column1_plus, column3 from partial_sorted order by column1_plus desc, column1 desc, other_column1_plus desc, column3 asc limit 3;
```
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#issuecomment-2788800050
> > Let's make it incremental for consistency.
>
> @berkaysynnada: Looking at this again, I'm pretty sure it should actually be `Final`! On partially sorted input, with or without fetch, the SortExec will only emit once it has processed all its necessary input data (eventually cancelling the input stream early). I've updated the PR with a new fix commit.
PartiallySorted case is actually the same of AggregateExec with an ordered group_by key. Final means the operator can only emit results after its inputs are fully consumed.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2031164505
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -183,6 +208,86 @@ impl TopK {
// update memory reservation
self.reservation.try_resize(self.size())?;
+
+ // flag the topK as finished if we know that all
+ // subsequent batches are guaranteed to be worse than the
+ // current topK
+ self.attempt_early_completion(&batch)?;
+
+ Ok(())
+ }
+
+ /// If input ordering shares a common sort prefix with the TopK, and if the TopK's heap is full,
+ /// check if the computation can be finished early.
+ /// This is the case if the last row of the current batch is strictly worse than the worst row in the heap,
+ /// comparing only on the shared prefix columns.
+ fn attempt_early_completion(&mut self, batch: &RecordBatch) -> Result<()> {
+ // Early exit if the batch is empty as there is no last row to extract from it.
+ if batch.num_rows() == 0 {
+ return Ok(());
+ }
+
+ // prefix_row_converter is only `Some` if the input ordering has a common prefix with the TopK,
+ // so early exit if it is `None`.
+ let prefix_converter = match &self.common_prefix_converter {
+ Some(pc) => pc,
+ None => return Ok(()),
+ };
+
+ // Early exit if the heap is not full (`heap.max()` only returns `Some` if the heap is full).
+ let worst_topk_row = match self.heap.max() {
+ Some(row) => row,
+ None => return Ok(()),
+ };
Review Comment:
β³
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2034706901
##########
datafusion/physical-expr/src/equivalence/properties/mod.rs:
##########
@@ -575,10 +576,35 @@ impl EquivalenceProperties {
// From the analysis above, we know that `[a ASC]` is satisfied. Then,
// we add column `a` as constant to the algorithm state. This enables us
// to deduce that `(b + c) ASC` is satisfied, given `a` is constant.
- eq_properties = eq_properties
- .with_constants(std::iter::once(ConstExpr::from(normalized_req.expr)));
+ eq_properties = eq_properties.with_constants(std::iter::once(
+ ConstExpr::from(Arc::clone(&normalized_req.expr)),
+ ));
}
- true
+
+ // All requirements are satisfied.
+ normalized_reqs.len()
+ }
+
+ /// Determines the longest prefix of `reqs` that is satisfied by the existing ordering.
+ /// Returns that prefix as a new `LexRequirement`, and a boolean indicating if all the requirements are satisfied.
+ pub fn extract_matching_prefix(
+ &self,
+ reqs: &LexRequirement,
+ ) -> (LexRequirement, bool) {
Review Comment:
Too bad, I was hoping I was missing something simple... I really liked your proposal of keeping only the count! Well let's keep it for the TopK refactor then!
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#issuecomment-2789220850
> All ready :) I need to look at PartialSortExec, I wasn't aware of it and it seems like there could be some code duplication?
No need to keep this open anymore. If you see any possible improvements, we can work on those in the new PR's.
Thank you @geoffreyclaude, happy to collaborate with you.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2031163210
##########
datafusion/core/tests/physical_optimizer/enforce_sorting.rs:
##########
@@ -1652,7 +1652,7 @@ async fn test_remove_unnecessary_sort7() -> Result<()> {
) as Arc<dyn ExecutionPlan>;
let expected_input = [
- "SortExec: TopK(fetch=2), expr=[non_nullable_col@1 ASC], preserve_partitioning=[false]",
+ "SortExec: TopK(fetch=2), expr=[non_nullable_col@1 ASC], preserve_partitioning=[false], sort_prefix=[non_nullable_col@1 ASC]",
Review Comment:
Careful, the `expr` is unnormalized, the `sort_prefix` is normalized. I agree this is a bit confusing, but `normalized_common_sort_prefix` seems a bit too verbose. Any suggestions?
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2028543416
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -90,15 +90,38 @@ pub struct TopK {
scratch_rows: Rows,
/// stores the top k values and their sort key values, in order
heap: TopKHeap,
+ /// row converter, for common keys between the sort keys and the input ordering
+ common_prefix_converter: Option<RowConverter>,
+ /// Common sort prefix between the input and the sort expressions to allow early exit optimization
+ common_sort_prefix: Arc<[PhysicalSortExpr]>,
+ /// If true, indicates that all rows of subsequent batches are guaranteed to be worse than the top K
+ pub(crate) finished: bool,
+}
+
+fn build_sort_fields(
+ ordering: &LexOrdering,
+ schema: &SchemaRef,
+) -> Result<Vec<SortField>> {
+ ordering
+ .iter()
+ .map(|e| {
+ Ok(SortField::new_with_options(
+ e.expr.data_type(schema)?,
+ e.options,
+ ))
+ })
+ .collect::<Result<_>>()
}
impl TopK {
/// Create a new [`TopK`] that stores the top `k` values, as
/// defined by the sort expressions in `expr`.
// TODO: make a builder or some other nicer API
+ #[allow(clippy::too_many_arguments)]
Review Comment:
The `TopK` code could benefit from a refactoring for better readability. It's probably grown a bit too much out of it's original compact format... But leaving this out of the scope of this PR.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2030883289
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -1066,22 +1071,33 @@ impl SortExec {
}
/// This function creates the cache object that stores the plan properties such as schema, equivalence properties, ordering, partitioning, etc.
+ /// It also returns the common sort prefix between the input and the sort expressions.
fn compute_properties(
input: &Arc<dyn ExecutionPlan>,
sort_exprs: LexOrdering,
preserve_partitioning: bool,
- ) -> PlanProperties {
+ ) -> (PlanProperties, LexOrdering) {
// Determine execution mode:
let requirement = LexRequirement::from(sort_exprs);
- let sort_satisfied = input
+
+ let (sort_prefix, sort_satisfied) = input
.equivalence_properties()
- .ordering_satisfy_requirement(&requirement);
+ .extract_matching_prefix(&requirement);
+
+ let sort_partially_satisfied = sort_satisfied || !sort_prefix.is_empty();
// The emission type depends on whether the input is already sorted:
- // - If already sorted, we can emit results in the same way as the input
+ // - If already fully sorted, we can emit results in the same way as the input
+ // - If partially sorted, we might be able to emit results incrementally, but it is not guaranteed (Both)
// - If not sorted, we must wait until all data is processed to emit results (Final)
let emission_type = if sort_satisfied {
input.pipeline_behavior()
+ } else if sort_partially_satisfied {
+ if input.pipeline_behavior() == EmissionType::Incremental {
+ EmissionType::Both
Review Comment:
What if the common prefix never changes though? The operator will then accumulate and only emit once done.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#issuecomment-2782914604
π€: Benchmark completed
<details><summary>Details</summary>
<p>
```
Comparing HEAD and perf_partitioned_topk
--------------------
Benchmark clickbench_1.json
--------------------
ββββββββββββββββ³βββββββββββββ³ββββββββββββββββββββββββ³ββββββββββββββββ
β Query β HEAD β perf_partitioned_topk β Change β
β‘ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ©
β QQuery 0 β 0.55ms β 0.58ms β no change β
β QQuery 1 β 71.87ms β 67.67ms β +1.06x faster β
β QQuery 2 β 124.36ms β 119.37ms β no change β
β QQuery 3 β 127.85ms β 129.09ms β no change β
β QQuery 4 β 787.41ms β 801.05ms β no change β
β QQuery 5 β 1045.75ms β 1013.35ms β no change β
β QQuery 6 β 0.63ms β 0.63ms β no change β
β QQuery 7 β 85.09ms β 84.11ms β no change β
β QQuery 8 β 980.13ms β 965.56ms β no change β
β QQuery 9 β 1305.97ms β 1259.63ms β no change β
β QQuery 10 β 307.22ms β 310.27ms β no change β
β QQuery 11 β 351.03ms β 352.62ms β no change β
β QQuery 12 β 1124.58ms β 1081.10ms β no change β
β QQuery 13 β 1514.46ms β 1474.48ms β no change β
β QQuery 14 β 1047.96ms β 1004.22ms β no change β
β QQuery 15 β 1123.57ms β 1121.84ms β no change β
β QQuery 16 β 1914.02ms β 1918.52ms β no change β
β QQuery 17 β 1765.11ms β 1744.91ms β no change β
β QQuery 18 β 3287.40ms β 3350.44ms β no change β
β QQuery 19 β 119.46ms β 116.30ms β no change β
β QQuery 20 β 1303.02ms β 1322.82ms β no change β
β QQuery 21 β 1680.96ms β 1670.27ms β no change β
β QQuery 22 β 4623.36ms β 4219.07ms β +1.10x faster β
β QQuery 23 β 10483.17ms β 10245.87ms β no change β
β QQuery 24 β 681.01ms β 646.43ms β +1.05x faster β
β QQuery 25 β 611.16ms β 575.18ms β +1.06x faster β
β QQuery 26 β 759.73ms β 695.54ms β +1.09x faster β
β QQuery 27 β 1941.41ms β 1956.46ms β no change β
β QQuery 28 β 13420.97ms β 13171.83ms β no change β
β QQuery 29 β 586.72ms β 577.07ms β no change β
β QQuery 30 β 1056.45ms β 1018.84ms β no change β
β QQuery 31 β 1129.84ms β 1069.49ms β +1.06x faster β
β QQuery 32 β 2757.28ms β 2830.42ms β no change β
β QQuery 33 β 3609.33ms β 3617.67ms β no change β
β QQuery 34 β 3616.82ms β 3599.22ms β no change β
β QQuery 35 β 1358.64ms β 1366.65ms β no change β
β QQuery 36 β 212.72ms β 213.59ms β no change β
β QQuery 37 β 188.84ms β 173.86ms β +1.09x faster β
β QQuery 38 β 208.16ms β 205.21ms β no change β
β QQuery 39 β 308.09ms β 301.35ms β no change β
β QQuery 40 β 113.99ms β 95.40ms β +1.19x faster β
β QQuery 41 β 106.37ms β 104.36ms β no change β
β QQuery 42 β 103.30ms β 99.06ms β no change β
ββββββββββββββββ΄βββββββββββββ΄ββββββββββββββββββββββββ΄ββββββββββββββββ
ββββββββββββββββββββββββββββββββββββββββ³βββββββββββββ
β Benchmark Summary β β
β‘ββββββββββββββββββββββββββββββββββββββββββββββββββββ©
β Total Time (HEAD) β 67945.74ms β
β Total Time (perf_partitioned_topk) β 66691.39ms β
β Average Time (HEAD) β 1580.13ms β
β Average Time (perf_partitioned_topk) β 1550.96ms β
β Queries Faster β 8 β
β Queries Slower β 0 β
β Queries with No Change β 35 β
ββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββ
--------------------
Benchmark sort_tpch.json
--------------------
ββββββββββββββββ³ββββββββββββ³ββββββββββββββββββββββββ³βββββββββββββββ
β Query β HEAD β perf_partitioned_topk β Change β
β‘ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ©
β Q1 β 353.11ms β 365.59ms β no change β
β Q2 β 295.45ms β 319.07ms β 1.08x slower β
β Q3 β 1188.51ms β 1189.09ms β no change β
β Q4 β 424.02ms β 428.25ms β no change β
β Q5 β 436.02ms β 441.91ms β no change β
β Q6 β 475.06ms β 475.58ms β no change β
β Q7 β 973.21ms β 971.26ms β no change β
β Q8 β 810.55ms β 793.97ms β no change β
β Q9 β 826.30ms β 817.77ms β no change β
β Q10 β 1263.00ms β 1272.90ms β no change β
β Q11 β 752.28ms β 761.43ms β no change β
ββββββββββββββββ΄ββββββββββββ΄ββββββββββββββββββββββββ΄βββββββββββββββ
ββββββββββββββββββββββββββββββββββββββββ³ββββββββββββ
β Benchmark Summary β β
β‘βββββββββββββββββββββββββββββββββββββββββββββββββββ©
β Total Time (HEAD) β 7797.50ms β
β Total Time (perf_partitioned_topk) β 7836.81ms β
β Average Time (HEAD) β 708.86ms β
β Average Time (perf_partitioned_topk) β 712.44ms β
β Queries Faster β 0 β
β Queries Slower β 1 β
β Queries with No Change β 10 β
ββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββ
--------------------
Benchmark tpch_mem_sf1.json
--------------------
ββββββββββββββββ³βββββββββββ³ββββββββββββββββββββββββ³βββββββββββββββ
β Query β HEAD β perf_partitioned_topk β Change β
β‘βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ©
β QQuery 1 β 123.41ms β 123.87ms β no change β
β QQuery 2 β 25.24ms β 24.42ms β no change β
β QQuery 3 β 35.05ms β 35.18ms β no change β
β QQuery 4 β 20.49ms β 20.85ms β no change β
β QQuery 5 β 58.48ms β 57.27ms β no change β
β QQuery 6 β 8.06ms β 8.16ms β no change β
β QQuery 7 β 103.88ms β 106.34ms β no change β
β QQuery 8 β 26.11ms β 28.06ms β 1.07x slower β
β QQuery 9 β 62.55ms β 62.46ms β no change β
β QQuery 10 β 59.68ms β 59.06ms β no change β
β QQuery 11 β 13.01ms β 13.07ms β no change β
β QQuery 12 β 38.75ms β 37.78ms β no change β
β QQuery 13 β 30.97ms β 32.02ms β no change β
β QQuery 14 β 9.92ms β 9.85ms β no change β
β QQuery 15 β 25.88ms β 25.29ms β no change β
β QQuery 16 β 23.79ms β 24.08ms β no change β
β QQuery 17 β 98.83ms β 95.66ms β no change β
β QQuery 18 β 252.93ms β 251.98ms β no change β
β QQuery 19 β 28.98ms β 29.12ms β no change β
β QQuery 20 β 39.47ms β 40.29ms β no change β
β QQuery 21 β 178.84ms β 176.28ms β no change β
β QQuery 22 β 17.82ms β 17.51ms β no change β
ββββββββββββββββ΄βββββββββββ΄ββββββββββββββββββββββββ΄βββββββββββββββ
ββββββββββββββββββββββββββββββββββββββββ³ββββββββββββ
β Benchmark Summary β β
β‘βββββββββββββββββββββββββββββββββββββββββββββββββββ©
β Total Time (HEAD) β 1282.15ms β
β Total Time (perf_partitioned_topk) β 1278.61ms β
β Average Time (HEAD) β 58.28ms β
β Average Time (perf_partitioned_topk) β 58.12ms β
β Queries Faster β 0 β
β Queries Slower β 1 β
β Queries with No Change β 21 β
ββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββ
```
</p>
</details>
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2029892886
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -681,4 +793,98 @@ mod tests {
record_batch_store.unuse(0);
assert_eq!(record_batch_store.batches_size, 0);
}
+
+ /// This test validates that the `try_finish` method marks the TopK operator as finished
+ /// when the prefix (on column "a") of the last row in the current batch is strictly greater
+ /// than the worst topβk row.
+ /// The full sort expression is defined on both columns ("a", "b"), but the input ordering is only on "a".
+ #[tokio::test]
+ async fn test_try_finish_marks_finished_with_prefix() -> Result<()> {
+ // Create a schema with two columns.
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("a", DataType::Int32, false),
+ Field::new("b", DataType::Float64, false),
+ ]));
+
+ // Create sort expressions.
+ // Full sort: first by "a", then by "b".
+ let sort_expr_a = PhysicalSortExpr {
+ expr: col("a", schema.as_ref())?,
+ options: SortOptions::default(),
+ };
+ let sort_expr_b = PhysicalSortExpr {
+ expr: col("b", schema.as_ref())?,
+ options: SortOptions::default(),
+ };
+
+ // Input ordering uses only column "a" (a prefix of the full sort).
+ let input_ordering = LexOrdering::from(vec![sort_expr_a.clone()]);
+ let full_expr = LexOrdering::from(vec![sort_expr_a, sort_expr_b]);
+
+ // Create a dummy runtime environment and metrics.
+ let runtime = Arc::new(RuntimeEnv::default());
+ let metrics = ExecutionPlanMetricsSet::new();
+
+ // Create a TopK instance with k = 3 and batch_size = 2.
+ let mut topk = TopK::try_new(
+ 0,
+ Arc::clone(&schema),
+ input_ordering,
+ full_expr,
+ 3,
+ 2,
+ runtime,
+ &metrics,
+ )?;
+
+ // Create the first batch with two columns:
+ // Column "a": [1, 1, 2], Column "b": [10.0, 20.0, 10.0].
Review Comment:
Nice catch, I had updated the `b` in the comment but not in the code... I think what we really want is the "comment" data:
```
First batch:
a | b
---+-----
1 | 10.0
1 | 20.0
2 | 10.0
Second batch:
a | b
---+-----
2 | 30.0
3 | 10.0
```
Like that in the top3 we get the first two rows from the first batch and the third row from the second batch. wdyt?
I can also swap the first two rows of the first batch to enforce sorting as you suggested: `(1,20.0), (1, 10.0), (2, 10.0)`
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#issuecomment-2788703235
> > @geoffreyclaude I'm going to merge if you're done with this?
>
> @berkaysynnada: Fine by me! We resolved the (unfortunately, necessary) semi-redundant common prefix field.
>
> Only remaining question is the Emission type: if it makes sense to leave it as `Both` you can merge, but if you think `Incremental` makes more sense I can do a quick new commit to change it.
Let's make it incremental for consistency. We're thinking on this, and likely figure out a refactor to make all things more clear. (if you wonder, there is also an issue here https://github.com/apache/datafusion/pull/15479#issuecomment-2786362233. These two cases seem to be related and I believe I'll solve them all)
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2031026473
##########
datafusion/physical-expr/src/equivalence/properties/mod.rs:
##########
@@ -575,10 +576,35 @@ impl EquivalenceProperties {
// From the analysis above, we know that `[a ASC]` is satisfied. Then,
// we add column `a` as constant to the algorithm state. This enables us
// to deduce that `(b + c) ASC` is satisfied, given `a` is constant.
- eq_properties = eq_properties
- .with_constants(std::iter::once(ConstExpr::from(normalized_req.expr)));
+ eq_properties = eq_properties.with_constants(std::iter::once(
+ ConstExpr::from(Arc::clone(&normalized_req.expr)),
+ ));
}
- true
+
+ // All requirements are satisfied.
+ normalized_reqs.len()
+ }
+
+ /// Determines the longest prefix of `reqs` that is satisfied by the existing ordering.
+ /// Returns that prefix as a new `LexRequirement`, and a boolean indicating if all the requirements are satisfied.
+ pub fn extract_matching_prefix(
+ &self,
+ reqs: &LexRequirement,
+ ) -> (LexRequirement, bool) {
+ // First, standardize the given requirement:
+ let normalized_reqs = self.normalize_sort_requirements(reqs);
Review Comment:
Great suggestion! It seems I missed a spot in the `EnforceSorting` optimizer rule, which currently removes the TopK in some cases. I'll update the code and unit tests with this case.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "gabotechs (via GitHub)" <gi...@apache.org>.
gabotechs commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2030583037
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -197,6 +302,9 @@ impl TopK {
row_converter: _,
scratch_rows: _,
mut heap,
+ common_prefix_converter: _,
+ common_sort_prefix: _,
+ finished: _,
Review Comment:
π€ I wonder why the spread operator was just not used here on the first place. For consistency it might make more sense to leave it as is.
```suggestion
..
```
##########
datafusion/physical-expr/src/equivalence/properties/mod.rs:
##########
@@ -546,22 +546,23 @@ impl EquivalenceProperties {
self.ordering_satisfy_requirement(&sort_requirements)
}
- /// Checks whether the given sort requirements are satisfied by any of the
- /// existing orderings.
- pub fn ordering_satisfy_requirement(&self, reqs: &LexRequirement) -> bool {
- let mut eq_properties = self.clone();
- // First, standardize the given requirement:
- let normalized_reqs = eq_properties.normalize_sort_requirements(reqs);
-
+ /// Returns the number of consecutive requirements (starting from the left)
+ /// that are satisfied by the plan ordering.
+ fn compute_matching_prefix_length(&self, normalized_reqs: &LexRequirement) -> usize {
Review Comment:
I see that through this PR multiple terms are used for referring to the same thing: "matching_prefix", "sort_prefix", "common_prefix", "common_sort_prefix". As it's not obvious at first sight that all are referring to the same thing, it might help readers to use the same term for everywhere: `compute_common_sort_prefix_length`, `extract_common_sort_prefix`, `common_sort_prefix_converter`, `compute_common_sort_prefix`, `common_sort_prefix=[non_nullable_col@1 ASC]`
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -183,6 +208,86 @@ impl TopK {
// update memory reservation
self.reservation.try_resize(self.size())?;
+
+ // flag the topK as finished if we know that all
+ // subsequent batches are guaranteed to be worse than the
+ // current topK
+ self.attempt_early_completion(&batch)?;
+
+ Ok(())
+ }
+
+ /// If input ordering shares a common sort prefix with the TopK, and if the TopK's heap is full,
+ /// check if the computation can be finished early.
+ /// This is the case if the last row of the current batch is strictly worse than the worst row in the heap,
+ /// comparing only on the shared prefix columns.
+ fn attempt_early_completion(&mut self, batch: &RecordBatch) -> Result<()> {
+ // Early exit if the batch is empty as there is no last row to extract from it.
+ if batch.num_rows() == 0 {
+ return Ok(());
+ }
+
+ // prefix_row_converter is only `Some` if the input ordering has a common prefix with the TopK,
+ // so early exit if it is `None`.
+ let prefix_converter = match &self.common_prefix_converter {
+ Some(pc) => pc,
+ None => return Ok(()),
+ };
+
+ // Early exit if the heap is not full (`heap.max()` only returns `Some` if the heap is full).
+ let worst_topk_row = match self.heap.max() {
+ Some(row) => row,
+ None => return Ok(()),
+ };
Review Comment:
Nit: you should be able to save some keystrokes with let-else statements here:
```suggestion
// prefix_row_converter is only `Some` if the input ordering has a common prefix with the TopK,
// so early exit if it is `None`.
let Some(prefix_converter) = &self.common_prefix_converter else {
return Ok(())
};
// Early exit if the heap is not full (`heap.max()` only returns `Some` if the heap is full).
let Some(worst_topk_row) = self.heap.max() else {
return Ok(())
};
```
##########
datafusion/physical-expr/src/equivalence/properties/mod.rs:
##########
@@ -575,10 +576,35 @@ impl EquivalenceProperties {
// From the analysis above, we know that `[a ASC]` is satisfied. Then,
// we add column `a` as constant to the algorithm state. This enables us
// to deduce that `(b + c) ASC` is satisfied, given `a` is constant.
- eq_properties = eq_properties
- .with_constants(std::iter::once(ConstExpr::from(normalized_req.expr)));
+ eq_properties = eq_properties.with_constants(std::iter::once(
+ ConstExpr::from(Arc::clone(&normalized_req.expr)),
+ ));
}
- true
+
+ // All requirements are satisfied.
+ normalized_reqs.len()
+ }
+
+ /// Determines the longest prefix of `reqs` that is satisfied by the existing ordering.
+ /// Returns that prefix as a new `LexRequirement`, and a boolean indicating if all the requirements are satisfied.
+ pub fn extract_matching_prefix(
+ &self,
+ reqs: &LexRequirement,
+ ) -> (LexRequirement, bool) {
+ // First, standardize the given requirement:
+ let normalized_reqs = self.normalize_sort_requirements(reqs);
Review Comment:
I imagine that this will normalize cases where columns get aliased, duplicate sort expressions, etc. But would this normalize cases where expressions that do not alter the order are applied to columns? For example, would `[int_column+1 DESC, int_column DESC]` be normalized to `[int_column DESC]`? if that's the case, maybe adding a sql logic test for this?
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -183,6 +208,86 @@ impl TopK {
// update memory reservation
self.reservation.try_resize(self.size())?;
+
+ // flag the topK as finished if we know that all
+ // subsequent batches are guaranteed to be worse than the
+ // current topK
+ self.attempt_early_completion(&batch)?;
+
+ Ok(())
+ }
+
+ /// If input ordering shares a common sort prefix with the TopK, and if the TopK's heap is full,
+ /// check if the computation can be finished early.
+ /// This is the case if the last row of the current batch is strictly worse than the worst row in the heap,
+ /// comparing only on the shared prefix columns.
+ fn attempt_early_completion(&mut self, batch: &RecordBatch) -> Result<()> {
+ // Early exit if the batch is empty as there is no last row to extract from it.
+ if batch.num_rows() == 0 {
+ return Ok(());
+ }
+
+ // prefix_row_converter is only `Some` if the input ordering has a common prefix with the TopK,
+ // so early exit if it is `None`.
+ let prefix_converter = match &self.common_prefix_converter {
+ Some(pc) => pc,
+ None => return Ok(()),
+ };
+
+ // Early exit if the heap is not full (`heap.max()` only returns `Some` if the heap is full).
+ let worst_topk_row = match self.heap.max() {
+ Some(row) => row,
+ None => return Ok(()),
+ };
+
+ // Evaluate the prefix for the last row of the current batch.
+ let last_row_idx = batch.num_rows() - 1;
+ let mut batch_prefix_scratch = prefix_converter.empty_rows(1, 20);
Review Comment:
1 here is the number of rows, and 20 is the initial capacity in bytes for storing the raw arrow data that represents the rows (just 1 in this case). This does not mean that only 20 bytes of data can be stored, IIUC this is just the amount of data that can be stored without dynamically resizing the underlaying buffer, but upon storing more data, the underlaying buffer will just get resized.
This might me worth a comment.
##########
datafusion/sqllogictest/test_files/topk.slt:
##########
@@ -233,3 +233,104 @@ d 1 -98 y7C453hRWd4E7ImjNDWlpexB8nUqjh y7C453hRWd4E7ImjNDWlpexB8nUqjh
e 2 52 xipQ93429ksjNcXPX5326VSg1xJZcW xipQ93429ksjNcXPX5326VSg1xJZcW
d 1 -72 wwXqSGKLyBQyPkonlzBNYUJTCo4LRS wwXqSGKLyBQyPkonlzBNYUJTCo4LRS
a 1 -5 waIGbOGl1PM6gnzZ4uuZt4E2yDWRHs waIGbOGl1PM6gnzZ4uuZt4E2yDWRHs
+
+#####################################
+## Test TopK with Partially Sorted Inputs
+#####################################
+
+
+# Create an external table where data is pre-sorted by (column1 DESC, column2 ASC) only.
+statement ok
+CREATE EXTERNAL TABLE partial_sorted (
+ column1 VARCHAR,
+ column2 INT,
+ column3 INT
+)
+STORED AS parquet
+LOCATION 'test_files/scratch/topk/partial_sorted/1.parquet'
+WITH ORDER (column1 DESC, column2 ASC);
+
+# Insert test data into the external table.
+query I
+COPY (VALUES
+ ('A', 12, 100),
+ ('A', 8, 50),
+ ('B', 9, 70),
+ ('B', 10, 80),
+ ('C', 7, 60),
+ ('C', 11, 90))
+TO 'test_files/scratch/topk/partial_sorted/1.parquet';
+----
+6
+
+# Run a TopK query that orders by all columns.
+# Although the table is only guaranteed to be sorted by (column1 DESC, column2 ASC),
+# DataFusion should use the common prefix optimization
+# and return the correct top 3 rows when ordering by all columns.
+query TII
+select column1, column2, column3 from partial_sorted order by column1 desc, column2 asc, column3 desc limit 3;
Review Comment:
How about adding some tests that try to mess around with `NULLS LAST` and `NULLS FIRST`?
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2030901421
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -966,6 +966,8 @@ pub struct SortExec {
preserve_partitioning: bool,
/// Fetch highest/lowest n results
fetch: Option<usize>,
+ /// Common sort prefix between the input and the sort expressions (only used with fetch)
+ common_sort_prefix: LexOrdering,
Review Comment:
I'm not sure we can do that simply, as the `common_sort_prefix` is normalized, and the `expr` is not. It would mean we'd need to re-normalize `expr` everytime we need `common_sort_prefix`.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#issuecomment-2789171297
> Exactly, except for now the SortExec without fetch does _not_ incrementally emit results on partially sorted input: it behaves the same as on completely unsorted input.
Oh, you are right. I was thinking that case as if it runs like PartialSortExec.
> And with fetch (so TopK), it still buffers everything in memory before emitting its results. I think the important thing here is that all records are emitted only once the node's execution terminates (whether all the input has been read or not should be irrelevant to the emission type.)
I'm sorry, I can realize the case just now. You are right about partial sort case is Final indeed in SortExec, whether there is a fetch or not
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2030868240
##########
datafusion/physical-expr/src/equivalence/properties/mod.rs:
##########
@@ -546,22 +546,23 @@ impl EquivalenceProperties {
self.ordering_satisfy_requirement(&sort_requirements)
}
- /// Checks whether the given sort requirements are satisfied by any of the
- /// existing orderings.
- pub fn ordering_satisfy_requirement(&self, reqs: &LexRequirement) -> bool {
- let mut eq_properties = self.clone();
- // First, standardize the given requirement:
- let normalized_reqs = eq_properties.normalize_sort_requirements(reqs);
-
+ /// Returns the number of consecutive requirements (starting from the left)
+ /// that are satisfied by the plan ordering.
+ fn compute_matching_prefix_length(&self, normalized_reqs: &LexRequirement) -> usize {
Review Comment:
absolutely! `common_sort_prefix` everywhere it is.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#issuecomment-2789107136
> PartiallySorted case is actually the same of AggregateExec with an ordered group_by key.
Exactly, expect for now the SortExec without fetch does *not* incrementally emit results on partially sorted input: it behaves the same as on completely unsorted input. And with fetch (so TopK), it still buffers everything in memory before emitting its results.
I think the important thing here is that all records are emitted only once the node's execution terminates (whether all the input has been read or not should be irrelevant to the emission type.)
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada merged PR #15563:
URL: https://github.com/apache/datafusion/pull/15563
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2031112051
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -183,6 +209,87 @@ impl TopK {
// update memory reservation
self.reservation.try_resize(self.size())?;
+
+ // flag the topK as finished if we know that all
+ // subsequent batches are guaranteed to be worse than the
+ // current topK
+ self.attempt_early_completion(&batch)?;
+
+ Ok(())
+ }
+
+ /// If input ordering shares a common sort prefix with the TopK, and if the TopK's heap is full,
+ /// check if the computation can be finished early.
+ /// This is the case if the last row of the current batch is strictly worse than the worst row in the heap,
+ /// comparing only on the shared prefix columns.
+ fn attempt_early_completion(&mut self, batch: &RecordBatch) -> Result<()> {
+ // Early exit if the batch is empty as there is no last row to extract from it.
+ if batch.num_rows() == 0 {
+ return Ok(());
+ }
+
+ // prefix_row_converter is only `Some` if the input ordering has a common prefix with the TopK,
+ // so early exit if it is `None`.
+ let Some(prefix_converter) = &self.common_sort_prefix_converter else {
+ return Ok(());
+ };
+
+ // Early exit if the heap is not full (`heap.max()` only returns `Some` if the heap is full).
+ let Some(worst_topk_row) = self.heap.max() else {
Review Comment:
nit: Maybe rename all the `worst` to `max` like `worst_topk_row` -> `max_topk_row`, to keep the naming consistent?
I think in this context, the heap follows the convention of referring to the heap root as the maximum, because it uses byte order for the converted rows, and it's always min-heap regardless of query order.
##########
datafusion/sqllogictest/test_files/topk.slt:
##########
@@ -233,3 +233,104 @@ d 1 -98 y7C453hRWd4E7ImjNDWlpexB8nUqjh y7C453hRWd4E7ImjNDWlpexB8nUqjh
e 2 52 xipQ93429ksjNcXPX5326VSg1xJZcW xipQ93429ksjNcXPX5326VSg1xJZcW
d 1 -72 wwXqSGKLyBQyPkonlzBNYUJTCo4LRS wwXqSGKLyBQyPkonlzBNYUJTCo4LRS
a 1 -5 waIGbOGl1PM6gnzZ4uuZt4E2yDWRHs waIGbOGl1PM6gnzZ4uuZt4E2yDWRHs
+
+#####################################
+## Test TopK with Partially Sorted Inputs
+#####################################
+
+
+# Create an external table where data is pre-sorted by (column1 DESC, column2 ASC) only.
+statement ok
+CREATE EXTERNAL TABLE partial_sorted (
+ column1 VARCHAR,
+ column2 INT,
+ column3 INT
+)
+STORED AS parquet
+LOCATION 'test_files/scratch/topk/partial_sorted/1.parquet'
+WITH ORDER (column1 DESC, column2 ASC);
+
+# Insert test data into the external table.
+query I
+COPY (VALUES
Review Comment:
I think `CREATE EXTERNAL TABLE WITH ORDER` only acts as a metadata hint: when writing data into the external table, it doesnβt enforce the specified order, instead `VALUES` here should be declared with the order specified in `CREATE EXTERNAL TABLE` statement.
The test case didn't fail because the whole parquet file fits in one batch, maybe we can let test execute in a smaller batch size config:
```
set datafusion.execution.batch_size = 2;
```
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "NGA-TRAN (via GitHub)" <gi...@apache.org>.
NGA-TRAN commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2029861706
##########
datafusion/physical-expr/src/equivalence/properties/mod.rs:
##########
@@ -575,10 +576,35 @@ impl EquivalenceProperties {
// From the analysis above, we know that `[a ASC]` is satisfied. Then,
// we add column `a` as constant to the algorithm state. This enables us
// to deduce that `(b + c) ASC` is satisfied, given `a` is constant.
- eq_properties = eq_properties
- .with_constants(std::iter::once(ConstExpr::from(normalized_req.expr)));
+ eq_properties = eq_properties.with_constants(std::iter::once(
+ ConstExpr::from(Arc::clone(&normalized_req.expr)),
+ ));
}
- true
+
+ // All requirements are satisfied.
+ normalized_reqs.len()
+ }
+
+ /// Determines the longest prefix of `reqs` that is satisfied by the existing ordering.
+ /// Returns that prefix as a new `LexRequirement`, and a boolean indicating if all the requirements are satisfied.
+ pub fn extract_matching_prefix(
+ &self,
+ reqs: &LexRequirement,
+ ) -> (LexRequirement, bool) {
+ // First, standardize the given requirement:
+ let normalized_reqs = self.normalize_sort_requirements(reqs);
+
+ let prefix_len = self.compute_matching_prefix_length(&normalized_reqs);
+ (
+ LexRequirement::new(normalized_reqs[..prefix_len].to_vec()),
+ prefix_len == normalized_reqs.len(),
+ )
+ }
+
+ /// Checks whether the given sort requirements are satisfied by any of the
+ /// existing orderings.
+ pub fn ordering_satisfy_requirement(&self, reqs: &LexRequirement) -> bool {
+ self.extract_matching_prefix(reqs).1
Review Comment:
I have review carefully this mod.rs file. Very nice work to refactor and add functions to get the sorted prefix
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -183,6 +208,86 @@ impl TopK {
// update memory reservation
self.reservation.try_resize(self.size())?;
+
+ // flag the topK as finished if we know that all
+ // subsequent batches are guaranteed to be worse than the
+ // current topK
+ self.attempt_early_completion(&batch)?;
+
+ Ok(())
+ }
+
+ /// If input ordering shares a common sort prefix with the TopK, and if the TopK's heap is full,
+ /// check if the computation can be finished early.
+ /// This is the case if the last row of the current batch is strictly worse than the worst row in the heap,
+ /// comparing only on the shared prefix columns.
+ fn attempt_early_completion(&mut self, batch: &RecordBatch) -> Result<()> {
+ // Early exit if the batch is empty as there is no last row to extract from it.
+ if batch.num_rows() == 0 {
+ return Ok(());
+ }
+
+ // prefix_row_converter is only `Some` if the input ordering has a common prefix with the TopK,
+ // so early exit if it is `None`.
+ let prefix_converter = match &self.common_prefix_converter {
+ Some(pc) => pc,
+ None => return Ok(()),
+ };
+
+ // Early exit if the heap is not full (`heap.max()` only returns `Some` if the heap is full).
+ let worst_topk_row = match self.heap.max() {
+ Some(row) => row,
+ None => return Ok(()),
+ };
+
+ // Evaluate the prefix for the last row of the current batch.
+ let last_row_idx = batch.num_rows() - 1;
+ let mut batch_prefix_scratch = prefix_converter.empty_rows(1, 20);
+ self.compute_common_prefix(batch, last_row_idx, &mut batch_prefix_scratch)?;
+
+ // Retrieve the "worst" row from the heap.
+ let store_entry = self
+ .heap
+ .store
+ .get(worst_topk_row.batch_id)
+ .ok_or(internal_datafusion_err!("Invalid batch id in topK heap"))?;
+ let worst_batch = &store_entry.batch;
+ let mut heap_prefix_scratch = prefix_converter.empty_rows(1, 20);
+ self.compute_common_prefix(
+ worst_batch,
+ worst_topk_row.index,
+ &mut heap_prefix_scratch,
+ )?;
+
+ // If the last row's prefix is strictly greater than the worst prefix, mark as finished.
+ if batch_prefix_scratch.row(0).as_ref() > heap_prefix_scratch.row(0).as_ref() {
+ self.finished = true;
Review Comment:
Nice
##########
datafusion/sqllogictest/test_files/topk.slt:
##########
@@ -233,3 +233,104 @@ d 1 -98 y7C453hRWd4E7ImjNDWlpexB8nUqjh y7C453hRWd4E7ImjNDWlpexB8nUqjh
e 2 52 xipQ93429ksjNcXPX5326VSg1xJZcW xipQ93429ksjNcXPX5326VSg1xJZcW
d 1 -72 wwXqSGKLyBQyPkonlzBNYUJTCo4LRS wwXqSGKLyBQyPkonlzBNYUJTCo4LRS
a 1 -5 waIGbOGl1PM6gnzZ4uuZt4E2yDWRHs waIGbOGl1PM6gnzZ4uuZt4E2yDWRHs
+
+#####################################
+## Test TopK with Partially Sorted Inputs
+#####################################
+
+
+# Create an external table where data is pre-sorted by (column1 DESC, column2 ASC) only.
+statement ok
+CREATE EXTERNAL TABLE partial_sorted (
+ column1 VARCHAR,
+ column2 INT,
+ column3 INT
+)
+STORED AS parquet
+LOCATION 'test_files/scratch/topk/partial_sorted/1.parquet'
+WITH ORDER (column1 DESC, column2 ASC);
+
+# Insert test data into the external table.
+query I
+COPY (VALUES
+ ('A', 12, 100),
+ ('A', 8, 50),
+ ('B', 9, 70),
+ ('B', 10, 80),
+ ('C', 7, 60),
+ ('C', 11, 90))
+TO 'test_files/scratch/topk/partial_sorted/1.parquet';
+----
+6
+
+# Run a TopK query that orders by all columns.
+# Although the table is only guaranteed to be sorted by (column1 DESC, column2 ASC),
+# DataFusion should use the common prefix optimization
+# and return the correct top 3 rows when ordering by all columns.
+query TII
+select column1, column2, column3 from partial_sorted order by column1 desc, column2 asc, column3 desc limit 3;
+----
+C 7 60
+C 11 90
+B 9 70
+
+## explain_physical_plan_only
+statement ok
+set datafusion.explain.physical_plan_only = true
+
+# Verify that the physical plan includes the sort prefix.
+# The output should display a "sort_prefix" in the SortExec node.
+query TT
+explain select column1, column2, column3 from partial_sorted order by column1 desc, column2 asc, column3 desc limit 3;
+----
+physical_plan
+01)SortExec: TopK(fetch=3), expr=[column1@0 DESC, column2@1 ASC NULLS LAST, column3@2 DESC], preserve_partitioning=[false], sort_prefix=[column1@0 DESC, column2@1 ASC NULLS LAST]
+02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/topk/partial_sorted/1.parquet]]}, projection=[column1, column2, column3], output_ordering=[column1@0 DESC, column2@1 ASC NULLS LAST], file_type=parquet
+
+
+# Explain variations of the above query with different orderings, and different sort prefixes.
+# The "sort_prefix" in the SortExec node should only be present if the TopK's ordering starts with either (column1 DESC, column2 ASC) or just (column1 DESC).
+query TT
+explain select column1, column2, column3 from partial_sorted order by column3 desc limit 3;
+----
+physical_plan
+01)SortExec: TopK(fetch=3), expr=[column3@2 DESC], preserve_partitioning=[false]
+02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/topk/partial_sorted/1.parquet]]}, projection=[column1, column2, column3], output_ordering=[column1@0 DESC, column2@1 ASC NULLS LAST], file_type=parquet
+
+query TT
+explain select column1, column2, column3 from partial_sorted order by column1 desc, column2 desc limit 3;
+----
+physical_plan
+01)SortExec: TopK(fetch=3), expr=[column1@0 DESC, column2@1 DESC], preserve_partitioning=[false], sort_prefix=[column1@0 DESC]
+02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/topk/partial_sorted/1.parquet]]}, projection=[column1, column2, column3], output_ordering=[column1@0 DESC, column2@1 ASC NULLS LAST], file_type=parquet
+
+query TT
+explain select column1, column2, column3 from partial_sorted order by column1 asc limit 3;
+----
+physical_plan
+01)SortExec: TopK(fetch=3), expr=[column1@0 ASC NULLS LAST], preserve_partitioning=[false]
+02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/topk/partial_sorted/1.parquet]]}, projection=[column1, column2, column3], output_ordering=[column1@0 DESC, column2@1 ASC NULLS LAST], file_type=parquet
+
+query TT
+explain select column1, column2, column3 from partial_sorted order by column2 asc, column1 desc limit 3;
+----
+physical_plan
+01)SortExec: TopK(fetch=3), expr=[column2@1 ASC NULLS LAST, column1@0 DESC], preserve_partitioning=[false]
+02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/topk/partial_sorted/1.parquet]]}, projection=[column1, column2, column3], output_ordering=[column1@0 DESC, column2@1 ASC NULLS LAST], file_type=parquet
+
+
+# Verify that the sort prefix is correctly computed on the normalized ordering (removing redundant aliased columns for example).
+query TT
+explain select column1, column2, column3, column1 as column4, column2 as column5 from partial_sorted order by column1 desc, column4 desc, column2 asc, column5 asc, column3 desc limit 3;
+----
+physical_plan
+01)SortExec: TopK(fetch=3), expr=[column1@0 DESC, column4@3 DESC, column2@1 ASC NULLS LAST, column5@4 ASC NULLS LAST, column3@2 DESC], preserve_partitioning=[false], sort_prefix=[column1@0 DESC, column2@1 ASC NULLS LAST]
+02)--ProjectionExec: expr=[column1@0 as column1, column2@1 as column2, column3@2 as column3, column1@0 as column4, column2@1 as column5]
+03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/topk/partial_sorted/1.parquet]]}, projection=[column1, column2, column3], output_ordering=[column1@0 DESC, column2@1 ASC NULLS LAST], file_type=parquet
+
+# Cleanup
+statement ok
+DROP TABLE partial_sorted;
+
+statement ok
+set datafusion.explain.physical_plan_only = false
Review Comment:
Very nice explain tests. π
##########
datafusion/core/tests/physical_optimizer/enforce_sorting.rs:
##########
@@ -1652,7 +1652,7 @@ async fn test_remove_unnecessary_sort7() -> Result<()> {
) as Arc<dyn ExecutionPlan>;
let expected_input = [
- "SortExec: TopK(fetch=2), expr=[non_nullable_col@1 ASC], preserve_partitioning=[false]",
+ "SortExec: TopK(fetch=2), expr=[non_nullable_col@1 ASC], preserve_partitioning=[false], sort_prefix=[non_nullable_col@1 ASC]",
Review Comment:
Very nice and clear addition to the explain
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -1114,11 +1130,14 @@ impl SortExec {
let output_partitioning =
Self::output_partitioning_helper(input, preserve_partitioning);
- PlanProperties::new(
- eq_properties,
- output_partitioning,
- emission_type,
- boundedness,
+ (
+ PlanProperties::new(
+ eq_properties,
+ output_partitioning,
+ emission_type,
+ boundedness,
+ ),
+ LexOrdering::from(sort_prefix),
Review Comment:
Very nice addition logic in this `compute_properties` function
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -681,4 +793,98 @@ mod tests {
record_batch_store.unuse(0);
assert_eq!(record_batch_store.batches_size, 0);
}
+
+ /// This test validates that the `try_finish` method marks the TopK operator as finished
+ /// when the prefix (on column "a") of the last row in the current batch is strictly greater
+ /// than the worst topβk row.
+ /// The full sort expression is defined on both columns ("a", "b"), but the input ordering is only on "a".
+ #[tokio::test]
+ async fn test_try_finish_marks_finished_with_prefix() -> Result<()> {
+ // Create a schema with two columns.
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("a", DataType::Int32, false),
+ Field::new("b", DataType::Float64, false),
+ ]));
+
+ // Create sort expressions.
+ // Full sort: first by "a", then by "b".
+ let sort_expr_a = PhysicalSortExpr {
+ expr: col("a", schema.as_ref())?,
+ options: SortOptions::default(),
+ };
+ let sort_expr_b = PhysicalSortExpr {
+ expr: col("b", schema.as_ref())?,
+ options: SortOptions::default(),
+ };
+
+ // Input ordering uses only column "a" (a prefix of the full sort).
+ let input_ordering = LexOrdering::from(vec![sort_expr_a.clone()]);
+ let full_expr = LexOrdering::from(vec![sort_expr_a, sort_expr_b]);
+
+ // Create a dummy runtime environment and metrics.
+ let runtime = Arc::new(RuntimeEnv::default());
+ let metrics = ExecutionPlanMetricsSet::new();
+
+ // Create a TopK instance with k = 3 and batch_size = 2.
+ let mut topk = TopK::try_new(
+ 0,
+ Arc::clone(&schema),
+ input_ordering,
+ full_expr,
+ 3,
+ 2,
+ runtime,
+ &metrics,
+ )?;
+
+ // Create the first batch with two columns:
+ // Column "a": [1, 1, 2], Column "b": [10.0, 20.0, 10.0].
Review Comment:
To further test the output data sorted in both a and b, I suggest to make data of column b like this: `"b": [20.0, 10.0, 30.0].
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -108,17 +131,7 @@ impl TopK {
let reservation = MemoryConsumer::new(format!("TopK[{partition_id}]"))
.register(&runtime.memory_pool);
- let expr: Arc<[PhysicalSortExpr]> = expr.into();
-
- let sort_fields: Vec<_> = expr
- .iter()
- .map(|e| {
- Ok(SortField::new_with_options(
- e.expr.data_type(&schema)?,
- e.options,
- ))
- })
- .collect::<Result<_>>()?;
+ let sort_fields: Vec<_> = build_sort_fields(&expr, &schema)?;
Review Comment:
Nice refactor
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -183,6 +208,86 @@ impl TopK {
// update memory reservation
self.reservation.try_resize(self.size())?;
+
+ // flag the topK as finished if we know that all
+ // subsequent batches are guaranteed to be worse than the
+ // current topK
+ self.attempt_early_completion(&batch)?;
+
+ Ok(())
+ }
+
+ /// If input ordering shares a common sort prefix with the TopK, and if the TopK's heap is full,
+ /// check if the computation can be finished early.
+ /// This is the case if the last row of the current batch is strictly worse than the worst row in the heap,
+ /// comparing only on the shared prefix columns.
+ fn attempt_early_completion(&mut self, batch: &RecordBatch) -> Result<()> {
+ // Early exit if the batch is empty as there is no last row to extract from it.
+ if batch.num_rows() == 0 {
+ return Ok(());
+ }
+
+ // prefix_row_converter is only `Some` if the input ordering has a common prefix with the TopK,
+ // so early exit if it is `None`.
+ let prefix_converter = match &self.common_prefix_converter {
+ Some(pc) => pc,
+ None => return Ok(()),
+ };
+
+ // Early exit if the heap is not full (`heap.max()` only returns `Some` if the heap is full).
+ let worst_topk_row = match self.heap.max() {
+ Some(row) => row,
+ None => return Ok(()),
+ };
+
+ // Evaluate the prefix for the last row of the current batch.
+ let last_row_idx = batch.num_rows() - 1;
+ let mut batch_prefix_scratch = prefix_converter.empty_rows(1, 20);
+ self.compute_common_prefix(batch, last_row_idx, &mut batch_prefix_scratch)?;
+
+ // Retrieve the "worst" row from the heap.
+ let store_entry = self
+ .heap
+ .store
+ .get(worst_topk_row.batch_id)
+ .ok_or(internal_datafusion_err!("Invalid batch id in topK heap"))?;
+ let worst_batch = &store_entry.batch;
+ let mut heap_prefix_scratch = prefix_converter.empty_rows(1, 20);
Review Comment:
Same here
##########
datafusion/sqllogictest/test_files/topk.slt:
##########
@@ -233,3 +233,104 @@ d 1 -98 y7C453hRWd4E7ImjNDWlpexB8nUqjh y7C453hRWd4E7ImjNDWlpexB8nUqjh
e 2 52 xipQ93429ksjNcXPX5326VSg1xJZcW xipQ93429ksjNcXPX5326VSg1xJZcW
d 1 -72 wwXqSGKLyBQyPkonlzBNYUJTCo4LRS wwXqSGKLyBQyPkonlzBNYUJTCo4LRS
a 1 -5 waIGbOGl1PM6gnzZ4uuZt4E2yDWRHs waIGbOGl1PM6gnzZ4uuZt4E2yDWRHs
+
+#####################################
+## Test TopK with Partially Sorted Inputs
+#####################################
+
+
+# Create an external table where data is pre-sorted by (column1 DESC, column2 ASC) only.
+statement ok
+CREATE EXTERNAL TABLE partial_sorted (
+ column1 VARCHAR,
+ column2 INT,
+ column3 INT
+)
+STORED AS parquet
+LOCATION 'test_files/scratch/topk/partial_sorted/1.parquet'
+WITH ORDER (column1 DESC, column2 ASC);
+
+# Insert test data into the external table.
+query I
+COPY (VALUES
+ ('A', 12, 100),
+ ('A', 8, 50),
+ ('B', 9, 70),
+ ('B', 10, 80),
+ ('C', 7, 60),
+ ('C', 11, 90))
+TO 'test_files/scratch/topk/partial_sorted/1.parquet';
+----
+6
+
+# Run a TopK query that orders by all columns.
+# Although the table is only guaranteed to be sorted by (column1 DESC, column2 ASC),
+# DataFusion should use the common prefix optimization
+# and return the correct top 3 rows when ordering by all columns.
+query TII
+select column1, column2, column3 from partial_sorted order by column1 desc, column2 asc, column3 desc limit 3;
+----
+C 7 60
+C 11 90
+B 9 70
+
+## explain_physical_plan_only
+statement ok
+set datafusion.explain.physical_plan_only = true
+
+# Verify that the physical plan includes the sort prefix.
+# The output should display a "sort_prefix" in the SortExec node.
+query TT
+explain select column1, column2, column3 from partial_sorted order by column1 desc, column2 asc, column3 desc limit 3;
+----
+physical_plan
+01)SortExec: TopK(fetch=3), expr=[column1@0 DESC, column2@1 ASC NULLS LAST, column3@2 DESC], preserve_partitioning=[false], sort_prefix=[column1@0 DESC, column2@1 ASC NULLS LAST]
+02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/topk/partial_sorted/1.parquet]]}, projection=[column1, column2, column3], output_ordering=[column1@0 DESC, column2@1 ASC NULLS LAST], file_type=parquet
+
+
+# Explain variations of the above query with different orderings, and different sort prefixes.
+# The "sort_prefix" in the SortExec node should only be present if the TopK's ordering starts with either (column1 DESC, column2 ASC) or just (column1 DESC).
+query TT
+explain select column1, column2, column3 from partial_sorted order by column3 desc limit 3;
+----
+physical_plan
+01)SortExec: TopK(fetch=3), expr=[column3@2 DESC], preserve_partitioning=[false]
Review Comment:
π no sort_prefix
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -183,6 +208,86 @@ impl TopK {
// update memory reservation
self.reservation.try_resize(self.size())?;
+
+ // flag the topK as finished if we know that all
+ // subsequent batches are guaranteed to be worse than the
+ // current topK
+ self.attempt_early_completion(&batch)?;
+
+ Ok(())
+ }
+
+ /// If input ordering shares a common sort prefix with the TopK, and if the TopK's heap is full,
+ /// check if the computation can be finished early.
+ /// This is the case if the last row of the current batch is strictly worse than the worst row in the heap,
+ /// comparing only on the shared prefix columns.
+ fn attempt_early_completion(&mut self, batch: &RecordBatch) -> Result<()> {
+ // Early exit if the batch is empty as there is no last row to extract from it.
+ if batch.num_rows() == 0 {
+ return Ok(());
+ }
+
+ // prefix_row_converter is only `Some` if the input ordering has a common prefix with the TopK,
+ // so early exit if it is `None`.
+ let prefix_converter = match &self.common_prefix_converter {
+ Some(pc) => pc,
+ None => return Ok(()),
+ };
+
+ // Early exit if the heap is not full (`heap.max()` only returns `Some` if the heap is full).
+ let worst_topk_row = match self.heap.max() {
+ Some(row) => row,
+ None => return Ok(()),
+ };
+
+ // Evaluate the prefix for the last row of the current batch.
+ let last_row_idx = batch.num_rows() - 1;
+ let mut batch_prefix_scratch = prefix_converter.empty_rows(1, 20);
Review Comment:
Can you add comment explaining why 1 and 20? Can they be defined and assigned to constants or, at least variables, and use the variables here?
##########
datafusion/sqllogictest/test_files/topk.slt:
##########
@@ -233,3 +233,104 @@ d 1 -98 y7C453hRWd4E7ImjNDWlpexB8nUqjh y7C453hRWd4E7ImjNDWlpexB8nUqjh
e 2 52 xipQ93429ksjNcXPX5326VSg1xJZcW xipQ93429ksjNcXPX5326VSg1xJZcW
d 1 -72 wwXqSGKLyBQyPkonlzBNYUJTCo4LRS wwXqSGKLyBQyPkonlzBNYUJTCo4LRS
a 1 -5 waIGbOGl1PM6gnzZ4uuZt4E2yDWRHs waIGbOGl1PM6gnzZ4uuZt4E2yDWRHs
+
+#####################################
+## Test TopK with Partially Sorted Inputs
+#####################################
+
+
+# Create an external table where data is pre-sorted by (column1 DESC, column2 ASC) only.
+statement ok
+CREATE EXTERNAL TABLE partial_sorted (
+ column1 VARCHAR,
+ column2 INT,
+ column3 INT
+)
+STORED AS parquet
+LOCATION 'test_files/scratch/topk/partial_sorted/1.parquet'
+WITH ORDER (column1 DESC, column2 ASC);
+
+# Insert test data into the external table.
+query I
+COPY (VALUES
+ ('A', 12, 100),
+ ('A', 8, 50),
+ ('B', 9, 70),
+ ('B', 10, 80),
+ ('C', 7, 60),
+ ('C', 11, 90))
+TO 'test_files/scratch/topk/partial_sorted/1.parquet';
+----
+6
+
+# Run a TopK query that orders by all columns.
+# Although the table is only guaranteed to be sorted by (column1 DESC, column2 ASC),
+# DataFusion should use the common prefix optimization
+# and return the correct top 3 rows when ordering by all columns.
+query TII
+select column1, column2, column3 from partial_sorted order by column1 desc, column2 asc, column3 desc limit 3;
+----
+C 7 60
+C 11 90
+B 9 70
+
+## explain_physical_plan_only
+statement ok
+set datafusion.explain.physical_plan_only = true
+
+# Verify that the physical plan includes the sort prefix.
+# The output should display a "sort_prefix" in the SortExec node.
+query TT
+explain select column1, column2, column3 from partial_sorted order by column1 desc, column2 asc, column3 desc limit 3;
+----
+physical_plan
+01)SortExec: TopK(fetch=3), expr=[column1@0 DESC, column2@1 ASC NULLS LAST, column3@2 DESC], preserve_partitioning=[false], sort_prefix=[column1@0 DESC, column2@1 ASC NULLS LAST]
+02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/topk/partial_sorted/1.parquet]]}, projection=[column1, column2, column3], output_ordering=[column1@0 DESC, column2@1 ASC NULLS LAST], file_type=parquet
+
+
+# Explain variations of the above query with different orderings, and different sort prefixes.
+# The "sort_prefix" in the SortExec node should only be present if the TopK's ordering starts with either (column1 DESC, column2 ASC) or just (column1 DESC).
+query TT
+explain select column1, column2, column3 from partial_sorted order by column3 desc limit 3;
+----
+physical_plan
+01)SortExec: TopK(fetch=3), expr=[column3@2 DESC], preserve_partitioning=[false]
+02)--DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/sqllogictest/test_files/scratch/topk/partial_sorted/1.parquet]]}, projection=[column1, column2, column3], output_ordering=[column1@0 DESC, column2@1 ASC NULLS LAST], file_type=parquet
+
+query TT
+explain select column1, column2, column3 from partial_sorted order by column1 desc, column2 desc limit 3;
+----
+physical_plan
+01)SortExec: TopK(fetch=3), expr=[column1@0 DESC, column2@1 DESC], preserve_partitioning=[false], sort_prefix=[column1@0 DESC]
Review Comment:
π one-column sort prefix
##########
datafusion/sqllogictest/test_files/topk.slt:
##########
@@ -233,3 +233,104 @@ d 1 -98 y7C453hRWd4E7ImjNDWlpexB8nUqjh y7C453hRWd4E7ImjNDWlpexB8nUqjh
e 2 52 xipQ93429ksjNcXPX5326VSg1xJZcW xipQ93429ksjNcXPX5326VSg1xJZcW
d 1 -72 wwXqSGKLyBQyPkonlzBNYUJTCo4LRS wwXqSGKLyBQyPkonlzBNYUJTCo4LRS
a 1 -5 waIGbOGl1PM6gnzZ4uuZt4E2yDWRHs waIGbOGl1PM6gnzZ4uuZt4E2yDWRHs
+
+#####################################
+## Test TopK with Partially Sorted Inputs
+#####################################
+
+
+# Create an external table where data is pre-sorted by (column1 DESC, column2 ASC) only.
+statement ok
+CREATE EXTERNAL TABLE partial_sorted (
+ column1 VARCHAR,
+ column2 INT,
+ column3 INT
+)
+STORED AS parquet
+LOCATION 'test_files/scratch/topk/partial_sorted/1.parquet'
+WITH ORDER (column1 DESC, column2 ASC);
+
+# Insert test data into the external table.
+query I
+COPY (VALUES
+ ('A', 12, 100),
+ ('A', 8, 50),
+ ('B', 9, 70),
+ ('B', 10, 80),
+ ('C', 7, 60),
+ ('C', 11, 90))
+TO 'test_files/scratch/topk/partial_sorted/1.parquet';
+----
+6
+
+# Run a TopK query that orders by all columns.
+# Although the table is only guaranteed to be sorted by (column1 DESC, column2 ASC),
+# DataFusion should use the common prefix optimization
+# and return the correct top 3 rows when ordering by all columns.
+query TII
+select column1, column2, column3 from partial_sorted order by column1 desc, column2 asc, column3 desc limit 3;
+----
+C 7 60
+C 11 90
+B 9 70
+
+## explain_physical_plan_only
+statement ok
+set datafusion.explain.physical_plan_only = true
+
+# Verify that the physical plan includes the sort prefix.
+# The output should display a "sort_prefix" in the SortExec node.
+query TT
+explain select column1, column2, column3 from partial_sorted order by column1 desc, column2 asc, column3 desc limit 3;
+----
+physical_plan
+01)SortExec: TopK(fetch=3), expr=[column1@0 DESC, column2@1 ASC NULLS LAST, column3@2 DESC], preserve_partitioning=[false], sort_prefix=[column1@0 DESC, column2@1 ASC NULLS LAST]
Review Comment:
Nicely 2-column sort_prefix
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -681,4 +793,98 @@ mod tests {
record_batch_store.unuse(0);
assert_eq!(record_batch_store.batches_size, 0);
}
+
+ /// This test validates that the `try_finish` method marks the TopK operator as finished
+ /// when the prefix (on column "a") of the last row in the current batch is strictly greater
+ /// than the worst topβk row.
+ /// The full sort expression is defined on both columns ("a", "b"), but the input ordering is only on "a".
+ #[tokio::test]
+ async fn test_try_finish_marks_finished_with_prefix() -> Result<()> {
+ // Create a schema with two columns.
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("a", DataType::Int32, false),
+ Field::new("b", DataType::Float64, false),
+ ]));
+
+ // Create sort expressions.
+ // Full sort: first by "a", then by "b".
+ let sort_expr_a = PhysicalSortExpr {
+ expr: col("a", schema.as_ref())?,
+ options: SortOptions::default(),
+ };
+ let sort_expr_b = PhysicalSortExpr {
+ expr: col("b", schema.as_ref())?,
+ options: SortOptions::default(),
+ };
+
+ // Input ordering uses only column "a" (a prefix of the full sort).
+ let input_ordering = LexOrdering::from(vec![sort_expr_a.clone()]);
+ let full_expr = LexOrdering::from(vec![sort_expr_a, sort_expr_b]);
+
+ // Create a dummy runtime environment and metrics.
+ let runtime = Arc::new(RuntimeEnv::default());
+ let metrics = ExecutionPlanMetricsSet::new();
+
+ // Create a TopK instance with k = 3 and batch_size = 2.
+ let mut topk = TopK::try_new(
+ 0,
+ Arc::clone(&schema),
+ input_ordering,
+ full_expr,
+ 3,
+ 2,
+ runtime,
+ &metrics,
+ )?;
+
+ // Create the first batch with two columns:
+ // Column "a": [1, 1, 2], Column "b": [10.0, 20.0, 10.0].
+ let array_a1: ArrayRef =
+ Arc::new(Int32Array::from(vec![Some(1), Some(1), Some(3)]));
+ let array_b1: ArrayRef = Arc::new(Float64Array::from(vec![10.0, 20.0, 30.0]));
+ let batch1 = RecordBatch::try_new(Arc::clone(&schema), vec![array_a1, array_b1])?;
+
+ // Insert the first batch.
+ // At this point the heap is not yet βfinishedβ because the prefix (last row value in column "a" is 3)
+ // is not strictly greater than the worst topβk row.
+ topk.insert_batch(batch1)?;
+ assert!(
+ !topk.finished,
+ "Expected 'finished' to be false after the first batch."
+ );
+
+ // Create the second batch with two columns:
+ // Column "a": [2, 3], Column "b": [30.0, 10.0].
Review Comment:
Make `"b": [20.0, 10.0]`.
The purpose of the change and the above change is to have data still return top 3 rows but the third row will come from batch2. Also 2 first rows of batch1 will also get sorted by on a and b
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2031142700
##########
datafusion/physical-expr/src/equivalence/properties/mod.rs:
##########
@@ -575,10 +576,35 @@ impl EquivalenceProperties {
// From the analysis above, we know that `[a ASC]` is satisfied. Then,
// we add column `a` as constant to the algorithm state. This enables us
// to deduce that `(b + c) ASC` is satisfied, given `a` is constant.
- eq_properties = eq_properties
- .with_constants(std::iter::once(ConstExpr::from(normalized_req.expr)));
+ eq_properties = eq_properties.with_constants(std::iter::once(
+ ConstExpr::from(Arc::clone(&normalized_req.expr)),
+ ));
}
- true
+
+ // All requirements are satisfied.
+ normalized_reqs.len()
+ }
+
+ /// Determines the longest prefix of `reqs` that is satisfied by the existing ordering.
+ /// Returns that prefix as a new `LexRequirement`, and a boolean indicating if all the requirements are satisfied.
+ pub fn extract_matching_prefix(
+ &self,
+ reqs: &LexRequirement,
+ ) -> (LexRequirement, bool) {
+ // First, standardize the given requirement:
+ let normalized_reqs = self.normalize_sort_requirements(reqs);
Review Comment:
=> new test added:
```sql
explain
select
column1 + 1 as column1_plus,
column1,
column1 + 1 as other_column1_plus,
column3
from partial_sorted
order by
column1_plus desc,
column1 desc,
other_column1_plus desc,
column3 asc
limit 3;
```
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2030894828
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -1066,22 +1071,33 @@ impl SortExec {
}
/// This function creates the cache object that stores the plan properties such as schema, equivalence properties, ordering, partitioning, etc.
+ /// It also returns the common sort prefix between the input and the sort expressions.
fn compute_properties(
input: &Arc<dyn ExecutionPlan>,
sort_exprs: LexOrdering,
preserve_partitioning: bool,
- ) -> PlanProperties {
+ ) -> (PlanProperties, LexOrdering) {
// Determine execution mode:
let requirement = LexRequirement::from(sort_exprs);
- let sort_satisfied = input
+
+ let (sort_prefix, sort_satisfied) = input
.equivalence_properties()
- .ordering_satisfy_requirement(&requirement);
+ .extract_matching_prefix(&requirement);
+
+ let sort_partially_satisfied = sort_satisfied || !sort_prefix.is_empty();
Review Comment:
absolutely! In my first draft I didn't always compute the `sort_prefix` so the `OR` made sense. It's completely redundant now, I'll remove it.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2030890353
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -183,6 +208,86 @@ impl TopK {
// update memory reservation
self.reservation.try_resize(self.size())?;
+
+ // flag the topK as finished if we know that all
+ // subsequent batches are guaranteed to be worse than the
+ // current topK
+ self.attempt_early_completion(&batch)?;
Review Comment:
I don't think that's possible as we need to insert the batch into the `heap` to update its max value first.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2031147337
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -183,6 +209,87 @@ impl TopK {
// update memory reservation
self.reservation.try_resize(self.size())?;
+
+ // flag the topK as finished if we know that all
+ // subsequent batches are guaranteed to be worse than the
+ // current topK
+ self.attempt_early_completion(&batch)?;
+
+ Ok(())
+ }
+
+ /// If input ordering shares a common sort prefix with the TopK, and if the TopK's heap is full,
+ /// check if the computation can be finished early.
+ /// This is the case if the last row of the current batch is strictly worse than the worst row in the heap,
+ /// comparing only on the shared prefix columns.
+ fn attempt_early_completion(&mut self, batch: &RecordBatch) -> Result<()> {
+ // Early exit if the batch is empty as there is no last row to extract from it.
+ if batch.num_rows() == 0 {
+ return Ok(());
+ }
+
+ // prefix_row_converter is only `Some` if the input ordering has a common prefix with the TopK,
+ // so early exit if it is `None`.
+ let Some(prefix_converter) = &self.common_sort_prefix_converter else {
+ return Ok(());
+ };
+
+ // Early exit if the heap is not full (`heap.max()` only returns `Some` if the heap is full).
+ let Some(worst_topk_row) = self.heap.max() else {
Review Comment:
makes sense. I chose `worst` to avoid `min/max` confusion, but it actually doesn't help! Let's go with `max` everywhere.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#issuecomment-2782810629
π€ `./gh_compare_branch.sh` [Benchmark Script](https://github.com/alamb/datafusion-benchmarking) Running
Linux aal-dev 6.8.0-1016-gcp #18-Ubuntu SMP Fri Oct 4 22:16:29 UTC 2024 x86_64 x86_64 x86_64 GNU/Linux
Comparing perf/partitioned_topk (9e8968856543d41bdc05a85f2002c4a8494c6b58) to 19a1e58071cd60e74faabab805d97fd269418925 [diff](https://github.com/apache/datafusion/compare/19a1e58071cd60e74faabab805d97fd269418925..9e8968856543d41bdc05a85f2002c4a8494c6b58)
Benchmarks: sort_tpch clickbench_1 tpch_mem
Results will be posted here when complete
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2031123145
##########
datafusion/physical-expr/src/equivalence/properties/mod.rs:
##########
@@ -575,10 +576,35 @@ impl EquivalenceProperties {
// From the analysis above, we know that `[a ASC]` is satisfied. Then,
// we add column `a` as constant to the algorithm state. This enables us
// to deduce that `(b + c) ASC` is satisfied, given `a` is constant.
- eq_properties = eq_properties
- .with_constants(std::iter::once(ConstExpr::from(normalized_req.expr)));
+ eq_properties = eq_properties.with_constants(std::iter::once(
+ ConstExpr::from(Arc::clone(&normalized_req.expr)),
+ ));
}
- true
+
+ // All requirements are satisfied.
+ normalized_reqs.len()
+ }
+
+ /// Determines the longest prefix of `reqs` that is satisfied by the existing ordering.
+ /// Returns that prefix as a new `LexRequirement`, and a boolean indicating if all the requirements are satisfied.
+ pub fn extract_matching_prefix(
+ &self,
+ reqs: &LexRequirement,
+ ) -> (LexRequirement, bool) {
+ // First, standardize the given requirement:
+ let normalized_reqs = self.normalize_sort_requirements(reqs);
Review Comment:
Nevermind it actually works as is! I'll simply update the tests, much simpler that way ;)
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#issuecomment-2788659010
@geoffreyclaude I'm going to merge this if you're done with this?
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#issuecomment-2788773538
> Let's make it incremental for consistency.
@berkaysynnada: Looking at this again, I'm pretty sure it should actually be `Final`! On partially sorted input, with or without fetch, the SortExec will only emit once it has processed all it's necessary input data (eventually cancelling the input stream early). I've updated the PR with a new fix commit.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2034693873
##########
datafusion/physical-expr/src/equivalence/properties/mod.rs:
##########
@@ -575,10 +576,35 @@ impl EquivalenceProperties {
// From the analysis above, we know that `[a ASC]` is satisfied. Then,
// we add column `a` as constant to the algorithm state. This enables us
// to deduce that `(b + c) ASC` is satisfied, given `a` is constant.
- eq_properties = eq_properties
- .with_constants(std::iter::once(ConstExpr::from(normalized_req.expr)));
+ eq_properties = eq_properties.with_constants(std::iter::once(
+ ConstExpr::from(Arc::clone(&normalized_req.expr)),
+ ));
}
- true
+
+ // All requirements are satisfied.
+ normalized_reqs.len()
+ }
+
+ /// Determines the longest prefix of `reqs` that is satisfied by the existing ordering.
+ /// Returns that prefix as a new `LexRequirement`, and a boolean indicating if all the requirements are satisfied.
+ pub fn extract_matching_prefix(
+ &self,
+ reqs: &LexRequirement,
+ ) -> (LexRequirement, bool) {
Review Comment:
Yes, I suppose my idea ends up at that point, but it would be an overkill, I realize it now. That way can only be reasonable when we cache the denormalized->normalized mappings in the equivalence properties, and it's not the case right now. So, let's leave it as is. Thank you for convincing me :D
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2038053887
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -70,6 +70,25 @@ use datafusion_physical_expr_common::sort_expr::LexOrdering;
/// The same answer can be produced by simply keeping track of the top
/// K=3 elements, reducing the total amount of required buffer memory.
///
+/// # Partial Sort Optimization
+///
+/// This implementation additionally optimizes queries where the input is already
Review Comment:
π― this is great
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#issuecomment-2782439557
and @gabotechs shared valuable suggestions while I was reviewing the PR. I've approved it as it's good enough to go, but let's go over the given ideas
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2030866742
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -183,6 +208,86 @@ impl TopK {
// update memory reservation
self.reservation.try_resize(self.size())?;
+
+ // flag the topK as finished if we know that all
+ // subsequent batches are guaranteed to be worse than the
+ // current topK
+ self.attempt_early_completion(&batch)?;
+
+ Ok(())
+ }
+
+ /// If input ordering shares a common sort prefix with the TopK, and if the TopK's heap is full,
+ /// check if the computation can be finished early.
+ /// This is the case if the last row of the current batch is strictly worse than the worst row in the heap,
+ /// comparing only on the shared prefix columns.
+ fn attempt_early_completion(&mut self, batch: &RecordBatch) -> Result<()> {
+ // Early exit if the batch is empty as there is no last row to extract from it.
+ if batch.num_rows() == 0 {
+ return Ok(());
+ }
+
+ // prefix_row_converter is only `Some` if the input ordering has a common prefix with the TopK,
+ // so early exit if it is `None`.
+ let prefix_converter = match &self.common_prefix_converter {
+ Some(pc) => pc,
+ None => return Ok(()),
+ };
+
+ // Early exit if the heap is not full (`heap.max()` only returns `Some` if the heap is full).
+ let worst_topk_row = match self.heap.max() {
+ Some(row) => row,
+ None => return Ok(()),
+ };
+
+ // Evaluate the prefix for the last row of the current batch.
+ let last_row_idx = batch.num_rows() - 1;
+ let mut batch_prefix_scratch = prefix_converter.empty_rows(1, 20);
Review Comment:
=> Moved to `const ESTIMATED_BYTES_PER_ROW: usize = 20;`
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2029892886
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -681,4 +793,98 @@ mod tests {
record_batch_store.unuse(0);
assert_eq!(record_batch_store.batches_size, 0);
}
+
+ /// This test validates that the `try_finish` method marks the TopK operator as finished
+ /// when the prefix (on column "a") of the last row in the current batch is strictly greater
+ /// than the worst topβk row.
+ /// The full sort expression is defined on both columns ("a", "b"), but the input ordering is only on "a".
+ #[tokio::test]
+ async fn test_try_finish_marks_finished_with_prefix() -> Result<()> {
+ // Create a schema with two columns.
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("a", DataType::Int32, false),
+ Field::new("b", DataType::Float64, false),
+ ]));
+
+ // Create sort expressions.
+ // Full sort: first by "a", then by "b".
+ let sort_expr_a = PhysicalSortExpr {
+ expr: col("a", schema.as_ref())?,
+ options: SortOptions::default(),
+ };
+ let sort_expr_b = PhysicalSortExpr {
+ expr: col("b", schema.as_ref())?,
+ options: SortOptions::default(),
+ };
+
+ // Input ordering uses only column "a" (a prefix of the full sort).
+ let input_ordering = LexOrdering::from(vec![sort_expr_a.clone()]);
+ let full_expr = LexOrdering::from(vec![sort_expr_a, sort_expr_b]);
+
+ // Create a dummy runtime environment and metrics.
+ let runtime = Arc::new(RuntimeEnv::default());
+ let metrics = ExecutionPlanMetricsSet::new();
+
+ // Create a TopK instance with k = 3 and batch_size = 2.
+ let mut topk = TopK::try_new(
+ 0,
+ Arc::clone(&schema),
+ input_ordering,
+ full_expr,
+ 3,
+ 2,
+ runtime,
+ &metrics,
+ )?;
+
+ // Create the first batch with two columns:
+ // Column "a": [1, 1, 2], Column "b": [10.0, 20.0, 10.0].
Review Comment:
Nice catch, I had updated the `b` in the comment but not in the code... and got confused. I was aiming for what you suggested!
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input (10x speedup on top10 bench) [datafusion]
Posted by "berkaysynnada (via GitHub)" <gi...@apache.org>.
berkaysynnada commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2030660456
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -966,6 +966,8 @@ pub struct SortExec {
preserve_partitioning: bool,
/// Fetch highest/lowest n results
fetch: Option<usize>,
+ /// Common sort prefix between the input and the sort expressions (only used with fetch)
+ common_sort_prefix: LexOrdering,
Review Comment:
Here, can we just keep the common prefix expr count of
```rust
/// Sort expressions
expr: LexOrdering
```
? I think it'll be more simplified, and avoiding duplication
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -1066,22 +1071,33 @@ impl SortExec {
}
/// This function creates the cache object that stores the plan properties such as schema, equivalence properties, ordering, partitioning, etc.
+ /// It also returns the common sort prefix between the input and the sort expressions.
fn compute_properties(
input: &Arc<dyn ExecutionPlan>,
sort_exprs: LexOrdering,
preserve_partitioning: bool,
- ) -> PlanProperties {
+ ) -> (PlanProperties, LexOrdering) {
// Determine execution mode:
let requirement = LexRequirement::from(sort_exprs);
- let sort_satisfied = input
+
+ let (sort_prefix, sort_satisfied) = input
.equivalence_properties()
- .ordering_satisfy_requirement(&requirement);
+ .extract_matching_prefix(&requirement);
+
+ let sort_partially_satisfied = sort_satisfied || !sort_prefix.is_empty();
Review Comment:
Having a non-empty sort_prefix should be enough IMO, since there should be no possibility of having an empty `sort_exprs: LexOrdering` from the input arguments
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -183,6 +208,86 @@ impl TopK {
// update memory reservation
self.reservation.try_resize(self.size())?;
+
+ // flag the topK as finished if we know that all
+ // subsequent batches are guaranteed to be worse than the
+ // current topK
+ self.attempt_early_completion(&batch)?;
Review Comment:
If you can somehow check this attempt before registering the batch, we won't need to clone the batch
##########
datafusion/core/tests/physical_optimizer/enforce_sorting.rs:
##########
@@ -1652,7 +1652,7 @@ async fn test_remove_unnecessary_sort7() -> Result<()> {
) as Arc<dyn ExecutionPlan>;
let expected_input = [
- "SortExec: TopK(fetch=2), expr=[non_nullable_col@1 ASC], preserve_partitioning=[false]",
+ "SortExec: TopK(fetch=2), expr=[non_nullable_col@1 ASC], preserve_partitioning=[false], sort_prefix=[non_nullable_col@1 ASC]",
Review Comment:
If we just keep the common prefix count, it will simplify the displays too
##########
datafusion/physical-plan/src/sorts/sort.rs:
##########
@@ -1066,22 +1071,33 @@ impl SortExec {
}
/// This function creates the cache object that stores the plan properties such as schema, equivalence properties, ordering, partitioning, etc.
+ /// It also returns the common sort prefix between the input and the sort expressions.
fn compute_properties(
input: &Arc<dyn ExecutionPlan>,
sort_exprs: LexOrdering,
preserve_partitioning: bool,
- ) -> PlanProperties {
+ ) -> (PlanProperties, LexOrdering) {
// Determine execution mode:
let requirement = LexRequirement::from(sort_exprs);
- let sort_satisfied = input
+
+ let (sort_prefix, sort_satisfied) = input
.equivalence_properties()
- .ordering_satisfy_requirement(&requirement);
+ .extract_matching_prefix(&requirement);
+
+ let sort_partially_satisfied = sort_satisfied || !sort_prefix.is_empty();
// The emission type depends on whether the input is already sorted:
- // - If already sorted, we can emit results in the same way as the input
+ // - If already fully sorted, we can emit results in the same way as the input
+ // - If partially sorted, we might be able to emit results incrementally, but it is not guaranteed (Both)
// - If not sorted, we must wait until all data is processed to emit results (Final)
let emission_type = if sort_satisfied {
input.pipeline_behavior()
+ } else if sort_partially_satisfied {
+ if input.pipeline_behavior() == EmissionType::Incremental {
+ EmissionType::Both
Review Comment:
You can just say `input.pipeline_behavior()`, as Both means there is an internal accumulation within the operator, and those accumulated results are emitted after input exhaust. However the emission depends on the changes of common prefix values mainly, not the input termination.
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -90,15 +90,38 @@ pub struct TopK {
scratch_rows: Rows,
/// stores the top k values and their sort key values, in order
heap: TopKHeap,
+ /// row converter, for common keys between the sort keys and the input ordering
+ common_prefix_converter: Option<RowConverter>,
+ /// Common sort prefix between the input and the sort expressions to allow early exit optimization
+ common_sort_prefix: Arc<[PhysicalSortExpr]>,
Review Comment:
If we decide keeping the count only, this field simplifies as well
##########
datafusion/physical-expr/src/equivalence/properties/mod.rs:
##########
@@ -575,10 +576,35 @@ impl EquivalenceProperties {
// From the analysis above, we know that `[a ASC]` is satisfied. Then,
// we add column `a` as constant to the algorithm state. This enables us
// to deduce that `(b + c) ASC` is satisfied, given `a` is constant.
- eq_properties = eq_properties
- .with_constants(std::iter::once(ConstExpr::from(normalized_req.expr)));
+ eq_properties = eq_properties.with_constants(std::iter::once(
+ ConstExpr::from(Arc::clone(&normalized_req.expr)),
+ ));
}
- true
+
+ // All requirements are satisfied.
+ normalized_reqs.len()
+ }
+
+ /// Determines the longest prefix of `reqs` that is satisfied by the existing ordering.
+ /// Returns that prefix as a new `LexRequirement`, and a boolean indicating if all the requirements are satisfied.
+ pub fn extract_matching_prefix(
+ &self,
+ reqs: &LexRequirement,
+ ) -> (LexRequirement, bool) {
Review Comment:
Again, we can just return the count of matched prefix length here
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] perf: Introduce sort prefix computation for early TopK exit optimization on partially sorted input [datafusion]
Posted by "geoffreyclaude (via GitHub)" <gi...@apache.org>.
geoffreyclaude commented on code in PR #15563:
URL: https://github.com/apache/datafusion/pull/15563#discussion_r2028543416
##########
datafusion/physical-plan/src/topk/mod.rs:
##########
@@ -90,15 +90,38 @@ pub struct TopK {
scratch_rows: Rows,
/// stores the top k values and their sort key values, in order
heap: TopKHeap,
+ /// row converter, for common keys between the sort keys and the input ordering
+ common_prefix_converter: Option<RowConverter>,
+ /// Common sort prefix between the input and the sort expressions to allow early exit optimization
+ common_sort_prefix: Arc<[PhysicalSortExpr]>,
+ /// If true, indicates that all rows of subsequent batches are guaranteed to be worse than the top K
+ pub(crate) finished: bool,
+}
+
+fn build_sort_fields(
+ ordering: &LexOrdering,
+ schema: &SchemaRef,
+) -> Result<Vec<SortField>> {
+ ordering
+ .iter()
+ .map(|e| {
+ Ok(SortField::new_with_options(
+ e.expr.data_type(schema)?,
+ e.options,
+ ))
+ })
+ .collect::<Result<_>>()
}
impl TopK {
/// Create a new [`TopK`] that stores the top `k` values, as
/// defined by the sort expressions in `expr`.
// TODO: make a builder or some other nicer API
+ #[allow(clippy::too_many_arguments)]
Review Comment:
The `TopK` code could benefit from a deep refactoring for clarity. It's probably grown a bit too much out of it's original compact format...
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org