You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "peter-toth (via GitHub)" <gi...@apache.org> on 2026/09/30 17:48:32 UTC

[PR] [SPARK-59887][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

peter-toth opened a new pull request, #59165:
URL: https://github.com/apache/spark/pull/59165

   ### What changes were proposed in this pull request?
   
   A storage-partitioned join now refuses to pair a partition transform whose argument is not a bare column, i.e. is an expression or a struct field:
   
   - `TransformExpression.isSameFunction` and `TransformExpression.reducers` say no when either transform has an argument that is not an `Attribute`. `isCompatible` now goes through `reducers`, so the one check covers the reducer path too.
   - `KeyedShuffleSpec.canCreatePartitioning` asks the same question, so such a layout is never the one other children are shuffled onto. `createPartitioning` replaces a transform's argument with the other child's cluster key, which drops whatever surrounds the key.
   - The `keyPositions` doc now says what its reference-based mapping does not tell apart.
   
   ### Why are the changes needed?
   
   With `spark.sql.sources.v2.bucketing.shuffle.enabled` on, this query returns 0 rows instead of 7. `t1(id)` and `t3(x)` are partitioned by `bucket(4, ...)`, `plain(b)` is not partitioned, and each holds the values 0 to 7:
   
   ```sql
   SELECT t1.id, p.b, t3.x FROM t1
   JOIN plain p ON t1.id = p.b + 1
   JOIN t3 ON p.b = t3.x
   ```
   
   1. The first join shuffles `plain` onto `t1`'s partitioning. `KeyedShuffleSpec.createPartitioning` builds that partitioning from `plain`'s join key, so it is `bucket(4, b + 1)`. This join is correct.
   2. The second join clusters `plain` on the bare `b`. `KeyedShuffleSpec.keyPositions` maps a partition expression to a cluster key through its reference, so `bucket(4, b + 1)` counts as a function of `b`, the counterpart of `x`.
   3. `isSameFunction` compares only the function name and the bucket count. So `bucket(4, b + 1)` is the same as `t3`'s `bucket(4, x)`, and the join pairs the partitions as they stand. A row with `b = x` sits in bucket `(b + 1) % 4` on one side and in `x % 4` on the other.
   
   The comparison ignores which column an argument is, and relies on `keyPositions` to pair the columns up. That is sound only when the argument is the column itself. `bucket(4, b + 1)` is a function of `b`, but not the same function of it as `bucket(4, x)` is of `x`. A scan never reports such a transform, so only a one-side shuffle can produce one. The same problem shows up in three more shapes, all measured on master:
   
   - **The reducer path.** Under `spark.sql.sources.v2.bucketing.allowCompatibleTransforms.enabled`, a `bucket(8, x)` third table loses the rows the same way.
   - **A struct field.** A join key `p.s.a` gives `bucket(4, s.a)`, which `keyPositions` pairs through `s`. Joining two such sides on `s` pairs `bucket(4, s.a)` with `bucket(4, s.b)` and returns 0 of 8 rows. Shuffling another side onto such a layout builds `bucket(4, s)`, which fails on executors with a `ClassCastException`.
   - **Shuffling onto the layout.** In `plain p JOIN t1 ON p.b + 1 = t1.id JOIN xy q ON t1.id = q.x AND p.b = q.y`, the second join shuffles `xy` onto the first join's `bucket(4, b + 1)` layout. That builds `bucket(4, y)` for `xy`, drops the `+ 1`, and returns 0 of 8 rows.
   
   The one-side shuffle of transform expressions came with SPARK-48012, in 4.0.0.
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes, it fixes the wrong results and the crash above. Such a query now shuffles the side instead of pairing it or shuffling onto it.
   
   That costs shuffles in a few shapes whose plan was already correct:
   - When two sides carry the same expression shape, e.g. `bucket(4, b + 1)` and `bucket(4, c + 1)` joined on `b = c`, both sides are shuffled.
   - When a join's output offers such a layout next to a usable one, e.g. `t1 JOIN plain p ON t1.id = p.b + 1 JOIN xy q ON t1.id = q.x AND p.b = q.y`, the next join takes 3 shuffles instead of 2. `ShuffleSpecCollection.canCreatePartitioning` requires every member to be usable, so the usable `bucket(4, id)` layout is ruled out too. The shuffling-onto-the-layout test below pays the same.
   
   A follow-up can give these back by describing a transform's argument relative to its column, so that `b + 1` and `c + 1` compare equal while `b + 1` and `x` do not.
   
   ### How was this patch tested?
   
   New tests, each of which fails on master:
   - `KeyGroupedPartitioningSuite`, "SPARK-59887: a side shuffled onto a transform of an expression is not paired as it is". It runs the query above against a `bucket(4)` third table, and with `allowCompatibleTransforms` against a `bucket(8)` one that the join reduces, and asserts two shuffles. Master returns 0 of 7 rows.
   - `KeyGroupedPartitioningSuite`, "SPARK-59887: a side shuffled onto a transform of a struct field is not paired as it is". Master returns 0 of 8 rows.
   - `KeyGroupedPartitioningSuite`, "SPARK-59887: a side is not shuffled onto a transform of a struct field". Master fails with the `ClassCastException`.
   - `KeyGroupedPartitioningSuite`, "SPARK-59887: a side is not shuffled onto a transform of an expression". Master returns 0 of 8 rows.
   - `TransformExpressionSuite`, "SPARK-59887: a transform of an expression is not the same as any transform". It covers `isSameFunction`, `reducers` in both directions and `isCompatible` for transforms over `a + 1` and over a struct field, with a column-argument control.
   
   Each of the three clauses was removed on its own:
   - without the `isSameFunction` one, the `bucket(4)` case returns 0 of 7 rows and the struct field test 0 of 8;
   - without the `reducers` one, the `bucket(8)` case returns 0 of 7 rows;
   - without the `canCreatePartitioning` one, both struct field tests fail with the `ClassCastException`, and the first test fails on the shuffle count.
   
   The third test passes with any one of them removed. Both the `isSameFunction` clause and the `canCreatePartitioning` clause keep `xy` off that layout, the first because the layout then does not pair with its own side.
   
   Also ran `TransformExpressionSuite`, `ShuffleSpecSuite`, `DistributionSuite`, `KeyGroupedPartitioningSuite` (and the other `KeyGroupedPartitioning*` suites), `WriteDistributionAndOrderingSuite`, `PlannerSuite`, `ProjectedOrderingAndPartitioningSuite`, `GroupPartitionsExecSuite` and `EnsureRequirementsSuite`, 583 tests in all, plus `dev/lint-scala`.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   
   Generated-by: Claude Code
   


-- 
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-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on code in PR #59165:
URL: https://github.com/apache/spark/pull/59165#discussion_r4172168311


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2086,6 +2119,48 @@ case class KeyedShuffleSpec(
     }
   }
 
+  /**
+   * Whether every argument of `transform` is a bare column. `isExpressionCompatible` asks it of
+   * both sides before it compares anything, `canCreatePartitioning` asks it of a template, and
+   * `rebuiltOver` asserts it.
+   *
+   * `keyPositions` pairs two sides up by the column each expression references. That pairing
+   * describes one key space when the argument is the column itself. `bucket(4, b + 1)` is a
+   * function of `b`, but not the same function of it as `bucket(4, x)` is of `x`. Nor is
+   * `bucket(4, s.a)` the same function of `s` as `bucket(4, t.b)` is of `t`. So such a transform
+   * pairs only with a transform over the same `argumentShape`. Over the same shape, the two
+   * compare as two transforms of columns do, e.g. `bucket(4, b + 1)` with `bucket(4, c + 1)` on a
+   * join `b = c`. A reduce of `bucket(8, b + 1)` onto `bucket(4, c + 1)` is fine too, since it
+   * maps the partition keys and evaluates no argument. An identity side is not reduced onto such a
+   * transform, since that would evaluate `id + 1` on keys the query never computes it for, which
+   * can overflow.
+   */
+  private def argumentsAreColumns(transform: TransformExpression): Boolean =
+    transform.children.forall(_.isInstanceOf[Attribute])
+
+  /**
+   * `transform` with its argument replaced by `column`. Only a transform of bare columns can be
+   * rebuilt this way. Any other argument would lose what surrounds its column, e.g. the `+ 1` of
+   * `bucket(4, b + 1)`.
+   */
+  private def rebuiltOver(transform: TransformExpression, column: Expression)

Review Comment:
   Done in [71c37c6](https://github.com/apache/spark/pull/59165/commits/71c37c6eedc6dbfd10abdcecf6c89b472dca02a6). The parameter is `key` now, and the doc says that `transform`'s arguments are bare columns while `key` may be any expression.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -1941,8 +1949,20 @@ case class KeyedShuffleSpec(
    * `KeyedPartitioning.positionsCoveringClusterKeys` counts it. See that method for why the two
    * stay apart.
    *
-   * The assertion is what makes the reference reading sound. With one reference per expression,
-   * "some reference is a cluster key" and "every reference is" are the same statement.
+   * Only an expression with a single reference maps to a position. With one reference, "some
+   * reference is a cluster key" and "every reference is" are the same statement, which is what
+   * makes the reference reading sound. A scan reports no other expression
+   * (`KeyedPartitioning.supportsExpressions`), but two planner paths build one over the other

Review Comment:
   Thanks, confirmed by running it. An in-memory table partitioned by `bucket(4, s.a)` reports `bucket(4, s.a AS a)`, and its scan's `outputPartitioning` is `UnknownPartitioning`. The same holds for `identity(s.a)`. I dropped the bullet, and the description now says that a scan reports neither a transform of an expression nor one of a struct field.



-- 
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-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "dongjoon-hyun (via GitHub)" <gi...@apache.org>.
dongjoon-hyun commented on PR #59165:
URL: https://github.com/apache/spark/pull/59165#issuecomment-5941244803

   I merged the following. Please rebase to master branch once more.
   - https://github.com/apache/spark/pull/59189


-- 
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-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on code in PR #59165:
URL: https://github.com/apache/spark/pull/59165#discussion_r4152408936


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -92,19 +113,8 @@ case class TransformExpression(
    * @param other the transform expression to compare to
    * @return true if compatible, false if not
    */
-  def isCompatible(other: TransformExpression): Boolean = {
-    if (isSameFunction(other)) {
-      true
-    } else {
-      (function, other.function) match {
-        case (f: ReducibleFunction[_, _], o: ReducibleFunction[_, _]) =>
-          val thisReducer = reducer(f, numBucketsOpt, o, other.numBucketsOpt)
-          val otherReducer = reducer(o, other.numBucketsOpt, f, numBucketsOpt)
-          thisReducer.isDefined || otherReducer.isDefined
-        case _ => false
-      }
-    }
-  }
+  def isCompatible(other: TransformExpression): Boolean =
+    isSameFunction(other) || reducers(other).isDefined || other.reducers(this).isDefined

Review Comment:
   Done in [69f16ab](https://github.com/apache/spark/pull/59165/commits/69f16abd834a271f68e04905d5391b887fcb4a49). With the guard out of `TransformExpression`, its docs hold again as they were. The `ShuffleSpec.isCompatibleWith` note now lists the specs that are not reflexive, and says what keeps the planner from picking one as a layout.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -65,6 +65,16 @@ case class TransformExpression(
   lazy val functionId: TransformFunctionId =
     TransformFunctionId(function.canonicalName(), numBucketsOpt)
 
+  /**
+   * Whether every argument is a bare column, an [[Attribute]]. See [[isSameFunction]] for why only
+   * such a transform can be compared with another one. A literal argument is a parameter of the
+   * transform rather than a column, so it does not count.
+   */
+  private[sql] lazy val argumentsAreAttributes: Boolean = children.forall {
+    case _: Literal => true

Review Comment:
   Done in [69f16ab](https://github.com/apache/spark/pull/59165/commits/69f16abd834a271f68e04905d5391b887fcb4a49). The check is `children.forall(_.isInstanceOf[Attribute])`, without the literal case.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala:
##########
@@ -1520,6 +1520,113 @@ class KeyGroupedPartitioningSuite
     }
   }
 
+  // Each key is a function of `b` other than `b` itself. A check on the leaves of the key would
+  // reject `b + 1` for its literal, but not `-b`, so both are tested.
+  Seq("p.b + 1" -> ((b: Long) => b + 1), "-p.b" -> ((b: Long) => -b)).foreach {
+    case (key, keyOf) =>
+      // `plain` holds `b` in 0..7, and `keys`, bucketed on `id`, holds the key of each `b`.
+      def createKeyTables(): Unit = {
+        createTable("plain", Array(Column.create("b", LongType)), Array.empty)
+        sql("INSERT INTO testcat.ns.plain VALUES " + (0 until 8).map(b => s"($b)").mkString(", "))
+        createTable("keys", Array(Column.create("id", LongType)), Array(bucket(4, "id")))
+        sql("INSERT INTO testcat.ns.keys VALUES " +
+          (0 until 8).map(b => s"(${keyOf(b)})").mkString(", "))
+      }
+
+      test("SPARK-59887: a side shuffled onto a transform of an expression is not paired as it " +
+          s"is ($key)") {
+        createKeyTables()
+        Seq(4, 8).foreach(n => createBucketedIdTable(s"bucket$n", n, numIds = 8))
+
+        // The first join shuffles `plain` onto the bucket of its key, which is a function of `b`,
+        // but not the same function of it as the third table's `bucket(n, id)` is of `id`. The
+        // second join clusters `plain` on `b`, so pairing the two as they stand, or after reducing
+        // `bucket(8, id)` onto 4 buckets, puts a row with `b = id` on a different partition on
+        // each side.
+        Seq(4 -> "false", 8 -> "true").foreach { case (third, allowCompatibleTransforms) =>
+          withSQLConf(
+            SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+            SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> allowCompatibleTransforms) {
+            val df = sql(
+              s"""SELECT k.id, p.b, t.id FROM testcat.ns.keys k
+                 |JOIN testcat.ns.plain p ON k.id = $key
+                 |JOIN testcat.ns.bucket$third t ON p.b = t.id""".stripMargin)
+            checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, b.toLong)))
+            // One shuffle per join: `plain` for the first, the first join's output for the
+            // second, and none for the third table. The second join does not shuffle onto the
+            // bucket of the key, since that would move both of its sides.
+            assert(collectShuffles(stripAQEPlan(df.queryExecution.executedPlan)).size == 2)
+          }
+        }
+      }
+
+      test(s"SPARK-59887: a side is not shuffled onto a transform of an expression ($key)") {
+        createKeyTables()
+        createTable("xy", Array(Column.create("x", LongType), Column.create("y", LongType)),
+          Array.empty)
+        sql("INSERT INTO testcat.ns.xy VALUES " +
+          (0 until 8).map(b => s"(${keyOf(b)}, $b)").mkString(", "))
+
+        // The first join shuffles `plain` onto the bucket of its key, so its output offers that
+        // layout next to `bucket(4, id)`. The second join must not shuffle `xy` onto the first
+        // one. That builds `bucket(4, y)` for `xy`, not the bucket of the same function of `y`,
+        // so a row with `b = y` lands in a different bucket on each side.
+        withSQLConf(SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
+          val df = sql(
+            s"""SELECT k.id, p.b, q.x FROM testcat.ns.plain p
+               |JOIN testcat.ns.keys k ON $key = k.id
+               |JOIN testcat.ns.xy q ON k.id = q.x AND p.b = q.y""".stripMargin)
+          checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, keyOf(b))))
+        }
+      }
+  }
+
+  test("SPARK-59887: a side shuffled onto a transform of a struct field is not paired as it is") {
+    createBucketedIdTable("bucket4", 4, numIds = 8)
+    val structColumn = Array(
+      Column.create("s", new StructType().add("a", LongType).add("b", LongType)))
+    Seq("ps", "qs").foreach { name =>
+      createTable(name, structColumn, Array.empty)
+      sql(s"INSERT INTO testcat.ns.$name VALUES " +
+        (0 until 8).map(i => s"(named_struct('a', ${i}L, 'b', ${7 - i}L))").mkString(", "))
+    }
+
+    // Each side is shuffled onto the bucket of a different field of `s`, `bucket(4, s.a)` and
+    // `bucket(4, s.b)`. Both are functions of `s`, but not the same one, so the join on `s` must
+    // not pair them as they stand: a row lands in bucket `a % 4` on one side and `b % 4` on the
+    // other.
+    withSQLConf(SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
+      val df = sql(
+        """SELECT l.id, r.id FROM
+          |  (SELECT x.id, ps.s FROM testcat.ns.bucket4 x JOIN testcat.ns.ps ps ON x.id = ps.s.a) l
+          |  JOIN
+          |  (SELECT y.id, qs.s FROM testcat.ns.bucket4 y JOIN testcat.ns.qs qs ON y.id = qs.s.b) r
+          |  ON l.s = r.s""".stripMargin)
+      checkAnswer(df, (0 until 8).map(i => Row(i.toLong, (7 - i).toLong)))
+    }
+  }
+
+  test("SPARK-59887: a side is not shuffled onto a transform of a struct field") {

Review Comment:
   Merged into one test in [69f16ab](https://github.com/apache/spark/pull/59165/commits/69f16abd834a271f68e04905d5391b887fcb4a49). The `ClassCastException` shape is its second query, over a plain `ps`.
   



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/TransformExpressionSuite.scala:
##########
@@ -41,6 +41,24 @@ class TransformExpressionSuite extends SparkFunSuite {
     override def hashCode(): Int = canonicalName().hashCode
   }
 
+  /** Reduces a bucket count onto any smaller count that divides it. */
+  private object DivisibleBucketFunction

Review Comment:
   Gone in [69f16ab](https://github.com/apache/spark/pull/59165/commits/69f16abd834a271f68e04905d5391b887fcb4a49). The unit test moved to `ShuffleSpecSuite`, where it uses `FakeBucket`.
   



-- 
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-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "dongjoon-hyun (via GitHub)" <gi...@apache.org>.
dongjoon-hyun commented on code in PR #59165:
URL: https://github.com/apache/spark/pull/59165#discussion_r4168744978


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2086,6 +2119,48 @@ case class KeyedShuffleSpec(
     }
   }
 
+  /**
+   * Whether every argument of `transform` is a bare column. `isExpressionCompatible` asks it of
+   * both sides before it compares anything, `canCreatePartitioning` asks it of a template, and
+   * `rebuiltOver` asserts it.
+   *
+   * `keyPositions` pairs two sides up by the column each expression references. That pairing
+   * describes one key space when the argument is the column itself. `bucket(4, b + 1)` is a
+   * function of `b`, but not the same function of it as `bucket(4, x)` is of `x`. Nor is
+   * `bucket(4, s.a)` the same function of `s` as `bucket(4, t.b)` is of `t`. So such a transform
+   * pairs only with a transform over the same `argumentShape`. Over the same shape, the two
+   * compare as two transforms of columns do, e.g. `bucket(4, b + 1)` with `bucket(4, c + 1)` on a
+   * join `b = c`. A reduce of `bucket(8, b + 1)` onto `bucket(4, c + 1)` is fine too, since it
+   * maps the partition keys and evaluates no argument. An identity side is not reduced onto such a
+   * transform, since that would evaluate `id + 1` on keys the query never computes it for, which
+   * can overflow.
+   */
+  private def argumentsAreColumns(transform: TransformExpression): Boolean =
+    transform.children.forall(_.isInstanceOf[Attribute])
+
+  /**
+   * `transform` with its argument replaced by `column`. Only a transform of bare columns can be
+   * rebuilt this way. Any other argument would lose what surrounds its column, e.g. the `+ 1` of
+   * `bucket(4, b + 1)`.
+   */
+  private def rebuiltOver(transform: TransformExpression, column: Expression)

Review Comment:
   Nit: the parameter name says that the replacement is a column, but only the source has to be one, which is what the assert checks. `createPartitioning` passes the other child's join key at L2298, and that is an expression in exactly the cases this PR handles: `bucket(4, t1.id)` becomes `bucket(4, p.b + 1)`, as the same-shape tests in `KeyGroupedPartitioningSuite` expect. Could it be named `key`, with the doc saying "`transform`, whose arguments are bare columns, with each replaced by `key`, which may be any expression"?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -1941,8 +1949,20 @@ case class KeyedShuffleSpec(
    * `KeyedPartitioning.positionsCoveringClusterKeys` counts it. See that method for why the two
    * stay apart.
    *
-   * The assertion is what makes the reference reading sound. With one reference per expression,
-   * "some reference is a cluster key" and "every reference is" are the same statement.
+   * Only an expression with a single reference maps to a position. With one reference, "some
+   * reference is a cluster key" and "every reference is" are the same statement, which is what
+   * makes the reference reading sound. A scan reports no other expression
+   * (`KeyedPartitioning.supportsExpressions`), but two planner paths build one over the other

Review Comment:
   Minor: a scan cannot report a transform of a struct field either, so the cost that the PR description lists for "a scan that reports a bucket of a struct field, e.g. `bucket(4, s.a)`" does not seem to arise. `V2ExpressionUtils.resolveRef` resolves `s.a` through `LogicalPlan.resolve`, which wraps a nested field in an `Alias` (package.scala:405-410). So the scan's transform is over an `Alias`, which `supportsExpressions` (L1110-L1117) refuses, since it accepts only an `Attribute` or a `GetStructField` chain. `DataSourceV2ScanExecBase` then reports no `KeyedPartitioning` (DataSourceV2ScanExecBase.scala:105), and I found nothing in between that strips the alias. Such a table gets no storage-partitioned join on master either, which would also explain why the in-memory catalog cannot test it. Could the description drop that bullet, or say that such layouts come only from joins? I traced this but did not run it.



-- 
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-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on code in PR #59165:
URL: https://github.com/apache/spark/pull/59165#discussion_r4167942387


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala:
##########
@@ -139,8 +139,10 @@ case class EnsureRequirements(
               // OrderedDistribution requires grouped KeyedPartitioning with sorted keys
               // according to the distribution's ordering.
               val satisfyingKeyedPartitioning = resolution.fold(identity, _._1)
-              // The single-column invariant in KeyedPartitioning.supportsExpressions guarantees
-              // one attribute per partition expression.
+              // This binds the ordering to the partition expressions' references, which is right

Review Comment:
   #59189 rewords both ([comment](https://github.com/apache/spark/pull/59189#discussion_r4158266464)), and [765c526](https://github.com/apache/spark/pull/59165/commits/765c526071fd7c35ba80b518564272a344e64036) is rebased onto it.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala:
##########
@@ -604,8 +604,15 @@ private[sql] object GroupPartitionsExec {
                   // `reduced` came from the one member `checkKeyGroupCompatible` paired
                   // this side on, which need not be the member being rewritten. The keys are
                   // reduced once, from the shared key rows, so `reduced` describes them
-                  // whichever member this is, and only the key attribute is re-targeted.
-                  reduced.withReference(expr.references.head)
+                  // whichever member this is. Its argument is a bare column, since the pairing
+                  // admits no other. The member's own argument takes its place, since that need
+                  // not be one. A side shuffled onto this layout reports `bucket(8, b + 1)` next
+                  // to `bucket(8, id)`, or `b + 1` next to an identity `id`.
+                  val argument = expr match {
+                    case t: TransformExpression => t.children
+                    case e => Seq(e)
+                  }
+                  reduced.copy(children = argument)

Review Comment:
   Done in [765c526](https://github.com/apache/spark/pull/59165/commits/765c526071fd7c35ba80b518564272a344e64036). The identity arm rebuilds the transform with `copy`, through a helper it shares with `createPartitioning`. `withReference` is gone together with its `TransformExpressionSuite` assertion.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -1951,8 +1961,11 @@ case class KeyedShuffleSpec(
     }
     partitioning.expressions.map { e =>
       val refs = e.references
-      assert(refs.size == 1, s"Expected exactly one child from $e, but found ${refs.size}")
-      distKeyToPos.getOrElse(refs.head.canonicalized, mutable.BitSet.empty)
+      if (refs.size == 1) {
+        distKeyToPos.getOrElse(refs.head.canonicalized, mutable.BitSet.empty)

Review Comment:
   Thanks, that's a neat way to make the checks agree by construction, and it evaluates nothing new either. I'll take it into SPARK-59900, since it also changes what a position means for the projection in `createShuffleSpec`.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala:
##########
@@ -367,12 +369,14 @@ case class EnsureRequirements(
     val shouldConsiderMinParallelism = children.zip(specs).forall { case (child, spec) =>
       spec.forall(!_.canCreatePartitioning) || child.isInstanceOf[ShuffleExchangeLike]
     }
-    // Choose all the specs that can be used to shuffle other children
+    // Choose all the specs that can be used to shuffle other children, keeping only the members
+    // that can serve as the layout. Any other member would build a partitioning its own child is
+    // not laid out on.
     val candidateSpecs = children.zip(specs).collect {
       case (child, Some(spec)) if spec.canCreatePartitioning &&

Review Comment:
   Done in [765c526](https://github.com/apache/spark/pull/59165/commits/765c526071fd7c35ba80b518564272a344e64036). The candidates are the children with a serving member, and the comments say serving members.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/ShuffleSpecSuite.scala:
##########
@@ -761,6 +761,84 @@ class ShuffleSpecSuite extends SparkFunSuite with SQLHelper {
     }
   }
 
+  test("SPARK-59887: a spec over a transform of an expression pairs with nothing") {
+    // A join pairs its two sides up by the column each partition expression references. Over
+    // `a = b` it would pair `bucket(4, a + 1)` with `bucket(4, b)`, and over `s = b` it would pair
+    // `bucket(4, s.x)` with `bucket(4, b)`. A row with `a = b` sits in a different bucket on each
+    // side.
+    val fn = new FakeBucket
+    val a = $"a".long
+    val b = $"b".long
+    val s = $"s".struct(new StructType().add("x", LongType))
+    // A spec clustered on the column its one partition expression references.
+    def keyed(expression: Expression): KeyedShuffleSpec =
+      KeyedShuffleSpec(
+        KeyedPartitioning(Seq(expression), Seq(InternalRow(0L), InternalRow(1L))),
+        ClusteredDistribution(expression.references.toSeq))
+    def bucket(argument: Expression, numBuckets: Int): TransformExpression =

Review Comment:
   Done in [765c526](https://github.com/apache/spark/pull/59165/commits/765c526071fd7c35ba80b518564272a344e64036). The helper takes the bucket count first, and the comment uses `s = t`.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala:
##########
@@ -1520,6 +1534,203 @@ class KeyGroupedPartitioningSuite
     }
   }
 
+  // Each key is a function of `b` other than `b` itself. A check on the leaves of the key would
+  // reject `b + 1` for its literal, but not `-b`, so both are tested.
+  Seq("p.b + 1" -> ((b: Long) => b + 1), "-p.b" -> ((b: Long) => -b)).foreach {
+    case (key, keyOf) =>
+      // `plain` holds `b` in 0..7, and `keys`, bucketed on `id`, holds the key of each `b`.
+      def createKeyTables(): Unit = {
+        createTable("plain", Array(Column.create("b", LongType)), Array.empty)
+        sql("INSERT INTO testcat.ns.plain VALUES " + (0 until 8).map(b => s"($b)").mkString(", "))
+        createTable("keys", Array(Column.create("id", LongType)), Array(bucket(4, "id")))
+        sql("INSERT INTO testcat.ns.keys VALUES " +
+          (0 until 8).map(b => s"(${keyOf(b)})").mkString(", "))
+      }
+
+      test("SPARK-59887: a side shuffled onto a transform of an expression is not paired as it " +
+          s"is ($key)") {
+        createKeyTables()
+        Seq(4, 8).foreach(n => createBucketedIdTable(s"bucket$n", n, numIds = 8))
+
+        // The first join shuffles `plain` onto the bucket of its key. That is a function of `b`,
+        // but not the same function of it as the third table's `bucket(n, id)` is of `id`. The
+        // second join clusters `plain` on `b`. Pairing the two there, as they stand or after
+        // reducing `bucket(8, id)` onto 4 buckets, puts a row with `b = id` on a different
+        // partition on each side.
+        Seq(4 -> "false", 8 -> "true").foreach { case (third, allowCompatibleTransforms) =>
+          withSQLConf(
+            SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+            SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> allowCompatibleTransforms) {
+            val df = sql(
+              s"""SELECT k.id, p.b, t.id FROM testcat.ns.keys k
+                 |JOIN testcat.ns.plain p ON k.id = $key
+                 |JOIN testcat.ns.bucket$third t ON p.b = t.id""".stripMargin)
+            checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, b.toLong)))
+            // One shuffle per join: `plain` for the first, the first join's output for the
+            // second, and none for the third table. The second join does not shuffle onto the
+            // bucket of the key, since that would move both of its sides.
+            assert(collectShuffles(stripAQEPlan(df.queryExecution.executedPlan)).size == 2)
+          }
+        }
+      }
+
+      test(s"SPARK-59887: a side is not shuffled onto a transform of an expression ($key)") {
+        createKeyTables()
+        createTable("xy", Array(Column.create("x", LongType), Column.create("y", LongType)),
+          Array.empty)
+        sql("INSERT INTO testcat.ns.xy VALUES " +
+          (0 until 8).map(b => s"(${keyOf(b)}, $b)").mkString(", "))
+
+        // The first join shuffles `plain` onto the bucket of its key, so its output offers that
+        // layout next to `bucket(4, id)`. The second join must not shuffle `xy` onto the first
+        // one. That builds `bucket(4, y)` for `xy`, not the bucket of the same function of `y`. A
+        // row with `b = y` then lands in a different bucket on each side. The join order decides
+        // which of the two layouts comes first, so both orders run.
+        withSQLConf(SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
+          Seq(
+            s"testcat.ns.plain p JOIN testcat.ns.keys k ON $key = k.id",
+            s"testcat.ns.keys k JOIN testcat.ns.plain p ON k.id = $key").foreach { firstJoin =>
+            val df = sql(
+              s"""SELECT k.id, p.b, q.x FROM $firstJoin
+                 |JOIN testcat.ns.xy q ON k.id = q.x AND p.b = q.y""".stripMargin)
+            checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, keyOf(b))))
+            // `xy` is shuffled onto the usable layout, `bucket(4, x)`, and never onto a bucket of
+            // `y`. So `plain` and `xy` are the only sides that move.
+            val shuffles = collectShuffles(stripAQEPlan(df.queryExecution.executedPlan))
+            assert(shuffles.size == 2)
+            assert(!keyedPartitioningsOf(shuffles).exists(_.references.exists(_.name == "y")))
+          }
+        }
+      }
+
+      test("SPARK-59887: a broadcast join's layout over a join key is not paired as it is " +
+          s"($key)") {
+        createKeyTables()
+        createBucketedIdTable("bucket4", 4, numIds = 8)
+
+        // An inner broadcast join reports the streamed side's layout over the build side's join
+        // key too, so the first join also offers the bucket of `plain`'s key. That needs no conf
+        // beyond the defaults. The second join clusters `plain` on `b`, so pairing that layout with
+        // `bucket(4, id)` as it stands puts a row with `b = id` on a different partition on each
+        // side.
+        val df = sql(
+          s"""SELECT /*+ BROADCAST(p) */ k.id, p.b, t.id FROM testcat.ns.keys k
+             |JOIN testcat.ns.plain p ON k.id = $key
+             |JOIN testcat.ns.bucket4 t ON p.b = t.id""".stripMargin)
+        checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, b.toLong)))
+        assert(collect(df.queryExecution.executedPlan) { case j: BroadcastHashJoinExec => j }
+          .nonEmpty, "the first join is a broadcast join")
+      }
+  }
+
+  test("SPARK-59887: a layout over a transform of a struct field is not paired nor shuffled onto") {
+    createBucketedIdTable("bucket4", 4, numIds = 8)
+    createStructTable()
+    // `l` shuffles `ps` onto `bucket(4, s.a)`, and `r` shuffles it onto `bucket(4, s.b)`.
+    val l = "SELECT x.id, ps.s FROM testcat.ns.bucket4 x JOIN testcat.ns.ps ps ON x.id = ps.s.a"
+    val r = "SELECT y.id, qs.s FROM testcat.ns.bucket4 y JOIN testcat.ns.ps qs ON y.id = qs.s.b"
+
+    withSQLConf(SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
+      // Both layouts are functions of `s`, but not the same one, so the join on `s` must not pair
+      // them as they stand. A row lands in bucket `a % 4` on one side and `b % 4` on the other.
+      checkAnswer(
+        sql(s"SELECT l.id, r.id FROM ($l) l JOIN ($r) r ON l.s = r.s"),
+        (0 until 8).map(i => Row(i.toLong, (7 - i).toLong)))
+      // Nor may a join shuffle a plain `ps` onto `l`'s layout. That builds `bucket(4, s)` for it,
+      // which drops the `.a` and hands the whole struct to a bucket function over a long.
+      checkAnswer(
+        sql(s"SELECT l.id FROM ($l) l JOIN testcat.ns.ps r ON l.s = r.s"),
+        (0 until 8).map(i => Row(i.toLong)))
+    }
+  }
+
+  test("SPARK-59887: a reduce keeps what each member's keys are computed from") {
+    Seq(4, 2).foreach(n => createBucketedIdTable(s"bucket$n", n, numIds = 8))
+    createIdentityIdTable()
+    createTable("plain", Array(Column.create("b", LongType)), Array.empty)
+    sql("INSERT INTO testcat.ns.plain VALUES " + (0 until 8).map(b => s"($b)").mkString(", "))
+    createStructTable()
+
+    withSQLConf(
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> "true") {
+      // The first join shuffles `plain` onto `bucket(4, b + 1)`, or onto `b + 1` for the
+      // identity-partitioned `ident`. The second join reduces the first one's output onto
+      // `bucket(2)`, `plain`'s member included. That member is still over `b + 1`. So the third
+      // join, on the bare `b`, must neither pair it with `bucket(2, id)` nor shuffle a plain
+      // side onto it.
+      for {
+        first <- Seq("bucket4", "ident")
+        (third, thirdKey) <- Seq("bucket2" -> "id", "plain" -> "b")
+      } {
+        val df = sql(
+          s"""SELECT f.id, p.b, t2.id, t3.$thirdKey FROM testcat.ns.$first f
+             |JOIN testcat.ns.plain p ON f.id = p.b + 1
+             |JOIN testcat.ns.bucket2 t2 ON f.id = t2.id
+             |JOIN testcat.ns.$third t3 ON p.b = t3.$thirdKey""".stripMargin)
+        checkAnswer(df, (0 until 7).map(b => Row(b + 1L, b.toLong, b + 1L, b.toLong)))
+      }
+
+      // The same for a struct field. `ps`'s member is still over `s.a` after the reduce, so the
+      // third join must not shuffle a plain `ps` onto it, which would build `bucket(2, s)`.
+      val df = sql(
+        """SELECT x.id FROM testcat.ns.bucket4 x
+          |JOIN testcat.ns.ps ps ON x.id = ps.s.a
+          |JOIN testcat.ns.bucket2 t2 ON x.id = t2.id
+          |JOIN testcat.ns.ps r ON ps.s = r.s""".stripMargin)
+      checkAnswer(df, (0 until 8).map(i => Row(i.toLong)))
+    }
+  }
+
+  test("SPARK-59887: an identity side is not reduced onto a transform of an expression") {
+    createBucketedIdTable("bucket4", 4, numIds = 8)
+    createTable("plain", Array(Column.create("b", LongType)), Array.empty)
+    sql("INSERT INTO testcat.ns.plain VALUES " + (0 until 7).map(b => s"($b)").mkString(", "))

Review Comment:
   Done in [765c526](https://github.com/apache/spark/pull/59165/commits/765c526071fd7c35ba80b518564272a344e64036). `createPlainTable` takes the values, defaults to `0 until 8`, and sits after `createBucketedIdTables` with the other helpers.



-- 
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-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on PR #59165:
URL: https://github.com/apache/spark/pull/59165#issuecomment-5957282464

   Thanks for round 2, @dongjoon-hyun, and for merging #59189. [765c526](https://github.com/apache/spark/pull/59165/commits/765c526071fd7c35ba80b518564272a344e64036) is rebased onto master and takes round 2. It goes further on item 1. Instead of only documenting the cost, it pairs the same argument shape again. Item 11 goes to SPARK-59900, and item 9 came with #59189. I also fixed the `Generated-by` line (item 15) and updated the description. Besides your items, [765c526](https://github.com/apache/spark/pull/59165/commits/765c526071fd7c35ba80b518564272a344e64036) pairs two transforms reduced through the same pairing over the same shape, as it does for columns. A new test checks that a different pairing is not paired. Since this PR fixes SPARK-59901, the SPARK-59905 test now runs its `p.b + p.c` query with AQE on too. The identity arm of `reducersBothWays` and `createPartitioning` now rebuild a transform through one helper, which asserts that its argument is a column.


-- 
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-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on PR #59165:
URL: https://github.com/apache/spark/pull/59165#issuecomment-5925879386

   Thanks a lot for the thorough review, @dongjoon-hyun. [69f16ab](https://github.com/apache/spark/pull/59165/commits/69f16abd834a271f68e04905d5391b887fcb4a49) takes all of it except item 3, now SPARK-59905, and item 5, which the description lists as a cost. It also takes SPARK-59901 in, for item 2. I updated the title and the description.
   


-- 
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-59887][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "dongjoon-hyun (via GitHub)" <gi...@apache.org>.
dongjoon-hyun commented on code in PR #59165:
URL: https://github.com/apache/spark/pull/59165#discussion_r4148432829


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -77,10 +87,21 @@ case class TransformExpression(
    * It compares the transforms only. A caller that compares partition keys has to consult
    * `reducedWith` as well, since a reduced key space is not the one its transform names.
    *
+   * Only a transform whose arguments are all bare columns can be the same as another. The
+   * comparison ignores which column an argument is, and `KeyedShuffleSpec.keyPositions` pairs the
+   * two sides up by the column each expression references. That pairing is sound only when the
+   * argument is the column itself. `KeyedShuffleSpec.createPartitioning` builds a transform over
+   * the other side's join key, which can be an expression or a struct field. `bucket(4, b + 1)` is
+   * a function of `b`, but not the same function of it as `bucket(4, x)` is of `x`, so a join on
+   * `b = x` must not pair the two, and neither may a join on `s = t` pair `bucket(4, s.a)` with
+   * `bucket(4, t.b)`. Such a transform is not the same as any transform, itself included, which
+   * costs a shuffle rather than a match.
+   *
    * @param other the transform expression to compare to
    * @return true if this and `other` has the same semantics w.r.t to transform, false otherwise.
    */
-  def isSameFunction(other: TransformExpression): Boolean = functionId == other.functionId
+  def isSameFunction(other: TransformExpression): Boolean =
+    argumentsAreAttributes && other.argumentsAreAttributes && functionId == other.functionId

Review Comment:
   **The new guard is bypassed once a later join reduces the keys, and the wrong result comes back.** `GroupPartitionsExec` rewrites every member of the reduced child's partitioning with the reduced expression re-targeted at the member's first reference:
   
   https://github.com/apache/spark/blob/14141b9e262ccc61b5ba8b721874a288965c7b9a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala#L603-L608
   
   So a `bucket(4, b + 1)` member, which the one-side shuffle created, is reported as `bucket(2, b)` after a join reduces `bucket(4)` onto `bucket(2)`. Its argument is a bare column, so `isSameFunction` pairs it and `canCreatePartitioning` accepts it, while its rows still sit in `(b + 1) % 2`. The following returns 0 of 7 rows on both this PR and its base commit:
   
   ```scala
   Seq("bucket4" -> 4, "bucket2a" -> 2, "bucket2b" -> 2).foreach { case (name, n) =>
     createBucketedIdTable(name, n, numIds = 8)
   }
   createTable("plain", Array(Column.create("b", LongType)), Array.empty)
   sql("INSERT INTO testcat.ns.plain VALUES " + (0 until 8).map(b => s"($b)").mkString(", "))
   withSQLConf(
       SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
       SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> "true") {
     val df = sql(
       """SELECT b4.id, p.b, t2.id, t3.id FROM testcat.ns.bucket4 b4
         |JOIN testcat.ns.plain p ON b4.id = p.b + 1
         |JOIN testcat.ns.bucket2a t2 ON b4.id = t2.id
         |JOIN testcat.ns.bucket2b t3 ON p.b = t3.id""".stripMargin)
     checkAnswer(df, (0 until 7).map(b => Row(b + 1L, b.toLong, b + 1L, b.toLong)))
   }
   ```
   
   The second join reduces the left side's `bucket(4, id)` onto `bucket(2)`, and the third join pairs the re-targeted `bucket(2, b)` with `bucket(2, id)` without any exchange. The same happens in three more shapes:
   - When the third table is unpartitioned, it is shuffled onto `bucket(2, y)`, and the query returns 0 of 7 rows.
   - When the first table is identity-partitioned, the identity reduce turns the bare `b + 1` member into `bucket(2, b)`, and the query returns 0 of 7 rows.
   - In the struct form, `bucket(4, s.a)` becomes `bucket(2, s)`, and another side shuffled onto it fails with the same `ClassCastException` as the struct-field tests of this PR.
   
   Could `GroupPartitionsExec` re-target by the member's own argument instead? That means replacing the argument of `reduced` with the member's argument, i.e. the child of a transform, or the member itself for a bare expression. The member is then reported as `bucket(2, b + 1)`, which describes its keys and which the new guard refuses.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2199,8 +2203,14 @@ case class KeyedShuffleSpec(
       // cannot rewrite it. This also keeps the unprojected spec returned by `createShuffleSpec`
       // for a marked narrowing projection from being chosen as the best spec.
       keyPositions.forall(_.nonEmpty) &&

Review Comment:
   **A two-column join-key expression fails planning in `keyPositions`, before the new clause below is reached.** `createPartitioning` builds the partition expression over the other child's join key, which can reference two columns, e.g. `bucket(4, b + c)`, or the bare `b + c` for an identity-partitioned side. Any spec over it then fails the assertion at L1958. This single join fails on both this PR and its base commit:
   
   ```scala
   createTable("ident", Array(Column.create("id", LongType)), Array(identity("id")))
   sql("INSERT INTO testcat.ns.ident VALUES " + (0 until 8).map(i => s"($i)").mkString(", "))
   createTable("plain2", Array(Column.create("b", LongType), Column.create("c", LongType)),
     Array.empty)
   sql("INSERT INTO testcat.ns.plain2 VALUES (0, 1), (0, 2), (1, 1), (1, 2)")
   withSQLConf(SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
     sql("SELECT * FROM testcat.ns.ident i JOIN testcat.ns.plain2 p ON i.id = p.b + p.c")
       .collect()
   }
   ```
   
   ```
   [INTERNAL_ERROR] The Spark SQL phase planning failed with an internal error. ...
   Cause: java.lang.AssertionError: assertion failed: Expected exactly one child from
   (b#10L + c#11L), but found 2
   ```
   
   It is reached through AQE's `OptimizeSkewedJoin`, which validates the plan with `ValidateRequirements`, so it needs nothing but `spark.sql.sources.v2.bucketing.shuffle.enabled`. With a bucketed side, `bucket4 b4 JOIN plain2 p ON b4.id = p.b + p.c JOIN xy q ON p.b = q.x AND p.c = q.y` fails the same way in `EnsureRequirements.pickCoPartitionTarget`, through this line.
   
   I know this predates this PR, but it is the same `createPartitioning` shape. Moving the new clause ahead of `keyPositions` fixes only the second path. So `createPartitioning`, or `EnsureRequirements` when it picks the target, would need to refuse a cluster key with more than one reference. Alternatively, `keyPositions` could return an empty position set instead of asserting.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2199,8 +2203,14 @@ case class KeyedShuffleSpec(
       // cannot rewrite it. This also keeps the unprojected spec returned by `createShuffleSpec`
       // for a marked narrowing projection from being chosen as the best spec.
       keyPositions.forall(_.nonEmpty) &&
-      partitioning.expressions.forall { e =>
-        e.isInstanceOf[AttributeReference] || e.isInstanceOf[TransformExpression]
+      partitioning.expressions.forall {
+        case _: AttributeReference => true
+        // `createPartitioning` replaces a transform's argument with the other child's cluster key,
+        // which drops whatever surrounds the key, e.g. the `+ 1` of `bucket(4, b + 1)` or the `.a`
+        // of `bucket(4, s.a)`. Such a spec's own child would then be laid out differently from the
+        // children shuffled onto it.
+        case t: TransformExpression => t.argumentsAreAttributes

Review Comment:
   **One refused member disables the whole collection, so the cost is larger than the PR description says.** `ShuffleSpecCollection.canCreatePartitioning` is a `forall`, so this clause also rules out the usable `bucket(4, id)` member of the same join output. The keyed layout is then lost for every operator above it too. I measured these with `spark.sql.sources.v2.bucketing.shuffle.enabled` on, and both return correct results:
   - The example in the PR description, `t1 JOIN plain p ON t1.id = p.b + 1 JOIN xy q ON t1.id = q.x AND p.b = q.y`, followed by `GROUP BY t1.id`, takes 4 shuffles instead of 2. `xy` and the first join's output are hash-shuffled on `(x, y)` and `(id, b)`, and the aggregate then needs another exchange on `id`.
   - Two one-side-shuffled legs, `(t1 JOIN p ON t1.id = p.b + 1) JOIN (t2 JOIN q ON t2.id = q.c + 1) ON t1.id = t2.id AND p.b = q.c`, take 4 shuffles instead of 2. On the base commit, the outer join pairs the two legs as they stand.
   
   Could the refusal be per member instead? For instance, `ShuffleSpecCollection.canCreatePartitioning` could be an `exists`, and `EnsureRequirements.pickCoPartitionTarget` could keep only the winner's members whose own `canCreatePartitioning` holds when it builds `bestMembers`. Then `bucket(4, id)` stays usable, and `bucket(4, b + 1)` is never used as a template. The change is as local as this clause, so it seems safe to backport too.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -1943,6 +1943,10 @@ case class KeyedShuffleSpec(
    *
    * The assertion is what makes the reference reading sound. With one reference per expression,
    * "some reference is a cluster key" and "every reference is" are the same statement.
+   *
+   * This says which cluster key an expression is a function of, not which function it is:
+   * `bucket(4, b + 1)` maps to `b` just as `bucket(4, b)` does. Telling those two apart is

Review Comment:
   **The same reference-based reading also breaks `ORDER BY`.** When `EnsureRequirements` checks a keyed child against an `OrderedDistribution`, it binds the required ordering to `expressions.flatMap(_.references)`:
   
   https://github.com/apache/spark/blob/14141b9e262ccc61b5ba8b721874a288965c7b9a/sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala#L142-L145
   
   For a bare expression member that `createPartitioning` built over an identity side, e.g. `100 - b`, the key rows already hold `100 - b`. The ordering then computes `100 - (100 - b)` and sorts the partitions the wrong way. The global sort is removed, and the rows come back in reverse order on both this PR and its base commit:
   
   ```scala
   // `ident` is identity-partitioned on `id` and holds 94..100, and `plain(b)` holds 0..6.
   withSQLConf(
       SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
       SQLConf.V2_BUCKETING_SORTING_ENABLED.key -> "true") {
     val df = sql(
       """SELECT p.b FROM testcat.ns.ident i JOIN testcat.ns.plain p ON i.id = 100 - p.b
         |ORDER BY 100 - p.b""".stripMargin)
     // Returns 0, 1, ..., 6 instead of 6, 5, ..., 0.
     assert(df.collect().map(_.getLong(0)).toSeq == (0 to 6).reverse.map(_.toLong))
   }
   ```
   
   This isn't from this PR either. But it is one more consumer that relies on the argument being the column itself, like the one this paragraph describes, so it may be worth covering here or in a separate JIRA.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -65,6 +65,16 @@ case class TransformExpression(
   lazy val functionId: TransformFunctionId =
     TransformFunctionId(function.canonicalName(), numBucketsOpt)
 
+  /**
+   * Whether every argument is a bare column, an [[Attribute]]. See [[isSameFunction]] for why only
+   * such a transform can be compared with another one. A literal argument is a parameter of the
+   * transform rather than a column, so it does not count.
+   */
+  private[sql] lazy val argumentsAreAttributes: Boolean = children.forall {
+    case _: Literal => true
+    case c => c.isInstanceOf[Attribute]

Review Comment:
   **This also refuses an implicit widening `Cast` on the join key.** When `t1.id` is `BIGINT` and `p.b` is `INT`, type coercion casts only the `INT` side, so the first join shuffles `p` onto `bucket(4, cast(b as bigint))`. A second join `p.b = t3.x`, with `t3` bucketed on an `INT` column `x`, was paired as it stood before this PR. For a connector whose bucket function has one canonical name for `INT` and `BIGINT`, that was a correct plan, and with this PR it costs one more shuffle of the first join's output. The PR description doesn't list this shape among the costs. Connectors with type-specific canonical names are not affected, since their functions never compared equal. If this matters, a widening cast of an attribute that `Cast.canUpCast` allows could count as the column.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala:
##########
@@ -1520,6 +1520,113 @@ class KeyGroupedPartitioningSuite
     }
   }
 
+  // Each key is a function of `b` other than `b` itself. A check on the leaves of the key would
+  // reject `b + 1` for its literal, but not `-b`, so both are tested.
+  Seq("p.b + 1" -> ((b: Long) => b + 1), "-p.b" -> ((b: Long) => -b)).foreach {
+    case (key, keyOf) =>
+      // `plain` holds `b` in 0..7, and `keys`, bucketed on `id`, holds the key of each `b`.
+      def createKeyTables(): Unit = {
+        createTable("plain", Array(Column.create("b", LongType)), Array.empty)
+        sql("INSERT INTO testcat.ns.plain VALUES " + (0 until 8).map(b => s"($b)").mkString(", "))
+        createTable("keys", Array(Column.create("id", LongType)), Array(bucket(4, "id")))
+        sql("INSERT INTO testcat.ns.keys VALUES " +
+          (0 until 8).map(b => s"(${keyOf(b)})").mkString(", "))
+      }
+
+      test("SPARK-59887: a side shuffled onto a transform of an expression is not paired as it " +
+          s"is ($key)") {
+        createKeyTables()
+        Seq(4, 8).foreach(n => createBucketedIdTable(s"bucket$n", n, numIds = 8))
+
+        // The first join shuffles `plain` onto the bucket of its key, which is a function of `b`,
+        // but not the same function of it as the third table's `bucket(n, id)` is of `id`. The
+        // second join clusters `plain` on `b`, so pairing the two as they stand, or after reducing
+        // `bucket(8, id)` onto 4 buckets, puts a row with `b = id` on a different partition on
+        // each side.
+        Seq(4 -> "false", 8 -> "true").foreach { case (third, allowCompatibleTransforms) =>
+          withSQLConf(
+            SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+            SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> allowCompatibleTransforms) {
+            val df = sql(
+              s"""SELECT k.id, p.b, t.id FROM testcat.ns.keys k
+                 |JOIN testcat.ns.plain p ON k.id = $key
+                 |JOIN testcat.ns.bucket$third t ON p.b = t.id""".stripMargin)
+            checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, b.toLong)))
+            // One shuffle per join: `plain` for the first, the first join's output for the
+            // second, and none for the third table. The second join does not shuffle onto the
+            // bucket of the key, since that would move both of its sides.
+            assert(collectShuffles(stripAQEPlan(df.queryExecution.executedPlan)).size == 2)
+          }
+        }
+      }
+
+      test(s"SPARK-59887: a side is not shuffled onto a transform of an expression ($key)") {
+        createKeyTables()
+        createTable("xy", Array(Column.create("x", LongType), Column.create("y", LongType)),
+          Array.empty)
+        sql("INSERT INTO testcat.ns.xy VALUES " +
+          (0 until 8).map(b => s"(${keyOf(b)}, $b)").mkString(", "))
+
+        // The first join shuffles `plain` onto the bucket of its key, so its output offers that
+        // layout next to `bucket(4, id)`. The second join must not shuffle `xy` onto the first
+        // one. That builds `bucket(4, y)` for `xy`, not the bucket of the same function of `y`,
+        // so a row with `b = y` lands in a different bucket on each side.
+        withSQLConf(SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
+          val df = sql(
+            s"""SELECT k.id, p.b, q.x FROM testcat.ns.plain p

Review Comment:
   **This test fails on the base commit only because `plain` is the left side of the first join.** Both members of the first join's output have 4 partitions, and `pickCoPartitionTarget` breaks the tie with `maxByOption`, which returns the first member, i.e. `plain`'s. With the keyed table on the left, the base commit already picks `bucket(4, id)` and returns the right answer. I checked the `p.b + 1` case on the base with `bucket4 b4 JOIN plain p ON b4.id = p.b + 1 JOIN xy q ON b4.id = q.x AND p.b = q.y`: `xy` is shuffled onto `bucket(4, x)`, and the answer is correct. Since this test checks only the answer, a change in the member order or in how members are ranked would let it pass even with both clauses reverted. How about asserting the plan too, e.g. that `xy` is not laid out on a bucket of `y`, or the number of shuffles?



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/TransformExpressionSuite.scala:
##########
@@ -116,4 +135,32 @@ class TransformExpressionSuite extends SparkFunSuite {
     // `GroupPartitionsExec` apply to a reported partitioning.
     assert(left.hasSameReducedKeys(left.withReference(b)))
   }
+
+  test("SPARK-59887: a transform of an expression is not the same as any transform") {
+    // A join pairs its two sides up by the column each partition expression references, so over
+    // `a = b` it would pair `bucket(4, a + 1)` with `bucket(4, b)`. A row with `a = b` sits in a
+    // different bucket on each side.
+    val fn = new NamedFunction("test.bucket")
+    val overExpression = bucket(fn, Add(a, Literal(1)))
+    assert(bucket(fn, a).isSameFunction(bucket(fn, b)), "two columns are the same function")
+    assert(!overExpression.isSameFunction(bucket(fn, b)))
+    assert(!bucket(fn, b).isSameFunction(overExpression))
+    assert(!overExpression.isSameFunction(overExpression), "not even as itself")
+
+    // A struct field is not the column the pairing uses either: that is the struct.

Review Comment:
   **`reducers` and `isCompatible` are not tested for a struct-field argument.** The PR description says this test covers `isSameFunction`, `reducers` in both directions and `isCompatible` for transforms over `a + 1` and over a struct field. For the struct field, only `isSameFunction` is checked, while `reducers` and `isCompatible` are checked with `Add(a, Literal(1))` only. Both struct-field tests in `KeyGroupedPartitioningSuite` run without `allowCompatibleTransforms` as well. So a regression that lets `bucket(8, s.a)` reduce onto `bucket(4, t.b)` passes every test. How about the same `reducers` and `isCompatible` assertions for a struct field, e.g. with `bucket(DivisibleBucketFunction, GetStructField(s, 0), 8)`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -117,7 +127,10 @@ case class TransformExpression(
    */
   def reducers(other: TransformExpression): Option[Reducer[_, _]] = {
     (function, other.function) match {
-      case(e1: ReducibleFunction[_, _], e2: ReducibleFunction[_, _]) =>
+      // A reduce pairs the two sides up the same way `isSameFunction` does, so it needs the same
+      // arguments.
+      case (e1: ReducibleFunction[_, _], e2: ReducibleFunction[_, _])
+          if argumentsAreAttributes && other.argumentsAreAttributes =>

Review Comment:
   **Could the pairing rule live in `KeyedShuffleSpec.isExpressionCompatible` instead?** The rule exists because `KeyedShuffleSpec.keyPositions` pairs the two sides by reference. But it is written into the general `TransformExpression` API twice, in `isSameFunction` and here, and `isCompatible` is rewritten to inherit it. As a result, a transform of an expression is not the same function as itself, although the name of `isSameFunction` and the `TransformFunctionId` doc promise function identity. A single guard in the `(TransformExpression, TransformExpression)` case of `KeyedShuffleSpec.isExpressionCompatible` gives the same results on every production path:
   - In production code, `isSameFunction` and `isCompatible` are called only from `isExpressionCompatible`.
   - `reducersBothWays`, the only other caller of `reducers`, is called only for a pair that `areKeysCompatible(allowReduce = true)` admitted, at `EnsureRequirements` L705 and L764.
   
   It would also sit next to the existing rule there that admits only leaf expressions, and it is just as small to backport. I understand that a check here also protects future callers, so please take this as a suggestion.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -92,19 +113,8 @@ case class TransformExpression(
    * @param other the transform expression to compare to
    * @return true if compatible, false if not
    */
-  def isCompatible(other: TransformExpression): Boolean = {
-    if (isSameFunction(other)) {
-      true
-    } else {
-      (function, other.function) match {
-        case (f: ReducibleFunction[_, _], o: ReducibleFunction[_, _]) =>
-          val thisReducer = reducer(f, numBucketsOpt, o, other.numBucketsOpt)
-          val otherReducer = reducer(o, other.numBucketsOpt, f, numBucketsOpt)
-          thisReducer.isDefined || otherReducer.isDefined
-        case _ => false
-      }
-    }
-  }
+  def isCompatible(other: TransformExpression): Boolean =
+    isSameFunction(other) || reducers(other).isDefined || other.reducers(this).isDefined

Review Comment:
   **The Scaladocs still describe the old contract.** The `isCompatible` Scaladoc right above says it is true if both functions are `ReducibleFunction`s and a `Reducer` exists, and the `reducers` Scaladoc says a reducer exists whenever one function is reducible on the other. The new test contradicts both: `bucket8.reducers(bucket4)` is defined, but `bucket8OfExpression.isCompatible(bucket4)` is false for the same functions. In addition, `ShuffleSpec.isCompatibleWith` still says "Spark assumes this to be reflexive, symmetric and transitive". It already had an exception in `RangeShuffleSpec`, and now a spec over `bucket(4, b + 1)` is incompatible with itself too. `pickCoPartitionTarget` avoids such a winner only because of the new `canCreatePartitioning` clause. Could you mention the argument condition in these docs?



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/TransformExpressionSuite.scala:
##########
@@ -41,6 +41,24 @@ class TransformExpressionSuite extends SparkFunSuite {
     override def hashCode(): Int = canonicalName().hashCode
   }
 
+  /** Reduces a bucket count onto any smaller count that divides it. */
+  private object DivisibleBucketFunction

Review Comment:
   nit: `ShuffleSpecSuite.FakeBucket` already reduces a bucket count onto a divisor with `% otherNumBuckets`, and its doc says it is local only because catalyst has no `BucketFunction`. Moving it next to `FlipLowBitFunction` in `sql/catalyst/src/test/scala/org/apache/spark/sql/connector/catalog/functions/` would let both suites share it. Also, only the positive branch of this `reducer` runs, since the new guard in `reducers` refuses the other cases before the function is called.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2199,8 +2203,14 @@ case class KeyedShuffleSpec(
       // cannot rewrite it. This also keeps the unprojected spec returned by `createShuffleSpec`
       // for a marked narrowing projection from being chosen as the best spec.
       keyPositions.forall(_.nonEmpty) &&
-      partitioning.expressions.forall { e =>
-        e.isInstanceOf[AttributeReference] || e.isInstanceOf[TransformExpression]
+      partitioning.expressions.forall {
+        case _: AttributeReference => true
+        // `createPartitioning` replaces a transform's argument with the other child's cluster key,

Review Comment:
   **The underlying issue is that `createPartitioning` replaces the whole argument (L2225).** This clause refuses a template because the rewrite drops whatever surrounds the key. Substituting only the reference that `keyPositions` mapped, as `withReference` and the `IdentityReducer` case already do, would be sound for a single-reference argument. `bucket(4, b + 1)` would become `bucket(4, y + 1)` for `xy`, and `bucket(4, s.a)` would become `bucket(4, t.a)`, which also removes the `ClassCastException`. It is not a drop-in replacement for this clause, though:
   - To get the conceded shuffles back, `isSameFunction` would also have to compare the shapes and stay reflexive, since `pickCoPartitionTarget` keeps the winning child in place only when its member pairs with itself.
   - The shuffled side would evaluate `y + 1` on rows where the query never computes it, and that can overflow under ANSI mode.
   
   So I'm raising it as input for SPARK-59900 rather than as a change to this PR.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala:
##########
@@ -1520,6 +1520,113 @@ class KeyGroupedPartitioningSuite
     }
   }
 
+  // Each key is a function of `b` other than `b` itself. A check on the leaves of the key would
+  // reject `b + 1` for its literal, but not `-b`, so both are tested.
+  Seq("p.b + 1" -> ((b: Long) => b + 1), "-p.b" -> ((b: Long) => -b)).foreach {
+    case (key, keyOf) =>
+      // `plain` holds `b` in 0..7, and `keys`, bucketed on `id`, holds the key of each `b`.
+      def createKeyTables(): Unit = {
+        createTable("plain", Array(Column.create("b", LongType)), Array.empty)
+        sql("INSERT INTO testcat.ns.plain VALUES " + (0 until 8).map(b => s"($b)").mkString(", "))
+        createTable("keys", Array(Column.create("id", LongType)), Array(bucket(4, "id")))
+        sql("INSERT INTO testcat.ns.keys VALUES " +
+          (0 until 8).map(b => s"(${keyOf(b)})").mkString(", "))
+      }
+
+      test("SPARK-59887: a side shuffled onto a transform of an expression is not paired as it " +
+          s"is ($key)") {
+        createKeyTables()
+        Seq(4, 8).foreach(n => createBucketedIdTable(s"bucket$n", n, numIds = 8))
+
+        // The first join shuffles `plain` onto the bucket of its key, which is a function of `b`,
+        // but not the same function of it as the third table's `bucket(n, id)` is of `id`. The
+        // second join clusters `plain` on `b`, so pairing the two as they stand, or after reducing
+        // `bucket(8, id)` onto 4 buckets, puts a row with `b = id` on a different partition on
+        // each side.
+        Seq(4 -> "false", 8 -> "true").foreach { case (third, allowCompatibleTransforms) =>
+          withSQLConf(
+            SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+            SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> allowCompatibleTransforms) {
+            val df = sql(
+              s"""SELECT k.id, p.b, t.id FROM testcat.ns.keys k
+                 |JOIN testcat.ns.plain p ON k.id = $key
+                 |JOIN testcat.ns.bucket$third t ON p.b = t.id""".stripMargin)
+            checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, b.toLong)))
+            // One shuffle per join: `plain` for the first, the first join's output for the
+            // second, and none for the third table. The second join does not shuffle onto the
+            // bucket of the key, since that would move both of its sides.
+            assert(collectShuffles(stripAQEPlan(df.queryExecution.executedPlan)).size == 2)
+          }
+        }
+      }
+
+      test(s"SPARK-59887: a side is not shuffled onto a transform of an expression ($key)") {
+        createKeyTables()
+        createTable("xy", Array(Column.create("x", LongType), Column.create("y", LongType)),
+          Array.empty)
+        sql("INSERT INTO testcat.ns.xy VALUES " +
+          (0 until 8).map(b => s"(${keyOf(b)}, $b)").mkString(", "))
+
+        // The first join shuffles `plain` onto the bucket of its key, so its output offers that
+        // layout next to `bucket(4, id)`. The second join must not shuffle `xy` onto the first
+        // one. That builds `bucket(4, y)` for `xy`, not the bucket of the same function of `y`,
+        // so a row with `b = y` lands in a different bucket on each side.
+        withSQLConf(SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
+          val df = sql(
+            s"""SELECT k.id, p.b, q.x FROM testcat.ns.plain p
+               |JOIN testcat.ns.keys k ON $key = k.id
+               |JOIN testcat.ns.xy q ON k.id = q.x AND p.b = q.y""".stripMargin)
+          checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, keyOf(b))))
+        }
+      }
+  }
+
+  test("SPARK-59887: a side shuffled onto a transform of a struct field is not paired as it is") {
+    createBucketedIdTable("bucket4", 4, numIds = 8)
+    val structColumn = Array(
+      Column.create("s", new StructType().add("a", LongType).add("b", LongType)))
+    Seq("ps", "qs").foreach { name =>
+      createTable(name, structColumn, Array.empty)
+      sql(s"INSERT INTO testcat.ns.$name VALUES " +
+        (0 until 8).map(i => s"(named_struct('a', ${i}L, 'b', ${7 - i}L))").mkString(", "))
+    }
+
+    // Each side is shuffled onto the bucket of a different field of `s`, `bucket(4, s.a)` and
+    // `bucket(4, s.b)`. Both are functions of `s`, but not the same one, so the join on `s` must
+    // not pair them as they stand: a row lands in bucket `a % 4` on one side and `b % 4` on the
+    // other.
+    withSQLConf(SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
+      val df = sql(
+        """SELECT l.id, r.id FROM
+          |  (SELECT x.id, ps.s FROM testcat.ns.bucket4 x JOIN testcat.ns.ps ps ON x.id = ps.s.a) l
+          |  JOIN
+          |  (SELECT y.id, qs.s FROM testcat.ns.bucket4 y JOIN testcat.ns.qs qs ON y.id = qs.s.b) r
+          |  ON l.s = r.s""".stripMargin)
+      checkAnswer(df, (0 until 8).map(i => Row(i.toLong, (7 - i).toLong)))
+    }
+  }
+
+  test("SPARK-59887: a side is not shuffled onto a transform of a struct field") {

Review Comment:
   nit: This test repeats the setup of the previous one (`bucket4` with 8 ids and the same `named_struct` rows) and its `l` subquery. Per the ablation in the PR description, it fails only when the `canCreatePartitioning` clause is removed, and the previous test fails then too. If you want to keep this `ClassCastException` shape, it could be a second query in the previous test, `SELECT l.id FROM <the same l> JOIN testcat.ns.qs r ON l.s = r.s`, like `createKeyTables()` shares the setup of the expression tests. That saves the `rs` table and about 20 lines.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -65,6 +65,16 @@ case class TransformExpression(
   lazy val functionId: TransformFunctionId =
     TransformFunctionId(function.canonicalName(), numBucketsOpt)
 
+  /**
+   * Whether every argument is a bare column, an [[Attribute]]. See [[isSameFunction]] for why only
+   * such a transform can be compared with another one. A literal argument is a parameter of the
+   * transform rather than a column, so it does not count.
+   */
+  private[sql] lazy val argumentsAreAttributes: Boolean = children.forall {
+    case _: Literal => true

Review Comment:
   **The `Literal` case is unreachable, and its rationale doesn't hold for either consumer.** No transform with a literal child reaches `isSameFunction`, `reducers` or `canCreatePartitioning`. A scan's transform has to pass `KeyedPartitioning.supportsExpressions`, which requires a single reference child, and `createPartitioning` keeps the arity and fills the argument with a join key. If one did arrive, e.g. `truncate(a, 2)`, both consumers would get it wrong. `functionId` ignores the literal's value, so `truncate(a, 2)` would be the same function as `truncate(b, 5)`. And `createPartitioning` would overwrite the literal and build `truncate(x, x)`, which is the hazard the new comment in `canCreatePartitioning` describes. How about `children.forall(_.isInstanceOf[Attribute])`, without the sentence about literals? It is equivalent today, and it fails safe.



-- 
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-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on code in PR #59165:
URL: https://github.com/apache/spark/pull/59165#discussion_r4152407781


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -77,10 +87,21 @@ case class TransformExpression(
    * It compares the transforms only. A caller that compares partition keys has to consult
    * `reducedWith` as well, since a reduced key space is not the one its transform names.
    *
+   * Only a transform whose arguments are all bare columns can be the same as another. The
+   * comparison ignores which column an argument is, and `KeyedShuffleSpec.keyPositions` pairs the
+   * two sides up by the column each expression references. That pairing is sound only when the
+   * argument is the column itself. `KeyedShuffleSpec.createPartitioning` builds a transform over
+   * the other side's join key, which can be an expression or a struct field. `bucket(4, b + 1)` is
+   * a function of `b`, but not the same function of it as `bucket(4, x)` is of `x`, so a join on
+   * `b = x` must not pair the two, and neither may a join on `s = t` pair `bucket(4, s.a)` with
+   * `bucket(4, t.b)`. Such a transform is not the same as any transform, itself included, which
+   * costs a shuffle rather than a match.
+   *
    * @param other the transform expression to compare to
    * @return true if this and `other` has the same semantics w.r.t to transform, false otherwise.
    */
-  def isSameFunction(other: TransformExpression): Boolean = functionId == other.functionId
+  def isSameFunction(other: TransformExpression): Boolean =
+    argumentsAreAttributes && other.argumentsAreAttributes && functionId == other.functionId

Review Comment:
   Thanks, confirmed, and fixed in [69f16ab](https://github.com/apache/spark/pull/59165/commits/69f16abd834a271f68e04905d5391b887fcb4a49) the way you suggest. `GroupPartitionsExec` now rebuilds `reduced` over the member's own argument, the child of a transform or the member itself. So a `bucket(4, b + 1)` member becomes `bucket(2, b + 1)`, which the guard refuses. `reduced`'s own argument is always a bare column now, since the guard also covers the identity arm ([thread](https://github.com/apache/spark/pull/59165#discussion_r4148432898)).
   
   "SPARK-59887: a reduce keeps what each member's keys are computed from" runs your four shapes. It returns 0 of 7 rows without the change.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2199,8 +2203,14 @@ case class KeyedShuffleSpec(
       // cannot rewrite it. This also keeps the unprojected spec returned by `createShuffleSpec`
       // for a marked narrowing projection from being chosen as the best spec.
       keyPositions.forall(_.nonEmpty) &&

Review Comment:
   Fixed in [69f16ab](https://github.com/apache/spark/pull/59165/commits/69f16abd834a271f68e04905d5391b887fcb4a49), as SPARK-59901, which I had filed for this and have now added to the title. `keyPositions` maps an expression with more than one reference to no position instead of asserting. `canCreatePartitioning` and `areKeysCompatible` both turn an empty position away, so a spec over `b + c` pairs with nothing and is no layout to shuffle onto. Both of your queries are in "SPARK-59901: a join key over two columns is not paired through one of them".
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -1943,6 +1943,10 @@ case class KeyedShuffleSpec(
    *
    * The assertion is what makes the reference reading sound. With one reference per expression,
    * "some reference is a cluster key" and "every reference is" are the same statement.
+   *
+   * This says which cluster key an expression is a function of, not which function it is:
+   * `bucket(4, b + 1)` maps to `b` just as `bucket(4, b)` does. Telling those two apart is

Review Comment:
   Confirmed. It is a separate consumer, so I filed SPARK-59905 for it rather than growing this PR. The same binding also fails planning for `ORDER BY p.b + p.c` over the two-column key, with an `ArrayIndexOutOfBoundsException`, so I added that shape to the ticket. The `EnsureRequirements` comment that claimed one attribute per partition expression for this binding now points there.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2199,8 +2203,14 @@ case class KeyedShuffleSpec(
       // cannot rewrite it. This also keeps the unprojected spec returned by `createShuffleSpec`
       // for a marked narrowing projection from being chosen as the best spec.
       keyPositions.forall(_.nonEmpty) &&
-      partitioning.expressions.forall { e =>
-        e.isInstanceOf[AttributeReference] || e.isInstanceOf[TransformExpression]
+      partitioning.expressions.forall {
+        case _: AttributeReference => true
+        // `createPartitioning` replaces a transform's argument with the other child's cluster key,
+        // which drops whatever surrounds the key, e.g. the `+ 1` of `bucket(4, b + 1)` or the `.a`
+        // of `bucket(4, s.a)`. Such a spec's own child would then be laid out differently from the
+        // children shuffled onto it.
+        case t: TransformExpression => t.argumentsAreAttributes

Review Comment:
   Thanks, done in [69f16ab](https://github.com/apache/spark/pull/59165/commits/69f16abd834a271f68e04905d5391b887fcb4a49). `ShuffleSpecCollection.canCreatePartitioning` is now an `exists`, and `pickCoPartitionTarget` offers only the winner's members that can serve. `PartitioningCollection.createShuffleSpec` admits only members that could satisfy the distribution, so a collection without a keyed member hardly ever mixes the two answers. The planner, join, bucketed read, AQE and plan stability suites pass unchanged. Your two shapes and the `xy` one take 2 shuffles again, and the description no longer lists them as costs.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -65,6 +65,16 @@ case class TransformExpression(
   lazy val functionId: TransformFunctionId =
     TransformFunctionId(function.canonicalName(), numBucketsOpt)
 
+  /**
+   * Whether every argument is a bare column, an [[Attribute]]. See [[isSameFunction]] for why only
+   * such a transform can be compared with another one. A literal argument is a parameter of the
+   * transform rather than a column, so it does not count.
+   */
+  private[sql] lazy val argumentsAreAttributes: Boolean = children.forall {
+    case _: Literal => true
+    case c => c.isInstanceOf[Attribute]

Review Comment:
   Right. I added it to the costs in the description. I'd rather not treat an up-cast as the column in a fix meant for the maintenance branches. That leans on each connector's canonical name meaning the same across input types.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala:
##########
@@ -1520,6 +1520,113 @@ class KeyGroupedPartitioningSuite
     }
   }
 
+  // Each key is a function of `b` other than `b` itself. A check on the leaves of the key would
+  // reject `b + 1` for its literal, but not `-b`, so both are tested.
+  Seq("p.b + 1" -> ((b: Long) => b + 1), "-p.b" -> ((b: Long) => -b)).foreach {
+    case (key, keyOf) =>
+      // `plain` holds `b` in 0..7, and `keys`, bucketed on `id`, holds the key of each `b`.
+      def createKeyTables(): Unit = {
+        createTable("plain", Array(Column.create("b", LongType)), Array.empty)
+        sql("INSERT INTO testcat.ns.plain VALUES " + (0 until 8).map(b => s"($b)").mkString(", "))
+        createTable("keys", Array(Column.create("id", LongType)), Array(bucket(4, "id")))
+        sql("INSERT INTO testcat.ns.keys VALUES " +
+          (0 until 8).map(b => s"(${keyOf(b)})").mkString(", "))
+      }
+
+      test("SPARK-59887: a side shuffled onto a transform of an expression is not paired as it " +
+          s"is ($key)") {
+        createKeyTables()
+        Seq(4, 8).foreach(n => createBucketedIdTable(s"bucket$n", n, numIds = 8))
+
+        // The first join shuffles `plain` onto the bucket of its key, which is a function of `b`,
+        // but not the same function of it as the third table's `bucket(n, id)` is of `id`. The
+        // second join clusters `plain` on `b`, so pairing the two as they stand, or after reducing
+        // `bucket(8, id)` onto 4 buckets, puts a row with `b = id` on a different partition on
+        // each side.
+        Seq(4 -> "false", 8 -> "true").foreach { case (third, allowCompatibleTransforms) =>
+          withSQLConf(
+            SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+            SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> allowCompatibleTransforms) {
+            val df = sql(
+              s"""SELECT k.id, p.b, t.id FROM testcat.ns.keys k
+                 |JOIN testcat.ns.plain p ON k.id = $key
+                 |JOIN testcat.ns.bucket$third t ON p.b = t.id""".stripMargin)
+            checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, b.toLong)))
+            // One shuffle per join: `plain` for the first, the first join's output for the
+            // second, and none for the third table. The second join does not shuffle onto the
+            // bucket of the key, since that would move both of its sides.
+            assert(collectShuffles(stripAQEPlan(df.queryExecution.executedPlan)).size == 2)
+          }
+        }
+      }
+
+      test(s"SPARK-59887: a side is not shuffled onto a transform of an expression ($key)") {
+        createKeyTables()
+        createTable("xy", Array(Column.create("x", LongType), Column.create("y", LongType)),
+          Array.empty)
+        sql("INSERT INTO testcat.ns.xy VALUES " +
+          (0 until 8).map(b => s"(${keyOf(b)}, $b)").mkString(", "))
+
+        // The first join shuffles `plain` onto the bucket of its key, so its output offers that
+        // layout next to `bucket(4, id)`. The second join must not shuffle `xy` onto the first
+        // one. That builds `bucket(4, y)` for `xy`, not the bucket of the same function of `y`,
+        // so a row with `b = y` lands in a different bucket on each side.
+        withSQLConf(SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
+          val df = sql(
+            s"""SELECT k.id, p.b, q.x FROM testcat.ns.plain p

Review Comment:
   Good point, done in [69f16ab](https://github.com/apache/spark/pull/59165/commits/69f16abd834a271f68e04905d5391b887fcb4a49). The test now runs both join orders, and it asserts 2 shuffles with none keyed on `y`.
   



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/TransformExpressionSuite.scala:
##########
@@ -116,4 +135,32 @@ class TransformExpressionSuite extends SparkFunSuite {
     // `GroupPartitionsExec` apply to a reported partitioning.
     assert(left.hasSameReducedKeys(left.withReference(b)))
   }
+
+  test("SPARK-59887: a transform of an expression is not the same as any transform") {
+    // A join pairs its two sides up by the column each partition expression references, so over
+    // `a = b` it would pair `bucket(4, a + 1)` with `bucket(4, b)`. A row with `a = b` sits in a
+    // different bucket on each side.
+    val fn = new NamedFunction("test.bucket")
+    val overExpression = bucket(fn, Add(a, Literal(1)))
+    assert(bucket(fn, a).isSameFunction(bucket(fn, b)), "two columns are the same function")
+    assert(!overExpression.isSameFunction(bucket(fn, b)))
+    assert(!bucket(fn, b).isSameFunction(overExpression))
+    assert(!overExpression.isSameFunction(overExpression), "not even as itself")
+
+    // A struct field is not the column the pairing uses either: that is the struct.

Review Comment:
   Added in [69f16ab](https://github.com/apache/spark/pull/59165/commits/69f16abd834a271f68e04905d5391b887fcb4a49). The unit test moved to `ShuffleSpecSuite` together with the guard, and it now runs every assertion, the reduce in both directions included, for the struct field as well.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -117,7 +127,10 @@ case class TransformExpression(
    */
   def reducers(other: TransformExpression): Option[Reducer[_, _]] = {
     (function, other.function) match {
-      case(e1: ReducibleFunction[_, _], e2: ReducibleFunction[_, _]) =>
+      // A reduce pairs the two sides up the same way `isSameFunction` does, so it needs the same
+      // arguments.
+      case (e1: ReducibleFunction[_, _], e2: ReducibleFunction[_, _])
+          if argumentsAreAttributes && other.argumentsAreAttributes =>

Review Comment:
   Agreed, moved in [69f16ab](https://github.com/apache/spark/pull/59165/commits/69f16abd834a271f68e04905d5391b887fcb4a49). `TransformExpression` is back to master. The guard is `KeyedShuffleSpec.argumentsAreColumns`, asked at the entry of `isExpressionCompatible` and by `canCreatePartitioning`.
   
   At the entry it also covers the identity arm. That arm used to reduce an identity side onto `bucket(4, b + 1)` by evaluating `bucket(4, id + 1)` on the identity side's partition keys while planning. Under ANSI, a key of `Long.MaxValue` then fails the query with `ARITHMETIC_OVERFLOW`, although the query never computes `id + 1`. "SPARK-59887: an identity side is not reduced onto a transform of an expression" covers it.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2199,8 +2203,14 @@ case class KeyedShuffleSpec(
       // cannot rewrite it. This also keeps the unprojected spec returned by `createShuffleSpec`
       // for a marked narrowing projection from being chosen as the best spec.
       keyPositions.forall(_.nonEmpty) &&
-      partitioning.expressions.forall { e =>
-        e.isInstanceOf[AttributeReference] || e.isInstanceOf[TransformExpression]
+      partitioning.expressions.forall {
+        case _: AttributeReference => true
+        // `createPartitioning` replaces a transform's argument with the other child's cluster key,

Review Comment:
   Thanks, this is very useful for SPARK-59900, the ANSI point especially. Substituting the reference makes the shuffled side evaluate `y + 1` on rows where the query never computes it.
   



-- 
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-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on PR #59165:
URL: https://github.com/apache/spark/pull/59165#issuecomment-5970562199

   Thank you @dongjoon-hyun for the review and approval, but let me investigate one more corner case before merging.


-- 
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-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "dongjoon-hyun (via GitHub)" <gi...@apache.org>.
dongjoon-hyun commented on PR #59165:
URL: https://github.com/apache/spark/pull/59165#issuecomment-5997206842

   Sounds good to me, @peter-toth .


-- 
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-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth closed pull request #59165: [SPARK-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column
URL: https://github.com/apache/spark/pull/59165


-- 
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-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on PR #59165:
URL: https://github.com/apache/spark/pull/59165#issuecomment-5937582338

   @dongjoon-hyun, your broadcast join point on #59189 ([comment](https://github.com/apache/spark/pull/59189#discussion_r4158266417)) applies here too. `BroadcastHashJoinExec.expandOutputPartitioning` reports `bucket(4, id)` as `bucket(4, p.b + 1)` as well, so this PR's wrong result does not need `spark.sql.sources.v2.bucketing.shuffle.enabled`. With every conf at its default, `SELECT /*+ BROADCAST(p) */ ... FROM t1 JOIN plain p ON t1.id = p.b + 1 JOIN t3 ON p.b = t3.x` returns 0 of 7 rows on master.
   
   This PR already returns all 7 rows, since the guard does not depend on where the layout came from. [5375cc3](https://github.com/apache/spark/pull/59165/commits/5375cc3ca7bb8469c45c686ddfe3189eb6a250d3) adds a test for it, and I updated the description.
   


-- 
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-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "dongjoon-hyun (via GitHub)" <gi...@apache.org>.
dongjoon-hyun commented on code in PR #59165:
URL: https://github.com/apache/spark/pull/59165#discussion_r4159568724


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala:
##########
@@ -1121,8 +1125,8 @@ case class EnsureRequirements(
       // the skew of joining on keys that are coarser than the join keys. Key order and duplicated
       // cluster keys don't matter.
       def allClusterKeysCovered: Boolean =
-        // The single-column invariant in KeyedPartitioning.supportsExpressions guarantees one
-        // attribute per partition expression.
+        // Every column a partition expression references counts as covered. A scan reports one

Review Comment:
   **A member over two columns passes this check, and `KeyedPartitioning.createShuffleSpec` then projects it away.** This counts every column that `p.b + p.c` references as covered, but `keyPositions` now maps `p.b + p.c` to no position (partitioning.scala:1964-1968). So under `spark.sql.sources.v2.bucketing.allowKeysSubsetOfPartitionKeys.enabled`, `createShuffleSpec` drops that position (partitioning.scala:1015). For instance, take two sides that each report `[p.b + p.c, p.d]`, e.g. the output of a broadcast join `ON i.x = p.b + p.c AND i.d = p.d` over a table partitioned by `identity(x), identity(d)`. A join of the two on `(b, c, d)` passes this check with `{b, c, d}`, but both specs are projected to `[p.d]`, and the storage-partitioned join pairs them on `d` alone. The rows are right, but the join runs on as many partitions as there are distinct values of `d`, which is the skew `spark.sql.requireAllClusterKeysForCoPartition` is there to prevent. On the base the same plan failed th
 e `keyPositions` assertion, so it is a newly reachable plan rather than a regression. Could this count only the columns of expressions with a single reference, or check the projected spec instead?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2061,7 +2074,15 @@ case class KeyedShuffleSpec(
       left: Expression,
       right: Expression,
       allowReduce: Boolean): Boolean = {
-    if (TransformExpression.hasReducedKeys(left) || TransformExpression.hasReducedKeys(right)) {
+    val overExpression = Seq(left, right).exists {

Review Comment:
   **The costs listed in the description now also reach plans that use only default confs, through the broadcast expansion.** The description says an inner broadcast hash join builds such a layout with every conf at its default, but the costs still read as if they need `spark.sql.sources.v2.bucketing.shuffle.enabled`. For example, take `orders` and `returns` bucketed by `bucket(16, cust_id)` on a `BIGINT` column, and an `INT` `customers.id` broadcast into both:
   
   ```sql
   SELECT a.id FROM
     (SELECT c1.id FROM orders o JOIN customers c1 ON o.cust_id = c1.id) a
   JOIN
     (SELECT c2.id FROM returns r JOIN customers c2 ON r.cust_id = c2.id) b
   ON a.id = b.id
   ```
   
   Each broadcast join also reports `bucket(16, cast(cN.id as bigint))`. The base pairs the two as they stand, with no shuffle, and that is correct since both sides have the same shape. With this guard, both fact-sized sides are hash-shuffled, since keyed shuffles are off by default. The `t.id = d.k + 1` shape behaves the same. It is the first cost in the list, but on the maintenance branches it changes plans for users who set nothing. Could the description say that these costs apply with default confs too?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala:
##########
@@ -604,8 +604,15 @@ private[sql] object GroupPartitionsExec {
                   // `reduced` came from the one member `checkKeyGroupCompatible` paired
                   // this side on, which need not be the member being rewritten. The keys are
                   // reduced once, from the shared key rows, so `reduced` describes them
-                  // whichever member this is, and only the key attribute is re-targeted.
-                  reduced.withReference(expr.references.head)
+                  // whichever member this is. Its argument is a bare column, since the pairing
+                  // admits no other. The member's own argument takes its place, since that need
+                  // not be one. A side shuffled onto this layout reports `bucket(8, b + 1)` next
+                  // to `bucket(8, id)`, or `b + 1` next to an identity `id`.
+                  val argument = expr match {

Review Comment:
   **This also fixes a `GROUP BY` or window over a member with two columns, but no test covers that.** The base re-targeted a `p.b + p.c` member at its first reference, `bucket(2, p.b)`, which satisfies `ClusteredDistribution([p.b])`, so a `GROUP BY p.b` or `PARTITION BY p.b` above it skipped its shuffle. With `spark.sql.sources.v2.bucketing.allowCompatibleTransforms.enabled` on, `plain2` holding `(0, 1), (0, 2), (1, 1), (1, 2)`, and the `ident` and `bucket2` tables of the new tests:
   
   ```scala
   sql("""SELECT /*+ BROADCAST(p) */ p.b, max(p.c) FROM testcat.ns.ident i
         |JOIN testcat.ns.plain2 p ON i.id = p.b + p.c
         |JOIN testcat.ns.bucket2 t2 ON i.id = t2.id
         |GROUP BY p.b""".stripMargin)
   ```
   
   The base returns `(0, 2), (1, 1), (0, 1), (1, 2)`, since the rows of `b = 0` sit in two buckets, and this PR returns `(0, 2), (1, 2)`. The aggregate has to keep `p.c`: with `count(*)`, column pruning drops the member before the second join. The reduce test (KeyGroupedPartitioningSuite.scala:1647) covers single-column members under a later join only, and the SPARK-59901 test (KeyGroupedPartitioningSuite.scala:1707) has no reduce. Could one of them add this shape, or its `row_number() OVER (PARTITION BY p.b ORDER BY p.c)` variant?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala:
##########
@@ -367,12 +369,14 @@ case class EnsureRequirements(
     val shouldConsiderMinParallelism = children.zip(specs).forall { case (child, spec) =>
       spec.forall(!_.canCreatePartitioning) || child.isInstanceOf[ShuffleExchangeLike]
     }
-    // Choose all the specs that can be used to shuffle other children
+    // Choose all the specs that can be used to shuffle other children, keeping only the members
+    // that can serve as the layout. Any other member would build a partitioning its own child is
+    // not laid out on.
     val candidateSpecs = children.zip(specs).collect {
       case (child, Some(spec)) if spec.canCreatePartitioning &&
           (!shouldConsiderMinParallelism ||
             child.outputPartitioning.numPartitions >= conf.defaultNumShufflePartitions) =>
-        child -> spec
+        child -> spec.flatten.filter(_.canCreatePartitioning)

Review Comment:
   **This filter is not only defensive: it can change which child the layout comes from.** The description says that removing it changes no test, since the guard already keeps a refused member from pairing with its own side. That holds for the pairing, but the ranking at L391 now takes the max over the serving members only, and with `spark.sql.sources.v2.bucketing.allowKeysSubsetOfPartitionKeys.enabled` the members of one collection can project to different counts. For example, with that conf and `spark.sql.sources.v2.bucketing.shuffle.enabled` on, take `t1` partitioned by `identity(a), identity(c)` with keys `(1, 1), (1, 2), (1, 3), (2, 4), (2, 5)`, and `SELECT /*+ BROADCAST(p) */ * FROM t1 JOIN p ON t1.c = p.y + 1 JOIN q ON t1.a = q.m AND p.y = q.n`, where `q` reports 3 partitions without an exchange. The broadcast join reports `[a, c]` and `[a, y + 1]`. The first projects to `[a]`, 2 partitions, and can serve. The second keeps 5 and cannot. With the filter, `q` wins with 3, as on 
 the base. Without it, `t1` ranks at 5 and wins, and `q` is shuffled onto 2 partitions. Both plans are correct, so only the parallelism differs. Could the description say so, and could a test in EnsureRequirementsSuite pin the ranking?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -1588,15 +1584,21 @@ sealed trait ShuffleSpec {
    * co-partitioned with the `other`, and therefore no shuffle is required when joining the two
    * sides.
    *
-   * Note that Spark assumes this to be reflexive, symmetric and transitive.
+   * Note that Spark assumes this to be reflexive, symmetric and transitive. Some specs are not
+   * reflexive:
+   *  - a [[RangeShuffleSpec]], whose boundaries are sampled;
+   *  - a [[KeyedShuffleSpec]] with a partition expression that is neither a column nor a transform

Review Comment:
   Minor: following up on R1-10, this list reads as complete, but it misses specs over a column, or a transform of a column, whose `keyPositions` entry is empty. `years(ts)` clustered on `years(ts)` maps to nothing, since `keyPositions` looks up `ts` (EnsureRequirementsSuite, "SPARK-59289: a partitioning is never projected onto no position"). So does the unprojected spec of a marked narrowing projection (ShuffleSpecSuite, "createShuffleSpec: a marked narrowing projection yields an unusable spec"). Both fail `left.intersect(right).nonEmpty` in `areKeysCompatible` against themselves, while the last sentence still holds for them. Could the note state the two conditions, a partition expression that maps to no cluster key in `keyPositions`, or one that is neither a column nor a transform of columns, instead of listing shapes?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -1941,8 +1943,16 @@ case class KeyedShuffleSpec(
    * `KeyedPartitioning.positionsCoveringClusterKeys` counts it. See that method for why the two
    * stay apart.
    *
-   * The assertion is what makes the reference reading sound. With one reference per expression,
-   * "some reference is a cluster key" and "every reference is" are the same statement.
+   * Only an expression with a single reference maps to a position. With one reference, "some
+   * reference is a cluster key" and "every reference is" are the same statement, which is what
+   * makes the reference reading sound. A scan reports no other expression

Review Comment:
   Minor: this paragraph names `createPartitioning` as the only producer, and its last sentence holds only in a narrow case. Since 5375cc3, the description also names the broadcast expansion, which builds such an expression with default confs. And `createShuffleSpec` projects the position away only under `spark.sql.sources.v2.bucketing.allowKeysSubsetOfPartitionKeys.enabled`, for an unmarked layout where another position maps. It returns a marked layout unprojected at L1030-L1031, and every `createPartitioning` output is marked (L2270-L2272). It returns the single `bucket(4, b + c)` of this example unprojected too, at L1039-L1040, and the comment at L1036-L1037 still attributes that only to "a clustering that names the partition expression itself". EnsureRequirements.scala:143-145 likewise mentions only "a side shuffled onto another side's layout". Could these comments name both producers, and say when the projection happens?



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala:
##########
@@ -1520,6 +1534,203 @@ class KeyGroupedPartitioningSuite
     }
   }
 
+  // Each key is a function of `b` other than `b` itself. A check on the leaves of the key would
+  // reject `b + 1` for its literal, but not `-b`, so both are tested.
+  Seq("p.b + 1" -> ((b: Long) => b + 1), "-p.b" -> ((b: Long) => -b)).foreach {
+    case (key, keyOf) =>
+      // `plain` holds `b` in 0..7, and `keys`, bucketed on `id`, holds the key of each `b`.
+      def createKeyTables(): Unit = {
+        createTable("plain", Array(Column.create("b", LongType)), Array.empty)
+        sql("INSERT INTO testcat.ns.plain VALUES " + (0 until 8).map(b => s"($b)").mkString(", "))
+        createTable("keys", Array(Column.create("id", LongType)), Array(bucket(4, "id")))
+        sql("INSERT INTO testcat.ns.keys VALUES " +
+          (0 until 8).map(b => s"(${keyOf(b)})").mkString(", "))
+      }
+
+      test("SPARK-59887: a side shuffled onto a transform of an expression is not paired as it " +
+          s"is ($key)") {
+        createKeyTables()
+        Seq(4, 8).foreach(n => createBucketedIdTable(s"bucket$n", n, numIds = 8))
+
+        // The first join shuffles `plain` onto the bucket of its key. That is a function of `b`,
+        // but not the same function of it as the third table's `bucket(n, id)` is of `id`. The
+        // second join clusters `plain` on `b`. Pairing the two there, as they stand or after
+        // reducing `bucket(8, id)` onto 4 buckets, puts a row with `b = id` on a different
+        // partition on each side.
+        Seq(4 -> "false", 8 -> "true").foreach { case (third, allowCompatibleTransforms) =>
+          withSQLConf(
+            SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+            SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> allowCompatibleTransforms) {
+            val df = sql(
+              s"""SELECT k.id, p.b, t.id FROM testcat.ns.keys k
+                 |JOIN testcat.ns.plain p ON k.id = $key
+                 |JOIN testcat.ns.bucket$third t ON p.b = t.id""".stripMargin)
+            checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, b.toLong)))
+            // One shuffle per join: `plain` for the first, the first join's output for the
+            // second, and none for the third table. The second join does not shuffle onto the
+            // bucket of the key, since that would move both of its sides.
+            assert(collectShuffles(stripAQEPlan(df.queryExecution.executedPlan)).size == 2)
+          }
+        }
+      }
+
+      test(s"SPARK-59887: a side is not shuffled onto a transform of an expression ($key)") {
+        createKeyTables()
+        createTable("xy", Array(Column.create("x", LongType), Column.create("y", LongType)),
+          Array.empty)
+        sql("INSERT INTO testcat.ns.xy VALUES " +
+          (0 until 8).map(b => s"(${keyOf(b)}, $b)").mkString(", "))
+
+        // The first join shuffles `plain` onto the bucket of its key, so its output offers that
+        // layout next to `bucket(4, id)`. The second join must not shuffle `xy` onto the first
+        // one. That builds `bucket(4, y)` for `xy`, not the bucket of the same function of `y`. A
+        // row with `b = y` then lands in a different bucket on each side. The join order decides
+        // which of the two layouts comes first, so both orders run.
+        withSQLConf(SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
+          Seq(
+            s"testcat.ns.plain p JOIN testcat.ns.keys k ON $key = k.id",
+            s"testcat.ns.keys k JOIN testcat.ns.plain p ON k.id = $key").foreach { firstJoin =>
+            val df = sql(
+              s"""SELECT k.id, p.b, q.x FROM $firstJoin
+                 |JOIN testcat.ns.xy q ON k.id = q.x AND p.b = q.y""".stripMargin)
+            checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, keyOf(b))))
+            // `xy` is shuffled onto the usable layout, `bucket(4, x)`, and never onto a bucket of
+            // `y`. So `plain` and `xy` are the only sides that move.
+            val shuffles = collectShuffles(stripAQEPlan(df.queryExecution.executedPlan))
+            assert(shuffles.size == 2)
+            assert(!keyedPartitioningsOf(shuffles).exists(_.references.exists(_.name == "y")))
+          }
+        }
+      }
+
+      test("SPARK-59887: a broadcast join's layout over a join key is not paired as it is " +
+          s"($key)") {
+        createKeyTables()
+        createBucketedIdTable("bucket4", 4, numIds = 8)
+
+        // An inner broadcast join reports the streamed side's layout over the build side's join
+        // key too, so the first join also offers the bucket of `plain`'s key. That needs no conf
+        // beyond the defaults. The second join clusters `plain` on `b`, so pairing that layout with
+        // `bucket(4, id)` as it stands puts a row with `b = id` on a different partition on each
+        // side.
+        val df = sql(
+          s"""SELECT /*+ BROADCAST(p) */ k.id, p.b, t.id FROM testcat.ns.keys k
+             |JOIN testcat.ns.plain p ON k.id = $key
+             |JOIN testcat.ns.bucket4 t ON p.b = t.id""".stripMargin)
+        checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, b.toLong)))
+        assert(collect(df.queryExecution.executedPlan) { case j: BroadcastHashJoinExec => j }
+          .nonEmpty, "the first join is a broadcast join")
+      }
+  }
+
+  test("SPARK-59887: a layout over a transform of a struct field is not paired nor shuffled onto") {
+    createBucketedIdTable("bucket4", 4, numIds = 8)
+    createStructTable()
+    // `l` shuffles `ps` onto `bucket(4, s.a)`, and `r` shuffles it onto `bucket(4, s.b)`.
+    val l = "SELECT x.id, ps.s FROM testcat.ns.bucket4 x JOIN testcat.ns.ps ps ON x.id = ps.s.a"
+    val r = "SELECT y.id, qs.s FROM testcat.ns.bucket4 y JOIN testcat.ns.ps qs ON y.id = qs.s.b"
+
+    withSQLConf(SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
+      // Both layouts are functions of `s`, but not the same one, so the join on `s` must not pair
+      // them as they stand. A row lands in bucket `a % 4` on one side and `b % 4` on the other.
+      checkAnswer(
+        sql(s"SELECT l.id, r.id FROM ($l) l JOIN ($r) r ON l.s = r.s"),
+        (0 until 8).map(i => Row(i.toLong, (7 - i).toLong)))
+      // Nor may a join shuffle a plain `ps` onto `l`'s layout. That builds `bucket(4, s)` for it,
+      // which drops the `.a` and hands the whole struct to a bucket function over a long.
+      checkAnswer(
+        sql(s"SELECT l.id FROM ($l) l JOIN testcat.ns.ps r ON l.s = r.s"),
+        (0 until 8).map(i => Row(i.toLong)))
+    }
+  }
+
+  test("SPARK-59887: a reduce keeps what each member's keys are computed from") {
+    Seq(4, 2).foreach(n => createBucketedIdTable(s"bucket$n", n, numIds = 8))
+    createIdentityIdTable()
+    createTable("plain", Array(Column.create("b", LongType)), Array.empty)
+    sql("INSERT INTO testcat.ns.plain VALUES " + (0 until 8).map(b => s"($b)").mkString(", "))
+    createStructTable()
+
+    withSQLConf(
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> "true") {
+      // The first join shuffles `plain` onto `bucket(4, b + 1)`, or onto `b + 1` for the
+      // identity-partitioned `ident`. The second join reduces the first one's output onto
+      // `bucket(2)`, `plain`'s member included. That member is still over `b + 1`. So the third
+      // join, on the bare `b`, must neither pair it with `bucket(2, id)` nor shuffle a plain
+      // side onto it.
+      for {
+        first <- Seq("bucket4", "ident")
+        (third, thirdKey) <- Seq("bucket2" -> "id", "plain" -> "b")
+      } {
+        val df = sql(
+          s"""SELECT f.id, p.b, t2.id, t3.$thirdKey FROM testcat.ns.$first f
+             |JOIN testcat.ns.plain p ON f.id = p.b + 1
+             |JOIN testcat.ns.bucket2 t2 ON f.id = t2.id
+             |JOIN testcat.ns.$third t3 ON p.b = t3.$thirdKey""".stripMargin)
+        checkAnswer(df, (0 until 7).map(b => Row(b + 1L, b.toLong, b + 1L, b.toLong)))
+      }
+
+      // The same for a struct field. `ps`'s member is still over `s.a` after the reduce, so the
+      // third join must not shuffle a plain `ps` onto it, which would build `bucket(2, s)`.
+      val df = sql(
+        """SELECT x.id FROM testcat.ns.bucket4 x
+          |JOIN testcat.ns.ps ps ON x.id = ps.s.a
+          |JOIN testcat.ns.bucket2 t2 ON x.id = t2.id
+          |JOIN testcat.ns.ps r ON ps.s = r.s""".stripMargin)
+      checkAnswer(df, (0 until 8).map(i => Row(i.toLong)))
+    }
+  }
+
+  test("SPARK-59887: an identity side is not reduced onto a transform of an expression") {
+    createBucketedIdTable("bucket4", 4, numIds = 8)
+    createTable("plain", Array(Column.create("b", LongType)), Array.empty)
+    sql("INSERT INTO testcat.ns.plain VALUES " + (0 until 7).map(b => s"($b)").mkString(", "))
+    createIdentityIdTable((0L until 8L) :+ Long.MaxValue)
+
+    // The first join shuffles `plain` onto `bucket(4, b + 1)`. Reducing `ident` onto it would
+    // evaluate `id + 1` on `ident`'s partition keys while planning, and that overflows for
+    // `Long.MaxValue` under ANSI. The query itself never computes it, since no `b` matches that
+    // key.
+    withSQLConf(
+        SQLConf.ANSI_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> "true") {
+      val df = sql(
+        """SELECT k.id, p.b, i.id FROM testcat.ns.bucket4 k
+          |JOIN testcat.ns.plain p ON k.id = p.b + 1

Review Comment:
   **This test would pass on branch-4.2 without the fix.** It is the only end-to-end test of the identity arm, and it runs with `p.b + 1` only. As the description says, branch-4.2 never pairs `p.b + 1`, because its `createKeyedShuffleSpec` compares the leaves of the partition expressions with the clustering and sees the literal. But branch-4.2 has the identity arm too, `IdentityReducer(t.withReference(a))`, so `-p.b` does pair with `ident` there, and the planner evaluates `bucket(4, -id)` on the keys of `ident`. Under ANSI that fails with `ARITHMETIC_OVERFLOW` for a key of `Long.MinValue`, although the query never negates it. The two expression tests above run both keys for the same reason. Could this test run `-p.b` as well, with `Long.MinValue` in `ident`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -1892,8 +1894,8 @@ case class KeyReducer(reducer: Reducer[_, _], reducedExpression: TransformExpres
  * @param transform the partition transform, re-targeted at the identity side's key attribute
  */
 case class IdentityReducer(transform: TransformExpression) extends Reducer[Any, Any] {
-  // `transform` has a single leaf attribute (`KeyedPartitioning.supportsExpressions`), which is
-  // bound to ordinal 0 of the single-value row `reduce` evaluates it against.
+  // `transform` is over a single bare column (`KeyedShuffleSpec.isExpressionCompatible` admits no

Review Comment:
   Nit: this credits `isExpressionCompatible` with the single column, but `argumentsAreColumns` admits any number of columns. The single reference comes from `keyPositions`, as the comment at L2203-L2205 says. Relatedly, step 3.3 of `isCompatibleWith` (L1982-L1985) still says that "the same transform function, or the two sides of one reduce" describe one key space, while the guard now refuses both when an argument is not a column, as ShuffleSpecSuite.scala:807 and ShuffleSpecSuite.scala:815 assert. Could both comments mention the argument condition?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -1951,8 +1961,11 @@ case class KeyedShuffleSpec(
     }
     partitioning.expressions.map { e =>
       val refs = e.references
-      assert(refs.size == 1, s"Expected exactly one child from $e, but found ${refs.size}")
-      distKeyToPos.getOrElse(refs.head.canonicalized, mutable.BitSet.empty)
+      if (refs.size == 1) {
+        distKeyToPos.getOrElse(refs.head.canonicalized, mutable.BitSet.empty)

Review Comment:
   Minor: how about mapping by the argument here instead of by the reference? `createPartitioning` replaces the argument of a transform, and `GroupPartitionsExec` now rebuilds over it (GroupPartitionsExec.scala:611-615), but this maps an expression by its single reference. If it looked up `t.children.head` for a single-child transform, and the expression itself otherwise, every shape the new tests refuse would map to no position: `bucket(4, a + 1)` under `[a]`, `bucket(4, s.x)` under `[s]`, `a + b` under `[a, b]`, and the reduced `bucket(2, p.b + 1)` under `[p.b]`. The overlap test in `areKeysCompatible`, `canCreatePartitioning` and `createPartitioning` would then agree by construction, without `argumentsAreColumns` or the `refs.size == 1` branch. Today three shape checks have to be kept in step by hand, and they already differ: `refs.size == 1` here, the leaf match after `overExpression` in `isExpressionCompatible`, and `AttributeReference` or `argumentsAreColumns` in `canCreatePart
 itioning`. Unlike the SPARK-59900 idea, this evaluates nothing new, so the ANSI concern does not arise. The identity arm at L2207 and L2211 would have to switch to `t.copy(children = Seq(a))` at the same time. Otherwise, with `spark.sql.requireAllClusterKeysForCoPartition` off, a join keyed on `p.b + 1` would give `bucket(4, p.b + 1)` a position, and `withReference` would build `bucket(4, id + 1)`. I understand this may fit SPARK-59900 better, so please take it as input.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala:
##########
@@ -604,8 +604,15 @@ private[sql] object GroupPartitionsExec {
                   // `reduced` came from the one member `checkKeyGroupCompatible` paired
                   // this side on, which need not be the member being rewritten. The keys are
                   // reduced once, from the shared key rows, so `reduced` describes them
-                  // whichever member this is, and only the key attribute is re-targeted.
-                  reduced.withReference(expr.references.head)
+                  // whichever member this is. Its argument is a bare column, since the pairing
+                  // admits no other. The member's own argument takes its place, since that need
+                  // not be one. A side shuffled onto this layout reports `bucket(8, b + 1)` next
+                  // to `bucket(8, id)`, or `b + 1` next to an identity `id`.
+                  val argument = expr match {
+                    case t: TransformExpression => t.children
+                    case e => Seq(e)
+                  }
+                  reduced.copy(children = argument)

Review Comment:
   Nit: this replaces the use that `TransformExpression.withReference` was added for in SPARK-59045, but its Scaladoc (TransformExpression.scala:127-131) still relies on the single leaf of `KeyedPartitioning.supportsExpressions` and warns about field paths. TransformExpressionSuite.scala:115-116 also still says the marker survives the rewrites that "`GroupPartitionsExec` apply". The only callers left are the identity arm (partitioning.scala:2207 and partitioning.scala:2211), which sees a transform over a single bare column. Could the identity arm use `t.copy(children = Seq(a))` like this line, so that `withReference` and its test can go? Otherwise, could the two comments be updated?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala:
##########
@@ -139,8 +139,10 @@ case class EnsureRequirements(
               // OrderedDistribution requires grouped KeyedPartitioning with sorted keys
               // according to the distribution's ordering.
               val satisfyingKeyedPartitioning = resolution.fold(identity, _._1)
-              // The single-column invariant in KeyedPartitioning.supportsExpressions guarantees
-              // one attribute per partition expression.
+              // This binds the ordering to the partition expressions' references, which is right

Review Comment:
   Nit: this rewrites one of four copies of the single-column comment, and L1128-L1129 rewrite another. The two in `reorderJoinKeysRecursively`, at L534-L535 and L541-L542, still say "The single-column invariant in KeyedPartitioning.supportsExpressions guarantees one attribute per partition expression". The SPARK-59901 test and the broadcast expansion now reach that code with `p.b + p.c`, where `flatMap(_.references)` returns two columns for one expression. `reorder` then finds no order, or only permutes key pairs, so nothing breaks. Could those two be reworded the same way?



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/ShuffleSpecSuite.scala:
##########
@@ -761,6 +761,84 @@ class ShuffleSpecSuite extends SparkFunSuite with SQLHelper {
     }
   }
 
+  test("SPARK-59887: a spec over a transform of an expression pairs with nothing") {
+    // A join pairs its two sides up by the column each partition expression references. Over
+    // `a = b` it would pair `bucket(4, a + 1)` with `bucket(4, b)`, and over `s = b` it would pair
+    // `bucket(4, s.x)` with `bucket(4, b)`. A row with `a = b` sits in a different bucket on each
+    // side.
+    val fn = new FakeBucket
+    val a = $"a".long
+    val b = $"b".long
+    val s = $"s".struct(new StructType().add("x", LongType))
+    // A spec clustered on the column its one partition expression references.
+    def keyed(expression: Expression): KeyedShuffleSpec =
+      KeyedShuffleSpec(
+        KeyedPartitioning(Seq(expression), Seq(InternalRow(0L), InternalRow(1L))),
+        ClusteredDistribution(expression.references.toSeq))
+    def bucket(argument: Expression, numBuckets: Int): TransformExpression =

Review Comment:
   Nit: this reverses the argument order of `bucket(numBuckets, expr)` at L676, of the connector `Expressions.bucket(numBuckets, ...)`, and of the comments of this test, e.g. L782 says `bucket(8, argument)` while L784 calls `bucket(argument, 8)`. Also, the `s = b` example at L766-L767 joins a struct with a long, which the analyzer rejects. The shape that can happen is a join of two structs, `s = t`, which pairs `bucket(4, s.a)` with `bucket(4, t.b)`. Could the helper take the bucket count first, and the comment use `s = t`?



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala:
##########
@@ -1520,6 +1534,203 @@ class KeyGroupedPartitioningSuite
     }
   }
 
+  // Each key is a function of `b` other than `b` itself. A check on the leaves of the key would
+  // reject `b + 1` for its literal, but not `-b`, so both are tested.
+  Seq("p.b + 1" -> ((b: Long) => b + 1), "-p.b" -> ((b: Long) => -b)).foreach {
+    case (key, keyOf) =>
+      // `plain` holds `b` in 0..7, and `keys`, bucketed on `id`, holds the key of each `b`.
+      def createKeyTables(): Unit = {
+        createTable("plain", Array(Column.create("b", LongType)), Array.empty)
+        sql("INSERT INTO testcat.ns.plain VALUES " + (0 until 8).map(b => s"($b)").mkString(", "))
+        createTable("keys", Array(Column.create("id", LongType)), Array(bucket(4, "id")))
+        sql("INSERT INTO testcat.ns.keys VALUES " +
+          (0 until 8).map(b => s"(${keyOf(b)})").mkString(", "))
+      }
+
+      test("SPARK-59887: a side shuffled onto a transform of an expression is not paired as it " +
+          s"is ($key)") {
+        createKeyTables()
+        Seq(4, 8).foreach(n => createBucketedIdTable(s"bucket$n", n, numIds = 8))
+
+        // The first join shuffles `plain` onto the bucket of its key. That is a function of `b`,
+        // but not the same function of it as the third table's `bucket(n, id)` is of `id`. The
+        // second join clusters `plain` on `b`. Pairing the two there, as they stand or after
+        // reducing `bucket(8, id)` onto 4 buckets, puts a row with `b = id` on a different
+        // partition on each side.
+        Seq(4 -> "false", 8 -> "true").foreach { case (third, allowCompatibleTransforms) =>
+          withSQLConf(
+            SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+            SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> allowCompatibleTransforms) {
+            val df = sql(
+              s"""SELECT k.id, p.b, t.id FROM testcat.ns.keys k
+                 |JOIN testcat.ns.plain p ON k.id = $key
+                 |JOIN testcat.ns.bucket$third t ON p.b = t.id""".stripMargin)
+            checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, b.toLong)))
+            // One shuffle per join: `plain` for the first, the first join's output for the
+            // second, and none for the third table. The second join does not shuffle onto the
+            // bucket of the key, since that would move both of its sides.
+            assert(collectShuffles(stripAQEPlan(df.queryExecution.executedPlan)).size == 2)
+          }
+        }
+      }
+
+      test(s"SPARK-59887: a side is not shuffled onto a transform of an expression ($key)") {
+        createKeyTables()
+        createTable("xy", Array(Column.create("x", LongType), Column.create("y", LongType)),
+          Array.empty)
+        sql("INSERT INTO testcat.ns.xy VALUES " +
+          (0 until 8).map(b => s"(${keyOf(b)}, $b)").mkString(", "))
+
+        // The first join shuffles `plain` onto the bucket of its key, so its output offers that
+        // layout next to `bucket(4, id)`. The second join must not shuffle `xy` onto the first
+        // one. That builds `bucket(4, y)` for `xy`, not the bucket of the same function of `y`. A
+        // row with `b = y` then lands in a different bucket on each side. The join order decides
+        // which of the two layouts comes first, so both orders run.
+        withSQLConf(SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
+          Seq(
+            s"testcat.ns.plain p JOIN testcat.ns.keys k ON $key = k.id",
+            s"testcat.ns.keys k JOIN testcat.ns.plain p ON k.id = $key").foreach { firstJoin =>
+            val df = sql(
+              s"""SELECT k.id, p.b, q.x FROM $firstJoin
+                 |JOIN testcat.ns.xy q ON k.id = q.x AND p.b = q.y""".stripMargin)
+            checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, keyOf(b))))
+            // `xy` is shuffled onto the usable layout, `bucket(4, x)`, and never onto a bucket of
+            // `y`. So `plain` and `xy` are the only sides that move.
+            val shuffles = collectShuffles(stripAQEPlan(df.queryExecution.executedPlan))
+            assert(shuffles.size == 2)
+            assert(!keyedPartitioningsOf(shuffles).exists(_.references.exists(_.name == "y")))
+          }
+        }
+      }
+
+      test("SPARK-59887: a broadcast join's layout over a join key is not paired as it is " +
+          s"($key)") {
+        createKeyTables()
+        createBucketedIdTable("bucket4", 4, numIds = 8)
+
+        // An inner broadcast join reports the streamed side's layout over the build side's join
+        // key too, so the first join also offers the bucket of `plain`'s key. That needs no conf
+        // beyond the defaults. The second join clusters `plain` on `b`, so pairing that layout with
+        // `bucket(4, id)` as it stands puts a row with `b = id` on a different partition on each
+        // side.
+        val df = sql(
+          s"""SELECT /*+ BROADCAST(p) */ k.id, p.b, t.id FROM testcat.ns.keys k
+             |JOIN testcat.ns.plain p ON k.id = $key
+             |JOIN testcat.ns.bucket4 t ON p.b = t.id""".stripMargin)
+        checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, b.toLong)))
+        assert(collect(df.queryExecution.executedPlan) { case j: BroadcastHashJoinExec => j }
+          .nonEmpty, "the first join is a broadcast join")
+      }
+  }
+
+  test("SPARK-59887: a layout over a transform of a struct field is not paired nor shuffled onto") {
+    createBucketedIdTable("bucket4", 4, numIds = 8)
+    createStructTable()
+    // `l` shuffles `ps` onto `bucket(4, s.a)`, and `r` shuffles it onto `bucket(4, s.b)`.
+    val l = "SELECT x.id, ps.s FROM testcat.ns.bucket4 x JOIN testcat.ns.ps ps ON x.id = ps.s.a"
+    val r = "SELECT y.id, qs.s FROM testcat.ns.bucket4 y JOIN testcat.ns.ps qs ON y.id = qs.s.b"
+
+    withSQLConf(SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
+      // Both layouts are functions of `s`, but not the same one, so the join on `s` must not pair
+      // them as they stand. A row lands in bucket `a % 4` on one side and `b % 4` on the other.
+      checkAnswer(
+        sql(s"SELECT l.id, r.id FROM ($l) l JOIN ($r) r ON l.s = r.s"),
+        (0 until 8).map(i => Row(i.toLong, (7 - i).toLong)))
+      // Nor may a join shuffle a plain `ps` onto `l`'s layout. That builds `bucket(4, s)` for it,
+      // which drops the `.a` and hands the whole struct to a bucket function over a long.
+      checkAnswer(
+        sql(s"SELECT l.id FROM ($l) l JOIN testcat.ns.ps r ON l.s = r.s"),
+        (0 until 8).map(i => Row(i.toLong)))
+    }
+  }
+
+  test("SPARK-59887: a reduce keeps what each member's keys are computed from") {
+    Seq(4, 2).foreach(n => createBucketedIdTable(s"bucket$n", n, numIds = 8))
+    createIdentityIdTable()
+    createTable("plain", Array(Column.create("b", LongType)), Array.empty)
+    sql("INSERT INTO testcat.ns.plain VALUES " + (0 until 8).map(b => s"($b)").mkString(", "))
+    createStructTable()
+
+    withSQLConf(
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> "true") {
+      // The first join shuffles `plain` onto `bucket(4, b + 1)`, or onto `b + 1` for the
+      // identity-partitioned `ident`. The second join reduces the first one's output onto
+      // `bucket(2)`, `plain`'s member included. That member is still over `b + 1`. So the third
+      // join, on the bare `b`, must neither pair it with `bucket(2, id)` nor shuffle a plain
+      // side onto it.
+      for {
+        first <- Seq("bucket4", "ident")
+        (third, thirdKey) <- Seq("bucket2" -> "id", "plain" -> "b")
+      } {
+        val df = sql(
+          s"""SELECT f.id, p.b, t2.id, t3.$thirdKey FROM testcat.ns.$first f
+             |JOIN testcat.ns.plain p ON f.id = p.b + 1
+             |JOIN testcat.ns.bucket2 t2 ON f.id = t2.id
+             |JOIN testcat.ns.$third t3 ON p.b = t3.$thirdKey""".stripMargin)
+        checkAnswer(df, (0 until 7).map(b => Row(b + 1L, b.toLong, b + 1L, b.toLong)))
+      }
+
+      // The same for a struct field. `ps`'s member is still over `s.a` after the reduce, so the
+      // third join must not shuffle a plain `ps` onto it, which would build `bucket(2, s)`.
+      val df = sql(
+        """SELECT x.id FROM testcat.ns.bucket4 x
+          |JOIN testcat.ns.ps ps ON x.id = ps.s.a
+          |JOIN testcat.ns.bucket2 t2 ON x.id = t2.id
+          |JOIN testcat.ns.ps r ON ps.s = r.s""".stripMargin)
+      checkAnswer(df, (0 until 8).map(i => Row(i.toLong)))
+    }
+  }
+
+  test("SPARK-59887: an identity side is not reduced onto a transform of an expression") {
+    createBucketedIdTable("bucket4", 4, numIds = 8)
+    createTable("plain", Array(Column.create("b", LongType)), Array.empty)
+    sql("INSERT INTO testcat.ns.plain VALUES " + (0 until 7).map(b => s"($b)").mkString(", "))

Review Comment:
   Nit: `plain` is created inline three times in the new tests (L1543-L1544, L1650-L1651 and here), and only this copy inserts `0 until 7`, with no comment saying why. The expected rows at L1703 stay the same with `0 until 8`, since `p.b + 1 = 8` is not in `bucket4`. How about a `createPlainTable(bs: Seq[Long] = 0L until 8L)` next to `createIdentityIdTable`? Also, the two new helpers sit between `createBucketedIdTable` (L740) and its wrapper `createBucketedIdTables` (L764), which were adjacent before. Could they move after that group?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala:
##########
@@ -367,12 +369,14 @@ case class EnsureRequirements(
     val shouldConsiderMinParallelism = children.zip(specs).forall { case (child, spec) =>
       spec.forall(!_.canCreatePartitioning) || child.isInstanceOf[ShuffleExchangeLike]
     }
-    // Choose all the specs that can be used to shuffle other children
+    // Choose all the specs that can be used to shuffle other children, keeping only the members
+    // that can serve as the layout. Any other member would build a partitioning its own child is
+    // not laid out on.
     val candidateSpecs = children.zip(specs).collect {
       case (child, Some(spec)) if spec.canCreatePartitioning &&

Review Comment:
   Nit: `spec.canCreatePartitioning` here is the same as the member list below being non-empty, since a collection now answers `exists` over its members. So one decision has two sources, and the `.max` at L391 depends on that identity in partitioning.scala. If `ShuffleSpecCollection.canCreatePartitioning` changes, the `.max` throws on an empty list, which the SPARK-59256 test comment warns about. Could this drop the guard and keep the children whose `members` are non-empty instead? The comments at L385-L386 ("the best any member offers") and L405 ("over all of its members") could then say serving members.



-- 
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-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on code in PR #59165:
URL: https://github.com/apache/spark/pull/59165#discussion_r4167940664


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2061,7 +2074,15 @@ case class KeyedShuffleSpec(
       left: Expression,
       right: Expression,
       allowReduce: Boolean): Boolean = {
-    if (TransformExpression.hasReducedKeys(left) || TransformExpression.hasReducedKeys(right)) {
+    val overExpression = Seq(left, right).exists {

Review Comment:
   Thanks, measured, and you're right. Master pairs the two as they stand with no shuffle, and the guard shuffled both sides. Rather than only documenting it, [765c526](https://github.com/apache/spark/pull/59165/commits/765c526071fd7c35ba80b518564272a344e64036) pairs a transform of an expression with a transform over the same argument shape, i.e. the argument with its one column replaced by a placeholder. Your query, and two one-side shuffles onto `bucket(4, b + 1)` and `bucket(4, c + 1)`, add no shuffle again ("two layouts over the same shape of a join key pair as two columns do"). Over the same shape the two compare as two transforms of columns do, so `bucket(8, b + 1)` also reduces onto `bucket(4, c + 1)`. A reduce maps the partition keys and evaluates no argument, so the ANSI concern does not come up. An identity side is still not reduced onto such a transform. The description now lists the costs that remain, and which of them apply with default confs.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala:
##########
@@ -1121,8 +1125,8 @@ case class EnsureRequirements(
       // the skew of joining on keys that are coarser than the join keys. Key order and duplicated
       // cluster keys don't matter.
       def allClusterKeysCovered: Boolean =
-        // The single-column invariant in KeyedPartitioning.supportsExpressions guarantees one
-        // attribute per partition expression.
+        // Every column a partition expression references counts as covered. A scan reports one

Review Comment:
   Confirmed and fixed in [765c526](https://github.com/apache/spark/pull/59165/commits/765c526071fd7c35ba80b518564272a344e64036). `allClusterKeysCovered` now counts only expressions over a single column. Your shape is the new test "SPARK-59901: a join key over two columns does not cover its columns", which paired on `d` alone before.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala:
##########
@@ -604,8 +604,15 @@ private[sql] object GroupPartitionsExec {
                   // `reduced` came from the one member `checkKeyGroupCompatible` paired
                   // this side on, which need not be the member being rewritten. The keys are
                   // reduced once, from the shared key rows, so `reduced` describes them
-                  // whichever member this is, and only the key attribute is re-targeted.
-                  reduced.withReference(expr.references.head)
+                  // whichever member this is. Its argument is a bare column, since the pairing
+                  // admits no other. The member's own argument takes its place, since that need
+                  // not be one. A side shuffled onto this layout reports `bucket(8, b + 1)` next
+                  // to `bucket(8, id)`, or `b + 1` next to an identity `id`.
+                  val argument = expr match {

Review Comment:
   Thanks, measured. Master returns 4 groups for your query. Added as "a reduce keeps a member over two columns" in [765c526](https://github.com/apache/spark/pull/59165/commits/765c526071fd7c35ba80b518564272a344e64036).



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala:
##########
@@ -1520,6 +1534,203 @@ class KeyGroupedPartitioningSuite
     }
   }
 
+  // Each key is a function of `b` other than `b` itself. A check on the leaves of the key would
+  // reject `b + 1` for its literal, but not `-b`, so both are tested.
+  Seq("p.b + 1" -> ((b: Long) => b + 1), "-p.b" -> ((b: Long) => -b)).foreach {
+    case (key, keyOf) =>
+      // `plain` holds `b` in 0..7, and `keys`, bucketed on `id`, holds the key of each `b`.
+      def createKeyTables(): Unit = {
+        createTable("plain", Array(Column.create("b", LongType)), Array.empty)
+        sql("INSERT INTO testcat.ns.plain VALUES " + (0 until 8).map(b => s"($b)").mkString(", "))
+        createTable("keys", Array(Column.create("id", LongType)), Array(bucket(4, "id")))
+        sql("INSERT INTO testcat.ns.keys VALUES " +
+          (0 until 8).map(b => s"(${keyOf(b)})").mkString(", "))
+      }
+
+      test("SPARK-59887: a side shuffled onto a transform of an expression is not paired as it " +
+          s"is ($key)") {
+        createKeyTables()
+        Seq(4, 8).foreach(n => createBucketedIdTable(s"bucket$n", n, numIds = 8))
+
+        // The first join shuffles `plain` onto the bucket of its key. That is a function of `b`,
+        // but not the same function of it as the third table's `bucket(n, id)` is of `id`. The
+        // second join clusters `plain` on `b`. Pairing the two there, as they stand or after
+        // reducing `bucket(8, id)` onto 4 buckets, puts a row with `b = id` on a different
+        // partition on each side.
+        Seq(4 -> "false", 8 -> "true").foreach { case (third, allowCompatibleTransforms) =>
+          withSQLConf(
+            SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+            SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> allowCompatibleTransforms) {
+            val df = sql(
+              s"""SELECT k.id, p.b, t.id FROM testcat.ns.keys k
+                 |JOIN testcat.ns.plain p ON k.id = $key
+                 |JOIN testcat.ns.bucket$third t ON p.b = t.id""".stripMargin)
+            checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, b.toLong)))
+            // One shuffle per join: `plain` for the first, the first join's output for the
+            // second, and none for the third table. The second join does not shuffle onto the
+            // bucket of the key, since that would move both of its sides.
+            assert(collectShuffles(stripAQEPlan(df.queryExecution.executedPlan)).size == 2)
+          }
+        }
+      }
+
+      test(s"SPARK-59887: a side is not shuffled onto a transform of an expression ($key)") {
+        createKeyTables()
+        createTable("xy", Array(Column.create("x", LongType), Column.create("y", LongType)),
+          Array.empty)
+        sql("INSERT INTO testcat.ns.xy VALUES " +
+          (0 until 8).map(b => s"(${keyOf(b)}, $b)").mkString(", "))
+
+        // The first join shuffles `plain` onto the bucket of its key, so its output offers that
+        // layout next to `bucket(4, id)`. The second join must not shuffle `xy` onto the first
+        // one. That builds `bucket(4, y)` for `xy`, not the bucket of the same function of `y`. A
+        // row with `b = y` then lands in a different bucket on each side. The join order decides
+        // which of the two layouts comes first, so both orders run.
+        withSQLConf(SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
+          Seq(
+            s"testcat.ns.plain p JOIN testcat.ns.keys k ON $key = k.id",
+            s"testcat.ns.keys k JOIN testcat.ns.plain p ON k.id = $key").foreach { firstJoin =>
+            val df = sql(
+              s"""SELECT k.id, p.b, q.x FROM $firstJoin
+                 |JOIN testcat.ns.xy q ON k.id = q.x AND p.b = q.y""".stripMargin)
+            checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, keyOf(b))))
+            // `xy` is shuffled onto the usable layout, `bucket(4, x)`, and never onto a bucket of
+            // `y`. So `plain` and `xy` are the only sides that move.
+            val shuffles = collectShuffles(stripAQEPlan(df.queryExecution.executedPlan))
+            assert(shuffles.size == 2)
+            assert(!keyedPartitioningsOf(shuffles).exists(_.references.exists(_.name == "y")))
+          }
+        }
+      }
+
+      test("SPARK-59887: a broadcast join's layout over a join key is not paired as it is " +
+          s"($key)") {
+        createKeyTables()
+        createBucketedIdTable("bucket4", 4, numIds = 8)
+
+        // An inner broadcast join reports the streamed side's layout over the build side's join
+        // key too, so the first join also offers the bucket of `plain`'s key. That needs no conf
+        // beyond the defaults. The second join clusters `plain` on `b`, so pairing that layout with
+        // `bucket(4, id)` as it stands puts a row with `b = id` on a different partition on each
+        // side.
+        val df = sql(
+          s"""SELECT /*+ BROADCAST(p) */ k.id, p.b, t.id FROM testcat.ns.keys k
+             |JOIN testcat.ns.plain p ON k.id = $key
+             |JOIN testcat.ns.bucket4 t ON p.b = t.id""".stripMargin)
+        checkAnswer(df, (0 until 8).map(b => Row(keyOf(b), b.toLong, b.toLong)))
+        assert(collect(df.queryExecution.executedPlan) { case j: BroadcastHashJoinExec => j }
+          .nonEmpty, "the first join is a broadcast join")
+      }
+  }
+
+  test("SPARK-59887: a layout over a transform of a struct field is not paired nor shuffled onto") {
+    createBucketedIdTable("bucket4", 4, numIds = 8)
+    createStructTable()
+    // `l` shuffles `ps` onto `bucket(4, s.a)`, and `r` shuffles it onto `bucket(4, s.b)`.
+    val l = "SELECT x.id, ps.s FROM testcat.ns.bucket4 x JOIN testcat.ns.ps ps ON x.id = ps.s.a"
+    val r = "SELECT y.id, qs.s FROM testcat.ns.bucket4 y JOIN testcat.ns.ps qs ON y.id = qs.s.b"
+
+    withSQLConf(SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
+      // Both layouts are functions of `s`, but not the same one, so the join on `s` must not pair
+      // them as they stand. A row lands in bucket `a % 4` on one side and `b % 4` on the other.
+      checkAnswer(
+        sql(s"SELECT l.id, r.id FROM ($l) l JOIN ($r) r ON l.s = r.s"),
+        (0 until 8).map(i => Row(i.toLong, (7 - i).toLong)))
+      // Nor may a join shuffle a plain `ps` onto `l`'s layout. That builds `bucket(4, s)` for it,
+      // which drops the `.a` and hands the whole struct to a bucket function over a long.
+      checkAnswer(
+        sql(s"SELECT l.id FROM ($l) l JOIN testcat.ns.ps r ON l.s = r.s"),
+        (0 until 8).map(i => Row(i.toLong)))
+    }
+  }
+
+  test("SPARK-59887: a reduce keeps what each member's keys are computed from") {
+    Seq(4, 2).foreach(n => createBucketedIdTable(s"bucket$n", n, numIds = 8))
+    createIdentityIdTable()
+    createTable("plain", Array(Column.create("b", LongType)), Array.empty)
+    sql("INSERT INTO testcat.ns.plain VALUES " + (0 until 8).map(b => s"($b)").mkString(", "))
+    createStructTable()
+
+    withSQLConf(
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> "true") {
+      // The first join shuffles `plain` onto `bucket(4, b + 1)`, or onto `b + 1` for the
+      // identity-partitioned `ident`. The second join reduces the first one's output onto
+      // `bucket(2)`, `plain`'s member included. That member is still over `b + 1`. So the third
+      // join, on the bare `b`, must neither pair it with `bucket(2, id)` nor shuffle a plain
+      // side onto it.
+      for {
+        first <- Seq("bucket4", "ident")
+        (third, thirdKey) <- Seq("bucket2" -> "id", "plain" -> "b")
+      } {
+        val df = sql(
+          s"""SELECT f.id, p.b, t2.id, t3.$thirdKey FROM testcat.ns.$first f
+             |JOIN testcat.ns.plain p ON f.id = p.b + 1
+             |JOIN testcat.ns.bucket2 t2 ON f.id = t2.id
+             |JOIN testcat.ns.$third t3 ON p.b = t3.$thirdKey""".stripMargin)
+        checkAnswer(df, (0 until 7).map(b => Row(b + 1L, b.toLong, b + 1L, b.toLong)))
+      }
+
+      // The same for a struct field. `ps`'s member is still over `s.a` after the reduce, so the
+      // third join must not shuffle a plain `ps` onto it, which would build `bucket(2, s)`.
+      val df = sql(
+        """SELECT x.id FROM testcat.ns.bucket4 x
+          |JOIN testcat.ns.ps ps ON x.id = ps.s.a
+          |JOIN testcat.ns.bucket2 t2 ON x.id = t2.id
+          |JOIN testcat.ns.ps r ON ps.s = r.s""".stripMargin)
+      checkAnswer(df, (0 until 8).map(i => Row(i.toLong)))
+    }
+  }
+
+  test("SPARK-59887: an identity side is not reduced onto a transform of an expression") {
+    createBucketedIdTable("bucket4", 4, numIds = 8)
+    createTable("plain", Array(Column.create("b", LongType)), Array.empty)
+    sql("INSERT INTO testcat.ns.plain VALUES " + (0 until 7).map(b => s"($b)").mkString(", "))
+    createIdentityIdTable((0L until 8L) :+ Long.MaxValue)
+
+    // The first join shuffles `plain` onto `bucket(4, b + 1)`. Reducing `ident` onto it would
+    // evaluate `id + 1` on `ident`'s partition keys while planning, and that overflows for
+    // `Long.MaxValue` under ANSI. The query itself never computes it, since no `b` matches that
+    // key.
+    withSQLConf(
+        SQLConf.ANSI_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true",
+        SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> "true") {
+      val df = sql(
+        """SELECT k.id, p.b, i.id FROM testcat.ns.bucket4 k
+          |JOIN testcat.ns.plain p ON k.id = p.b + 1

Review Comment:
   Added in [765c526](https://github.com/apache/spark/pull/59165/commits/765c526071fd7c35ba80b518564272a344e64036). The identity test now runs `-p.b` over a `Long.MinValue` key as well, and master fails that one with the `ARITHMETIC_OVERFLOW` too.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala:
##########
@@ -367,12 +369,14 @@ case class EnsureRequirements(
     val shouldConsiderMinParallelism = children.zip(specs).forall { case (child, spec) =>
       spec.forall(!_.canCreatePartitioning) || child.isInstanceOf[ShuffleExchangeLike]
     }
-    // Choose all the specs that can be used to shuffle other children
+    // Choose all the specs that can be used to shuffle other children, keeping only the members
+    // that can serve as the layout. Any other member would build a partitioning its own child is
+    // not laid out on.
     val candidateSpecs = children.zip(specs).collect {
       case (child, Some(spec)) if spec.canCreatePartitioning &&
           (!shouldConsiderMinParallelism ||
             child.outputPartitioning.numPartitions >= conf.defaultNumShufflePartitions) =>
-        child -> spec
+        child -> spec.flatten.filter(_.canCreatePartitioning)

Review Comment:
   Measured, thanks. With your query the join lands on 3 partitions with the filter and on 2 without it. [765c526](https://github.com/apache/spark/pull/59165/commits/765c526071fd7c35ba80b518564272a344e64036) adds it as "a member that cannot serve does not rank its collection", in `KeyGroupedPartitioningSuite` rather than `EnsureRequirementsSuite`, since the shape needs a broadcast join over partitioned catalog tables. The description says the filter decides the ranking. With the filter the plan is the one master takes, since master refuses that collection as a whole. With the shape pairing, the filter is not just defensive any more either. A member over the same shape pairs with itself, so without the filter the `xy` tests fail too. `createPartitioning` now rebuilds the template through a helper that asserts its argument is a column, so a regression there fails planning instead of returning wrong rows.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -1941,8 +1943,16 @@ case class KeyedShuffleSpec(
    * `KeyedPartitioning.positionsCoveringClusterKeys` counts it. See that method for why the two
    * stay apart.
    *
-   * The assertion is what makes the reference reading sound. With one reference per expression,
-   * "some reference is a cluster key" and "every reference is" are the same statement.
+   * Only an expression with a single reference maps to a position. With one reference, "some
+   * reference is a cluster key" and "every reference is" are the same statement, which is what
+   * makes the reference reading sound. A scan reports no other expression

Review Comment:
   Done in [765c526](https://github.com/apache/spark/pull/59165/commits/765c526071fd7c35ba80b518564272a344e64036). The doc names both producers now, and says the projection happens under `allowKeysSubsetOfPartitionKeys` for an unmarked layout where another position maps. The `createShuffleSpec` comment mentions the two-column case too. The `EnsureRequirements` ordering comment went away with #59189.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -1588,15 +1584,21 @@ sealed trait ShuffleSpec {
    * co-partitioned with the `other`, and therefore no shuffle is required when joining the two
    * sides.
    *
-   * Note that Spark assumes this to be reflexive, symmetric and transitive.
+   * Note that Spark assumes this to be reflexive, symmetric and transitive. Some specs are not
+   * reflexive:
+   *  - a [[RangeShuffleSpec]], whose boundaries are sampled;
+   *  - a [[KeyedShuffleSpec]] with a partition expression that is neither a column nor a transform

Review Comment:
   Done in [765c526](https://github.com/apache/spark/pull/59165/commits/765c526071fd7c35ba80b518564272a344e64036). The note now states the two conditions: a partition expression that `keyPositions` maps to no cluster key, or one that is neither a column nor a transform. A spec over a transform of an expression is reflexive again, through the shape pairing.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -1892,8 +1894,8 @@ case class KeyReducer(reducer: Reducer[_, _], reducedExpression: TransformExpres
  * @param transform the partition transform, re-targeted at the identity side's key attribute
  */
 case class IdentityReducer(transform: TransformExpression) extends Reducer[Any, Any] {
-  // `transform` has a single leaf attribute (`KeyedPartitioning.supportsExpressions`), which is
-  // bound to ordinal 0 of the single-value row `reduce` evaluates it against.
+  // `transform` is over a single bare column (`KeyedShuffleSpec.isExpressionCompatible` admits no

Review Comment:
   Done in [765c526](https://github.com/apache/spark/pull/59165/commits/765c526071fd7c35ba80b518564272a344e64036). The `IdentityReducer` comment credits `keyPositions` with the single reference, and step 3.3 mentions the argument condition.



-- 
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-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on PR #59165:
URL: https://github.com/apache/spark/pull/59165#issuecomment-5997359557

   **Merge Summary:**
   - merged into master https://github.com/apache/spark/commit/05a20fb758ba863c1f3a32e354f0e045552f9767
   
   *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-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on PR #59165:
URL: https://github.com/apache/spark/pull/59165#issuecomment-5997375931

   Thank you @dongjoon-hyun and @uros-b for the review!
   
   I will open backport PRs soon.


-- 
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-59887][SPARK-59901][SQL] Fix wrong results when a storage-partitioned join pairs a transform of a join-key expression with one of a column [spark]

Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on PR #59165:
URL: https://github.com/apache/spark/pull/59165#issuecomment-5971975711

   @dongjoon-hyun, I looked into the corner case. With `spark.sql.sources.v2.bucketing.shuffle.enabled`, a join on two keys whose sides pair only through a transform of an expression gets one more shuffle with this PR. I added it to the costs in the description. I'd intentionally not fix it here, since restoring master's plan is questionable. Both plans co-partition on only one of the two join keys, which `spark.sql.requireAllClusterKeysForCoPartition` is meant to prevent. I'll file a separate ticket for that.
   


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