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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/AliasAwareOutputExpression.scala:
##########
@@ -70,8 +70,10 @@ trait AliasAwareOutputExpression extends SQLConfHelper {
   protected def projectExpression(expr: Expression): LazyList[Expression] = {
     val outputSet = AttributeSet(outputExpressions.map(_.toAttribute))
     expr.multiTransformDown {
-      // Mapping with aliases
-      case e: Expression if aliasMap.contains(e.canonicalized) =>
+      // Mapping with aliases. A literal is left as it is: it means the same 
in any scope, and it
+      // may be a transform parameter, e.g. `2 AS w` would otherwise turn 
`truncate(data, 2)` into
+      // `truncate(d, w)`.
+      case e: Expression if !e.isInstanceOf[Literal] && 
aliasMap.contains(e.canonicalized) =>

Review Comment:
   **Finding 28.** This is the central version I suggested in finding 1 
([r4122106752](https://github.com/apache/spark/pull/55885#discussion_r4122106752)),
 and it reaches past transform parameters. For every alias-aware operator, a 
literal in the child's partitioning or ordering no longer maps to the alias 
that holds it. On master the alias form is a true claim too, since `z` is `0` 
in every row. Where `FoldablePropagation` can't inline the alias, that form is 
the one a parent asks for, and a cache is such a boundary.
   
   Measured on this head and on master, AQE off and on, with the same rows in 
all four:
   
   ```scala
   val src = spark.range(100).select($"id" % 10 as "a", $"id" as "b")
   val cached = src.repartition($"a", lit(0)).select($"a", lit(0).as("z"), 
$"b").cache()
   cached.groupBy("a", "z").agg(sum("b"))
   ```
   
   ```
                           master                     this head
   cached partitioning     hashpartitioning(a, z, 5)  hashpartitioning(a, 0, 5)
   aggregate shuffles      0                          1
   ```
   
   So my "what you want everywhere" in finding 1 was too broad. The narrow 
option from that thread works: skip only the literals that are a transform's 
own arguments, and let any other literal map to its alias as on master.
   
   ```scala
     protected def projectExpression(expr: Expression): LazyList[Expression] = {
       val outputSet = AttributeSet(outputExpressions.map(_.toAttribute))
       // A transform's literal parameters say what it computes, so they are 
not aliasable values, e.g.
       // `2 AS w` would otherwise turn `truncate(data, 2)` into `truncate(d, 
w)`. Any other literal
       // maps to its alias.
       val params = java.util.Collections.newSetFromMap(
         new java.util.IdentityHashMap[Expression, java.lang.Boolean])
       expr.foreach {
         case t: TransformExpression => t.literalChildren.foreach(params.add)
         case _ =>
       }
       expr.multiTransformDown {
         // Mapping with aliases.
         case e: Expression if !params.contains(e) && 
aliasMap.contains(e.canonicalized) =>
   ```
   
   It goes by identity because `multiTransformDown` also rewrites the children 
of what an arm returns, so a check on the node type alone would still reach the 
literal one level down. With it the aggregate above plans no shuffle again, as 
on master, and the PR's suites stay green, 
`ProjectedOrderingAndPartitioningSuite` and `PlannerSuite` included. A 
`ProjectedOrderingAndPartitioningSuite` case would pin the other half: 
`HashPartitioning(Seq(a, Literal(0)))` under `ProjectExec(Seq(a, 
Alias(Literal(0), "z")()))` should report `(a, z)`.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -153,7 +426,7 @@ case class TransformExpression(
    * carry the same pair.
    */
   private def reducedKeySpace: Option[Set[TransformFunctionId]] =
-    reducedWith.map(partner => Set(functionId, partner))
+    for (self <- functionId; partner <- reducedWith) yield Set(self, partner)

Review Comment:
   **Finding 29.** Finding 14 
([r4340180587](https://github.com/apache/spark/pull/55885#discussion_r4340180587))
 moved the partner's shape along in the `GroupPartitionsExec` rebuild. Any 
other rewrite of a reduced member still leaves the partner behind, since 
`withNewChildrenInternal` is a plain `copy(children = ...)`.
   
   `BroadcastHashJoinExec.expandOutputPartitioning` substitutes a streamed key 
with a build key through it:
   - It turns the reduced `bucket(12, id)` with partner `bucket(8, ColumnRef)` 
into `bucket(12, x + 1)` with the same partner.
   - The mirror side becomes `bucket(8, y + 1)` with partner `bucket(12, 
ColumnRef)`.
   
   So the two key spaces `reducedKeySpace` compares no longer match, although 
both are the same `% 4` space over `x + 1`.
   
   Measured on this head and on master, AQE off and on, under 
`allowCompatibleTransforms`. `ra` is `bucket(12, store_id)`, `rb` is `bucket(8, 
store_id)`, `rd` and `re` the mirror, and `rc` and `rf` are unpartitioned:
   
   ```sql
   SELECT /*+ MERGE(l, r) */ l.x, l.d1, r.d2 FROM
     (SELECT /*+ MERGE(a, b), BROADCAST(c) */ c.dept_id AS x, a.data AS d1
      FROM ra a JOIN rb b ON a.store_id = b.store_id
      JOIN rc c ON a.store_id = c.dept_id + 1) l
   JOIN
     (SELECT /*+ MERGE(d, e), BROADCAST(f) */ f.dept_id AS y, d.data AS d2
      FROM rd d JOIN re e ON d.store_id = e.store_id
      JOIN rf f ON d.store_id = f.dept_id + 1) r
   ON l.x = r.y
   ```
   
   ```
   master      shuffles=0
   this head   shuffles=2   (both legs of the top join; the two inner joins 
still reduce by % 4)
   ```
   
   An alias projection of `x + 1 AS y` over a member rebuilt over `x + 1` goes 
through the same method. Doing the rebuild in the expression covers every 
rewriter:
   
   ```scala
     override protected def withNewChildrenInternal(newChildren: 
IndexedSeq[Expression]): Expression = {
       val rebuilt = copy(children = newChildren)
       rebuilt.columnSlots match {
         case Seq(slot) if reducedWith.isDefined =>
           rebuilt.copy(reducedWith = 
reducedWith.map(TransformExpression.withColumnShape(_, slot)))
         case _ => rebuilt
       }
     }
   ```
   
   With it the query above plans no shuffle again, and the PR's suites stay 
green, "isSameFunction and hasSameReducedKeys agree on every pair" included. 
`GroupPartitionsExec` still needs its own `withColumnShape`, since 
`rewriteColumnSlots` builds with `copy`.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2539,9 +2543,10 @@ case class KeyedShuffleSpec(
           if TransformExpression.hasReducedKeys(e1) || 
TransformExpression.hasReducedKeys(e2) =>
         (None, None)
 
+      // A reducer that threw in either direction makes the pair not 
reducible, and so does a side
+      // with no identity, see `pairReducers`.
       case (e1: TransformExpression, e2: TransformExpression) =>
-        val thisReducer = e1.reducers(e2)
-        val otherReducer = e2.reducers(e1)
+        val (thisReducer, otherReducer) = e1.pairReducers(e2)

Review Comment:
   **Finding 30.** Finding 12 
([r4340180565](https://github.com/apache/spark/pull/55885#discussion_r4340180565))
 made one call decide both directions, but the planner still asks for a pair 
twice. `areKeysCompatible` asks `isCompatible`, which calls `pairReducers`. 
Then `EnsureRequirements.checkKeyGroupCompatible` calls `reducersBothWays`, 
which calls it again here. Nothing checks that the two answers agree. When this 
second call vetoes a pair the first admitted through a reducer, `leftReducers` 
and `rightReducers` come back `None`, and the raw keys of the two sides are 
merged as they stand (`EnsureRequirements.scala:796-802`).
   
   Measured on this head and on master, AQE off and on. The fixture is a bucket 
function that implements only the deprecated overload and throws from it when 
called under `reducersBothWays`, a stand-in for any failure that does not 
repeat on every call. It joins `bucket(16, id)` and `bucket(12, id)` over the 
same 48 ids under `allowCompatibleTransforms`:
   
   ```
   master      IllegalStateException: transient failure on the second probe
   this head   rows=12 expected=48 shuffles=0
   ```
   
   So a failure that master reported now drops three quarters of the rows. The 
javadoc's "the pair is treated as not reducible" needs the pair decided once. 
Either:
   - memoize `pairReducers`'s answer on the expression, keyed by the other 
side, so that `isCompatible` and `reducersBothWays` read the same one. That 
also stops each planning pass from calling connector code again for every probe.
   - or, in `checkKeyGroupCompatible`, fall back to the shuffle when a 
transform pair that is not the same function was admitted and 
`reducersBothWays` then returns no reducer for it.
   



##########
docs/sql-migration-guide.md:
##########
@@ -79,6 +79,7 @@ license: |
 - Since Spark 4.4, `spark.sql.sources.v2.bucketing.partition.filter.enabled` 
defaults to `true`. In a storage-partitioned join, the partition key groups 
pushed down to both sides may now be narrowed to those that can produce output 
for the join type, instead of always taking the union of the two sides' groups: 
an inner or semi join may keep only the groups present on both sides, a join 
that keeps or tests every left row (left outer, left anti, left single, 
existence) keeps the left side's groups, a right outer join keeps the right 
side's, and a full outer join is unaffected; a CROSS join carrying an equality 
condition is treated like an inner join. The narrowing is skipped when either 
side's partitioning may contain unknown partition keys, as after a shuffle on 
one side, so such a join keeps the full union. A group that is dropped is not 
scanned at all, so a query may read fewer files. To restore the previous 
behavior, set `spark.sql.sources.v2.bucketing.partition.filter.enabled` to
  `false`.
 - Since Spark 4.4, 
`spark.sql.sources.v2.bucketing.partitionKeyOrdering.enabled` defaults to 
`true`. A V2 scan that reports a keyed partitioning and no ordering that Spark 
keeps for the scan output now also reports itself sorted by its partition key 
expressions, because every row of such a partition evaluates them to the same 
value. That includes a scan that reports an empty ordering, or one that starts 
with a sort order on a column pruned from the scan output or on a partition 
transform and has no later sort order on a partition key other than a 
transform. It relies on each partition of the source holding a single partition 
key value, as `KeyGroupedPartitioning` requires. Partition transforms such as 
`days(ts)` or `bucket(8, id)` are left out of that ordering. This lets Spark 
drop a `Sort` it would otherwise place above the scan. An aggregate that groups 
by a leading run of the other key expressions, in key order, may also be 
planned as a sort aggregate rather than a hash aggregate
 . This is because `spark.sql.execution.replaceHashWithSortAgg` keys off the 
reported ordering. To restore the previous behavior, set 
`spark.sql.sources.v2.bucketing.partitionKeyOrdering.enabled` to `false`.
 - Since Spark 4.4, 
`spark.sql.sources.v2.bucketing.preserveKeyOrderingOnCoalesce.enabled` defaults 
to `true`. When `GroupPartitionsExec` merges several input partitions that 
share one partition key value into a single output partition, it now keeps sort 
orders over the partition key expressions in the ordering it reports, since 
those expressions are constant within the merged partition. Sort orders over 
partition transforms such as `days(ts)` or `bucket(8, id)` are left out. Orders 
over other columns are still dropped, as the concatenation invalidates them, 
and a join that reduced the partition keys onto a common key space (see 
`spark.sql.sources.v2.bucketing.allowCompatibleTransforms.enabled`) reports no 
order, since the merged partitions then share only the reduced key. This can 
remove a `Sort` downstream of the merge. To restore the previous behavior, set 
`spark.sql.sources.v2.bucketing.preserveKeyOrderingOnCoalesce.enabled` to 
`false`.
+- Since Spark 4.4, a V2 scan partitioned by a transform with literal 
parameters, such as `truncate(col, n)`, reports that partitioning as it does 
for `bucket(n, col)`. Joins, aggregates and windows over such a scan can skip 
their shuffle, and then run with one partition per partition key instead of 
`spark.sql.shuffle.partitions`. Previously, such a scan reported no 
partitioning, so these operators shuffled it. To restore the previous behavior, 
set `spark.sql.sources.v2.bucketing.enabled` to `false`; note that this also 
disables storage-partitioned joins over `bucket` and other transforms.

Review Comment:
   **Finding 31.** The restore line understates what it costs. 
`spark.sql.sources.v2.bucketing.enabled=false` drops the scan's keyed 
partitioning altogether, since `DataSourceV2Strategy` filters 
`relation.keyGroupedPartitioning` on it. So it turns off identity-partitioned 
joins and the aggregates and windows over any keyed scan, not only joins over 
`bucket` and other transforms. Could the line say so?
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -393,6 +678,82 @@ object TransformExpression extends Logging {
     logDebug(log"Cannot resolve a call of the " + transformLabel(function), e)
   }
 
+  /**
+   * Logs that `function`'s reducer threw: at WARN once per function, since 
every planning pass and
+   * AQE re-plan asks the pair again, and at DEBUG, with the stack trace, 
every time.
+   */
+  private def logReducerThrew(function: BoundFunction, name: String, e: 
Throwable): Unit = {
+    logOnce(s"reducerThrew:${function.getClass.getName}:$name", 
log.isWarnEnabled) {

Review Comment:
   **Finding 34.** These keys embed `name`, which is 
`function.canonicalName()`. For a function that keeps the default canonical 
name, a fresh UUID per call, every probe makes a new key. So the WARN repeats 
on every probe, against 15's "once per function" 
([r4340180601](https://github.com/apache/spark/pull/55885#discussion_r4340180601)).
 And `loggedOnce`, which is static and never evicted, grows by a key each time. 
Measured on this head: five `isCompatible` calls on one such pair log 
"implements no reducer" 10 times.
   
   Keying by the function class, as `notScalar:` and `failure:` already do, 
keeps the promise for any connector. The same goes for `literalTypes:` and 
`noReducer:` below. Adding the failure's class here, as `failure:` does, also 
keeps a later failure of another kind from staying at DEBUG:
   
   ```scala
       
logOnce(s"reducerThrew:${function.getClass.getName}:${e.getClass.getName}",
           log.isWarnEnabled) {
   ```
   



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/catalog/functions/transformFunctions.scala:
##########
@@ -213,20 +265,27 @@ object BucketFunction extends ScalarFunction[Int] with 
ReducibleFunction[Int, In
   }
 
   override def reducer(
-      thisNumBuckets: Int,
+      thisParams: Array[Literal[_]],

Review Comment:
   **Finding 33.** Moving `BucketFunction` to the generalized overload took the 
deprecated path's end-to-end coverage with it. On master, every 
compatible-bucket join test (SPARK-47094) went through `reducer(int, 
ReducibleFunction, int)`. Here `LegacyBucketFunction` is reached only through 
`reducers(...)` on hand-built transforms. Nothing runs the path a shipped 
connector such as Iceberg takes: `V2ExpressionUtils` marking 
`fromBucketTransform`, then `pairReducers`, `reducersBothWays` and 
`GroupPartitionsExec`. A regression in any of them would leave every test green.
   
   The path works on this head: the case below, with a deprecated-only fixture, 
plans no shuffle and returns every row. Could you add it?
   
   ```scala
   object UnboundLegacyBucketFunction extends UnboundFunction {
     override def bind(inputType: StructType): BoundFunction = 
LegacyBucketFunction
     override def description(): String = name()
     override def name(): String = "bucket"
   }
   ```
   
   ```scala
     test("SPARK-50593: a connector with only the deprecated reducer still gets 
SPJ") {
       withFunction(UnboundLegacyBucketFunction) {
         Seq((4, 2), (2, 4), (6, 4)).foreach { case (b1, b2) =>
           catalog.clearTables()
           createTable("t1", columns2, Array(bucket(b1, "store_id")))
           createTable("t2", columns2, Array(bucket(b2, "store_id")))
           val rows = (0 until 8).map(i => s"($i, 0, 'x$i')").mkString(", ")
           sql(s"INSERT INTO testcat.ns.t1 VALUES $rows")
           sql(s"INSERT INTO testcat.ns.t2 VALUES $rows")
           withSQLConf(
             SQLConf.V2_BUCKETING_PUSH_PART_VALUES_ENABLED.key -> "true",
             SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key 
-> "false",
             SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> "true") {
             val df = sql(
               s"""${selectWithMergeJoinHint("t1", "t2")}
                  |t1.store_id, t1.data, t2.data
                  |FROM testcat.ns.t1 t1 JOIN testcat.ns.t2 t2 ON t1.store_id = 
t2.store_id
                  |""".stripMargin)
             assert(collectShuffles(df.queryExecution.executedPlan).isEmpty)
             checkAnswer(df, (0 until 8).map(i => Row(i, s"x$i", s"x$i")))
           }
         }
       }
     }
   ```
   



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/KeyGroupedPartitioningSuite.scala:
##########
@@ -8048,6 +8078,1089 @@ class KeyGroupedPartitioningSuite
     }
   }
 
+  test("SPARK-50593: cross-function truncate vs bucket should NOT trigger 
SPJ") {
+    val partitions1 = Array(
+      Expressions.apply("truncate", Expressions.column("data"), 
Expressions.literal(3))
+    )
+    val partitions2 = Array(
+      Expressions.bucket(4, "data")
+    )
+
+    createTable("trunc_cross1", columns, partitions1)
+    sql("INSERT INTO testcat.ns.trunc_cross1 VALUES " +
+      "(0, 'aaa', CAST('2022-01-01' AS timestamp)), " +
+      "(1, 'bbb', CAST('2021-01-01' AS timestamp))")
+
+    createTable("trunc_cross2", columns2, partitions2)
+    sql("INSERT INTO testcat.ns.trunc_cross2 VALUES " +
+      "(1, 5, 'aaa'), " +
+      "(5, 10, 'bbb')")
+
+    withSQLConf(
+      SQLConf.V2_BUCKETING_PUSH_PART_VALUES_ENABLED.key -> "true",
+      SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> "true") {
+
+      val df = sql(
+        s"""
+           |${selectWithMergeJoinHint("trunc_cross1", "trunc_cross2")}
+           |trunc_cross1.id, trunc_cross2.store_id
+           |FROM testcat.ns.trunc_cross1 JOIN testcat.ns.trunc_cross2
+           |ON trunc_cross1.data = trunc_cross2.data
+           |ORDER BY trunc_cross1.id
+           |""".stripMargin)
+
+      // Different functions (truncate vs bucket) are not mutually reducible, 
so a shuffle
+      // must still be planned.
+      val shuffles = collectShuffles(df.queryExecution.executedPlan)
+      assert(shuffles.nonEmpty,
+        "truncate vs bucket are not compatible - a shuffle should be present, 
" +
+          "but none was planned")
+      checkAnswer(df, Seq(Row(0, 1), Row(1, 5)))
+    }
+  }
+
+  test("SPARK-50593: truncate(3) vs truncate(5) triggers SPJ via width 
reducer") {
+    // Exercises the Literal[]-based reducer path end-to-end: truncate widths 
3 and 5
+    // are mutually reducible (reduce the larger to the smaller), so SPJ must 
avoid the shuffle.
+    val table1 = "trunc_three"
+    val table2 = "trunc_five"
+
+    val partitions1 = Array(
+      Expressions.apply("truncate", Expressions.column("data"), 
Expressions.literal(3)))
+    val partitions2 = Array(
+      Expressions.apply("truncate", Expressions.column("data"), 
Expressions.literal(5)))
+
+    createTable(table1, columns, partitions1)
+    sql(s"INSERT INTO testcat.ns.$table1 VALUES " +
+      "(0, 'apple', CAST('2022-01-01' AS timestamp)), " +
+      "(1, 'grape', CAST('2021-01-01' AS timestamp)), " +
+      "(2, 'orange', CAST('2020-01-01' AS timestamp))")
+
+    createTable(table2, columns, partitions2)
+    sql(s"INSERT INTO testcat.ns.$table2 VALUES " +
+      "(10, 'apple', CAST('2022-01-01' AS timestamp)), " +
+      "(20, 'grape', CAST('2021-01-01' AS timestamp)), " +
+      "(30, 'orange', CAST('2020-01-01' AS timestamp))")
+
+    withSQLConf(
+      SQLConf.V2_BUCKETING_PUSH_PART_VALUES_ENABLED.key -> "true",
+      SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> "true") {
+
+      val df = sql(
+        s"""
+           |${selectWithMergeJoinHint(table1, table2)}
+           |$table1.id AS left_id, $table2.id AS right_id
+           |FROM testcat.ns.$table1 JOIN testcat.ns.$table2
+           |ON $table1.data = $table2.data
+           |ORDER BY $table1.id
+           |""".stripMargin)
+
+      val shuffles = collectShuffles(df.queryExecution.executedPlan)
+      assert(shuffles.isEmpty,
+        "truncate(3) vs truncate(5) should avoid shuffle via the width 
reducer, " +
+          "but a shuffle was planned")
+      checkAnswer(df, Seq(Row(0, 10), Row(1, 20), Row(2, 30)))
+    }
+  }
+
+  test("SPARK-50593: a sorted bucket with no sort columns resolves as a 
bucket") {
+    // The catalog registers `bucket` only. A sort-free `sorted_bucket` is the 
same partitioning,
+    // so it must resolve to that function and pair with a `bucket` table 
without a shuffle.
+    val sortFree = SortedBucketTransform(
+      LogicalExpressions.literal(4, IntegerType), Seq(FieldReference("id")))
+    createTable("sb_sorted", columns, Array(sortFree))
+    sql("INSERT INTO testcat.ns.sb_sorted VALUES " +
+      "(1, 'a', CAST('2022-01-01' AS timestamp)), (5, 'b', CAST('2022-01-01' 
AS timestamp))")
+    createTable("sb_plain", columns, Array(bucket(4, "id")))
+    sql("INSERT INTO testcat.ns.sb_plain VALUES " +
+      "(1, 'c', CAST('2022-01-01' AS timestamp)), (5, 'd', CAST('2022-01-01' 
AS timestamp))")
+    val df = sql(
+      s"""
+         |${selectWithMergeJoinHint("sb_sorted", "sb_plain")}
+         |sb_sorted.id FROM testcat.ns.sb_sorted JOIN testcat.ns.sb_plain
+         |ON sb_sorted.id = sb_plain.id
+         |""".stripMargin)
+    assert(collectShuffles(df.queryExecution.executedPlan).isEmpty)
+    checkAnswer(df, Seq(Row(1), Row(5)))
+  }
+
+  test("SPARK-50593: the integer truncate test function refuses a grid wider 
than an int") {
+    // 65536 and 65537 are coprime, so their common grid does not fit an int; 
wrapping it would
+    // hand Spark a negative width.
+    val a = attr("id")
+    val wide = TransformExpression(IntegerTruncateFunction, Seq(a, 
Literal(65536)))
+    val wider = TransformExpression(IntegerTruncateFunction, Seq(a, 
Literal(65537)))
+    assert(wide.pairReducers(wider) == ((None, None)))
+    val narrow = TransformExpression(IntegerTruncateFunction, Seq(a, 
Literal(4)))
+    val narrower = TransformExpression(IntegerTruncateFunction, Seq(a, 
Literal(6)))
+    assert(narrow.pairReducers(narrower) == ((Some(IntTruncateReducer(12)),
+      Some(IntTruncateReducer(12)))))
+  }
+
+  test("SPARK-50593: the truncate test functions take a null key") {
+    // A one-side shuffle onto a truncate layout evaluates the function on 
every row of the
+    // shuffled side, and an outer join before it gives those rows null keys.
+    val nullKey = TransformExpression(TruncateFunction,
+      Seq(Literal(null, StringType), Literal(3)))
+    assert(nullKey.eval(InternalRow.empty) == null)
+    assert(TruncateReducer(2).reduce(null) == null)
+  }
+
+  test("SPARK-50593: identical truncate widths trigger SPJ under the default 
config") {
+    val table1 = "trunc_same_a"
+    val table2 = "trunc_same_b"
+    val partitions = Array(
+      Expressions.apply("truncate", Expressions.column("data"), 
Expressions.literal(3)))
+
+    createTable(table1, columns, partitions)
+    sql(s"INSERT INTO testcat.ns.$table1 VALUES " +
+      "(0, 'apple', CAST('2022-01-01' AS timestamp)), " +
+      "(1, 'grape', CAST('2021-01-01' AS timestamp)), " +
+      "(2, 'orange', CAST('2020-01-01' AS timestamp))")
+
+    createTable(table2, columns, partitions)
+    sql(s"INSERT INTO testcat.ns.$table2 VALUES " +
+      "(10, 'apple', CAST('2022-01-01' AS timestamp)), " +
+      "(20, 'grape', CAST('2021-01-01' AS timestamp)), " +
+      "(30, 'orange', CAST('2020-01-01' AS timestamp))")
+
+    // No withSQLConf: identical widths are the same transform, so this has to 
work on the
+    // default config, where allowCompatibleTransforms is off.
+    val df = sql(
+      s"""
+         |${selectWithMergeJoinHint(table1, table2)}
+         |$table1.id AS left_id, $table2.id AS right_id
+         |FROM testcat.ns.$table1 JOIN testcat.ns.$table2
+         |ON $table1.data = $table2.data
+         |ORDER BY $table1.id
+         |""".stripMargin)
+
+    assert(collectShuffles(df.queryExecution.executedPlan).isEmpty,
+      "identical truncate widths are the same function, so no shuffle is 
needed")
+    checkAnswer(df, Seq(Row(0, 10), Row(1, 20), Row(2, 30)))
+  }
+
+  test("SPARK-50593: existing bucket SPJ still works with Literal[] API") {
+    // Exercises the new Literal[]-based reducer path end-to-end: bucket(4) and
+    // bucket(2) differ, so SPJ can only avoid the shuffle if BucketFunction's 
reducer
+    // (now implemented via Literal[] params) correctly returns a GCD-based 
Reducer.
+    // BucketFunction overrides only the new API, which the dispatch tries 
first, so no fallback to
+    // the deprecated overload is involved.
+    val table1 = "bucket_compat1"
+    val table2 = "bucket_compat2"
+
+    val partitions1 = Array(Expressions.bucket(4, "id"))
+    val partitions2 = Array(Expressions.bucket(2, "store_id"))
+
+    createTable(table1, columns, partitions1)
+    sql(s"INSERT INTO testcat.ns.$table1 VALUES " +
+      "(0, 'aaa', CAST('2022-01-01' AS timestamp)), " +
+      "(1, 'bbb', CAST('2021-01-01' AS timestamp)), " +
+      "(2, 'ccc', CAST('2020-01-01' AS timestamp)), " +
+      "(3, 'ddd', CAST('2019-01-01' AS timestamp))")
+
+    createTable(table2, columns2, partitions2)
+    sql(s"INSERT INTO testcat.ns.$table2 VALUES " +
+      "(0, 5, 'aaa'), " +
+      "(1, 10, 'bbb'), " +
+      "(2, 15, 'ccc'), " +
+      "(3, 20, 'ddd')")
+
+    withSQLConf(
+      SQLConf.V2_BUCKETING_PUSH_PART_VALUES_ENABLED.key -> "true",
+      SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> "true") {
+      val df = sql(
+        s"""
+           |${selectWithMergeJoinHint(table1, table2)}
+           |$table1.id, $table2.store_id
+           |FROM testcat.ns.$table1 JOIN testcat.ns.$table2
+           |ON $table1.id = $table2.store_id
+           |ORDER BY $table1.id
+           |""".stripMargin)
+
+      val shuffles = collectShuffles(df.queryExecution.executedPlan)
+      assert(shuffles.isEmpty,
+        "bucket(4) vs bucket(2) should avoid shuffle via the GCD reducer, " +
+          "but a shuffle was planned")
+      checkAnswer(df, Seq(Row(0, 0), Row(1, 1), Row(2, 2), Row(3, 3)))
+    }
+  }
+
+  test("SPARK-50593: bucket(4) vs bucket(3) - no common divisor, must 
shuffle") {
+    // GCD(4, 3) = 1 -- BucketFunction.reducer returns null. Spark must NOT 
enable SPJ.
+    // Regression guard: a buggy null-handling in TransformExpression's 
reducer dispatch (e.g.,
+    // Some(...) instead of Option(...)) would treat null as Some(null),
+    // enable SPJ, and produce wrong join results for incompatible bucket 
layouts.
+    val table1 = "bucket_gcd1_a"
+    val table2 = "bucket_gcd1_b"
+
+    val partitions1 = Array(Expressions.bucket(4, "id"))
+    val partitions2 = Array(Expressions.bucket(3, "store_id"))
+
+    createTable(table1, columns, partitions1)
+    sql(s"INSERT INTO testcat.ns.$table1 VALUES " +
+      "(0, 'aaa', CAST('2022-01-01' AS timestamp)), " +
+      "(1, 'bbb', CAST('2021-01-01' AS timestamp)), " +
+      "(2, 'ccc', CAST('2020-01-01' AS timestamp))")
+
+    createTable(table2, columns2, partitions2)
+    sql(s"INSERT INTO testcat.ns.$table2 VALUES " +
+      "(0, 5, 'aaa'), " +
+      "(1, 10, 'bbb'), " +
+      "(2, 15, 'ccc')")
+
+    withSQLConf(
+      SQLConf.V2_BUCKETING_PUSH_PART_VALUES_ENABLED.key -> "true",
+      SQLConf.V2_BUCKETING_ALLOW_COMPATIBLE_TRANSFORMS.key -> "true") {
+      val df = sql(
+        s"""
+           |${selectWithMergeJoinHint(table1, table2)}
+           |$table1.id, $table2.store_id
+           |FROM testcat.ns.$table1 JOIN testcat.ns.$table2
+           |ON $table1.id = $table2.store_id
+           |ORDER BY $table1.id
+           |""".stripMargin)
+
+      val shuffles = collectShuffles(df.queryExecution.executedPlan)
+      assert(shuffles.nonEmpty,
+        "bucket(4) vs bucket(3) have no common divisor (GCD=1), so the reducer 
" +
+          "returns null. SPJ must NOT be enabled; a shuffle is required.")
+      checkAnswer(df, Seq(Row(0, 0), Row(1, 1), Row(2, 2)))
+    }
+  }
+
+  test("SPARK-50593: isSameFunction is a structural per-position walk, not a 
literal bag") {
+    import org.apache.spark.sql.catalyst.expressions.{Add, Expression, 
GetStructField}
+    val a = attr("a")
+    val b = attr("b")
+    def bucket(n: Int, e: Expression): TransformExpression =
+      bucketTransform(BucketFunction, n, e)
+    def years(e: Expression): TransformExpression = 
TransformExpression(YearsFunction, Seq(e))
+    def days(e: Expression): TransformExpression = 
TransformExpression(DaysFunction, Seq(e))
+
+    // Column identity is ignored -- it is reconciled separately, via 
keyPositions.
+    assert(bucket(4, a).isSameFunction(bucket(4, b)))
+    assert(!bucket(4, a).isSameFunction(bucket(2, b)))
+
+    // Nested transforms are compared recursively, although both literal lists 
here are [4].
+    // supportsExpressions rejects nested shapes for SPJ, but isCompatible and 
ValidateRequirements
+    // consult identity too.
+    assert(!bucket(4, years(a)).isSameFunction(bucket(4, days(a))),
+      "a different nested transform is a different function")
+    assert(bucket(4, years(a)).isSameFunction(bucket(4, years(b))),
+      "the same nested transform over a different column is still the same 
function")
+    assert(!bucket(4, years(a)).isSameFunction(bucket(2, years(a))), "the 
literal still matters")
+
+    // An expression argument is compared by its shape, the same rule the 
join's pairing uses.
+    val ra = AttributeReference("a", IntegerType)()
+    val rb = AttributeReference("b", IntegerType)()
+    val add = bucket(4, Add(ra, Literal(1)))
+    assert(add.isSameFunction(bucket(4, Add(rb, Literal(1)))), "the same shape 
over another column")
+    assert(!add.isSameFunction(bucket(4, ra)), "an expression is not a bare 
column")
+
+    // A GetStructField chain IS a column reference, so it is ignored like any 
other column slot.

Review Comment:
   **Finding 35.** A few comments still describe the code before 
`ArgumentShape.Expr` and `pairReducers`:
   - Here: a `GetStructField` chain is an `Expr` shape now, not a column slot 
that identity ignores. And the assertion compares `sf` with itself, so it pins 
nothing. Two assertions would pin the rule: one against a second struct column 
of the same type, and a negative one against `bucket(4, s)`.
   - `TransformExpressionSuite.scala:84`: "`isSameFunction` ignores the 
arguments". It ignores which column, not the literals or the argument shapes.
   - `partitioning.scala:2513`: `reducersBothWays`'s scaladoc says the lookups 
go through `TransformExpression.reducers`. They go through `pairReducers`, and 
`reducers` is now reached only from tests.
   - `transformFunctions.scala:301`: `LegacyBucketFunction`'s doc says the new 
method's default "falls back to the deprecated int-based API". The default 
throws, and the fallback is Spark's dispatch.
   - `TransformExpression.callArguments` is now just `children`. Inlining it 
saves the reader looking for a difference.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -102,49 +217,207 @@ 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) || {
+      val (r1, r2) = pairReducers(other)
+      r1.isDefined || r2.isDefined
+    }
+
+  /**
+   * Extract all literal parameters of this transform as V2 [[V2Literal]]s, 
preserving each value's
+   * internal representation and its `DataType`, with no coercion. The 
generalized reducer is asked
+   * only when they match the declared input types 
([[literalParamsMatchInputTypes]]); the
+   * deprecated one reads a single `IntegerType` parameter as an `Int`. 
Memoized.
+   *
+   * Examples:
+   *   bucket(4, col)        => [Literal(4, IntegerType)]
+   *   truncate(col, 3)      => [Literal(3, IntegerType)]
+   *   days(col)             => []  (no literals)
+   */
+  private lazy val extractParameters: Array[V2Literal[_]] =
+    literalChildren.map(l => LiteralValue(l.value, l.dataType): 
V2Literal[_]).toArray
+
+  /**
+   * Whether every literal parameter has the type the bound function declares 
at its position in
+   * `inputTypes()`. Asked before the generalized reducer, which gets the 
literals' values without
+   * Analyzer type coercion: a literal of another type (a legal implicit cast 
under
+   * [[BoundFunction]]) would be handed to a connector that reads it as the 
declared type. Then the
+   * generalized overload counts as not implemented, and the other overloads, 
which read no literal
+   * by type, may still be asked. A literal past the declared arity has no 
declared type to compare
+   * against, e.g. for an arity-flexible function. Column arguments are not 
checked, since they are
+   * not passed to the connector; where Spark evaluates a transform, 
[[evaluableFunction]] checks
+   * every argument.
+   */
+  lazy val literalParamsMatchInputTypes: Boolean = {
+    val declaredTypes = function.inputTypes()
+    children.zipWithIndex.forall {
+      case (l: Literal, i) => i >= declaredTypes.length || l.dataType == 
declaredTypes(i)
+      case _ => true
     }
   }
 
   /**
-   * Return a [[Reducer]] for this transform expression on another
-   * on the transform expression.
-   * <p>
-   * A [[Reducer]] exists for a transform expression function if it is
-   * 'reducible' on the other expression function.
-   * <p>
-   * @return reducer function or None if not reducible on the other transform 
expression
+   * Whether each position holds a literal on both sides, a bare column on 
both sides, the same
+   * nested transform on both sides, or the same expression of one column on 
both sides (e.g.
+   * `b + 1` and `c + 1`, or `s.a` and `t.a`). These are the shapes 
[[functionId]] tells apart, and
+   * a nested transform is compared as it does, by identity, so two instances 
of one function bound
+   * for two scans line up. A pair this admits differs at most in literal 
values and arity, which
+   * the connector reducer decides.
    */
-  def reducers(other: TransformExpression): Option[Reducer[_, _]] = {
-    (function, other.function) match {
-      case(e1: ReducibleFunction[_, _], e2: ReducibleFunction[_, _]) =>
-        reducer(e1, numBucketsOpt, e2, other.numBucketsOpt)
-      case _ => None
+  private def sameArgumentLayout(other: TransformExpression): Boolean =
+    children.zip(other.children).forall {
+      case (_: Literal, _: Literal) => true
+      case (_: Attribute, _: Attribute) => true
+      case (t1: TransformExpression, t2: TransformExpression) => 
t1.isSameFunction(t2)
+      case (c1, c2) => TransformExpression.sameShape(c1, c2)
+    }
+
+  /**
+   * Whether no literal parameter is null or has an array, map, struct or UDT 
type; those are not
+   * passed to a connector reducer. Other scalars, such as intervals, are.
+   */
+  private def literalParamsPassable: Boolean =
+    literalChildren.forall(l => l.value != null && (l.dataType match {
+      case _: ArrayType | _: MapType | _: StructType | _: UserDefinedType[_] 
=> false
+      case _ => true
+    }))
+
+  /**
+   * Return a [[Reducer]] that maps this transform's partition keys onto 
`other`'s, or None if there
+   * is none: when either function is not a [[ReducibleFunction]], when the 
argument layouts or
+   * literal parameters rule a reducer out, or when the connector reports it 
is not reducible.
+   * Handles both parameterized (bucket, truncate) and non-parameterized 
(days, hours) functions.
+   *
+   * This answers one direction only, so it must not decide a pair: a 
direction that threw would
+   * look merely not reducible, and the other direction like a one-side 
reduce. Use
+   * [[pairReducers]].
+   */
+  private[sql] def reducers(other: TransformExpression): Option[Reducer[_, _]] 
=
+    TransformExpression.reducerOf(reducerOutcome(other))
+
+  /**
+   * Both directions' reducers, `reducers(other)` and `other.reducers(this)`, 
or `(None, None)` when
+   * either direction's reducer threw: then the pair is not reducible at all 
and shuffles. Reading a
+   * thrown direction as merely "not reducible" would leave the other 
direction looking like a
+   * one-side reduce, which is only right for a reducer that satisfies 
`r(f1(x)) = f2(x)`; a
+   * two-sided one such as a gcd of bucket counts would then pair keys from 
two different spaces.
+   *
+   * For the same reason, a reducer in one direction counts only if the other 
direction answered,
+   * by returning a reducer or `null`. A direction that implements no reducer, 
or was not asked
+   * because its literal types differ, says nothing about whether this one is 
one-sided, so the
+   * pair is `(None, None)` too.
+   *
+   * Also `(None, None)` when either side has no identity, since a reduce 
could be neither recorded
+   * (`reducedTogetherWith`) nor reported for it. `sameArgumentLayout` already 
refuses every such
+   * pair; deciding it here keeps `isCompatible` and `reducersBothWays` from 
disagreeing on one.
+   */
+  def pairReducers(other: TransformExpression)
+      : (Option[Reducer[_, _]], Option[Reducer[_, _]]) = {
+    import TransformExpression._
+    if (functionId.isEmpty || other.functionId.isEmpty) return (None, None)
+    (reducerOutcome(other), other.reducerOutcome(this)) match {
+      case (Threw(_, _), _) | (_, Threw(_, _)) => (None, None)
+      case (Reducible(_), Unimplemented | LiteralTypesDiffer) |
+           (Unimplemented | LiteralTypesDiffer, Reducible(_)) => (None, None)
+      case (o1, o2) => (reducerOf(o1), reducerOf(o2))
     }
   }
 
-  // Return a Reducer for a reducible function on another reducible function
-  private def reducer(
-      thisFunction: ReducibleFunction[_, _],
-      thisNumBucketsOpt: Option[Int],
-      otherFunction: ReducibleFunction[_, _],
-      otherNumBucketsOpt: Option[Int]): Option[Reducer[_, _]] = {
-    val res = (thisNumBucketsOpt, otherNumBucketsOpt) match {
-      case (Some(numBuckets), Some(otherNumBuckets)) =>
-        thisFunction.reducer(numBuckets, otherFunction, otherNumBuckets)
-      case _ => thisFunction.reducer(otherFunction)
+  /** What probing the connector for a reducer onto `other` gave, logged when 
it failed. */
+  private def reducerOutcome(other: TransformExpression): 
TransformExpression.Outcome = {
+    import TransformExpression._
+    val thisFunction: ReducibleFunction[_, _] = function match {
+      case f: ReducibleFunction[_, _] => f
+      case _ => return NotReducible
+    }
+    val otherFunction: ReducibleFunction[_, _] = other.function match {
+      case o: ReducibleFunction[_, _] => o
+      case _ => return NotReducible
+    }
+    if (!sameArgumentLayout(other) || !literalParamsPassable || 
!other.literalParamsPassable) {
+      return NotReducible
+    }
+
+    val thisParams = extractParameters
+    val otherParams = other.extractParameters
+    val thisName = function.canonicalName()
+
+    // A single IntegerType parameter on each side is the shape the deprecated
+    // reducer(int, ..., int) overload accepts. Null parameters were refused 
above.
+    def isSingleInt(p: Array[V2Literal[_]]): Boolean = {
+      p.length == 1 && p(0).dataType == IntegerType
+    }
+
+    // Connector code that throws, a `LinkageError` included, e.g. a 
`NoClassDefFoundError` for a
+    // missing dependency, makes the outcome `Threw`, so the pair is not 
reducible rather than
+    // failing the query. `Try` alone would let a `LinkageError` through. 
`ownCode` says whose code
+    // it is, see `Threw`.
+    def guarded(outcome: => Outcome, ownCode: Boolean = true): Outcome =
+      try outcome catch {
+        case e @ (NonFatal(_) | _: LinkageError) => Threw(e, ownCode)
+      }
+
+    // Probe one reducer overload into an Outcome. Pure -- logging is decided 
once, below.
+    def probe(call: => Reducer[_, _]): Outcome = guarded {
+      try Option(call).fold[Outcome](NotReducible)(Reducible(_)) catch {
+        case _: UnsupportedOperationException => Unimplemented
+      }
+    }
+
+    // Prefer the generalized overload. It reads its literal parameters by 
type, so it is asked only
+    // when they have their declared types; otherwise it counts as not 
implemented. Use another
+    // overload only if the generalized one is not implemented; any other 
outcome is final. The type
+    // check reads the connector's `inputTypes()`, so it is guarded too.
+    val outcome =
+      guarded {
+        if (!literalParamsMatchInputTypes) {
+          LiteralTypesDiffer
+        } else {
+          // The other side's check runs the other connector's code. A failure 
there is that
+          // side's to report, which the other direction does when it asks; 
here it only vetoes
+          // the pair. `probe` guards the reducer call itself, as this side's 
code.
+          guarded(ownCode = false, outcome =
+            if (!other.literalParamsMatchInputTypes) {
+              LiteralTypesDiffer
+            } else {
+              // A copy of the memoized arrays per call, so a connector cannot 
change them.
+              probe(thisFunction.reducer(thisParams.clone(), otherFunction, 
otherParams.clone()))
+            })
+        }
+      } match {
+        // A parameterless pair falls back to the parameterless overload.
+        case Unimplemented if thisParams.isEmpty && otherParams.isEmpty =>
+          probe(thisFunction.reducer(otherFunction))
+        // The deprecated overload is documented for bucket against bucket, 
and master offered it
+        // only a pair resolved from two V2 `bucket` transforms, see 
`fromBucketTransform`.
+        // If that finds nothing either, the outcome stays why the generalized 
one was not asked.
+        case skipped @ (Unimplemented | LiteralTypesDiffer)
+            if fromBucketTransform && other.fromBucketTransform &&
+              isSingleInt(thisParams) && isSingleInt(otherParams) &&
+              thisName == other.function.canonicalName() =>

Review Comment:
   **Finding 32.** This compares two `canonicalName()` calls. 
`BoundFunction.canonicalName()`'s default returns a fresh random UUID on every 
call, "so a function is never equivalent to another, even itself". So a 
connector that implements only the deprecated overload and keeps that default 
never passes here, even for a pair of one function. On master it got the reduce.
   
   Measured on this head and on master. The fixture is a singleton bucket 
function that overrides only `reducer(int, ReducibleFunction, int)` (gcd, 
checking `otherFunc == this`) and not `canonicalName()`. It joins `bucket(b1, 
store_id)` against `bucket(b2, store_id)` under `allowCompatibleTransforms`:
   
   ```
   (b1, b2)    master        this head
   (4, 2)      shuffles=0    shuffles=2
   (2, 4)      shuffles=0    shuffles=2
   (6, 4)      shuffles=0    shuffles=2
   ```
   
   The check is there for `CarelessLookalikeFunction`, which this PR has a 
reason to refuse. Function equality answers the same question for the 
default-name case, and `TransformExpression` already relies on it since 
SPARK-58769:
   
   ```suggestion
                 (thisName == other.function.canonicalName() || function == 
other.function) =>
   ```
   
   With it the three pairs above plan no shuffle again, and the PR's suites, 
the careless-lookalike tests included, stay green. The "implements no reducer" 
WARN such a pair logs today is part of 15's rewording.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

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


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

Reply via email to