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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -58,27 +95,84 @@ case class TransformFunctionId(canonicalName: String, 
numBucketsOpt: Option[Int]
  *                    exactly that, and names the other half of the pairing 
that produced the space,
  *                    which is the only thing that tells two such key spaces 
apart. See
  *                    `KeyedShuffleSpec.reducersBothWays`, which is the only 
producer.
+ * @param fromBucketTransform whether this was resolved from a V2 
`bucket(numBuckets, col)`
+ *                            transform. Only a pair of such transforms is 
offered the deprecated
+ *                            `ReducibleFunction.reducer(int, 
ReducibleFunction, int)`, which is
+ *                            documented for the bucket function. Nothing else 
tells a bucket
+ *                            apart: a `truncate(width, col)` has the same 
layout, and the bound
+ *                            function may report any name. Not part of the 
transform's identity
+ *                            (`functionId`), nor of its plan string, but part 
of case-class
+ *                            equality, since a marked and an unmarked 
transform are offered
+ *                            different reducers. Every production transform 
is resolved by
+ *                            `V2ExpressionUtils`, which sets it, and rebuilt 
with `copy`, which
+ *                            keeps it.
  */
 case class TransformExpression(
     function: BoundFunction,
     children: Seq[Expression],
-    numBucketsOpt: Option[Int] = None,
-    reducedWith: Option[TransformFunctionId] = None) extends Expression {
+    reducedWith: Option[TransformFunctionId] = None,
+    fromBucketTransform: Boolean = false) extends Expression {
 
   override def nullable: Boolean = true
 
-  /** Drops the trailing `reducedWith` when it is unset, so the ordinary form 
is unchanged. */
+  /** The function and the children, and `reducedWith` when it is set. */
   override protected def stringArgs: Iterator[Any] =
-    if (reducedWith.isEmpty) super.stringArgs.take(productArity - 1) else 
super.stringArgs
+    Iterator(function, children) ++ 
Option.when(reducedWith.isDefined)(reducedWith).iterator
 
-  /** The identity of this expression's transform function. */
-  lazy val functionId: TransformFunctionId =
-    TransformFunctionId(function.canonicalName(), numBucketsOpt)
+  /**
+   * Extract literal children (constant parameters) from this transform. These 
are constant
+   * arguments like the bucket count in `bucket(n, col)` or the width in 
`truncate(col, width)`.
+   * Positions are dropped, so this is for handing parameters to a connector 
reducer or naming
+   * them in a message, NOT for identity -- see [[functionId]] and
+   * [[TransformFunctionId.argumentShapes]].
+   */
+  private[sql] lazy val literalChildren: Seq[Literal] =
+    children.collect { case l: Literal => l }
 
   /**
-   * Whether this [[TransformExpression]] has the same semantics as `other`.
-   * For instance, `bucket(32, c)` is equal to `bucket(32, d)`, but not to 
`bucket(16, d)` or
-   * `year(c)`.
+   * Rewrites this transform's column arguments with `rewriteColumn`, leaving 
its literal parameters
+   * untouched.
+   *
+   * Since literal parameters (the bucket count, the truncate width) live in 
`children` rather than
+   * in a field of their own, any path that rewrites a transform's children 
has to skip them. A
+   * parameter is not an aliasable value: substituting it changes what the 
transform computes, and
+   * gives the transform a second reference, so 
`KeyedShuffleSpec.keyPositions` maps it to no
+   * cluster key and SPJ is silently lost. Use it for any retargeting of a 
partition transform.
+   *
+   * Callers: `KeyedShuffleSpec.rebuiltOver`, which rebuilds a transform over 
the other side's key,
+   * and `GroupPartitionsExec`, which rebuilds a reduced expression over each 
member's argument.
+   */
+  def rewriteColumnSlots(rewriteColumn: Expression => Expression): 
TransformExpression =

Review Comment:
   **Finding 38.** 29's fix 
([r4589254145](https://github.com/apache/spark/pull/55885#discussion_r4589254145))
 put "a reduced transform's partner follows its own column shape" into 
`withNewChildrenInternal`. This method rebuilds with a bare `copy`, so it skips 
that, and `GroupPartitionsExec.scala:707-708` repeats the partner update by 
hand. The doc above asks callers to use this "for any retargeting of a 
partition transform". So the next caller that retargets a reduced transform 
over an expression through it keeps a column partner, and the two sides of that 
reduce stop matching in `hasSameReducedKeys`.
   
   Going through `withNewChildren` keeps the rule in one place:
   
   ```scala
     def rewriteColumnSlots(rewriteColumn: Expression => Expression): 
TransformExpression =
       withNewChildren(children.map {
         case l: Literal => l
         case c => rewriteColumn(c)
       }).asInstanceOf[TransformExpression]
   ```
   
   `GroupPartitionsExec` then needs only `reduced.rewriteColumnSlots(_ => 
argument)`. With both changes, `TransformExpressionSuite`, `ShuffleSpecSuite`, 
`KeyGroupedPartitioningSuite`, `GroupPartitionsExecSuite` and 
`ProjectedOrderingAndPartitioningSuite` pass.
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala:
##########
@@ -760,6 +779,16 @@ case class EnsureRequirements(
     if (!compatibleAsIs && !pushCommonValues) {
       return None
     }
+    // The pair was admitted through `areKeysCompatible`, which may have 
relied on a reducer, and
+    // the push branch asks the connector for the reducers again. The answers 
can differ, e.g. a
+    // failure that does not repeat on every call, which reads as not 
reducible. A position whose
+    // transforms are different functions then has nothing to put its two 
sides in one key space,
+    // and merging their raw keys would pair partitions that do not hold the 
same rows. Shuffle
+    // instead.
+    lazy val reducers = leftSpec.reducersBothWays(rightSpec)
+    if (pushCommonValues && !reducersCoverAdmittedPositions(leftSpec, 
rightSpec, reducers)) {

Review Comment:
   **Finding 37.** This checks that some reducer exists at each admitted 
position, not that the second answer is the one the pair was admitted on. 
`pairReducers` reads `(Reducible, NotReducible)` as a one-side reduce. So a 
second answer of `null` for one side, without an exception, passes this guard, 
and that side is reduced alone.
   
   Measured with this PR's test "a pair admitted through a reducer shuffles if 
the reducer is gone when asked again". I changed 
`SecondAskFailingBucketFunction` to return `null` for the `bucket(12)` side on 
the second ask instead of throwing. The join then returns 16 of 48 rows, since 
the `bucket(16)` keys reduced onto 4 are merged against the raw `bucket(12)` 
keys.
   
   Master pairs this wrongly too, with no guard at all, so it is not a 
regression. But it is the case the guard is there for. Deciding the pair once 
closes it, the first option in 
[30](https://github.com/apache/spark/pull/55885#discussion_r4589254158): carry 
the reducers the pair was admitted on into the push branch, or memoize 
`pairReducers` per pair. Then this guard, its helper and the stack check in the 
fixture can go, and a planning pass calls the connector once per pair.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -393,6 +698,85 @@ 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 class and 
kind of failure,
+   * since every planning pass and AQE re-plan asks the pair again, and at 
DEBUG, with the stack
+   * trace, every time. Keyed by class rather than `canonicalName()`, whose 
default is a fresh name
+   * on every call.
+   */
+  private def logReducerThrew(function: BoundFunction, name: String, e: 
Throwable): Unit = {

Review Comment:
   **Finding 39.** The three reducer log helpers print `name`, which every 
caller passes as `function.canonicalName()`. 34 moved their keys to the class 
because the default is a fresh UUID per call, but the text still prints it. A 
connector that keeps the default then logs "V2 function 3f0c9a7e-... implements 
no reducer", with another UUID on each DEBUG line, and nothing says which 
function it is. The other log lines in this object use 
`transformLabel(function)`, which prints `name()` and the class. Using it in 
all three would fix it, and it can go with 15's rewording.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/catalog/functions/transformFunctions.scala:
##########
@@ -409,20 +729,371 @@ object SignedZerosFunction extends 
ScalarFunction[Double] {
 }
 
 object UnboundTruncateFunction extends UnboundFunction {
-  override def bind(inputType: StructType): BoundFunction = TruncateFunction
+  override def bind(inputType: StructType): BoundFunction = {
+    if (inputType.size == 2) {
+      inputType.head.dataType match {
+        case StringType => TruncateFunction
+        case IntegerType => IntegerTruncateFunction
+        case _ =>
+          throw new UnsupportedOperationException(
+            s"'truncate' does not support data type: 
${inputType.head.dataType}")
+      }
+    } else {
+      throw new UnsupportedOperationException(
+        "'truncate' requires exactly 2 arguments: (column, width)")
+    }
+  }
+
   override def description(): String = name()
   override def name(): String = "truncate"
 }
 
-object TruncateFunction extends ScalarFunction[UTF8String] {
+/**
+ * Truncate transform for String type.
+ * Follows Iceberg spec: truncate(str, L) = str[0:L]
+ *
+ * Implements ReducibleFunction: ANY two different widths are compatible.
+ * The reducer uses the smaller width.
+ */
+object TruncateFunction
+    extends ScalarFunction[UTF8String]
+    with ReducibleFunction[UTF8String, UTF8String] {
   override def inputTypes(): Array[DataType] = Array(StringType, IntegerType)
   override def resultType(): DataType = StringType
   override def name(): String = "truncate"
-  override def canonicalName(): String = name()
+  override def canonicalName(): String = "truncate(string)"
   override def toString: String = name()
   override def produceResult(input: InternalRow): UTF8String = {
+    // A one-side shuffle onto a truncate layout evaluates this on every row, 
null keys included.
+    if (input.isNullAt(0)) return null
     val str = input.getUTF8String(0)
-    val length = input.getInt(1)
-    str.substring(0, length)
+    val width = input.getInt(1)
+    str.substring(0, width)
+  }
+
+  override def reducer(
+      thisParams: Array[Literal[_]],
+      otherFunc: ReducibleFunction[_, _],
+      otherParams: Array[Literal[_]]): Reducer[UTF8String, UTF8String] = {
+
+    if (otherFunc == TruncateFunction && thisParams.length == 1 && 
otherParams.length == 1) {
+      val thisWidth = thisParams(0).value().asInstanceOf[Int]
+      val otherWidth = otherParams(0).value().asInstanceOf[Int]
+      val smallerWidth = math.min(thisWidth, otherWidth)
+
+      if (smallerWidth != thisWidth) {
+        return TruncateReducer(smallerWidth)
+      }
+    }
+    null
+  }
+}
+
+case class TruncateReducer(width: Int) extends Reducer[UTF8String, UTF8String] 
{
+  override def reduce(value: UTF8String): UTF8String = {
+    if (value == null) null else value.substring(0, width)
+  }
+  override def resultType(): DataType = StringType
+  override def displayName(): String = s"truncate($width)"
+}
+
+/**
+ * Truncate transform for Integer type.
+ * Follows Iceberg spec: truncate(value, W) = value - (((value % W) + W) % W), 
which snaps `value`
+ * down to a multiple of `W`.
+ *
+ * Implements ReducibleFunction: truncate(v, W1) and truncate(v, W2) are 
always reducible onto a
+ * common coarser grid of multiples of lcm(W1, W2). The finer side (whose 
width does not already
+ * equal the lcm) reduces by snapping to that grid; when W2 is a multiple of 
W1 the lcm is simply
+ * the coarser width W2.
+ */
+object IntegerTruncateFunction
+    extends ScalarFunction[Int]
+    with ReducibleFunction[Int, Int] {
+  override def inputTypes(): Array[DataType] = Array(IntegerType, IntegerType)
+  override def resultType(): DataType = IntegerType
+  override def name(): String = "truncate"
+  override def canonicalName(): String = "truncate(int)"
+  override def toString: String = name()
+  override def produceResult(input: InternalRow): Int = 
truncate(input.getInt(0), input.getInt(1))

Review Comment:
   **Finding 40.** This reads `input.getInt(0)` with no null check. The 
function has no magic `invoke`, so Spark calls it through 
`ApplyFunctionExpression`, which reuses one row, and a null key then reads as 
the previous row's value. `TruncateFunction` above checks for null for this 
reason: "A one-side shuffle onto a truncate layout evaluates this on every row, 
null keys included". The new "an unpartitioned side is shuffled onto integer 
truncate" test evaluates this on every row of the shuffled side, but it has no 
null ids today. A boxed result type, `ScalarFunction[Integer]`, would let it 
return null.
   



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