You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "jayzhan211 (via GitHub)" <gi...@apache.org> on 2026/08/30 14:17:28 UTC
[PR] perf: Avoid cloning EquivalenceProperties in ordering satisfaction checks [datafusion]
jayzhan211 opened a new pull request, #24800:
URL: https://github.com/apache/datafusion/pull/24800
## Which issue does this PR close?
- Closes #.
## Rationale for this change
Physical planning asks "is this ordering already satisfied?" constantly — sort
removal, `EnforceSorting`, `EnforceDistribution`, and the requirement checks for
windows, joins and aggregates all call into
`EquivalenceProperties::ordering_satisfy`, `ordering_satisfy_requirement` and
`extract_common_sort_prefix`.
Each of those calls deep-clones the entire `EquivalenceProperties` — every
equivalence class, every equivalent ordering, and the normalized ordering cache —
before doing anything else, even when it never modifies the copy.
The clone exists for a real reason: as the check walks a multi-key ordering left
to right, it registers each satisfied key as a constant so the next key is
evaluated within that key's tie group. That mutates state, so it needs its own
copy. But two cases pay for it and get nothing back:
1. **A single-key check never mutates anything.** There is no "next key" to set up
for, so the whole clone is wasted. This is the most common shape of these calls.
2. **The last key of *any* check registers constants nobody reads.** After the
final key is verified, the code still calls `add_satisfied_key_constants`,
which rebuilds the ordering cache and re-runs ordering discovery — and then the
object is dropped.
## What changes are included in this PR?
Two changes in `EquivalenceProperties`, to `ordering_satisfy_requirement` and
`common_sort_prefix_length` (the latter backs `ordering_satisfy`,
`extract_common_sort_prefix` and `reorder`):
- **Clone on first write instead of up front.** The loop borrows `self` and clones
only when it actually needs to register a constant. Single-key checks never
clone at all.
- **Skip the registration after the last key.** Nothing reads it.
Plus a new criterion benchmark, `equivalence_properties`, covering these entry
points.
This only changes *when* the copy is made — the results of these functions are
unchanged.
## Metrics
Apple M4 Pro, rustc 1.97.0, criterion. All changes significant at p = 0.00.
Properties under test: 3 equivalent orderings (`[c0,c1,c2,c3]`, `[c4,c5]`, `[c6]`)
and a varying number of equivalence classes.
**At 8 equivalence classes:**
| benchmark | before | after | change |
|---|---:|---:|---|
| `ordering_satisfy` — 1 key | 2.72 µs | 0.41 µs | **−84.9%** |
| `ordering_satisfy` — 1 key, unsatisfied | 1.47 µs | 0.41 µs | **−72.5%** |
| `ordering_satisfy_requirement` — 1 key | 2.70 µs | 0.36 µs | **−86.3%** |
| `ordering_satisfy_requirement` — 4 keys | 7.15 µs | 6.07 µs | −13.8% |
| `ordering_satisfy` — 4 keys | 6.99 µs | 6.20 µs | −11.6% |
| `extract_common_sort_prefix` — 4 keys | 7.22 µs | 6.38 µs | −9.2% |
**How it scales** (`ordering_satisfy`, 1 key):
| equivalence classes | before | after | change |
|---:|---:|---:|---|
| 2 | 2.44 µs | 0.43 µs | −82.5% |
| 8 | 2.72 µs | 0.41 µs | −84.9% |
| 32 | 4.63 µs | 0.41 µs | **−90.8%** |
Reading the tables: for an *N*-key check the work goes from
`1 clone + N registrations` to `(N > 1 ? 1 : 0) clones + (N − 1) registrations`.
- **1-key checks** drop both the clone and the registration. Note the "after"
column is flat at ~0.41 µs regardless of how many equivalence classes exist —
with the clone gone, the check no longer scales with the size of the
equivalence group at all. The "before" column does, which is why the win grows
from −82% to −91%.
- **Multi-key checks** still clone once and save one of *N* registrations. Since a
registration rebuilds the ordering cache and re-runs ordering discovery, that
single saved call is worth 9–14% here, rising to −37.8% for `4_keys` at 32
classes.
### Reproducing
The benchmark is included in this PR, so reverting just the one source file gives
you the baseline:
```bash
# baseline: this PR's parent version of the file, with the new benchmark kept
git checkout HEAD^ -- datafusion/physical-expr/src/equivalence/properties/mod.rs
cargo bench -p datafusion-physical-expr --bench equivalence_properties -- --save-baseline before
# with the change
git checkout HEAD -- datafusion/physical-expr/src/equivalence/properties/mod.rs
cargo bench -p datafusion-physical-expr --bench equivalence_properties -- --baseline before
```
The second run prints criterion's own `change: [...] (p = ...)` line per
benchmark.
## Are these changes tested?
No new correctness tests: this does not change what any of these functions
return, so existing coverage is the right check. Covered by the `equivalence`
unit tests in `datafusion/physical-expr` and, for plan-shape regressions, by
sqllogictest — these functions decide whether a `SortExec` can be removed, so a
behavior change would surface as a diff in an `EXPLAIN` plan.
Full workspace suite
(`--features avro,json,backtrace,extended_tests,recursive_protection,parquet_encryption`):
10,981 passed, 0 failed, and all 505 sqllogictest files pass. `./dev/rust_lint.sh`
is clean.
## Are there any user-facing changes?
No. No public API or behavior changes — planning is just faster.
--
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: Avoid cloning EquivalenceProperties in ordering satisfaction checks [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 merged PR #24800:
URL: https://github.com/apache/datafusion/pull/24800
--
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: Avoid cloning EquivalenceProperties in ordering satisfaction checks [datafusion]
Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #24800:
URL: https://github.com/apache/datafusion/pull/24800#issuecomment-5469320586
## [Codecov](https://app.codecov.io/gh/apache/datafusion/pull/24800?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `88.88889%` with `2 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 81.53%. Comparing base ([`4ada0dc`](https://app.codecov.io/gh/apache/datafusion/commit/4ada0dcabbf502f751a7c21cf6cb642154637af9?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`4cc4264`](https://app.codecov.io/gh/apache/datafusion/commit/4cc42645b7c13f60cd6bb26795903063f5b23531?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
:warning: Report is 2 commits behind head on main.
| [Files with missing lines](https://app.codecov.io/gh/apache/datafusion/pull/24800?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [...on/physical-expr/src/equivalence/properties/mod.rs](https://app.codecov.io/gh/apache/datafusion/pull/24800?src=pr&el=tree&filepath=datafusion%2Fphysical-expr%2Fsrc%2Fequivalence%2Fproperties%2Fmod.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9waHlzaWNhbC1leHByL3NyYy9lcXVpdmFsZW5jZS9wcm9wZXJ0aWVzL21vZC5ycw==) | 88.88% | [0 Missing and 2 partials :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/24800?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## main #24800 +/- ##
=======================================
Coverage 81.53% 81.53%
=======================================
Files 1123 1123
Lines 406041 406115 +74
Branches 406041 406115 +74
=======================================
+ Hits 331049 331117 +68
- Misses 55631 55632 +1
- Partials 19361 19366 +5
```
</details>
[:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/datafusion/pull/24800?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</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: Avoid cloning EquivalenceProperties in ordering satisfaction checks [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on PR #24800:
URL: https://github.com/apache/datafusion/pull/24800#issuecomment-5511162139
Thanks @kosiew !
--
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: Avoid cloning EquivalenceProperties in ordering satisfaction checks [datafusion]
Posted by "kosiew (via GitHub)" <gi...@apache.org>.
kosiew commented on code in PR #24800:
URL: https://github.com/apache/datafusion/pull/24800#discussion_r3912836586
##########
datafusion/physical-expr/benches/equivalence_properties.rs:
##########
@@ -0,0 +1,150 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Benchmarks for the ordering satisfaction checks on [`EquivalenceProperties`].
+//!
+//! These are called repeatedly during physical optimization (sort removal,
+//! `EnforceSorting`, `EnforceDistribution`, and the requirement checks for
+//! windows, joins and aggregates), so their cost shows up directly in planning
+//! time.
+//!
+//! The benchmarks are parameterized by the number of equivalence classes, since
+//! that -- not the schema width, which is behind an `Arc` -- is what these
+//! checks carry around.
+
+use std::sync::Arc;
+
+use arrow::compute::SortOptions;
+use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
+use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
+use datafusion_physical_expr::expressions::Column;
+use datafusion_physical_expr::{
+ EquivalenceProperties, LexOrdering, PhysicalExpr, PhysicalSortExpr,
+ PhysicalSortRequirement,
+};
+
+fn schema(n_cols: usize) -> SchemaRef {
+ Arc::new(Schema::new(
+ (0..n_cols)
+ .map(|i| Field::new(format!("c{i}"), DataType::Int32, true))
+ .collect::<Vec<_>>(),
+ ))
+}
+
+fn col(i: usize) -> Arc<dyn PhysicalExpr> {
+ Arc::new(Column::new(&format!("c{i}"), i))
+}
+
+fn asc(i: usize) -> PhysicalSortExpr {
+ PhysicalSortExpr::new(col(i), SortOptions::default())
+}
+
+/// Properties with three equivalent orderings and `n_classes` equivalence
+/// classes, i.e. roughly what a scan feeding a join and a window function looks
+/// like. Columns `c0..c7` carry the orderings; the equivalence classes are built
+/// from the columns above them.
+fn properties(n_classes: usize) -> EquivalenceProperties {
+ let schema = schema(8 + 2 * n_classes);
+ let mut props = EquivalenceProperties::new(schema);
+ props.add_orderings([
+ vec![asc(0), asc(1), asc(2), asc(3)],
+ vec![asc(4), asc(5)],
+ vec![asc(6)],
+ ]);
+ for i in 0..n_classes {
+ props
+ .add_equal_conditions(col(8 + 2 * i), col(9 + 2 * i))
+ .unwrap();
+ }
+ props
+}
+
+fn bench_ordering_satisfaction(c: &mut Criterion) {
+ let mut group = c.benchmark_group("equivalence_properties");
+
+ for n_classes in [2, 8, 32] {
+ let props = properties(n_classes);
+
+ // A single sort key: the most common shape by far.
+ group.bench_with_input(
Review Comment:
Nice to have benchmark coverage for this. One thought: if the goal is to isolate the cost of the satisfaction checks themselves, could we pre-build the ordering/requirement inputs and use `iter_batched` so the per-iteration setup stays outside the timed routine? Right now the closures also create `Column`s and `PhysicalSortExpr`s, and the prefix benchmark builds the `LexOrdering`, so those costs are included in the measurements. If the intention is to measure the end-to-end caller cost instead, keeping the setup here makes sense, but it would be helpful to document that scope. We would still want any cloning that is part of the operation under test to remain inside the timed iteration.
--
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: Avoid cloning EquivalenceProperties in ordering satisfaction checks [datafusion]
Posted by "jayzhan211 (via GitHub)" <gi...@apache.org>.
jayzhan211 commented on code in PR #24800:
URL: https://github.com/apache/datafusion/pull/24800#discussion_r3914329364
##########
datafusion/physical-expr/benches/equivalence_properties.rs:
##########
@@ -0,0 +1,150 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Benchmarks for the ordering satisfaction checks on [`EquivalenceProperties`].
+//!
+//! These are called repeatedly during physical optimization (sort removal,
+//! `EnforceSorting`, `EnforceDistribution`, and the requirement checks for
+//! windows, joins and aggregates), so their cost shows up directly in planning
+//! time.
+//!
+//! The benchmarks are parameterized by the number of equivalence classes, since
+//! that -- not the schema width, which is behind an `Arc` -- is what these
+//! checks carry around.
+
+use std::sync::Arc;
+
+use arrow::compute::SortOptions;
+use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
+use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
+use datafusion_physical_expr::expressions::Column;
+use datafusion_physical_expr::{
+ EquivalenceProperties, LexOrdering, PhysicalExpr, PhysicalSortExpr,
+ PhysicalSortRequirement,
+};
+
+fn schema(n_cols: usize) -> SchemaRef {
+ Arc::new(Schema::new(
+ (0..n_cols)
+ .map(|i| Field::new(format!("c{i}"), DataType::Int32, true))
+ .collect::<Vec<_>>(),
+ ))
+}
+
+fn col(i: usize) -> Arc<dyn PhysicalExpr> {
+ Arc::new(Column::new(&format!("c{i}"), i))
+}
+
+fn asc(i: usize) -> PhysicalSortExpr {
+ PhysicalSortExpr::new(col(i), SortOptions::default())
+}
+
+/// Properties with three equivalent orderings and `n_classes` equivalence
+/// classes, i.e. roughly what a scan feeding a join and a window function looks
+/// like. Columns `c0..c7` carry the orderings; the equivalence classes are built
+/// from the columns above them.
+fn properties(n_classes: usize) -> EquivalenceProperties {
+ let schema = schema(8 + 2 * n_classes);
+ let mut props = EquivalenceProperties::new(schema);
+ props.add_orderings([
+ vec![asc(0), asc(1), asc(2), asc(3)],
+ vec![asc(4), asc(5)],
+ vec![asc(6)],
+ ]);
+ for i in 0..n_classes {
+ props
+ .add_equal_conditions(col(8 + 2 * i), col(9 + 2 * i))
+ .unwrap();
+ }
+ props
+}
+
+fn bench_ordering_satisfaction(c: &mut Criterion) {
+ let mut group = c.benchmark_group("equivalence_properties");
+
+ for n_classes in [2, 8, 32] {
+ let props = properties(n_classes);
+
+ // A single sort key: the most common shape by far.
+ group.bench_with_input(
Review Comment:
Good point — the setup was measurable, not incidental. `asc(i)` does a `format!` plus an `Arc` allocation per key per iteration, which was a real fraction of a ~400 ns measurement.
Switched to `iter_batched`: the sort exprs, requirements and the `LexOrdering` are now built once up front, and since each check takes its input by value, the untimed setup step hands each iteration a fresh clone. Only the call is timed. Also swapped `bench_with_input` for `bench_function`, as the parameter was only being used as a label.
Cloning done *inside* the check stays inside the timed iteration — that is the thing this PR is about, so it has to be measured.
It moved the numbers in the direction you'd expect. At 8 equivalence classes, 1 key:
| | before | after | change |
|---|---:|---:|---|
| `ordering_satisfy` | 2.73 µs | 0.36 µs | −86.6% (was −84.9%) |
| `ordering_satisfy_requirement` | 2.90 µs | 0.30 µs | −89.2% (was −86.3%) |
The old numbers were understating the improvement, since the constant setup cost sat in both columns.
I also documented the scope in the module header rather than leaving it implicit:
```rust
//! # Scope
//!
//! These measure the satisfaction check itself, not the cost of assembling its
//! arguments. The sort expressions, requirements and orderings are built once,
//! up front. Because the checks take their input by value, each iteration gets a
//! fresh copy from the untimed setup step of `iter_batched`; only the call is
//! timed. Any copying the check does internally is part of what is measured.
```
Metrics in the PR description updated to match.
--
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