You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "ulysses-you (via GitHub)" <gi...@apache.org> on 2026/07/28 11:31:31 UTC
[PR] [SPARK-58405][SQL] Pull up project alias through window to eliminate redundant shuffle and sort [spark]
ulysses-you opened a new pull request, #57603:
URL: https://github.com/apache/spark/pull/57603
### What changes were proposed in this pull request?
This PR adds a new logical optimizer rule `PullUpProjectAliasThroughWindow`.
When a window function's partition/order key is an alias of an underlying
column, the rename lives in a `Project` *below* the window, while the
analyzer-inserted `Project` *above* the window references the renamed column
as a bare `Attribute` (empty alias map). Since `Window.outputPartitioning`
/`outputOrdering` are pure pass-throughs of the child, the upper project
cannot translate the child's `HashPartitioning(k)`/`SortOrder(k)` into the
renamed attribute a downstream operator requires.
The new rule pulls such aliases up from the bottom `Project` into the top
`Project`, across a chain of one or more adjacent `Window` operators
(`Project - Window+ - Project`), reusing the same exprId. After the rewrite,
the top project's alias map maps `k -> a`, so the existing
`PartitioningPreservingUnaryExecNode`/`OrderPreservingUnaryExecNode`
machinery that `ProjectExec` mixes in projects the window's partitioning and
ordering up through the alias. The `Window` operators themselves are left
untouched.
Example:
```sql
SELECT userid, count(*), sum(size(vset))
FROM (
SELECT key AS userid, collect_set(value) OVER (PARTITION BY key) AS vset
FROM testData
) u
GROUP BY 1
```
Before: the window shuffles on `key`, then a second, redundant shuffle on
`userid` is inserted for the aggregate. After: a single shuffle.
An entry of the bottom project is pulled up only when: it is an `Alias`; no
window in the chain references it; all of its input attributes remain
produced by the pruned bottom project; and the top project consumes its
output solely as a bare pass-through attribute.
Besides removing the redundant shuffle/sort, this also narrows the data
crossing the window's shuffle: the alias no longer flows through the window
as a separate column and is recomputed cheaply above the exchange.
### Why are the changes needed?
To avoid a redundant shuffle (and possibly a redundant sort) whenever a
downstream consumer (aggregate, repartition, chained window, ...) requires
distribution/ordering on an alias of a window partition/order key. The window
has already shuffled/sorted on the underlying key; the second exchange is
pure overhead.
### Does this PR introduce _any_ user-facing change?
No. It is a plan optimization; results are unchanged.
### How was this patch tested?
New unit tests:
- `PullUpProjectAliasThroughWindowSuite` (catalyst): 14 tests covering pull-up
of partition/order key renames, multi-key windows, computed aliases whose
inputs are all window keys, window chains, and the negative/idempotency/
schema-preservation cases.
- `ProjectedOrderingAndPartitioningSuite` (sql/core): 4 end-to-end tests
asserting a single shuffle (and single sort where applicable) plus
`checkAnswer` correctness, for aggregate/repartition/stacked-window/
window-chain consumers.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 4.8
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58405][SQL] Pull up project alias through window to eliminate redundant shuffle and sort [spark]
Posted by "ulysses-you (via GitHub)" <gi...@apache.org>.
ulysses-you closed pull request #57603: [SPARK-58405][SQL] Pull up project alias through window to eliminate redundant shuffle and sort
URL: https://github.com/apache/spark/pull/57603
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58405][SQL] Pull up project alias through window to eliminate redundant shuffle and sort [spark]
Posted by "sunchao (via GitHub)" <gi...@apache.org>.
sunchao commented on code in PR #57603:
URL: https://github.com/apache/spark/pull/57603#discussion_r3669026187
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PullUpProjectAliasThroughWindow.scala:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.catalyst.optimizer
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, AttributeMap, AttributeSet, NamedExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, Project, Window}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.WINDOW
+
+/**
+ * A [[Window]] operator does not project its output partitioning or ordering through aliases: its
+ * physical `outputPartitioning`/`outputOrdering` are pure pass-throughs of the child's. So when a
+ * window partitioned/ordered by `k` is followed by a consumer (aggregate, repartition, a chained
+ * window, ...) that requires distribution/ordering on a rename `k AS a`, a redundant shuffle and/or
+ * sort is inserted: the window already shuffled/sorted on `k`, but `HashPartitioning(k)` does not
+ * satisfy `ClusteredDistribution(a)` because the rename lives in a [[Project]] *below* the window
+ * while the analyzer-inserted [[Project]] *above* references `a` as a bare [[Attribute]] (empty
+ * alias map), and `k` and `a`, though value-identical, have distinct expr ids.
+ *
+ * This rule pulls such aliases up from the bottom [[Project]] into the top [[Project]], across the
+ * chain of one or more [[Window]] operators in between (`Project - Window+ - Project`; adjacent
+ * windows that cannot be collapsed, e.g. with different order specs, leave no [[Project]] between
+ * them). The top project's alias map then maps `k -> a`, and the
+ * `PartitioningPreservingUnaryExecNode` / `OrderPreservingUnaryExecNode` machinery that
+ * `ProjectExec` mixes in projects the windows' `HashPartitioning(k)`/`SortOrder(k)` up through the
+ * alias, satisfying the consumer. The [[Window]] operators themselves are left untouched.
+ *
+ * Besides removing the redundant shuffle/sort, this also narrows the data crossing the window's
+ * shuffle: the alias no longer flows through the window as a separate column (only its input `k`,
+ * already needed for partitioning, does) and is recomputed cheaply in the top project above the
+ * exchange.
+ *
+ * An entry of the bottom project is pulled up only when:
+ * - it is an [[Alias]] (bare pass-through attributes stay below so the windows keep producing
+ * them for the top project to reference);
+ * - no window in the chain references it, so window semantics are unaffected;
+ * - all of its input attributes remain produced by the pruned bottom project (i.e. they are
+ * referenced by some window and thus retained), so a computed alias whose inputs would be
+ * dropped is not lifted above windows that no longer output them;
+ * - the top project consumes its output solely as a bare pass-through attribute (never inside a
+ * larger expression), so replacing that attribute with the alias fully preserves it.
+ *
+ * The rewrite is a no-op on its own output (a moved alias is no longer a bare attribute above nor
+ * present below), so it converges immediately at the fixed point.
+ */
+object PullUpProjectAliasThroughWindow extends Rule[LogicalPlan] {
+
+ /**
+ * Matches a non-empty chain of [[Window]] operators bottomed out by a [[Project]], returning the
+ * windows top-to-bottom and that bottom project.
+ */
+ private object WindowChain {
+ def unapply(plan: LogicalPlan): Option[(Seq[Window], Project)] = plan match {
+ case w @ Window(_, _, _, lower: Project, _) => Some((Seq(w), lower))
+ case w @ Window(_, _, _, WindowChain(windows, lower), _) => Some((w +: windows, lower))
+ case _ => None
+ }
+ }
+
+ override def apply(plan: LogicalPlan): LogicalPlan = plan.transformWithPruning(
+ _.containsPattern(WINDOW), ruleId) {
+ // Match the `Project - Window+ - Project` shape: the top project is the windows' parent
+ // scaffolding, and the bottom project is where the rename (`key AS userid`) is defined.
+ case p @ Project(projectList, WindowChain(windows, lower)) =>
+ // Entries any window references must stay below: they define what the bottom project must
+ // keep producing, and in particular carry the partition/order key attributes the pulled-up
+ // aliases reuse.
+ val windowRefs = AttributeSet(windows.flatMap(_.references))
+ val (retained, candidates) =
+ lower.projectList.partition(e => windowRefs.contains(e.toAttribute))
+ val retainedAttrs = AttributeSet(retained.map(_.toAttribute))
+ // Attributes the top project consumes as bare pass-through entries, and those it consumes
+ // inside a larger expression (an alias child, a window-output reference, ...).
+ val bareAttrs = AttributeSet(projectList.collect { case a: Attribute => a })
+ val referencedByExpr = AttributeSet(projectList.flatMap {
+ case _: Attribute => Nil
+ case other => other.references
+ })
+ // Pull up an alias only when: its inputs survive in the pruned bottom project, the top
+ // project passes its output through as a bare attribute, and the top project does not also
+ // consume that output inside an expression (which would require the windows to keep it).
+ val pullUp = candidates.collect {
+ case a: Alias
+ if a.references.subsetOf(retainedAttrs) &&
+ bareAttrs.contains(a.toAttribute) &&
+ !referencedByExpr.contains(a.toAttribute) => a
+ }
+ if (pullUp.isEmpty) {
+ p
+ } else {
+ val pullUpSet: Set[NamedExpression] = pullUp.toSet
+ // Key the lookup by expr id (not by `Attribute.equals`, which also compares qualifier):
+ // the top project may reference these attributes with a different qualifier than the alias
+ // carries below (e.g. across a subquery alias).
+ val pullUpMap = AttributeMap(pullUp.map(a => a.toAttribute -> a))
+ val newProjectList = projectList.map {
+ case attr: Attribute => pullUpMap.getOrElse(attr, attr)
Review Comment:
[P2] Preserve the top attribute's field name
Because this lookup is intentionally keyed only by ExprId, a valid resolved top attribute can have a different cosmetic name from the lower alias, for example `x.toAttribute.withName("external")`. This replacement then emits the original `Alias(..., "x")`, changing the root schema from `external` to `x`. Spark's `LogicalPlanIntegrity.validateSchemaOutput` rejects that rewrite; with validation disabled, custom/extension Catalyst plans silently get a renamed output. Please either require the names to match or rebuild the lifted alias with the top attribute's name, and cover this resolved-plan case.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PullUpProjectAliasThroughWindow.scala:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.catalyst.optimizer
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, AttributeMap, AttributeSet, NamedExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, Project, Window}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.WINDOW
+
+/**
+ * A [[Window]] operator does not project its output partitioning or ordering through aliases: its
+ * physical `outputPartitioning`/`outputOrdering` are pure pass-throughs of the child's. So when a
+ * window partitioned/ordered by `k` is followed by a consumer (aggregate, repartition, a chained
+ * window, ...) that requires distribution/ordering on a rename `k AS a`, a redundant shuffle and/or
+ * sort is inserted: the window already shuffled/sorted on `k`, but `HashPartitioning(k)` does not
+ * satisfy `ClusteredDistribution(a)` because the rename lives in a [[Project]] *below* the window
+ * while the analyzer-inserted [[Project]] *above* references `a` as a bare [[Attribute]] (empty
+ * alias map), and `k` and `a`, though value-identical, have distinct expr ids.
+ *
+ * This rule pulls such aliases up from the bottom [[Project]] into the top [[Project]], across the
+ * chain of one or more [[Window]] operators in between (`Project - Window+ - Project`; adjacent
+ * windows that cannot be collapsed, e.g. with different order specs, leave no [[Project]] between
+ * them). The top project's alias map then maps `k -> a`, and the
+ * `PartitioningPreservingUnaryExecNode` / `OrderPreservingUnaryExecNode` machinery that
+ * `ProjectExec` mixes in projects the windows' `HashPartitioning(k)`/`SortOrder(k)` up through the
+ * alias, satisfying the consumer. The [[Window]] operators themselves are left untouched.
+ *
+ * Besides removing the redundant shuffle/sort, this also narrows the data crossing the window's
+ * shuffle: the alias no longer flows through the window as a separate column (only its input `k`,
+ * already needed for partitioning, does) and is recomputed cheaply in the top project above the
+ * exchange.
+ *
+ * An entry of the bottom project is pulled up only when:
+ * - it is an [[Alias]] (bare pass-through attributes stay below so the windows keep producing
+ * them for the top project to reference);
+ * - no window in the chain references it, so window semantics are unaffected;
+ * - all of its input attributes remain produced by the pruned bottom project (i.e. they are
+ * referenced by some window and thus retained), so a computed alias whose inputs would be
+ * dropped is not lifted above windows that no longer output them;
+ * - the top project consumes its output solely as a bare pass-through attribute (never inside a
+ * larger expression), so replacing that attribute with the alias fully preserves it.
+ *
+ * The rewrite is a no-op on its own output (a moved alias is no longer a bare attribute above nor
+ * present below), so it converges immediately at the fixed point.
+ */
+object PullUpProjectAliasThroughWindow extends Rule[LogicalPlan] {
+
+ /**
+ * Matches a non-empty chain of [[Window]] operators bottomed out by a [[Project]], returning the
+ * windows top-to-bottom and that bottom project.
+ */
+ private object WindowChain {
+ def unapply(plan: LogicalPlan): Option[(Seq[Window], Project)] = plan match {
+ case w @ Window(_, _, _, lower: Project, _) => Some((Seq(w), lower))
+ case w @ Window(_, _, _, WindowChain(windows, lower), _) => Some((w +: windows, lower))
+ case _ => None
+ }
+ }
+
+ override def apply(plan: LogicalPlan): LogicalPlan = plan.transformWithPruning(
+ _.containsPattern(WINDOW), ruleId) {
+ // Match the `Project - Window+ - Project` shape: the top project is the windows' parent
+ // scaffolding, and the bottom project is where the rename (`key AS userid`) is defined.
+ case p @ Project(projectList, WindowChain(windows, lower)) =>
+ // Entries any window references must stay below: they define what the bottom project must
+ // keep producing, and in particular carry the partition/order key attributes the pulled-up
+ // aliases reuse.
+ val windowRefs = AttributeSet(windows.flatMap(_.references))
+ val (retained, candidates) =
+ lower.projectList.partition(e => windowRefs.contains(e.toAttribute))
+ val retainedAttrs = AttributeSet(retained.map(_.toAttribute))
+ // Attributes the top project consumes as bare pass-through entries, and those it consumes
+ // inside a larger expression (an alias child, a window-output reference, ...).
+ val bareAttrs = AttributeSet(projectList.collect { case a: Attribute => a })
+ val referencedByExpr = AttributeSet(projectList.flatMap {
+ case _: Attribute => Nil
+ case other => other.references
+ })
+ // Pull up an alias only when: its inputs survive in the pruned bottom project, the top
+ // project passes its output through as a bare attribute, and the top project does not also
+ // consume that output inside an expression (which would require the windows to keep it).
+ val pullUp = candidates.collect {
+ case a: Alias
+ if a.references.subsetOf(retainedAttrs) &&
Review Comment:
[P1] Keep nondeterministic aliases below the window
This guard also accepts nondeterministic aliases because leaf expressions such as `rand(0)` have no references and therefore pass `subsetOf` vacuously. `ExtractWindowExpressions` produces this exact `Project - Window - Project` shape for ordinary SQL, so the rule can move `rand`, `spark_partition_id`, or `monotonically_increasing_id` across the window exchange/sort. Their values depend on partition index and/or evaluation order, so the optimized query can return different values. Please require `a.deterministic` here and cover a nondeterministic alias with a no-rewrite regression.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58405][SQL] Pull up project alias through window to eliminate redundant shuffle and sort [spark]
Posted by "ulysses-you (via GitHub)" <gi...@apache.org>.
ulysses-you commented on PR #57603:
URL: https://github.com/apache/spark/pull/57603#issuecomment-5117935311
also cc @cloud-fan @viirya @peter-toth thank 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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58405][SQL] Pull up project alias through window to eliminate redundant shuffle and sort [spark]
Posted by "ulysses-you (via GitHub)" <gi...@apache.org>.
ulysses-you commented on PR #57603:
URL: https://github.com/apache/spark/pull/57603#issuecomment-5125255764
@viirya thanks for the thorough trace. Addressed the qualifier/metadata finding in 4bc6601 exactly as you and @cloud-fan suggested: the lifted alias now keeps `a`'s child/exprId but adopts `attr`'s name, qualifier, and metadata (following the `RemoveRedundantAliases` precedent you pointed to). The name-preservation test is extended to cover a top attribute with a different qualifier and metadata as well.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58405][SQL] Pull up project alias through window to eliminate redundant shuffle and sort [spark]
Posted by "ulysses-you (via GitHub)" <gi...@apache.org>.
ulysses-you commented on code in PR #57603:
URL: https://github.com/apache/spark/pull/57603#discussion_r3679222868
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PullUpProjectAliasThroughWindow.scala:
##########
@@ -0,0 +1,136 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.catalyst.optimizer
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, AttributeMap, AttributeSet, NamedExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, Project, Window}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.WINDOW
+
+/**
+ * A [[Window]] operator does not project its output partitioning or ordering through aliases: its
+ * physical `outputPartitioning`/`outputOrdering` are pure pass-throughs of the child's. So when a
+ * window partitioned/ordered by `k` is followed by a consumer (aggregate, repartition, a chained
+ * window, ...) that requires distribution/ordering on a rename `k AS a`, a redundant shuffle and/or
+ * sort is inserted: the window already shuffled/sorted on `k`, but `HashPartitioning(k)` does not
+ * satisfy `ClusteredDistribution(a)` because the rename lives in a [[Project]] *below* the window
+ * while the analyzer-inserted [[Project]] *above* references `a` as a bare [[Attribute]] (empty
+ * alias map), and `k` and `a`, though value-identical, have distinct expr ids.
+ *
+ * This rule pulls such aliases up from the bottom [[Project]] into the top [[Project]], across the
+ * chain of one or more [[Window]] operators in between (`Project - Window+ - Project`; adjacent
+ * windows that cannot be collapsed, e.g. with different order specs, leave no [[Project]] between
+ * them). The top project's alias map then maps `k -> a`, and the
+ * `PartitioningPreservingUnaryExecNode` / `OrderPreservingUnaryExecNode` machinery that
+ * `ProjectExec` mixes in projects the windows' `HashPartitioning(k)`/`SortOrder(k)` up through the
+ * alias, satisfying the consumer. The [[Window]] operators themselves are left untouched.
+ *
+ * Besides removing the redundant shuffle/sort, this also narrows the data crossing the window's
+ * shuffle: the alias no longer flows through the window as a separate column (only its input `k`,
+ * already needed for partitioning, does) and is recomputed cheaply in the top project above the
+ * exchange.
+ *
+ * An entry of the bottom project is pulled up only when:
+ * - it is an [[Alias]] (bare pass-through attributes stay below so the windows keep producing
+ * them for the top project to reference);
+ * - it is deterministic: a nondeterministic alias (e.g. `rand()`, `spark_partition_id()`)
+ * evaluated above the window's exchange/sort instead of below it could produce different
+ * values, so it must stay below;
+ * - no window in the chain references it, so window semantics are unaffected;
+ * - all of its input attributes remain produced by the pruned bottom project (i.e. they are
+ * referenced by some window and thus retained), so a computed alias whose inputs would be
+ * dropped is not lifted above windows that no longer output them;
+ * - the top project consumes its output solely as a bare pass-through attribute (never inside a
+ * larger expression), so replacing that attribute with the alias fully preserves it.
+ *
+ * The rewrite is a no-op on its own output (a moved alias is no longer a bare attribute above nor
+ * present below), so it converges immediately at the fixed point.
+ */
+object PullUpProjectAliasThroughWindow extends Rule[LogicalPlan] {
+
+ /**
+ * Matches a non-empty chain of [[Window]] operators bottomed out by a [[Project]], returning the
+ * windows top-to-bottom and that bottom project.
+ */
+ private object WindowChain {
+ def unapply(plan: LogicalPlan): Option[(Seq[Window], Project)] = plan match {
+ case w @ Window(_, _, _, lower: Project, _) => Some((Seq(w), lower))
+ case w @ Window(_, _, _, WindowChain(windows, lower), _) => Some((w +: windows, lower))
+ case _ => None
+ }
+ }
+
+ override def apply(plan: LogicalPlan): LogicalPlan = plan.transformWithPruning(
+ _.containsPattern(WINDOW), ruleId) {
+ // Match the `Project - Window+ - Project` shape: the top project is the windows' parent
+ // scaffolding, and the bottom project is where the rename (`key AS userid`) is defined.
+ case p @ Project(projectList, WindowChain(windows, lower)) =>
+ // Entries any window references must stay below: they define what the bottom project must
+ // keep producing, and in particular carry the partition/order key attributes the pulled-up
+ // aliases reuse.
+ val windowRefs = AttributeSet(windows.flatMap(_.references))
+ val (retained, candidates) =
+ lower.projectList.partition(e => windowRefs.contains(e.toAttribute))
+ val retainedAttrs = AttributeSet(retained.map(_.toAttribute))
+ // Attributes the top project consumes as bare pass-through entries, and those it consumes
+ // inside a larger expression (an alias child, a window-output reference, ...).
+ val bareAttrs = AttributeSet(projectList.collect { case a: Attribute => a })
+ val referencedByExpr = AttributeSet(projectList.flatMap {
+ case _: Attribute => Nil
+ case other => other.references
+ })
+ // Pull up an alias only when: it is deterministic (a nondeterministic alias must not move
+ // across the window's exchange/sort, which would change its per-partition/per-row values);
+ // its inputs survive in the pruned bottom project; the top project passes its output through
+ // as a bare attribute; and the top project does not also consume that output inside an
+ // expression (which would require the windows to keep it).
+ val pullUp = candidates.collect {
+ case a: Alias
+ if a.deterministic &&
+ a.references.subsetOf(retainedAttrs) &&
+ bareAttrs.contains(a.toAttribute) &&
+ !referencedByExpr.contains(a.toAttribute) => a
+ }
+ if (pullUp.isEmpty) {
+ p
+ } else {
+ val pullUpSet: Set[NamedExpression] = pullUp.toSet
+ // Key the lookup by expr id (not by `Attribute.equals`, which also compares qualifier):
+ // the top project may reference these attributes with a different qualifier than the alias
+ // carries below (e.g. across a subquery alias).
+ val pullUpMap = AttributeMap(pullUp.map(a => a.toAttribute -> a))
+ val newProjectList = projectList.map {
+ // Rename the pulled-up alias to the top attribute's name: the lookup is keyed by expr id
+ // only, so a resolved top attribute may carry a different (but equivalent) cosmetic name
+ // than the lower alias. `withName` keeps the alias's child and expr id, so the output
+ // schema stays byte-for-byte identical.
+ case attr: Attribute =>
+ pullUpMap.get(attr) match {
+ case Some(a) => a.withName(attr.name)
Review Comment:
Good catch, fixed in 4bc6601. The lifted alias is now rebuilt with the lower alias's child/exprId but the top attribute's full identity:
```scala
case Some(a) => Alias(a.child, attr.name)(
exprId = a.exprId,
qualifier = attr.qualifier,
explicitMetadata = Some(attr.metadata))
```
This follows the `RemoveRedundantAliases` precedent. I also extended the regression test to give the top attribute a distinct name, qualifier, and metadata and assert all three are preserved on the output.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58405][SQL] Pull up project alias through window to eliminate redundant shuffle and sort [spark]
Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #57603:
URL: https://github.com/apache/spark/pull/57603#discussion_r3675261084
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PullUpProjectAliasThroughWindow.scala:
##########
@@ -0,0 +1,136 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.catalyst.optimizer
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, AttributeMap, AttributeSet, NamedExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, Project, Window}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.WINDOW
+
+/**
+ * A [[Window]] operator does not project its output partitioning or ordering through aliases: its
+ * physical `outputPartitioning`/`outputOrdering` are pure pass-throughs of the child's. So when a
+ * window partitioned/ordered by `k` is followed by a consumer (aggregate, repartition, a chained
+ * window, ...) that requires distribution/ordering on a rename `k AS a`, a redundant shuffle and/or
+ * sort is inserted: the window already shuffled/sorted on `k`, but `HashPartitioning(k)` does not
+ * satisfy `ClusteredDistribution(a)` because the rename lives in a [[Project]] *below* the window
+ * while the analyzer-inserted [[Project]] *above* references `a` as a bare [[Attribute]] (empty
+ * alias map), and `k` and `a`, though value-identical, have distinct expr ids.
+ *
+ * This rule pulls such aliases up from the bottom [[Project]] into the top [[Project]], across the
+ * chain of one or more [[Window]] operators in between (`Project - Window+ - Project`; adjacent
+ * windows that cannot be collapsed, e.g. with different order specs, leave no [[Project]] between
+ * them). The top project's alias map then maps `k -> a`, and the
+ * `PartitioningPreservingUnaryExecNode` / `OrderPreservingUnaryExecNode` machinery that
+ * `ProjectExec` mixes in projects the windows' `HashPartitioning(k)`/`SortOrder(k)` up through the
+ * alias, satisfying the consumer. The [[Window]] operators themselves are left untouched.
+ *
+ * Besides removing the redundant shuffle/sort, this also narrows the data crossing the window's
+ * shuffle: the alias no longer flows through the window as a separate column (only its input `k`,
+ * already needed for partitioning, does) and is recomputed cheaply in the top project above the
+ * exchange.
+ *
+ * An entry of the bottom project is pulled up only when:
+ * - it is an [[Alias]] (bare pass-through attributes stay below so the windows keep producing
+ * them for the top project to reference);
+ * - it is deterministic: a nondeterministic alias (e.g. `rand()`, `spark_partition_id()`)
+ * evaluated above the window's exchange/sort instead of below it could produce different
+ * values, so it must stay below;
+ * - no window in the chain references it, so window semantics are unaffected;
+ * - all of its input attributes remain produced by the pruned bottom project (i.e. they are
+ * referenced by some window and thus retained), so a computed alias whose inputs would be
+ * dropped is not lifted above windows that no longer output them;
+ * - the top project consumes its output solely as a bare pass-through attribute (never inside a
+ * larger expression), so replacing that attribute with the alias fully preserves it.
+ *
+ * The rewrite is a no-op on its own output (a moved alias is no longer a bare attribute above nor
+ * present below), so it converges immediately at the fixed point.
+ */
+object PullUpProjectAliasThroughWindow extends Rule[LogicalPlan] {
+
+ /**
+ * Matches a non-empty chain of [[Window]] operators bottomed out by a [[Project]], returning the
+ * windows top-to-bottom and that bottom project.
+ */
+ private object WindowChain {
+ def unapply(plan: LogicalPlan): Option[(Seq[Window], Project)] = plan match {
+ case w @ Window(_, _, _, lower: Project, _) => Some((Seq(w), lower))
+ case w @ Window(_, _, _, WindowChain(windows, lower), _) => Some((w +: windows, lower))
+ case _ => None
+ }
+ }
+
+ override def apply(plan: LogicalPlan): LogicalPlan = plan.transformWithPruning(
+ _.containsPattern(WINDOW), ruleId) {
+ // Match the `Project - Window+ - Project` shape: the top project is the windows' parent
+ // scaffolding, and the bottom project is where the rename (`key AS userid`) is defined.
+ case p @ Project(projectList, WindowChain(windows, lower)) =>
+ // Entries any window references must stay below: they define what the bottom project must
+ // keep producing, and in particular carry the partition/order key attributes the pulled-up
+ // aliases reuse.
+ val windowRefs = AttributeSet(windows.flatMap(_.references))
+ val (retained, candidates) =
+ lower.projectList.partition(e => windowRefs.contains(e.toAttribute))
+ val retainedAttrs = AttributeSet(retained.map(_.toAttribute))
+ // Attributes the top project consumes as bare pass-through entries, and those it consumes
+ // inside a larger expression (an alias child, a window-output reference, ...).
+ val bareAttrs = AttributeSet(projectList.collect { case a: Attribute => a })
+ val referencedByExpr = AttributeSet(projectList.flatMap {
+ case _: Attribute => Nil
+ case other => other.references
+ })
+ // Pull up an alias only when: it is deterministic (a nondeterministic alias must not move
+ // across the window's exchange/sort, which would change its per-partition/per-row values);
+ // its inputs survive in the pruned bottom project; the top project passes its output through
+ // as a bare attribute; and the top project does not also consume that output inside an
+ // expression (which would require the windows to keep it).
+ val pullUp = candidates.collect {
+ case a: Alias
+ if a.deterministic &&
+ a.references.subsetOf(retainedAttrs) &&
+ bareAttrs.contains(a.toAttribute) &&
+ !referencedByExpr.contains(a.toAttribute) => a
+ }
+ if (pullUp.isEmpty) {
+ p
+ } else {
+ val pullUpSet: Set[NamedExpression] = pullUp.toSet
+ // Key the lookup by expr id (not by `Attribute.equals`, which also compares qualifier):
+ // the top project may reference these attributes with a different qualifier than the alias
+ // carries below (e.g. across a subquery alias).
+ val pullUpMap = AttributeMap(pullUp.map(a => a.toAttribute -> a))
+ val newProjectList = projectList.map {
+ // Rename the pulled-up alias to the top attribute's name: the lookup is keyed by expr id
+ // only, so a resolved top attribute may carry a different (but equivalent) cosmetic name
+ // than the lower alias. `withName` keeps the alias's child and expr id, so the output
+ // schema stays byte-for-byte identical.
+ case attr: Attribute =>
+ pullUpMap.get(attr) match {
+ case Some(a) => a.withName(attr.name)
Review Comment:
The rewrite needs to preserve the complete upper `Attribute`, not only its name. `Alias.withName` retains the lower alias's qualifier and metadata, so an upper attribute with the same ExprId but different metadata is rewritten to a different output schema. Please rebuild the alias with `attr`'s qualifier and metadata, and extend this regression to cover both properties.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58405][SQL] Pull up project alias through window to eliminate redundant shuffle and sort [spark]
Posted by "ulysses-you (via GitHub)" <gi...@apache.org>.
ulysses-you commented on PR #57603:
URL: https://github.com/apache/spark/pull/57603#issuecomment-5139561646
**Merge Summary:**
- merged into master https://github.com/apache/spark/commit/0cb45c2cc03c3b245df4d8acf934805234b1fdd4
- merged into branch-4.x https://github.com/apache/spark/commit/4525284e193caa15143f00cb3d01c870e4612628
*Posted by `merge_spark_pr.py`*
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58405][SQL] Pull up project alias through window to eliminate redundant shuffle and sort [spark]
Posted by "ulysses-you (via GitHub)" <gi...@apache.org>.
ulysses-you commented on PR #57603:
URL: https://github.com/apache/spark/pull/57603#issuecomment-5139563574
thank you 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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58405][SQL] Pull up project alias through window to eliminate redundant shuffle and sort [spark]
Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #57603:
URL: https://github.com/apache/spark/pull/57603#discussion_r3667453333
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/ProjectedOrderingAndPartitioningSuite.scala:
##########
@@ -31,6 +32,8 @@ class ProjectedOrderingAndPartitioningSuite
extends SharedSparkSession with AdaptiveSparkPlanHelper {
import testImplicits._
+ setupTestData()
Review Comment:
I think we should avoid calling this at the class-body level, because it's not needed in many tests. Let's please scope the registration just to the four new tests instead.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58405][SQL] Pull up project alias through window to eliminate redundant shuffle and sort [spark]
Posted by "ulysses-you (via GitHub)" <gi...@apache.org>.
ulysses-you commented on code in PR #57603:
URL: https://github.com/apache/spark/pull/57603#discussion_r3670708378
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PullUpProjectAliasThroughWindow.scala:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.catalyst.optimizer
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, AttributeMap, AttributeSet, NamedExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, Project, Window}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.WINDOW
+
+/**
+ * A [[Window]] operator does not project its output partitioning or ordering through aliases: its
+ * physical `outputPartitioning`/`outputOrdering` are pure pass-throughs of the child's. So when a
+ * window partitioned/ordered by `k` is followed by a consumer (aggregate, repartition, a chained
+ * window, ...) that requires distribution/ordering on a rename `k AS a`, a redundant shuffle and/or
+ * sort is inserted: the window already shuffled/sorted on `k`, but `HashPartitioning(k)` does not
+ * satisfy `ClusteredDistribution(a)` because the rename lives in a [[Project]] *below* the window
+ * while the analyzer-inserted [[Project]] *above* references `a` as a bare [[Attribute]] (empty
+ * alias map), and `k` and `a`, though value-identical, have distinct expr ids.
+ *
+ * This rule pulls such aliases up from the bottom [[Project]] into the top [[Project]], across the
+ * chain of one or more [[Window]] operators in between (`Project - Window+ - Project`; adjacent
+ * windows that cannot be collapsed, e.g. with different order specs, leave no [[Project]] between
+ * them). The top project's alias map then maps `k -> a`, and the
+ * `PartitioningPreservingUnaryExecNode` / `OrderPreservingUnaryExecNode` machinery that
+ * `ProjectExec` mixes in projects the windows' `HashPartitioning(k)`/`SortOrder(k)` up through the
+ * alias, satisfying the consumer. The [[Window]] operators themselves are left untouched.
+ *
+ * Besides removing the redundant shuffle/sort, this also narrows the data crossing the window's
+ * shuffle: the alias no longer flows through the window as a separate column (only its input `k`,
+ * already needed for partitioning, does) and is recomputed cheaply in the top project above the
+ * exchange.
+ *
+ * An entry of the bottom project is pulled up only when:
+ * - it is an [[Alias]] (bare pass-through attributes stay below so the windows keep producing
+ * them for the top project to reference);
+ * - no window in the chain references it, so window semantics are unaffected;
+ * - all of its input attributes remain produced by the pruned bottom project (i.e. they are
+ * referenced by some window and thus retained), so a computed alias whose inputs would be
+ * dropped is not lifted above windows that no longer output them;
+ * - the top project consumes its output solely as a bare pass-through attribute (never inside a
+ * larger expression), so replacing that attribute with the alias fully preserves it.
+ *
+ * The rewrite is a no-op on its own output (a moved alias is no longer a bare attribute above nor
+ * present below), so it converges immediately at the fixed point.
+ */
+object PullUpProjectAliasThroughWindow extends Rule[LogicalPlan] {
+
+ /**
+ * Matches a non-empty chain of [[Window]] operators bottomed out by a [[Project]], returning the
+ * windows top-to-bottom and that bottom project.
+ */
+ private object WindowChain {
+ def unapply(plan: LogicalPlan): Option[(Seq[Window], Project)] = plan match {
+ case w @ Window(_, _, _, lower: Project, _) => Some((Seq(w), lower))
+ case w @ Window(_, _, _, WindowChain(windows, lower), _) => Some((w +: windows, lower))
+ case _ => None
+ }
+ }
+
+ override def apply(plan: LogicalPlan): LogicalPlan = plan.transformWithPruning(
+ _.containsPattern(WINDOW), ruleId) {
+ // Match the `Project - Window+ - Project` shape: the top project is the windows' parent
+ // scaffolding, and the bottom project is where the rename (`key AS userid`) is defined.
+ case p @ Project(projectList, WindowChain(windows, lower)) =>
+ // Entries any window references must stay below: they define what the bottom project must
+ // keep producing, and in particular carry the partition/order key attributes the pulled-up
+ // aliases reuse.
+ val windowRefs = AttributeSet(windows.flatMap(_.references))
+ val (retained, candidates) =
+ lower.projectList.partition(e => windowRefs.contains(e.toAttribute))
+ val retainedAttrs = AttributeSet(retained.map(_.toAttribute))
+ // Attributes the top project consumes as bare pass-through entries, and those it consumes
+ // inside a larger expression (an alias child, a window-output reference, ...).
+ val bareAttrs = AttributeSet(projectList.collect { case a: Attribute => a })
+ val referencedByExpr = AttributeSet(projectList.flatMap {
+ case _: Attribute => Nil
+ case other => other.references
+ })
+ // Pull up an alias only when: its inputs survive in the pruned bottom project, the top
+ // project passes its output through as a bare attribute, and the top project does not also
+ // consume that output inside an expression (which would require the windows to keep it).
+ val pullUp = candidates.collect {
+ case a: Alias
+ if a.references.subsetOf(retainedAttrs) &&
Review Comment:
Good catch, fixed in e16b666. Added an `a.deterministic` guard to the pull-up condition so nondeterministic aliases stay below the window, plus a "no rewrite for a nondeterministic alias" regression test using `spark_partition_id()`.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PullUpProjectAliasThroughWindow.scala:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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.
+ */
+
+package org.apache.spark.sql.catalyst.optimizer
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, AttributeMap, AttributeSet, NamedExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, Project, Window}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.WINDOW
+
+/**
+ * A [[Window]] operator does not project its output partitioning or ordering through aliases: its
+ * physical `outputPartitioning`/`outputOrdering` are pure pass-throughs of the child's. So when a
+ * window partitioned/ordered by `k` is followed by a consumer (aggregate, repartition, a chained
+ * window, ...) that requires distribution/ordering on a rename `k AS a`, a redundant shuffle and/or
+ * sort is inserted: the window already shuffled/sorted on `k`, but `HashPartitioning(k)` does not
+ * satisfy `ClusteredDistribution(a)` because the rename lives in a [[Project]] *below* the window
+ * while the analyzer-inserted [[Project]] *above* references `a` as a bare [[Attribute]] (empty
+ * alias map), and `k` and `a`, though value-identical, have distinct expr ids.
+ *
+ * This rule pulls such aliases up from the bottom [[Project]] into the top [[Project]], across the
+ * chain of one or more [[Window]] operators in between (`Project - Window+ - Project`; adjacent
+ * windows that cannot be collapsed, e.g. with different order specs, leave no [[Project]] between
+ * them). The top project's alias map then maps `k -> a`, and the
+ * `PartitioningPreservingUnaryExecNode` / `OrderPreservingUnaryExecNode` machinery that
+ * `ProjectExec` mixes in projects the windows' `HashPartitioning(k)`/`SortOrder(k)` up through the
+ * alias, satisfying the consumer. The [[Window]] operators themselves are left untouched.
+ *
+ * Besides removing the redundant shuffle/sort, this also narrows the data crossing the window's
+ * shuffle: the alias no longer flows through the window as a separate column (only its input `k`,
+ * already needed for partitioning, does) and is recomputed cheaply in the top project above the
+ * exchange.
+ *
+ * An entry of the bottom project is pulled up only when:
+ * - it is an [[Alias]] (bare pass-through attributes stay below so the windows keep producing
+ * them for the top project to reference);
+ * - no window in the chain references it, so window semantics are unaffected;
+ * - all of its input attributes remain produced by the pruned bottom project (i.e. they are
+ * referenced by some window and thus retained), so a computed alias whose inputs would be
+ * dropped is not lifted above windows that no longer output them;
+ * - the top project consumes its output solely as a bare pass-through attribute (never inside a
+ * larger expression), so replacing that attribute with the alias fully preserves it.
+ *
+ * The rewrite is a no-op on its own output (a moved alias is no longer a bare attribute above nor
+ * present below), so it converges immediately at the fixed point.
+ */
+object PullUpProjectAliasThroughWindow extends Rule[LogicalPlan] {
+
+ /**
+ * Matches a non-empty chain of [[Window]] operators bottomed out by a [[Project]], returning the
+ * windows top-to-bottom and that bottom project.
+ */
+ private object WindowChain {
+ def unapply(plan: LogicalPlan): Option[(Seq[Window], Project)] = plan match {
+ case w @ Window(_, _, _, lower: Project, _) => Some((Seq(w), lower))
+ case w @ Window(_, _, _, WindowChain(windows, lower), _) => Some((w +: windows, lower))
+ case _ => None
+ }
+ }
+
+ override def apply(plan: LogicalPlan): LogicalPlan = plan.transformWithPruning(
+ _.containsPattern(WINDOW), ruleId) {
+ // Match the `Project - Window+ - Project` shape: the top project is the windows' parent
+ // scaffolding, and the bottom project is where the rename (`key AS userid`) is defined.
+ case p @ Project(projectList, WindowChain(windows, lower)) =>
+ // Entries any window references must stay below: they define what the bottom project must
+ // keep producing, and in particular carry the partition/order key attributes the pulled-up
+ // aliases reuse.
+ val windowRefs = AttributeSet(windows.flatMap(_.references))
+ val (retained, candidates) =
+ lower.projectList.partition(e => windowRefs.contains(e.toAttribute))
+ val retainedAttrs = AttributeSet(retained.map(_.toAttribute))
+ // Attributes the top project consumes as bare pass-through entries, and those it consumes
+ // inside a larger expression (an alias child, a window-output reference, ...).
+ val bareAttrs = AttributeSet(projectList.collect { case a: Attribute => a })
+ val referencedByExpr = AttributeSet(projectList.flatMap {
+ case _: Attribute => Nil
+ case other => other.references
+ })
+ // Pull up an alias only when: its inputs survive in the pruned bottom project, the top
+ // project passes its output through as a bare attribute, and the top project does not also
+ // consume that output inside an expression (which would require the windows to keep it).
+ val pullUp = candidates.collect {
+ case a: Alias
+ if a.references.subsetOf(retainedAttrs) &&
+ bareAttrs.contains(a.toAttribute) &&
+ !referencedByExpr.contains(a.toAttribute) => a
+ }
+ if (pullUp.isEmpty) {
+ p
+ } else {
+ val pullUpSet: Set[NamedExpression] = pullUp.toSet
+ // Key the lookup by expr id (not by `Attribute.equals`, which also compares qualifier):
+ // the top project may reference these attributes with a different qualifier than the alias
+ // carries below (e.g. across a subquery alias).
+ val pullUpMap = AttributeMap(pullUp.map(a => a.toAttribute -> a))
+ val newProjectList = projectList.map {
+ case attr: Attribute => pullUpMap.getOrElse(attr, attr)
Review Comment:
Thanks, fixed in e16b666. The lifted alias is now rebuilt with the top attribute's name via `Alias.withName(attr.name)`, which preserves the child, expr id, qualifier, and metadata while keeping the top attribute's cosmetic name, so the output schema is unchanged. Added a regression test that references the top attribute under a different (expr-id-equivalent) name and asserts the output name is preserved.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-58405][SQL] Pull up project alias through window to eliminate redundant shuffle and sort [spark]
Posted by "ulysses-you (via GitHub)" <gi...@apache.org>.
ulysses-you commented on code in PR #57603:
URL: https://github.com/apache/spark/pull/57603#discussion_r3670707825
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/ProjectedOrderingAndPartitioningSuite.scala:
##########
@@ -31,6 +32,8 @@ class ProjectedOrderingAndPartitioningSuite
extends SharedSparkSession with AdaptiveSparkPlanHelper {
import testImplicits._
+ setupTestData()
Review Comment:
Good point, done in e16b666. Since `setupTestData()` only flips the `loadTestDataBeforeTests` flag consumed in `beforeAll`, I register the view by touching the `testData` lazy val (which calls `createOrReplaceTempView` as a side effect) at the start of each of the four new tests.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org