ulysses-you commented on code in PR #60553:
URL: https://github.com/apache/spark/pull/60553#discussion_r4611514758


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -201,27 +251,59 @@ case class PushDownShuffleExchangeThroughUnion(
       satisfied && !candidate.exists(node => 
!PartitioningOrigin.validateNode(node))
     }
 
-    val pushed = rewrite(preferRemovedLayout = false)
+    val (pushed, sites, usedRemovedLayout) = rewrite(removedLayoutSites = 
Set.empty, sites = None)
+
+    /**
+     * The rule's fallback without keyed targets: retry the whole plan on the 
layouts of the
+     * exchanges it removes, which every ancestor was planned against. The 
retry cannot help while
+     * every target the proposal adopted is such a layout already.
+     */
+    def retryOnRemovedLayouts(): SparkPlan = {
+      if (usedRemovedLayout) {
+        plan
+      } else {
+        val (retried, _, _) = rewrite(removedLayoutSites = sites, sites = None)
+        if (retried.fastEquals(plan) || !accepted(retried)) plan else retried
+      }
+    }
+
     if (pushed.fastEquals(plan)) {
       plan
     } else if (accepted(pushed)) {
       pushed
-    } else if (usedRemovedLayout) {
-      // Every site already used the layout of the exchange this rewrite 
removes, so the retry
-      // would rebuild the same proposal and fail again.
-      plan
-    } else {
-      // A target can satisfy the consumer and the fixed siblings yet break an 
ancestor, such as
-      // a join that pairs this branch with a different partition count. Retry 
once on the removed
-      // exchange's own layout, which every ancestor was planned against.
-      val retried = rewrite(preferRemovedLayout = true)
-      if (retried.fastEquals(plan)) {
-        plan
-      } else if (accepted(retried)) {
-        retried
+    } else if 
(conf.getConf(SQLConf.PUSH_DOWN_SHUFFLE_THROUGH_UNION_PARTIAL_REPLAY_ENABLED)) {
+      // The whole plan rejected the proposal, which a keyed target can cause 
without its own
+      // site, or the sites it was planned against, seeing it. Replay the 
proposal one site at a
+      // time over the input plan, keeping a site only while the whole plan 
still holds; a site
+      // the whole plan rejects takes the layout of the exchange it removes 
instead.
+      var adopted = Set.empty[Int]
+      var onRemovedLayout = Set.empty[Int]
+      var bestPlan = plan
+      def adopt(index: Int, removedLayoutSites: Set[Int]): Boolean = {
+        val (candidate, _, _) = rewrite(removedLayoutSites, sites = 
Some(adopted + index))
+        if (!candidate.fastEquals(bestPlan) && accepted(candidate)) {
+          adopted += index
+          onRemovedLayout = removedLayoutSites
+          bestPlan = candidate
+          true
+        } else {
+          false
+        }
+      }
+      sites.toSeq.sorted.foreach { index =>
+        adopt(index, onRemovedLayout) || adopt(index, onRemovedLayout + index)

Review Comment:
   Implemented in 38fa3834c67 as recommended. A failed joint attempt is retried 
with keyed targets off before the per-input fallback. When the whole-plan check 
rejects a pass, the rule plans the hash-only pass over the input plan and 
starts from it; with partialReplay on, keyed targets are replayed one site at a 
time on top of it, kept only while the whole plan holds. The replay over the 
input plan and the whole-plan retry on the removed layouts run when the 
hash-only pass changes nothing or fails, and the replay-off arm of 'a failed 
keyed target reverts only its own site' now expects the other site to keep its 
own target. The class and partialReplay docs follow the same order. Tests: two 
join inputs that share a hash target (plan level at both replay settings, and 
end to end), paired sites (plan level and end to end), a failed joint attempt 
that keeps the base push-down (end to end).



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnionSuite.scala:
##########
@@ -201,6 +213,38 @@ class PushDownShuffleExchangeThroughUnionSuite extends 
QueryTest with SharedSpar
       spark.sql(sql).collect().toSeq
     }
 
+  test("SPARK-61785: a query on the defaults keeps its shuffle") {
+    // The suite opens every opt-in for the rest of its tests. Here each goes 
back to its declared
+    // default, with only AQE turned on, so flipping a default changes this 
plan and the answer.

Review Comment:
   Fixed in 38fa3834c67: the test is now 'the rule's default keeps the union's 
shuffle'. It runs with every config at its declared default (numShufflesOnUnion 
== 1) and with only the rule's flag on (numShufflesOnUnion == 0), so flipping 
the rule's default fails it.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -9001,26 +9001,39 @@ object SQLConf {
   val PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED =
     buildConf("spark.sql.adaptive.pushDownShuffleThroughUnion.enabled")
       .internal()
-      .doc("When true, pushes an EnsureRequirements hash shuffle below a union 
during AQE " +
-        "query stage preparation. Eligible children already reporting the 
selected layout " +
-        "are retained; other children are retargeted or receive a new 
exchange. The target " +
-        "partition count must be at least the smaller of the replaced 
exchange's count and " +
-        "the effective initial shuffle count, including " +
-        s"${COALESCE_PARTITIONS_INITIAL_PARTITION_NUM.key} when set, and at 
most a bounded " +
-        "multiple of the larger of the two. Requires " +
-        s"${UNION_OUTPUT_PARTITIONING.key} to be enabled. Removing the union's 
direct shuffle " +
-        "stage can reduce AQE skew handling and join conversion opportunities. 
Retaining a " +
-        "shuffled join's layout can make skew optimization or local reads 
violate ancestor " +
-        "requirements; AQE may reject the optimization or add a shuffle when 
skew optimization " +
-        "is forced. Join inputs and join branches are opt-in. Cost 
compensation applies only " +
-        "to SimpleCostEvaluator. Custom evaluators should account for one 
union exchange " +
-        "becoming multiple branch exchanges; otherwise AQE may reject a 
re-plan and its other " +
-        "runtime optimizations due to the increased exchange count.")
+      .doc("When true, pushes an EnsureRequirements shuffle below a union 
during AQE query " +
+        "stage preparation. The shuffle and the target are hash or V2 keyed 
layouts. Children " +

Review Comment:
   Fixed in 38fa3834c67: the enabled doc says that eligible children already 
reporting the target keep their layouts, and that every other child, including 
an ineligible one that reports the target, is retargeted or given a new 
exchange.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -240,56 +322,77 @@ case class PushDownShuffleExchangeThroughUnion(
       maxUnionChildren: Int,
       maxTargetPartitionNumFactor: Double,
       keepJoinBranches: Boolean,
+      allowV2Bucketing: Boolean,
       allowSubsetTargets: Boolean,
       preferRemovedLayout: Boolean = false)
 
-  /** Lazily discover and rank layouts once per site for both joint and 
fallback attempts. */
-  private class PreparedChild(val pushable: PushableChild, policy: 
LayoutPolicy) {
+  /** Lazily discover the reported layouts and rank the targets once per site 
for both attempts. */
+  private class PreparedChild(
+      val pushable: PushableChild,
+      required: ClusteredDistribution,
+      policy: LayoutPolicy) {
     /**
-     * Eligible child layouts in child order, expressed in the union's output 
attributes.
-     * Collections offer their hash members; a child offering nothing takes a 
shuffle.
-     * Equality follows UnionExec's comparison after prepareOutputPartitioning 
rebinding.
+     * The hash or keyed layouts each child reports, in child order, expressed 
in the union's output
+     * attributes. A collection offers its hash members; a keyed layout offers 
itself when it is
+     * grouped and its grouped form when it is not, the form 
`EnsureRequirements` plans. A child
+     * offering nothing takes a shuffle.
+     *
+     * A marked leg is offered only when the union can merge it: it has to 
declare the target's

Review Comment:
   Fixed in 38fa3834c67: the layouts doc says every keepable keyed child offers 
its layout, marked or not, so any of them can supply the target, and that 
reportsDomain(kept = true) decides which legs are kept. reportsDomain now 
justifies the allowed unknown-keys difference by the kept leg's own placement 
(a subset for an unmarked leg, routing for a marked one) rather than by the 
target's source.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -201,27 +251,59 @@ case class PushDownShuffleExchangeThroughUnion(
       satisfied && !candidate.exists(node => 
!PartitioningOrigin.validateNode(node))
     }
 
-    val pushed = rewrite(preferRemovedLayout = false)
+    val (pushed, sites, usedRemovedLayout) = rewrite(removedLayoutSites = 
Set.empty, sites = None)
+
+    /**
+     * The rule's fallback without keyed targets: retry the whole plan on the 
layouts of the

Review Comment:
   Fixed in 38fa3834c67: the retry is documented as the whole-plan retry on the 
layouts of the removed exchanges. No comment or assertion message calls it the 
fallback without keyed targets or refers to the base branch; the test says the 
other site keeps its own target.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to