ulysses-you commented on code in PR #60553:
URL: https://github.com/apache/spark/pull/60553#discussion_r4624035302
##########
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:
The cost is real, and we are not changing the mechanism. The rule chooses
each site's target greedily; deciding whether the enclosing site's push-down is
worth more needs a planning-time cost estimate, and sizeInBytes is unreliable
for aggregate outputs and often missing, so a byte or pushed-set comparison can
invert the choice for a high-compression aggregate over a large scan, where the
keyed target saves far more than the enclosing exchange. allowV2Bucketing now
defaults to false, so both the keyed targets and this cost are opt-in; the
allowV2Bucketing doc keeps the disclosure. Fixed at d66c1e1b6fc.
##########
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:
Implemented as suggested in d66c1e1b6fc: rebuildChild declines a target with
!child.exists(node => !PartitioningOrigin.validateNode(node)), so the site
falls back to its next target before the whole-plan check and the other sites
keep their keyed targets. 'a recorded origin declines only the site that breaks
it' pins it; the suites pass (47/142/272).
##########
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:
We keep the replay, with the ineffective part removed. Dropping the replay
changes plans in reachable shapes: with the replay code removed, the four
replay end-to-end tests fail, including 'the replay keeps a keyed site beside a
hash site' and 'the replay keeps the keyed domain the planner pairs the union
on', and at plan level 'the replay takes a removed layout when no keyed layout
exists' pins the input-plan replay's second attempt. partialReplayKeyed no
longer tries the removed exchange's layout for a site the hash-only pass left
alone: a hash layout a child offers is already taken by that pass, and a keyed
one is recorded with HASH_ROUTING, which a scan never matches, so the
hashOnlySites plumbing is gone. The nested cost of the input-plan replay is
stated in the partialReplay doc; both switches are off by default. Fixed at
d66c1e1b6fc.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnion.scala:
##########
@@ -65,27 +68,48 @@ import org.apache.spark.sql.internal.SQLConf
* gate exists: the child is then shuffled before the reduction, which can
send more data than the
* one shuffle it replaces.
*
- * Targets are hash layouts reported by the union's children, ranked by how
many children offer
- * them when size estimates are unavailable; otherwise estimated bytes kept
decide first. The
- * count must be between the smaller and the larger of the replaced exchange's
count and the
- * effective initial shuffle partition count
(`coalescePartitions.initialPartitionNum` when set);
- * the larger side is scaled by `maxTargetPartitionNumFactor`. A branch that
is already a query
- * stage pins the target to the layout it reports, unless its stage wraps an
unmarked user
+ * Targets are eligible hash or keyed layouts reported by the union's
children, ranked by how many
+ * children offer them when size estimates are unavailable; otherwise
estimated bytes kept decide
+ * first. The count must be between the smaller and the larger of the replaced
exchange's count
+ * and the effective initial shuffle partition count
(`coalescePartitions.initialPartitionNum`
+ * when set); the larger side is scaled by `maxTargetPartitionNumFactor`. A
branch that is already
+ * a query stage pins the target to the layout it reports, unless its stage
wraps an unmarked user
* repartition: the rewrite could only stack on such a branch, and a re-plan
must be able to
* repeat that. At least one child keeps its layout; others are retargeted or
shuffled without
* changing child order.
* `spark.sql.adaptive.pushDownShuffleThroughUnion.maxMovedBranches` limits
moved children, and
* `maxUnionChildren` limits all branches whose tails run within each consumer
task.
- * The rebuilt child must satisfy its consumer's distribution and pair with
fixed siblings.
+ * The rebuilt child must satisfy its consumer's distribution and pair with
the siblings.
+ *
+ * A V2 keyed target additionally requires
+ * `spark.sql.adaptive.pushDownShuffleThroughUnion.allowV2Bucketing.enabled`,
which the V2
+ * bucketing configs further gate, and `spark.sql.unionOutputPartitioning`,
since the union has
Review Comment:
Fixed in d66c1e1b6fc: the class doc states spark.sql.unionOutputPartitioning
as a requirement of the whole rule, and the end-to-end comment no longer
explains it by what the rebuilt union reports.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/adaptive/PushDownShuffleExchangeThroughUnionSuite.scala:
##########
@@ -201,6 +214,41 @@ class PushDownShuffleExchangeThroughUnionSuite extends
QueryTest with SharedSpar
spark.sql(sql).collect().toSeq
}
+ test("SPARK-61785: the rule's default keeps the union's shuffle") {
+ // The suite opens every opt-in for the rest of its tests. Here the rule
goes back to its
+ // declared default, which keeps the union's shuffle. The query needs no
other opt-in: the
+ // second leg takes a column repartition hint, so turning only the rule on
removes the
+ // shuffle, and flipping the rule's own default fails this test.
Review Comment:
Fixed in d66c1e1b6fc: the comment names the first leg as the one carrying
the repartition hint.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -9001,26 +9001,44 @@ 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. Eligible " +
+ "children already reporting the target keep their layouts; every other
child, " +
Review Comment:
Fixed in d66c1e1b6fc: the enabled doc keeps the eligibility qualifier and
adds that a keyed target also keeps an unmarked child whose keys are a subset
of the domain's and a marked child that declares the domain's list in the same
order and still routes by hash.
##########
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 = {
+ var adopted = Set.empty[Int]
+ var onRemovedLayout = Set.empty[Int]
+ var bestPlan = hashOnly
+ def adopt(index: Int, removedLayoutSites: Set[Int]): Boolean = {
+ val (candidate, _, _, _) = rewrite(
+ removedLayoutSites = removedLayoutSites,
+ rewriteSites = None,
+ keyedSites = Some(adopted + index))
+ if (!candidate.fastEquals(bestPlan) && accepted(candidate)) {
+ adopted += index
+ onRemovedLayout = removedLayoutSites
+ bestPlan = candidate
+ true
+ } else {
+ false
+ }
+ }
+ candidateSites.toSeq.sorted.foreach { index =>
+ adopt(index, onRemovedLayout) ||
+ (!hashOnlySites.contains(index) && adopt(index, onRemovedLayout +
index))
+ }
+ bestPlan
+ }
+
+ /**
+ * Partially replay the proposal, with hash and keyed targets, over the
input plan, for a
+ * hash-only pass that is unavailable, changes nothing, or fails: a site
the whole plan
+ * rejects takes the layout of the exchange it removes, and a site no
child can lay out keeps
+ * the exchange it came with.
+ */
+ def partialReplayHashAndKeyed(): SparkPlan = {
+ 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,
+ rewriteSites = Some(adopted + index),
+ keyedSites = Some(adopted + index))
+ if (!candidate.fastEquals(bestPlan) && accepted(candidate)) {
+ adopted += index
+ onRemovedLayout = removedLayoutSites
+ bestPlan = candidate
+ true
+ } else {
+ false
+ }
+ }
+ candidateSites.toSeq.sorted.foreach { index =>
+ adopt(index, onRemovedLayout) || adopt(index, onRemovedLayout + index)
Review Comment:
The input-plan replay's second attempt is now pinned by 'the replay takes a
removed layout when no keyed layout exists' (d66c1e1b6fc). The keyed replay's
removed-layout attempt was removed as unreachable: a hash layout a child offers
is already taken by the hash-only pass, and a keyed one is recorded with
HASH_ROUTING, which a scan never matches.
--
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]