peter-toth commented on code in PR #60553:
URL: https://github.com/apache/spark/pull/60553#discussion_r4614320997


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -201,26 +272,130 @@ case class PushDownShuffleExchangeThroughUnion(
       satisfied && !candidate.exists(node => 
!PartitioningOrigin.validateNode(node))
     }
 
-    val pushed = rewrite(preferRemovedLayout = false)
+    val (pushed, usedRemovedLayout, candidateSites, _) =
+      rewrite(removedLayoutSites = Set.empty, rewriteSites = None, keyedSites 
= None)
+
+    /**
+     * The whole-plan retry on the layouts of the exchanges it removes, which 
every ancestor was
+     * planned against. The retry cannot help while every target a proposal 
adopted is such a
+     * layout already.
+     */
+    def retryOnRemovedLayouts(): SparkPlan = {
+      if (usedRemovedLayout) {
+        plan
+      } else {
+        val (retried, _, _, _) =
+          rewrite(removedLayoutSites = candidateSites, rewriteSites = None, 
keyedSites = None)
+        if (retried.fastEquals(plan) || !accepted(retried)) plan else retried
+      }
+    }
+
+    /**
+     * The plan of the base policy: keyed targets off, every other setting 
unchanged. A rejected
+     * keyed proposal falls back to it, so it keeps the push-down that policy 
gives every site,
+     * including ones that have to take one layout together, which a 
single-site replay cannot
+     * re-derive. `None` when keyed targets were never available, when the 
plan reports no keyed
+     * layout (so the first pass already is this pass), when the pass changes 
nothing, or when the
+     * whole plan rejects it too.
+     */
+    def hashOnlyPass(): Option[(SparkPlan, Set[Int])] = {
+      if (!policy.allowV2Bucketing ||
+          !plan.exists(_.outputPartitioning.isInstanceOf[KeyedPartitioning])) {
+        None
+      } else {
+        val (hashOnly, _, _, hashOnlyPushed) =
+          rewrite(removedLayoutSites = Set.empty, rewriteSites = None,
+            keyedSites = Some(Set.empty))
+        Option.when(!hashOnly.fastEquals(plan) && accepted(hashOnly))(
+          (hashOnly, hashOnlyPushed))
+      }
+    }
+
+    /**
+     * Partially replay keyed targets one site at a time over the accepted 
hash-only plan. Every
+     * site is re-derived on each attempt, with keyed targets off outside 
`adopted` and the site
+     * being tried, so the other sites keep the base policy's choice. A site 
keeps a keyed target
+     * only while the whole plan holds; a site the hash-only pass left on its 
exchange may also
+     * take that exchange's layout, which the hash-only pass had no target 
for, and keeps it in
+     * the later attempts.
+     */
+    def partialReplayKeyed(hashOnly: SparkPlan, hashOnlySites: Set[Int]): 
SparkPlan = {

Review Comment:
   **Finding 3.** The fallback the P1 thread asked for is the hash-only pass. A 
rejected keyed proposal is planned again with keyed targets off, which gives 
the base branch's plan. 
[r4613402326](https://github.com/apache/spark/pull/60553#discussion_r4613402326)
 confirms that with it, paired sites and the two union inputs of one join keep 
their shared hash target. The partial replay on top of it is what remains of 
the earlier fix in `3b7f95c`:
   - It is internal and off by default, so no default plan uses it.
   - When it runs, it costs one or two full rewrites per candidate site.
   - Its second attempt per site is pinned by no test. I replaced `adopt(index, 
onRemovedLayout) || adopt(index, onRemovedLayout + index)` in 
`partialReplayHashAndKeyed` with the first call alone, and 
`PushDownShuffleExchangeThroughUnionSuite` (140) and the `SPARK-61785` tests of 
`KeyGroupedPartitioningSuite` (24) all still pass. 
[r4613400595](https://github.com/apache/spark/pull/60553#discussion_r4613400595)
 reads it the same way.
   - In the recorded-origin case of finding 2, the replay is what keeps the 
second site. With finding 2's check, the replay-off path keeps it too.
   - The decision challenge in [spark-test's review of this 
head](https://github.com/apache/spark/pull/60553#pullrequestreview-5955957669) 
traces a nested shape under a join where the replay keeps a plan that shuffles 
an inner leg twice, where the retry would not. Without the replay, that 
question goes away.
   
   Without the replay, `partialReplayKeyed`, `partialReplayHashAndKeyed` and 
`spark.sql.adaptive.pushDownShuffleThroughUnion.partialReplay.enabled` go away. 
`rewrite` then needs only `removedLayoutSites` and a keyed on/off switch, since 
`rewriteSites` and the returned site sets serve only the replay. The seven 
replay tests go with it. A follow-up could bring the replay back together with 
the plan shape where keeping a keyed site after a rejection pays off.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -475,64 +695,167 @@ case class PushDownShuffleExchangeThroughUnion(
       }
 
     prepared.targets.view
-      .flatMap { target =>
-        rebuild(pushable.shuffle.child, target).map(child => (target, child))
+      .flatMap { case (target, offeredBy) =>
+        rebuild(pushable.shuffle.child, target, offeredBy).map(child => 
(target, child))
       }
       .map { case (target, child) =>
         (target, PartitioningOrigin.inherit(pushable.shuffle, child))
       }
-      .find { case (_, child) =>
+      // Keep a rebuilt child only if it answers the required distribution as 
rebuilt and pairs with
+      // the siblings. A keyed target's admission as a shuffle template was 
settled with the
+      // candidates; what remains is the rule's own subset permission, which 
reads the rebuilt
+      // layout's specs.
+      .filter { case (target, child) =>
         val partitioning = child.outputPartitioning
         partitioning.satisfies(required) &&
           PartitioningCollection.specsForPairing(partitioning, 
required).exists { spec =>
-            spec.canCreatePartitioning && (policy.allowSubsetTargets || (spec 
match {
-              case hash: HashShuffleSpec =>
-                
required.areAllClusterKeysMatched(hash.partitioning.expressions)
-              case _ => false
-            }))
+            // A keyed target was admitted as a template already; any other 
target asks its spec.
+            (target.isInstanceOf[KeyedPartitioning] || 
spec.canCreatePartitioning) &&
+              (policy.allowSubsetTargets || (spec match {
+                case hash: HashShuffleSpec =>
+                  
required.areAllClusterKeysMatched(hash.partitioning.expressions)
+                case keyed: KeyedShuffleSpec =>
+                  required.allClusterKeysAmong(keyed.partitioning.expressions)
+                case _ => false
+              }))
           } &&
           ValidateRequirements.satisfiesForPairing(
             child +: fixed.map(_._1), required +: fixed.map(_._2))

Review Comment:
   **Finding 2.** A recorded origin accepts only a hash layout 
(`PartitioningOrigin.validateNode`), and `PartitioningOrigin.inherit` puts that 
origin on the rebuilt child. So a keyed candidate at such a site passes this 
filter and fails only in `accepted`, which rejects the whole proposal. With the 
replay off, the hash-only pass then settles the plan, and every other site 
loses its keyed target too.
   
   What I ran: a plan-level test with two independent sites. The first is over 
a union of a keyed leg and a `hash(2)` leg, with a `REPARTITION_BY_COL` origin 
recorded on `hash(id, 2)`. The second is over a keyed leg and a plain leg:
   
   | | the second site |
   |---|---|
   | this head, replay off | keeps its exchange |
   | this head, replay on | grouped on the keyed domain |
   | with the change below, replay off | grouped on the keyed domain |
   
   With the origin checked here, the first site falls back to its hash target 
before the whole plan sees the keyed candidate. With the change, 
`PushDownShuffleExchangeThroughUnionSuite` passes 140 of 140, and the 
`SPARK-61785` tests of `KeyGroupedPartitioningSuite` pass 24 of 24.
   
   ```suggestion
             ValidateRequirements.satisfiesForPairing(
               child +: fixed.map(_._1), required +: fixed.map(_._2)) &&
             !child.exists(node => !PartitioningOrigin.validateNode(node))
   ```
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -9099,6 +9117,39 @@ object SQLConf {
       .checkValue(_ >= 0, "The maximum number of union children must be 
non-negative.")
       .createWithDefault(10)
 
+  val PUSH_DOWN_SHUFFLE_THROUGH_UNION_ALLOW_V2_BUCKETING_ENABLED =
+    
buildConf("spark.sql.adaptive.pushDownShuffleThroughUnion.allowV2Bucketing.enabled")
+      .internal()
+      .doc("When true, union shuffle push-down may use a V2 keyed layout as 
the union's " +
+        "output, whether the shuffle it replaces was keyed or hash. A child 
already reporting " +
+        "the picked domain keeps its layout, and so does an unmarked child 
reporting a subset " +
+        "of its keys; a marked child has to declare the domain's list in the 
same order and " +
+        "still route unlisted keys by hash. The " +
+        "other children are shuffled onto the domain, and rows of a key the 
domain does not " +
+        "declare are routed by hash, which the layout records. The grouping 
above the rebuilt " +
+        "union keeps the claim to that key set. When false, the rule uses hash 
layouts only. " +
+        s"Requires ${PUSH_DOWN_SHUFFLE_THROUGH_UNION_ENABLED.key}, " +
+        s"${V2_BUCKETING_ENABLED.key} and ${V2_BUCKETING_SHUFFLE_ENABLED.key}, 
since a child " +
+        s"may be shuffled onto the domain, with " +
+        s"${V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key} 
disabled. " +
+        "A target naming only part of the consumer's cluster keys needs " +
+        s"${V2_BUCKETING_REQUIRE_ALL_CLUSTER_KEYS_FOR_CO_PARTITION.key} 
disabled and " +
+        
"spark.sql.adaptive.pushDownShuffleThroughUnion.allowPartitionKeysSubsetOfClusterKeys."
 +
+        "enabled on. A target partitioned by a transform over the cluster 
keys, such as " +
+        "bucket(n, id), needs the subset permission whatever " +
+        s"${V2_BUCKETING_REQUIRE_ALL_CLUSTER_KEYS_FOR_CO_PARTITION.key} is set 
to. " +
+        "A source-reported keyed layout is kept only when the consumer's 
shuffle group cannot " +
+        s"coalesce: ${COALESCE_PARTITIONS_ENABLED.key} off, " +
+        
s"${PUSH_DOWN_SHUFFLE_THROUGH_UNION_KEEP_NON_COALESCIBLE_BRANCHES_ENABLED.key} 
on, or " +
+        "a consumer whose inputs do not all reach an exchange, which the rule 
admits without " +
+        "either setting. A keyed target kept at an inner union site leaves a 
grouped layout " +
+        "that an enclosing union site cannot take as its target, so a nested 
union can shuffle " +
+        "the inner site's moved legs a second time.")

Review Comment:
   **Finding 1.** This sentence discloses the cost that the first decision 
challenge in [spark-test's earlier 
review](https://github.com/apache/spark/pull/60553#pullrequestreview-5939344317)
 traces. I measured it end to end. The query is an outer window over two legs: 
an inner window over (a table bucketed by `identity(id)` UNION ALL a `VALUES` 
leg), and a second `VALUES` leg. The inner window's `r1` is carried to the top, 
so the inner window survives. The table has 12 rows on 6 keys, and the legs 
have 12 and 11 rows. `spark.sql.shuffle.partitions` is 6, coalescing is off and 
`keepNonCoalescibleBranches` is on:
   
   | | shuffle records written | exchanges |
   |---|---|---|
   | base (master at `e8081947d49`, whose rule equals this PR's merge base) | 
24 + 11 = 35 | 2 |
   | this head, `allowV2Bucketing` off | 24 + 11 = 35 | 2 |
   | this head, defaults | 35 + 12 = 47 | 2 |
   
   The rows are the same in all three. The inner site keeps the bucketed leg 
and lays the `VALUES` leg out on its domain. Its grouped union no longer routes 
by hash, so the outer site finds no target and keeps its exchange, which 
shuffles both inner legs again. The exchange count does not change, so neither 
`SimpleCostEvaluator` nor an exchange-count assertion sees it.
   
   There is no correctness reason for the extra rows, and `allowV2Bucketing` is 
on by default, so I'd rather avoid the cost than disclose it. The challenge's 
third answer does that. One way is to keep the hash-only plan when it moves 
fewer estimated bytes. The other is to decline a keyed target at a site whose 
output feeds another union site. I have not built either.
   



-- 
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