You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "comphead (via GitHub)" <gi...@apache.org> on 2026/10/03 22:14:07 UTC
[PR] feat: decorrelate a window below a correlated equality filter [datafusion]
comphead opened a new pull request, #26013:
URL: https://github.com/apache/datafusion/pull/26013
## Which issue does this PR close?
- Closes #25897.
## Rationale for this change
Since #25838, a correlated filter below a window function keeps the subquery correlated unless the filter reads only `PARTITION BY` columns. Such queries fail with "Physical plan does not support logical expression ...". For example (#25792):
```sql
SELECT t1.id, sub.id, sub.rn
FROM t1, LATERAL (
SELECT t2.id, row_number() OVER (ORDER BY t2.id) AS rn
FROM (SELECT * FROM t2 WHERE t2.t1_id = t1.id) AS t2
) AS sub;
```
One case still returns wrong results on `main`. When the correlated filter repeats the `IN` predicate, `remove_duplicated_filter` drops it before the pull up records its column, so the `Window` arm sees no correlated column and lets the filter move above the window:
```sql
CREATE TABLE win_outer(k INT) AS VALUES (1), (2), (5);
CREATE TABLE win_inner(id INT, y INT) AS VALUES (1, 1), (2, 2);
SELECT win_outer.k FROM win_outer
WHERE win_outer.k IN (
SELECT win_inner.y FROM win_inner
WHERE win_inner.y = win_outer.k
QUALIFY row_number() OVER (ORDER BY win_inner.id) = 1);
```
| `main` | This PR, DuckDB |
| --- | --- |
| `1` | `1`, `2` |
## What changes are included in this PR?
All in `PullUpCorrelatedExpr` (`decorrelate.rs`):
- When every correlated conjunct has the form `col = <outer expr>`, the filter keeps the rows of one `col` value for each outer row. The pull up adds `col` to the `PARTITION BY` of every window function and pulls the filter above the window, as Spark (`DecorrelateInnerQuery`) and DuckDB (`FlattenDependentJoins`) do. A Projection on top restores the old window column names. Window functions that become equal are computed once.
- Only a plain column qualifies. `can_pullup_over_aggregation` also accepts `CAST(col AS ..) = <outer expr>`, but a lossy cast lets several `col` values match one outer row, so that case stays correlated.
- A window over an input with count bug handling stays correlated, as before.
- A new map, `in_predicate_cols_map`, holds the columns of the conjuncts that `remove_duplicated_filter` drops because the `IN` predicate repeats them. The `Window` arm reads it next to `correlated_subquery_cols_map`, which fixes the wrong result above. The map stays empty unless the `IN` predicate repeats a correlated conjunct.
The core of the change is @adriangb's commit 1a2ad03ab, which #25838 reverted to stay a bug fix.
## What is the testing strategy for this PR?
- `subquery.slt` and `lateral_join.slt`: the window cases from #25838 that expected an error now check results (`EXISTS`, `NOT EXISTS`, `IN`, scalar, `LATERAL`, `PARTITION BY y + 0`), plus an `EXPLAIN` that shows `PARTITION BY [b.y]`.
- New cases: a lossy `CAST` and a non-equality filter stay correlated, and the `IN` + `QUALIFY` query above returns `1, 2`.
- `exists_subquery_window_functions_become_equal` in `decorrelate_predicate_subquery.rs` covers window functions that become equal. The SQL planner puts these two in different `Window` nodes, so the test builds the plan with `LogicalPlanBuilder::window`.
Each new case fails when its part of the change is reverted.
`sql_planner` (`physical_plan_tpch_all`, `physical_plan_tpcds_all`) shows no change beyond run-to-run drift. Two runs of `main` differ by 2.3% on TPC-H, and this PR is within 1.7% of `main` on TPC-H and 0.3% on TPC-DS.
## Are there any user-facing changes?
Queries with a correlated equality below a window function now run instead of failing with a not-implemented error. The `IN` case above returns correct results. No API change.
--
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] feat: decorrelate a window below a correlated equality filter [datafusion]
Posted by "kumarUjjawal (via GitHub)" <gi...@apache.org>.
kumarUjjawal commented on code in PR #26013:
URL: https://github.com/apache/datafusion/pull/26013#discussion_r4306661595
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -577,6 +581,17 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr {
.iter()
.all(|expr| partitions_by_all(expr, &local_correlated_cols))
{
+ // `inner.y = outer.k` keeps the rows of one `y` value for
+ // each outer row, so partitioning by `y` as well gives each
+ // window function the same rows.
+ if self.can_extend_partition_by
+ && !self.collected_count_expr_map.contains_key(&*window.input)
Review Comment:
There is still a gap when a projection discards the aggregate column. `SELECT 1 AS x` drops the `collected_count_expr_map` entry, so the window guard misses it.
I reproduced this on `0092bee2a`:
```sql
CREATE TABLE o(k INT) AS VALUES (1), (2), (5);
CREATE TABLE i(y INT) AS VALUES (1), (2);
SELECT o.k,
(SELECT count(*) OVER ()
FROM (
SELECT 1 AS x
FROM (SELECT count(*) AS c FROM i WHERE i.y = o.k) a
) b) AS n
FROM o ORDER BY o.k;
```
Expected: `(1,1), (2,1), (5,1)`. This PR returns `(5,NULL)` for the last row. The merge base rejects the query as unsupported.
The inner `count(*)` returns one row even without a match. We need to preserve that guard through the projection and add this regression test.
--
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] feat: decorrelate a window below a correlated equality filter [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #26013:
URL: https://github.com/apache/datafusion/pull/26013#discussion_r4296833568
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -828,6 +888,24 @@ fn can_pullup_over_aggregation(expr: &Expr) -> bool {
}
}
+/// Whether `expr` is `col = <expr>` or `<expr> = col`, where `<expr>` reads no
+/// subquery column. `CAST(col AS ..)` does not qualify: a lossy cast lets
+/// several `col` values match one outer row, see #26014.
+fn is_column_equality(expr: &Expr) -> bool {
+ let Expr::BinaryExpr(BinaryExpr {
+ left,
+ op: Operator::Eq,
+ right,
+ }) = expr
+ else {
+ return false;
+ };
+ match (&**left, &**right) {
+ (Expr::Column(_), other) | (other, Expr::Column(_)) => !other.any_column_refs(),
Review Comment:
Fixed in 0092bee2a. A cast now qualifies when `is_injective_cast` holds, so `INT = BIGINT` coercion is accepted. That helper existed as a private map key helper in `datafusion-common`, so I renamed it and made it `pub`. Lossy casts still stay correlated (#26014), and a new slt case covers the widening cast.
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -828,6 +888,24 @@ fn can_pullup_over_aggregation(expr: &Expr) -> bool {
}
}
+/// Whether `expr` is `col = <expr>` or `<expr> = col`, where `<expr>` reads no
+/// subquery column. `CAST(col AS ..)` does not qualify: a lossy cast lets
+/// several `col` values match one outer row, see #26014.
+fn is_column_equality(expr: &Expr) -> bool {
Review Comment:
Fixed in 0092bee2a. `can_pullup_over_aggregation` and the new check now share `split_column_equality`.
##########
datafusion/optimizer/src/decorrelate.rs:
##########
Review Comment:
This also fails on `main` today, because `remove_duplicated_filter` drops the correlated filter before `correlated_subquery_cols_map` records it. It is tracked in #26032, so I kept this PR scoped. The PR does not make that case worse.
##########
datafusion/optimizer/src/decorrelate.rs:
##########
Review Comment:
Updated in 0092bee2a.
--
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] feat: decorrelate a window below a correlated equality filter [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on PR #26013:
URL: https://github.com/apache/datafusion/pull/26013#issuecomment-6294445516
@kumarUjjawal PTAL, thanks
--
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] feat: decorrelate a window below a correlated equality filter [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #26013:
URL: https://github.com/apache/datafusion/pull/26013#discussion_r4338631913
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -664,6 +674,16 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr {
.iter()
.all(|expr| partitions_by_all(expr, &local_correlated_cols))
{
+ // `inner.y = outer.k` keeps the rows of one `y` value for
+ // each outer row, so partitioning by `y` as well gives each
+ // window function the same rows. A window over an
+ // aggregate with count bug handling stops the pull up in
+ // `pass_through_pulled_up_cols`.
+ if self.can_extend_partition_by {
Review Comment:
Thanks @kumarUjjawal the rabbit hole is going deeper, makes me thinks we need to improve test coverage
--
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] feat: decorrelate a window below a correlated equality filter [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead merged PR #26013:
URL: https://github.com/apache/datafusion/pull/26013
--
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] feat: decorrelate a window below a correlated equality filter [datafusion]
Posted by "kumarUjjawal (via GitHub)" <gi...@apache.org>.
kumarUjjawal commented on code in PR #26013:
URL: https://github.com/apache/datafusion/pull/26013#discussion_r4332369753
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -664,6 +674,16 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr {
.iter()
.all(|expr| partitions_by_all(expr, &local_correlated_cols))
{
+ // `inner.y = outer.k` keeps the rows of one `y` value for
+ // each outer row, so partitioning by `y` as well gives each
+ // window function the same rows. A window over an
+ // aggregate with count bug handling stops the pull up in
+ // `pass_through_pulled_up_cols`.
+ if self.can_extend_partition_by {
Review Comment:
`DISTINCT` or a `Filter` between the aggregate and window still drops the count-bug state, so this guard misses it. I reproduced `(5, NULL)` instead of `(5, 1)` on `b6debc1c6`; the merge base rejects the query as unsupported. Could we preserve that state, or stop decorrelation, and add regression tests for both cases?
--
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] feat: decorrelate a window below a correlated equality filter [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on PR #26013:
URL: https://github.com/apache/datafusion/pull/26013#issuecomment-5981978281
Thanks @kumarUjjawal for the review, I'll check it out today
--
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] feat: decorrelate a window below a correlated equality filter [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #26013:
URL: https://github.com/apache/datafusion/pull/26013#discussion_r4316877319
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -577,6 +581,17 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr {
.iter()
.all(|expr| partitions_by_all(expr, &local_correlated_cols))
{
+ // `inner.y = outer.k` keeps the rows of one `y` value for
+ // each outer row, so partitioning by `y` as well gives each
+ // window function the same rows.
+ if self.can_extend_partition_by
+ && !self.collected_count_expr_map.contains_key(&*window.input)
Review Comment:
Thanks, confirmed. The root cause was in the Projection: `proj_exprs_evaluation_result_on_empty_batch` only recorded expressions that read an aggregate column, so `1 AS x` left the map empty and the entry was dropped. It now also records expressions that read no column.
With that, the window query stays correlated, as on the merge base. The same projection without the window returned `(5, NULL)` on `main` too. It now returns `(5, 1)`. Both cases are in `subquery.slt`.
--
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] feat: decorrelate a window below a correlated equality filter [datafusion]
Posted by "kumarUjjawal (via GitHub)" <gi...@apache.org>.
kumarUjjawal commented on code in PR #26013:
URL: https://github.com/apache/datafusion/pull/26013#discussion_r4176552768
##########
datafusion/optimizer/src/decorrelate.rs:
##########
Review Comment:
https://github.com/apache/datafusion/blob/0f8bea64617e317c1b6bcec6921aa8dcc332900e/datafusion/optimizer/src/decorrelate.rs#L578
The Window check only sees the correlated columns that are left in `join_filters`. When an `IN` subquery's correlated filter is dropped as a duplicate of the IN predicate, `local_correlated_cols` is empty, so the filter is pulled above the window without any PARTITION BY change.
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -783,6 +798,51 @@ fn correlated_filter_columns(plan: &LogicalPlan) -> Vec<Column> {
cols
}
+/// Adds `cols` to the `PARTITION BY` of every window function of `window`. A
+/// Projection on top gives the window columns their old names back.
+fn partition_window_by(window: &Window, cols: &BTreeSet<Column>) -> Result<LogicalPlan> {
+ let new_window_expr = window
+ .window_expr
+ .iter()
+ .map(|expr| add_partition_by(expr, cols))
+ .collect::<Vec<_>>();
+ let mut proj_exprs = window
+ .input
+ .schema()
+ .columns()
+ .into_iter()
+ .map(Expr::Column)
+ .collect::<Vec<_>>();
+ for (old, new) in window.window_expr.iter().zip(&new_window_expr) {
+ let new_col = Expr::Column(Column::from_name(new.schema_name().to_string()));
Review Comment:
`partition_window_by` builds a new window expression whose name can match a column that already exists below it, so the new Window gets a duplicate field name and the rewrite fails with a plan error.
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -577,6 +581,17 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr {
.iter()
.all(|expr| partitions_by_all(expr, &local_correlated_cols))
{
+ // `inner.y = outer.k` keeps the rows of one `y` value for
+ // each outer row, so partitioning by `y` as well gives each
+ // window function the same rows.
+ if self.can_extend_partition_by
+ && !self.collected_count_expr_map.contains_key(&*window.input)
Review Comment:
The count-bug guard checks only whether the window's direct input is in `collected_count_expr_map`. Before this PR, any Window not partitioned by the column stopped the pull up; now it is extended whenever the direct input is missing from the map.
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -828,6 +888,24 @@ fn can_pullup_over_aggregation(expr: &Expr) -> bool {
}
}
+/// Whether `expr` is `col = <expr>` or `<expr> = col`, where `<expr>` reads no
+/// subquery column. `CAST(col AS ..)` does not qualify: a lossy cast lets
+/// several `col` values match one outer row, see #26014.
+fn is_column_equality(expr: &Expr) -> bool {
Review Comment:
`is_column_equality` repeats the first two arms of `can_pullup_over_aggregation`.
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -783,6 +798,51 @@ fn correlated_filter_columns(plan: &LogicalPlan) -> Vec<Column> {
cols
}
+/// Adds `cols` to the `PARTITION BY` of every window function of `window`. A
+/// Projection on top gives the window columns their old names back.
+fn partition_window_by(window: &Window, cols: &BTreeSet<Column>) -> Result<LogicalPlan> {
+ let new_window_expr = window
+ .window_expr
+ .iter()
+ .map(|expr| add_partition_by(expr, cols))
+ .collect::<Vec<_>>();
+ let mut proj_exprs = window
Review Comment:
The extra Projection only restores the old window column names. Wrapping each changed window expression in an Alias with its old name (`new.alias(old.schema_name())`) does the same job without the extra node and avoids the name collision above.
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -828,6 +888,24 @@ fn can_pullup_over_aggregation(expr: &Expr) -> bool {
}
}
+/// Whether `expr` is `col = <expr>` or `<expr> = col`, where `<expr>` reads no
+/// subquery column. `CAST(col AS ..)` does not qualify: a lossy cast lets
+/// several `col` values match one outer row, see #26014.
+fn is_column_equality(expr: &Expr) -> bool {
+ let Expr::BinaryExpr(BinaryExpr {
+ left,
+ op: Operator::Eq,
+ right,
+ }) = expr
+ else {
+ return false;
+ };
+ match (&**left, &**right) {
+ (Expr::Column(_), other) | (other, Expr::Column(_)) => !other.any_column_refs(),
Review Comment:
Rejecting every `CAST(col)` also rejects lossless widening casts added by type coercion, such as Int32 to Int64. Ordinary queries with mismatched key types still fail with the not-implemented error.
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -783,6 +798,51 @@ fn correlated_filter_columns(plan: &LogicalPlan) -> Vec<Column> {
cols
}
+/// Adds `cols` to the `PARTITION BY` of every window function of `window`. A
+/// Projection on top gives the window columns their old names back.
+fn partition_window_by(window: &Window, cols: &BTreeSet<Column>) -> Result<LogicalPlan> {
+ let new_window_expr = window
+ .window_expr
+ .iter()
+ .map(|expr| add_partition_by(expr, cols))
+ .collect::<Vec<_>>();
+ let mut proj_exprs = window
+ .input
+ .schema()
+ .columns()
+ .into_iter()
+ .map(Expr::Column)
+ .collect::<Vec<_>>();
+ for (old, new) in window.window_expr.iter().zip(&new_window_expr) {
+ let new_col = Expr::Column(Column::from_name(new.schema_name().to_string()));
Review Comment:
The restoring Projection uses `Column::from_name` and `alias_if_changed(old.schema_name())`, which keep only the bare name. Any qualifier on a window output field (an `Alias` with a `relation`) is dropped.
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -783,6 +798,51 @@ fn correlated_filter_columns(plan: &LogicalPlan) -> Vec<Column> {
cols
}
+/// Adds `cols` to the `PARTITION BY` of every window function of `window`. A
+/// Projection on top gives the window columns their old names back.
+fn partition_window_by(window: &Window, cols: &BTreeSet<Column>) -> Result<LogicalPlan> {
+ let new_window_expr = window
+ .window_expr
+ .iter()
+ .map(|expr| add_partition_by(expr, cols))
+ .collect::<Vec<_>>();
+ let mut proj_exprs = window
+ .input
+ .schema()
+ .columns()
+ .into_iter()
+ .map(Expr::Column)
+ .collect::<Vec<_>>();
+ for (old, new) in window.window_expr.iter().zip(&new_window_expr) {
+ let new_col = Expr::Column(Column::from_name(new.schema_name().to_string()));
+ proj_exprs.push(new_col.alias_if_changed(old.schema_name().to_string())?);
+ }
+ LogicalPlanBuilder::from(Arc::clone(&window.input))
+ .window(new_window_expr)?
+ .project(proj_exprs)?
Review Comment:
Avoid window output name collisions after extending partitions.
##########
datafusion/optimizer/src/decorrelate.rs:
##########
Review Comment:
https://github.com/apache/datafusion/blob/0f8bea64617e317c1b6bcec6921aa8dcc332900e/datafusion/optimizer/src/decorrelate.rs#L257
The f_down comment still says a filter moves above a Window only when it reads only `PARTITION BY` columns. f_up now also extends PARTITION BY for column equalities.
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -828,6 +888,24 @@ fn can_pullup_over_aggregation(expr: &Expr) -> bool {
}
}
+/// Whether `expr` is `col = <expr>` or `<expr> = col`, where `<expr>` reads no
+/// subquery column. `CAST(col AS ..)` does not qualify: a lossy cast lets
+/// several `col` values match one outer row, see #26014.
+fn is_column_equality(expr: &Expr) -> bool {
+ let Expr::BinaryExpr(BinaryExpr {
+ left,
+ op: Operator::Eq,
+ right,
+ }) = expr
+ else {
+ return false;
+ };
+ match (&**left, &**right) {
+ (Expr::Column(_), other) | (other, Expr::Column(_)) => !other.any_column_refs(),
Review Comment:
`is_column_equality` accepts `col = <outer expr>` even when `<outer expr>` is volatile, such as `random()`. One outer row can then match several `col` values, which breaks the reason the PARTITION BY rewrite is correct.
--
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] feat: decorrelate a window below a correlated equality filter [datafusion]
Posted by "kumarUjjawal (via GitHub)" <gi...@apache.org>.
kumarUjjawal commented on code in PR #26013:
URL: https://github.com/apache/datafusion/pull/26013#discussion_r4344215965
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -664,6 +674,16 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr {
.iter()
.all(|expr| partitions_by_all(expr, &local_correlated_cols))
{
+ // `inner.y = outer.k` keeps the rows of one `y` value for
+ // each outer row, so partitioning by `y` as well gives each
+ // window function the same rows. A window over an
+ // aggregate with count bug handling stops the pull up in
+ // `pass_through_pulled_up_cols`.
+ if self.can_extend_partition_by {
Review Comment:
Sounds good, thanks for taking care of 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] feat: decorrelate a window below a correlated equality filter [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #26013:
URL: https://github.com/apache/datafusion/pull/26013#discussion_r4338752701
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -664,6 +674,16 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr {
.iter()
.all(|expr| partitions_by_all(expr, &local_correlated_cols))
{
+ // `inner.y = outer.k` keeps the rows of one `y` value for
+ // each outer row, so partitioning by `y` as well gives each
+ // window function the same rows. A window over an
+ // aggregate with count bug handling stops the pull up in
+ // `pass_through_pulled_up_cols`.
+ if self.can_extend_partition_by {
Review Comment:
Thanks @kumarUjjawal. Reproduced both on `b6debc1c6`, and found that `EXISTS`, `NOT EXISTS` and `IN` had the same gap, since they never record count bug state. For example `EXISTS (SELECT count(*) OVER () FROM (SELECT count(*) ... WHERE i.y = o.k))` returned `1, 2` instead of `1, 2, 5`.
Rather than preserving the state through each node, the window now stays correlated whenever the pull up converted an aggregate without `GROUP BY` (`pulled_up_scalar_agg`), which is set for every subquery kind. A window over a grouped aggregate is still partitioned.
New `subquery.slt` cases: `DISTINCT`, a `Filter` that cannot be evaluated on an empty input (`random() >= 0`), `EXISTS`, `NOT EXISTS`, `IN` and `LATERAL` over a scalar aggregate, which stay correlated as on the merge base, and a grouped aggregate below the window, which returns results. The first five fail without the fix.
--
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] feat: decorrelate a window below a correlated equality filter [datafusion]
Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #26013:
URL: https://github.com/apache/datafusion/pull/26013#discussion_r4296832029
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -783,6 +798,51 @@ fn correlated_filter_columns(plan: &LogicalPlan) -> Vec<Column> {
cols
}
+/// Adds `cols` to the `PARTITION BY` of every window function of `window`. A
+/// Projection on top gives the window columns their old names back.
+fn partition_window_by(window: &Window, cols: &BTreeSet<Column>) -> Result<LogicalPlan> {
+ let new_window_expr = window
+ .window_expr
+ .iter()
+ .map(|expr| add_partition_by(expr, cols))
+ .collect::<Vec<_>>();
+ let mut proj_exprs = window
+ .input
+ .schema()
+ .columns()
+ .into_iter()
+ .map(Expr::Column)
+ .collect::<Vec<_>>();
+ for (old, new) in window.window_expr.iter().zip(&new_window_expr) {
+ let new_col = Expr::Column(Column::from_name(new.schema_name().to_string()));
Review Comment:
Fixed in 0092bee2a. Each extended window expression is now aliased to its old name, so the new `Window` has no duplicate field. A test covers a lower window that already outputs the extended name.
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -783,6 +798,51 @@ fn correlated_filter_columns(plan: &LogicalPlan) -> Vec<Column> {
cols
}
+/// Adds `cols` to the `PARTITION BY` of every window function of `window`. A
+/// Projection on top gives the window columns their old names back.
+fn partition_window_by(window: &Window, cols: &BTreeSet<Column>) -> Result<LogicalPlan> {
+ let new_window_expr = window
+ .window_expr
+ .iter()
+ .map(|expr| add_partition_by(expr, cols))
+ .collect::<Vec<_>>();
+ let mut proj_exprs = window
+ .input
+ .schema()
+ .columns()
+ .into_iter()
+ .map(Expr::Column)
+ .collect::<Vec<_>>();
+ for (old, new) in window.window_expr.iter().zip(&new_window_expr) {
+ let new_col = Expr::Column(Column::from_name(new.schema_name().to_string()));
+ proj_exprs.push(new_col.alias_if_changed(old.schema_name().to_string())?);
+ }
+ LogicalPlanBuilder::from(Arc::clone(&window.input))
+ .window(new_window_expr)?
+ .project(proj_exprs)?
Review Comment:
Fixed in 0092bee2a, same change as above. The extended expression keeps its old output name.
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -783,6 +798,51 @@ fn correlated_filter_columns(plan: &LogicalPlan) -> Vec<Column> {
cols
}
+/// Adds `cols` to the `PARTITION BY` of every window function of `window`. A
+/// Projection on top gives the window columns their old names back.
+fn partition_window_by(window: &Window, cols: &BTreeSet<Column>) -> Result<LogicalPlan> {
+ let new_window_expr = window
+ .window_expr
+ .iter()
+ .map(|expr| add_partition_by(expr, cols))
+ .collect::<Vec<_>>();
+ let mut proj_exprs = window
Review Comment:
Done in 0092bee2a. `partition_window_by` now builds `Window::try_new` with `alias_if_changed(old.schema_name())`, and the extra `Projection` is gone.
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -783,6 +798,51 @@ fn correlated_filter_columns(plan: &LogicalPlan) -> Vec<Column> {
cols
}
+/// Adds `cols` to the `PARTITION BY` of every window function of `window`. A
+/// Projection on top gives the window columns their old names back.
+fn partition_window_by(window: &Window, cols: &BTreeSet<Column>) -> Result<LogicalPlan> {
+ let new_window_expr = window
+ .window_expr
+ .iter()
+ .map(|expr| add_partition_by(expr, cols))
+ .collect::<Vec<_>>();
+ let mut proj_exprs = window
+ .input
+ .schema()
+ .columns()
+ .into_iter()
+ .map(Expr::Column)
+ .collect::<Vec<_>>();
+ for (old, new) in window.window_expr.iter().zip(&new_window_expr) {
+ let new_col = Expr::Column(Column::from_name(new.schema_name().to_string()));
Review Comment:
Fixed in 0092bee2a. An `Alias` keeps its `relation` because `add_partition_by` clones it, and the restoring `Projection` that dropped it no longer exists.
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -577,6 +581,17 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr {
.iter()
.all(|expr| partitions_by_all(expr, &local_correlated_cols))
{
+ // `inner.y = outer.k` keeps the rows of one `y` value for
+ // each outer row, so partitioning by `y` as well gives each
+ // window function the same rows.
+ if self.can_extend_partition_by
+ && !self.collected_count_expr_map.contains_key(&*window.input)
Review Comment:
I dropped the explicit guard in 0092bee2a. `pass_through_pulled_up_cols` already sets `can_pull_up = false` when a node input is in `collected_count_expr_map`. `Projection`, `SubqueryAlias`, `Limit` and `Filter` propagate that entry upward. A nested `Window` stops at the inner one. The existing slt case for a window over a count bug aggregate still stays correlated.
##########
datafusion/optimizer/src/decorrelate.rs:
##########
@@ -828,6 +888,24 @@ fn can_pullup_over_aggregation(expr: &Expr) -> bool {
}
}
+/// Whether `expr` is `col = <expr>` or `<expr> = col`, where `<expr>` reads no
+/// subquery column. `CAST(col AS ..)` does not qualify: a lossy cast lets
+/// several `col` values match one outer row, see #26014.
+fn is_column_equality(expr: &Expr) -> bool {
+ let Expr::BinaryExpr(BinaryExpr {
+ left,
+ op: Operator::Eq,
+ right,
+ }) = expr
+ else {
+ return false;
+ };
+ match (&**left, &**right) {
+ (Expr::Column(_), other) | (other, Expr::Column(_)) => !other.any_column_refs(),
Review Comment:
Fixed in 0092bee2a. `is_partitionable_equality` rejects a volatile outer expression, and a new slt case covers it. It fails if the check is removed.
--
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] feat: decorrelate a window below a correlated equality filter [datafusion]
Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #26013:
URL: https://github.com/apache/datafusion/pull/26013#issuecomment-5974242272
## [Codecov](https://app.codecov.io/gh/apache/datafusion/pull/26013?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 `81.63265%` with `27 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 82.64%. Comparing base ([`b2cfc23`](https://app.codecov.io/gh/apache/datafusion/commit/b2cfc23ad4cab1fd00b6e56d5a1dee84f70d111d?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`b534752`](https://app.codecov.io/gh/apache/datafusion/commit/b53475288709008fd2b31d4676a45a5c70122f2e?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
| [Files with missing lines](https://app.codecov.io/gh/apache/datafusion/pull/26013?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [datafusion/optimizer/src/decorrelate.rs](https://app.codecov.io/gh/apache/datafusion/pull/26013?src=pr&el=tree&filepath=datafusion%2Foptimizer%2Fsrc%2Fdecorrelate.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9vcHRpbWl6ZXIvc3JjL2RlY29ycmVsYXRlLnJz) | 85.18% | [10 Missing and 6 partials :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/26013?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [...on/optimizer/src/decorrelate\_predicate\_subquery.rs](https://app.codecov.io/gh/apache/datafusion/pull/26013?src=pr&el=tree&filepath=datafusion%2Foptimizer%2Fsrc%2Fdecorrelate_predicate_subquery.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-ZGF0YWZ1c2lvbi9vcHRpbWl6ZXIvc3JjL2RlY29ycmVsYXRlX3ByZWRpY2F0ZV9zdWJxdWVyeS5ycw==) | 71.79% | [1 Missing and 10 partials :warning: ](https://app.codecov.io/gh/apache/datafusion/pull/26013?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 #26013 +/- ##
==========================================
- Coverage 82.64% 82.64% -0.01%
==========================================
Files 1147 1147
Lines 445883 446007 +124
Branches 445883 446007 +124
==========================================
+ Hits 368519 368606 +87
- Misses 54977 54997 +20
- Partials 22387 22404 +17
```
</details>
[:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/datafusion/pull/26013?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