dongjoon-hyun commented on code in PR #59760:
URL: https://github.com/apache/spark/pull/59760#discussion_r4544653349


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -167,30 +177,219 @@ case class TransformExpression(
     copy(children = newChildren)
 
   /**
-   * The scalar function call this transform stands for, with the bucket count 
prepended as a
-   * literal argument. `None` when the bound function is not a 
[[ScalarFunction]], and also when a
-   * join reduced this expression's keys, since then the call no longer 
computes them. Evaluating it
-   * to place a row would send the row to a partition it does not belong to. 
That second arm is a
-   * local gate. No caller reaches it today, because every consumer of a 
reduced partitioning
-   * refuses it first, and the write path never sees one.
+   * The bound function, when Spark could call it for this transform: a 
[[ScalarFunction]], over
+   * keys no join reduced. See [[resolvedFunction]].
    */
-  lazy val resolvedFunction: Option[Expression] = function match {
-    case scalarFunc: ScalarFunction[_] if reducedWith.isEmpty =>
-      val arguments = numBucketsOpt.fold(children)(n => Literal(n) +: children)
-      Some(V2ExpressionUtils.resolveScalarFunction(scalarFunc, arguments))
+  private def scalarFunction: Option[ScalarFunction[_]] = function match {
+    case scalarFunc: ScalarFunction[_] if reducedWith.isEmpty => 
Some(scalarFunc)
     case _ => None
   }
 
-  override def eval(input: InternalRow): Any = resolvedFunction match {
-    case Some(fn) => fn.eval(input)
-    case None => throw QueryExecutionErrors.cannotEvaluateExpressionError(this)
+  /** The arguments of the call: the bucket count, if any, as a literal, then 
the children. */
+  private def callArguments: Seq[Expression] =
+    numBucketsOpt.fold(children)(n => Literal(n) +: children)
+
+  /**
+   * The scalar function call this transform stands for, over its arguments as 
they are. `None`
+   * when the bound function is not a [[ScalarFunction]], and also when a join 
reduced this
+   * expression's keys, since then the call no longer computes them. 
Evaluating it to place a row
+   * would send the row to a partition it does not belong to. That second arm 
is a local gate. No
+   * caller reaches it today, because every consumer of a reduced partitioning 
refuses it first,
+   * and the write path never sees one. The write path 
(`DistributionAndOrderingUtils`) casts the
+   * arguments to the function's input types itself. `eval` uses 
[[evaluableFunction]] instead.
+   */
+  lazy val resolvedFunction: Option[Expression] =
+    scalarFunction.map(V2ExpressionUtils.resolveScalarFunction(_, 
callArguments))
+
+  /**
+   * The call `eval` runs: [[resolvedFunction]], with each argument at the 
type the function
+   * declares for it in `inputTypes()`, see `atDeclaredType` for which 
arguments suit. `None` when
+   * an argument does not, when there is another number of arguments, when the 
call fails to
+   * resolve, and wherever `resolvedFunction` is `None`. `eval` rethrows a 
failure to resolve. A
+   * storage-partitioned join shuffles instead of evaluating such a transform, 
so each case but
+   * reduced keys is logged once, see `logNotScalar`, `logArgumentsMismatch` 
and
+   * `logCannotResolve`.
+   */
+  def evaluableFunction: Option[Expression] = evaluableFunctionAttempt match {
+    case Success(call) => call
+    case _ => None
+  }
+
+  /**
+   * The call, or why it failed to resolve, e.g. a `ScalarFunction` that 
inherits `produceResult`
+   * from a base class, connector code that throws, or a `LinkageError` for a 
connector class whose
+   * dependency is missing, which the planner would otherwise hit for a layout 
it does not pick.
+   * Computed and logged once, since a `lazy val` whose initializer throws 
runs it again on each
+   * access. Not serialized, so an executor resolves it again rather than 
receiving the call (or
+   * the failure) the driver resolved while planning.
+   */
+  @transient private lazy val evaluableFunctionAttempt: 
Try[Option[Expression]] =
+    try Success(resolveEvaluableFunction()) catch {
+      case e @ (NonFatal(_) | _: LinkageError) =>
+        TransformExpression.logCannotResolve(function, e)
+        Failure(e)
+    }
+
+  private def resolveEvaluableFunction(): Option[Expression] = scalarFunction 
match {
+    case None =>
+      // Reduced keys are the planner's own doing, so only a function Spark 
cannot call is logged.
+      if (!function.isInstanceOf[ScalarFunction[_]]) 
TransformExpression.logNotScalar(function)
+      None
+    case Some(scalarFunc) =>
+      val arguments = callArguments
+      val declaredTypes = scalarFunc.inputTypes().toSeq
+      val typed = arguments.zip(declaredTypes).map { case (argument, 
declaredType) =>
+        TransformExpression.atDeclaredType(argument, declaredType)
+      }
+      if (arguments.length == declaredTypes.length && 
typed.forall(_.isDefined)) {
+        val call = V2ExpressionUtils.resolveScalarFunction(scalarFunc, 
typed.flatten)
+        TransformExpression.methodLookupFailure(call) match {
+          case None => Some(call)
+          case failure =>
+            // The types the call was resolved over, i.e. after the casts of 
narrower arguments.
+            TransformExpression.logArgumentsMismatch(scalarFunc, 
typed.flatten.map(_.dataType),
+              declaredTypes, failure)
+            None
+        }
+      } else {
+        TransformExpression.logArgumentsMismatch(scalarFunc, 
arguments.map(_.dataType),
+          declaredTypes, None)
+        None
+      }
+  }
+
+  override def eval(input: InternalRow): Any = evaluableFunctionAttempt match {
+    case Success(Some(call)) => call.eval(input)
+    case Failure(e) => throw e
+    case _ => throw QueryExecutionErrors.cannotEvaluateExpressionError(this)
   }
 
   override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): 
ExprCode =
     throw QueryExecutionErrors.cannotGenerateCodeForExpressionError(this)
 }
 
-object TransformExpression {
+object TransformExpression extends Logging {
+  /**
+   * What was logged once, keyed by its kind: `notScalar:functionClass`,
+   * `mismatch:functionClass:argumentTypes:declaredTypes` and its 
`unreachable:` counterpart for a
+   * method that cannot be invoked, since one class can declare other input 
types per instance,
+   * e.g. one per column type, and `failure:functionClass:failureClass`, so 
that a function class
+   * that fails in another way is warned about again.
+   */
+  private val loggedOnce: java.util.Set[String] = 
ConcurrentHashMap.newKeySet[String]()
+
+  /** Runs `log` the first time `key` is seen. */
+  private def logOnce(key: String)(log: => Unit): Unit = if 
(loggedOnce.add(key)) log

Review Comment:
   **[34] `logOnce` takes the key even when its line is not logged.**
   
   `loggedOnce.add(key)` runs before `logInfo` or `logWarning` checks the level 
(`Logging.scala:189-190`). So if INFO is off the first time a function class 
and its types are refused, the key is taken without a line, and that line never 
appears in this JVM, even after INFO is turned on. For example, a driver 
started with `spark.log.level=WARN` runs an SPJ query over a `bucket` whose 
function declares `(INT, INT)` for a `BIGINT` column. After 
`spark.sparkContext.setLogLevel("INFO")`, the same query still shuffles both 
sides with no line saying why. The `failure:` kind behaves the same under 
`ERROR`.
   
   The add-then-log shape came from [finding 
10](https://github.com/apache/spark/pull/59760#discussion_r4435873420) and my 
[item 16](https://github.com/apache/spark/pull/59760#discussion_r4463685247), 
and neither looked at the level. Could the key be added only when the level is 
on, e.g. `log.isInfoEnabled && loggedOnce.add(key)`, and `log.isWarnEnabled` 
for `failure:`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2586,24 +2624,57 @@ case class KeyedShuffleSpec(
         // `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.
+        // children shuffled onto it. Whether Spark can evaluate it is 
`canEvaluatePartitioning`.
         case t: TransformExpression => argumentsAreColumns(t)
         case _ => false
       } &&
       // Shuffling another child onto these keys evaluates the partition 
expressions per row to
       // decide where each row goes, and reduced keys are not what those 
expressions compute.
       partitioning.expressionsDescribeKeys
 
+  /** Whether Spark can evaluate each transform of this layout, see 
`canEvaluate`. */
+  override lazy val canEvaluatePartitioning: Boolean = 
partitioning.expressions.forall(canEvaluate)
+
   override def createPartitioning(clustering: Seq[Expression]): Partitioning = 
{
     assert(clustering.size == distribution.clustering.size,
       "Required distributions of join legs should be the same size.")
-
     val newExpressions = partitioning.expressions.zip(keyPositions).map {
       case (te: TransformExpression, positionSet) =>
         // `canCreatePartitioning` admits only a template over bare columns, 
see there.
         rebuiltOver(te, clustering(positionSet.head))
       case (_, positionSet) => clustering(positionSet.head)
     }
+    // The child shuffled onto this layout is placed by evaluating what is 
built here, which would
+    // fail on an executor. A caller has to ask `canEvaluatePartitioning` 
first, which answers for
+    // this layout's own keys, so a caller that does not is a bug.
+    assert(canEvaluatePartitioning,
+      s"Cannot shuffle a child onto a layout Spark cannot evaluate: 
${partitioning.expressions}")
+    // A join's keys share their types, apart from nullability and field 
names, so that answers
+    // for what is built too. A Pandas or Arrow cogroup's need not 
(SPARK-60782). Its other key can
+    // be one the layout's function does not take, e.g. a `BIGINT` against a 
function declaring
+    // `INT`, or a string of another collation. Or one the function takes, but 
stored otherwise than
+    // the layout's column, e.g. an `INT` widened to a `BIGINT` column's 
declared type: every row is
+    // then placed, but the cogroup pairs its groups by comparing the two 
sides' key rows, so they
+    // do not pair, or the cogroup fails. Falling back to a hash shuffle would 
pair them wrongly
+    // too. So such a child fails here, while planning, with an error that 
names the key's type.
+    // This covers transform positions only. An identity position is rebuilt 
over the other key
+    // whatever its type, and a layout Spark cannot evaluate takes the hash 
shuffle. Both behave as
+    // before this check, and are left to SPARK-60782.
+    partitioning.expressions.zip(keyPositions).zip(newExpressions).foreach {
+      case ((te: TransformExpression, positionSet), t: TransformExpression)
+          if !canEvaluate(t) || !positionSet.forall { p =>
+            TransformExpression.keysStoredAlike(clustering(p).dataType, 
te.references.head.dataType)
+          } =>
+        // `name()` and `inputTypes()` are connector code, which must not 
replace this error.
+        val functionClass = t.function.getClass.getName
+        val name = TransformExpression.orElse(t.function.name(), functionClass)
+        throw QueryExecutionErrors.storagePartitionJoinKeyTypeMismatchError(
+          t.numBucketsOpt.fold(name)(n => s"$name($n)"),
+          te.references.head.dataType,
+          TransformExpression.orElse(t.function.inputTypes().toSeq, Nil),
+          t.children.head)

Review Comment:
   **[33] The key-type error names the key at the column's first cluster 
position, which may not be the key that failed.**
   
   This is where the change for [item 
21](https://github.com/apache/spark/pull/59760#discussion_r4532209397) meets 
the per-position check from [item 
17](https://github.com/apache/spark/pull/59760#discussion_r4532209360). 
L2665-2667 asks `keysStoredAlike` of the key at every position in 
`positionSet`, but the error names `t.children.head`, the key at 
`positionSet.head` that L2644 rebuilt `t` over, with that key's type. So when a 
column sits at two cluster positions and only the later key fails, the message 
names a key that passes.
   
   For example, with `spark.sql.sources.v2.bucketing.shuffle.enabled=true`, 
take a Pandas cogroup `t1.groupby("c", "c").cogroup(df2.groupby("x", "y"))`, 
where `t1` reports `bucket(4, c)` over `c INT` with a function declaring `(INT, 
INT)`, `x` is an `INT` and `y` a `BIGINT`. `keyPositions` maps `bucket(4, c)` 
to `{0, 1}`, `t` is `bucket(4, x)`, which Spark can evaluate, and position 1 
fails. From reading, the error then says (wrapped):
   
   ```
   [STORAGE_PARTITION_JOIN_KEY_TYPE_MISMATCH] Cannot shuffle a side onto the 
other side's storage
   partitioning: its key "x" of type "INT" does not match the partition 
transform bucket(4) over a
   column of type "INT", which declares the input types ("INT", "INT"). ...
   ```
   
   That is an `INT` key that does not match an `INT` column, and `y` is not 
named. A join cannot get here, since its keys at those positions share a type. 
Could the error name the first key that fails `keysStoredAlike`, i.e. 
`clustering(p)` and its type, and keep `t.children.head` for the 
`!canEvaluate(t)` case?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2586,24 +2624,57 @@ case class KeyedShuffleSpec(
         // `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.
+        // children shuffled onto it. Whether Spark can evaluate it is 
`canEvaluatePartitioning`.
         case t: TransformExpression => argumentsAreColumns(t)
         case _ => false
       } &&
       // Shuffling another child onto these keys evaluates the partition 
expressions per row to
       // decide where each row goes, and reduced keys are not what those 
expressions compute.
       partitioning.expressionsDescribeKeys
 
+  /** Whether Spark can evaluate each transform of this layout, see 
`canEvaluate`. */
+  override lazy val canEvaluatePartitioning: Boolean = 
partitioning.expressions.forall(canEvaluate)
+
   override def createPartitioning(clustering: Seq[Expression]): Partitioning = 
{
     assert(clustering.size == distribution.clustering.size,
       "Required distributions of join legs should be the same size.")
-
     val newExpressions = partitioning.expressions.zip(keyPositions).map {
       case (te: TransformExpression, positionSet) =>
         // `canCreatePartitioning` admits only a template over bare columns, 
see there.
         rebuiltOver(te, clustering(positionSet.head))
       case (_, positionSet) => clustering(positionSet.head)
     }
+    // The child shuffled onto this layout is placed by evaluating what is 
built here, which would
+    // fail on an executor. A caller has to ask `canEvaluatePartitioning` 
first, which answers for
+    // this layout's own keys, so a caller that does not is a bug.
+    assert(canEvaluatePartitioning,
+      s"Cannot shuffle a child onto a layout Spark cannot evaluate: 
${partitioning.expressions}")
+    // A join's keys share their types, apart from nullability and field 
names, so that answers
+    // for what is built too. A Pandas or Arrow cogroup's need not 
(SPARK-60782). Its other key can
+    // be one the layout's function does not take, e.g. a `BIGINT` against a 
function declaring
+    // `INT`, or a string of another collation. Or one the function takes, but 
stored otherwise than
+    // the layout's column, e.g. an `INT` widened to a `BIGINT` column's 
declared type: every row is
+    // then placed, but the cogroup pairs its groups by comparing the two 
sides' key rows, so they
+    // do not pair, or the cogroup fails. Falling back to a hash shuffle would 
pair them wrongly
+    // too. So such a child fails here, while planning, with an error that 
names the key's type.
+    // This covers transform positions only. An identity position is rebuilt 
over the other key
+    // whatever its type, and a layout Spark cannot evaluate takes the hash 
shuffle. Both behave as
+    // before this check, and are left to SPARK-60782.
+    partitioning.expressions.zip(keyPositions).zip(newExpressions).foreach {
+      case ((te: TransformExpression, positionSet), t: TransformExpression)
+          if !canEvaluate(t) || !positionSet.forall { p =>

Review Comment:
   **[35] Nit: a cogroup that fails here first logs that the join "does not 
evaluate" the transform.**
   
   `!canEvaluate(t)` comes first, and `t` is a fresh copy rebuilt over the 
other side's key, so asking it resolves the call and logs its mismatch. For the 
`BIGINT` key in the `(IntegerType, LongType)` row at 
`EnsureRequirementsSuite.scala:1861`, the driver logs at INFO "... declares the 
input types (int, int), which do not take arguments of types (int, bigint), so 
a storage-partitioned join does not evaluate it", which reads as a shuffle 
fallback, and then L2671 throws `STORAGE_PARTITION_JOIN_KEY_TYPE_MISMATCH` for 
the same transform. The line also takes its `mismatch:` key, so a later query 
that does fall back for that function class and those types logs nothing.
   
   Asking `keysStoredAlike` first throws the same error, and skips both the 
resolution and the line whenever the storage check already refuses the key, as 
it does here and for the collation row. A key it takes but the function does 
not, e.g. a nested decimal of more precision, would still log.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -167,30 +177,219 @@ case class TransformExpression(
     copy(children = newChildren)
 
   /**
-   * The scalar function call this transform stands for, with the bucket count 
prepended as a
-   * literal argument. `None` when the bound function is not a 
[[ScalarFunction]], and also when a
-   * join reduced this expression's keys, since then the call no longer 
computes them. Evaluating it
-   * to place a row would send the row to a partition it does not belong to. 
That second arm is a
-   * local gate. No caller reaches it today, because every consumer of a 
reduced partitioning
-   * refuses it first, and the write path never sees one.
+   * The bound function, when Spark could call it for this transform: a 
[[ScalarFunction]], over
+   * keys no join reduced. See [[resolvedFunction]].
    */
-  lazy val resolvedFunction: Option[Expression] = function match {
-    case scalarFunc: ScalarFunction[_] if reducedWith.isEmpty =>
-      val arguments = numBucketsOpt.fold(children)(n => Literal(n) +: children)
-      Some(V2ExpressionUtils.resolveScalarFunction(scalarFunc, arguments))
+  private def scalarFunction: Option[ScalarFunction[_]] = function match {
+    case scalarFunc: ScalarFunction[_] if reducedWith.isEmpty => 
Some(scalarFunc)
     case _ => None
   }
 
-  override def eval(input: InternalRow): Any = resolvedFunction match {
-    case Some(fn) => fn.eval(input)
-    case None => throw QueryExecutionErrors.cannotEvaluateExpressionError(this)
+  /** The arguments of the call: the bucket count, if any, as a literal, then 
the children. */
+  private def callArguments: Seq[Expression] =
+    numBucketsOpt.fold(children)(n => Literal(n) +: children)
+
+  /**
+   * The scalar function call this transform stands for, over its arguments as 
they are. `None`
+   * when the bound function is not a [[ScalarFunction]], and also when a join 
reduced this
+   * expression's keys, since then the call no longer computes them. 
Evaluating it to place a row
+   * would send the row to a partition it does not belong to. That second arm 
is a local gate. No
+   * caller reaches it today, because every consumer of a reduced partitioning 
refuses it first,
+   * and the write path never sees one. The write path 
(`DistributionAndOrderingUtils`) casts the
+   * arguments to the function's input types itself. `eval` uses 
[[evaluableFunction]] instead.
+   */
+  lazy val resolvedFunction: Option[Expression] =
+    scalarFunction.map(V2ExpressionUtils.resolveScalarFunction(_, 
callArguments))
+
+  /**
+   * The call `eval` runs: [[resolvedFunction]], with each argument at the 
type the function
+   * declares for it in `inputTypes()`, see `atDeclaredType` for which 
arguments suit. `None` when
+   * an argument does not, when there is another number of arguments, when the 
call fails to
+   * resolve, and wherever `resolvedFunction` is `None`. `eval` rethrows a 
failure to resolve. A
+   * storage-partitioned join shuffles instead of evaluating such a transform, 
so each case but
+   * reduced keys is logged once, see `logNotScalar`, `logArgumentsMismatch` 
and
+   * `logCannotResolve`.
+   */
+  def evaluableFunction: Option[Expression] = evaluableFunctionAttempt match {
+    case Success(call) => call
+    case _ => None
+  }
+
+  /**
+   * The call, or why it failed to resolve, e.g. a `ScalarFunction` that 
inherits `produceResult`
+   * from a base class, connector code that throws, or a `LinkageError` for a 
connector class whose
+   * dependency is missing, which the planner would otherwise hit for a layout 
it does not pick.
+   * Computed and logged once, since a `lazy val` whose initializer throws 
runs it again on each
+   * access. Not serialized, so an executor resolves it again rather than 
receiving the call (or
+   * the failure) the driver resolved while planning.
+   */
+  @transient private lazy val evaluableFunctionAttempt: 
Try[Option[Expression]] =
+    try Success(resolveEvaluableFunction()) catch {
+      case e @ (NonFatal(_) | _: LinkageError) =>
+        TransformExpression.logCannotResolve(function, e)
+        Failure(e)
+    }
+
+  private def resolveEvaluableFunction(): Option[Expression] = scalarFunction 
match {
+    case None =>
+      // Reduced keys are the planner's own doing, so only a function Spark 
cannot call is logged.
+      if (!function.isInstanceOf[ScalarFunction[_]]) 
TransformExpression.logNotScalar(function)
+      None
+    case Some(scalarFunc) =>
+      val arguments = callArguments
+      val declaredTypes = scalarFunc.inputTypes().toSeq
+      val typed = arguments.zip(declaredTypes).map { case (argument, 
declaredType) =>
+        TransformExpression.atDeclaredType(argument, declaredType)
+      }
+      if (arguments.length == declaredTypes.length && 
typed.forall(_.isDefined)) {
+        val call = V2ExpressionUtils.resolveScalarFunction(scalarFunc, 
typed.flatten)
+        TransformExpression.methodLookupFailure(call) match {
+          case None => Some(call)
+          case failure =>
+            // The types the call was resolved over, i.e. after the casts of 
narrower arguments.
+            TransformExpression.logArgumentsMismatch(scalarFunc, 
typed.flatten.map(_.dataType),
+              declaredTypes, failure)
+            None
+        }
+      } else {
+        TransformExpression.logArgumentsMismatch(scalarFunc, 
arguments.map(_.dataType),
+          declaredTypes, None)
+        None
+      }
+  }
+
+  override def eval(input: InternalRow): Any = evaluableFunctionAttempt match {
+    case Success(Some(call)) => call.eval(input)
+    case Failure(e) => throw e
+    case _ => throw QueryExecutionErrors.cannotEvaluateExpressionError(this)
   }
 
   override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): 
ExprCode =
     throw QueryExecutionErrors.cannotGenerateCodeForExpressionError(this)
 }
 
-object TransformExpression {
+object TransformExpression extends Logging {
+  /**
+   * What was logged once, keyed by its kind: `notScalar:functionClass`,
+   * `mismatch:functionClass:argumentTypes:declaredTypes` and its 
`unreachable:` counterpart for a
+   * method that cannot be invoked, since one class can declare other input 
types per instance,
+   * e.g. one per column type, and `failure:functionClass:failureClass`, so 
that a function class
+   * that fails in another way is warned about again.
+   */
+  private val loggedOnce: java.util.Set[String] = 
ConcurrentHashMap.newKeySet[String]()
+
+  /** Runs `log` the first time `key` is seen. */
+  private def logOnce(key: String)(log: => Unit): Unit = if 
(loggedOnce.add(key)) log
+
+  /**
+   * `value`, or `fallback` when it throws. `name()`, `inputTypes()` and a 
failure's message are
+   * connector code, which can throw as the call did, e.g. a 
`NoClassDefFoundError` for a missing
+   * dependency. A log line or an error message must not fail planning.
+   */
+  private[sql] def orElse[T](value: => T, fallback: => T): T =
+    try value catch { case NonFatal(_) | _: LinkageError => fallback }
+
+  /**
+   * `dataType` for a log line, a user-defined type by its class, since its 
`catalogString` is its
+   * `sqlType`'s. That `sqlType` is connector code, so `?` when it throws.
+   */
+  private def typeName(dataType: DataType): String = dataType match {
+    case udt: UserDefinedType[_] =>
+      s"${udt.getClass.getName}(${orElse(udt.sqlType.catalogString, "?")})"

Review Comment:
   **[37] Nit: the `sqlType` guard covers one shape, and the new test's comment 
claims more.**
   
   This `orElse` is reached for a top-level user-defined type only when the 
arity check fails, since `zip` (L241) then drops the type before 
`atDeclaredType`. A user-defined type at a declared position calls 
`udt.sqlType` in `storedAlike` first (L498), and a nested one reaches it 
through `catalogString` in the `case other` arm, e.g. 
`ArrayType.catalogString`. If `sqlType` throws there, the exception leaves 
`logArgumentsMismatch` for the catch at L226-231: the refusal is warned about 
as "Cannot resolve a call ..." under a `failure:` key, and `eval` would rethrow 
the type's exception.
   
   The test "a user-defined type whose sqlType throws does not change what is 
logged" (`TransformExpressionSuite.scala:659`) passes because its type is the 
second argument of a one-input function, while its comment says the line is 
logged as one "whatever the types' connector code does". Its assertion on 
`"ThrowingUDT$1(?))"` also depends on the compiler's numbering of local 
classes. Spark calls `sqlType` unguarded elsewhere, e.g. 
`OrderUtils.isOrderable` on join keys, so dropping this guard and the test may 
be simpler than guarding every arm. Either way, could the comment match what 
the test covers, and could the assertion use `classOf[ThrowingUDT].getName`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -202,4 +401,115 @@ object TransformExpression {
     case t: TransformExpression => t.reducedWith.isDefined
     case _ => false
   }
+
+  /**
+   * `argument` at `declaredType`, or `None` when the function could not take 
it. See
+   * [[TransformExpression.evaluableFunction]].
+   *
+   * An argument goes as it is when it is stored the way the declared type is 
(`storedAlike`),
+   * which is how a function read it before this check. A numeric argument 
narrower than declared
+   * (`UpCastRule.legalNumericPrecedence`), e.g. a `SMALLINT` against an `INT` 
or an `INT` against a
+   * `DOUBLE`, is held as another JVM type, so it is cast. That gives the 
value a magic `invoke` got
+   * from Java's widening before this check, which can lose digits for a 
`BIGINT` against a
+   * `DOUBLE` as it did there, and needs no time zone. Anything else is 
refused,
+   * a `DATE` against a `TIMESTAMP` in particular, whose cast takes the 
session time zone. A call
+   * whose arguments all suit is still refused when the method it invokes 
cannot take them, see
+   * `methodLookupFailure`.
+   */
+  private def atDeclaredType(argument: Expression, declaredType: DataType): 
Option[Expression] =
+    (argument.dataType, declaredType) match {
+      case (argumentType, _) if storedAlike(argumentType, declaredType, nested 
= false) =>
+        Some(argument)
+      case (argumentType, _) if 
UpCastRule.legalNumericPrecedence(argumentType, declaredType) =>
+        Some(Cast(argument, declaredType))
+      case _ =>
+        None
+    }
+
+  /**
+   * Why the method `call` invokes does not take its arguments, or `None` when 
it does. `Invoke`
+   * and `StaticInvoke` look it up again from the arguments' classes, a 
user-defined type's being
+   * `Object`, and only among public methods, so a magic `invoke` the declared 
types found may not
+   * be reachable. Looked up here, so that such a call is refused as the 
argument mismatch it is,
+   * rather than failing in `eval`.
+   */
+  private def methodLookupFailure(call: Expression): Option[Throwable] =
+    try {
+      call match {
+        case i: objects.Invoke => i.method
+        case s: objects.StaticInvoke => s.method
+        case _ =>
+      }
+      None
+    } catch {
+      case NonFatal(e) => Some(e)
+    }
+
+  /**
+   * Whether a key of type `from` and one of type `to` holding one value are 
stored as the same
+   * bytes in an unsafe row, and order alike read as either type. A cogroup 
pairs the groups of its
+   * two sides by comparing their key rows, ordered by its left side's key 
types, so keys of other
+   * types pair their groups wrongly, or fail, see 
`KeyedShuffleSpec.createPartitioning`. As
+   * `storedAlike` for a nested value, apart from decimals: two decimals of 
one scale are stored
+   * alike, whatever their precision, when both are stored as a `long`, up to
+   * `Decimal.MAX_LONG_DIGITS` digits, or both as bytes. A row, the key itself 
or a struct field,
+   * reads a `long` at a smaller precision than its value has as it is. An 
array element, or a
+   * map's key or value, is read with a check that fails for a value of more 
digits than that
+   * precision, as one stored as bytes is anywhere. So a cogroup over such 
keys can fail, but never
+   * pairs its groups wrongly.
+   */
+  private[sql] def keysStoredAlike(from: DataType, to: DataType): Boolean = 
(from, to) match {

Review Comment:
   **[39] Nit: `keysStoredAlike` repeats `storedAlike`'s walk.**
   
   The `from == to`, user-defined type, struct, array and map arms here are 
those of `storedAlike` (L497-507), and only the decimal arm differs, by leaving 
out `f.precision <= t.precision`, as the doc above says ("As `storedAlike` for 
a nested value, apart from decimals"). This is about the code only, not the 
rule from [item 
17](https://github.com/apache/spark/pull/59760#discussion_r4532209360): one 
flag on `storedAlike`, passed down, gives the same answer for every pair, with 
`keysStoredAlike(from, to)` as `storedAlike(from, to, nested = true, 
anyPrecision = true)` and the decimal arm as
   
   ```scala
   case (f: DecimalType, t: DecimalType) =>
     f.scale == t.scale && (!nested || ((anyPrecision || f.precision <= 
t.precision) &&
       DecimalType.isByteArrayDecimalType(f) == 
DecimalType.isByteArrayDecimalType(t)))
   ```
   
   `DataType.equalsIgnoreCompatibleNullability` and 
`equalsIgnoreNameAndCompatibleNullability` share one walk the same way. Then an 
arm added for another container or user-defined type shape could not reach one 
check and miss the other.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -1899,6 +1902,17 @@ trait LeafShuffleSpec extends ShuffleSpec {
   def createPartitioning(clustering: Seq[Expression]): Partitioning =
     throw SparkUnsupportedOperationException()
 
+  /**
+   * Whether Spark can evaluate the partitioning [[createPartitioning]] 
builds, to place the rows
+   * of a child shuffled onto this layout. [[canCreatePartitioning]] does not 
ask it, since a child
+   * that pairs with this layout as it stands evaluates nothing. A caller that 
shuffles a child onto
+   * this layout has to ask it too. Only a [[KeyedShuffleSpec]] can answer 
false, and its
+   * [[createPartitioning]] asserts it, so a caller that does not ask fails 
while planning. What it
+   * builds over a Pandas or Arrow cogroup child's key of another type can 
still be one Spark

Review Comment:
   **[38] Nit: two things on the cogroup sentences from my [item 
19](https://github.com/apache/spark/pull/59760#discussion_r4532209380).**
   
   - Item 19 suggested keeping this explanation once, in `createPartitioning`. 
`canEvaluate` and `storedAlike` now point there, but this copy still explains 
it, and since 0ff948c it tells only half of it. The error also fires for a key 
Spark can evaluate but that is stored otherwise: an `INT` key onto a `BIGINT` 
bucket column whose function declares `(INT, BIGINT)` builds `bucket(4, 
CAST(key AS BIGINT))`, which evaluates, and `keysStoredAlike` refuses it. 
Ending with "fails while planning too, see `createPartitioning`" would keep it 
from drifting again.
   - My premise there was wrong. I wrote that a typed Dataset cogroup cannot 
have keys of different types, since `CoGroup.apply` requires both grouping 
schemas to be equal. That holds in classic, but Spark Connect builds `CoGroup` 
with its constructor (`SparkConnectPlanner.scala:994-1009`), which skips that 
`require`. So over Connect, `dfInt.groupBy($"id").as[Long, 
Long].cogroup(dfLong.groupBy($"id").as[Long, Long])(f)` plans a `CoGroupExec` 
with an `INT` and a `BIGINT` key, as far as I can tell. `createPartitioning` 
handles it as it handles a Pandas cogroup, so the behavior is right. Only the 
wording here, at L2458 and L2653, at `TransformExpression.scala:489`, and at 
`EnsureRequirementsSuite.scala:1800` and `EnsureRequirementsSuite.scala:1840` 
says "a Pandas or Arrow cogroup". Something like "a cogroup that does not 
coerce its keys, e.g. a Pandas or Arrow cogroup" would keep a later change from 
narrowing the check to the Python operators. Sorry for steering this the wrong 
way.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -167,30 +177,219 @@ case class TransformExpression(
     copy(children = newChildren)
 
   /**
-   * The scalar function call this transform stands for, with the bucket count 
prepended as a
-   * literal argument. `None` when the bound function is not a 
[[ScalarFunction]], and also when a
-   * join reduced this expression's keys, since then the call no longer 
computes them. Evaluating it
-   * to place a row would send the row to a partition it does not belong to. 
That second arm is a
-   * local gate. No caller reaches it today, because every consumer of a 
reduced partitioning
-   * refuses it first, and the write path never sees one.
+   * The bound function, when Spark could call it for this transform: a 
[[ScalarFunction]], over
+   * keys no join reduced. See [[resolvedFunction]].
    */
-  lazy val resolvedFunction: Option[Expression] = function match {
-    case scalarFunc: ScalarFunction[_] if reducedWith.isEmpty =>
-      val arguments = numBucketsOpt.fold(children)(n => Literal(n) +: children)
-      Some(V2ExpressionUtils.resolveScalarFunction(scalarFunc, arguments))
+  private def scalarFunction: Option[ScalarFunction[_]] = function match {
+    case scalarFunc: ScalarFunction[_] if reducedWith.isEmpty => 
Some(scalarFunc)
     case _ => None
   }
 
-  override def eval(input: InternalRow): Any = resolvedFunction match {
-    case Some(fn) => fn.eval(input)
-    case None => throw QueryExecutionErrors.cannotEvaluateExpressionError(this)
+  /** The arguments of the call: the bucket count, if any, as a literal, then 
the children. */
+  private def callArguments: Seq[Expression] =
+    numBucketsOpt.fold(children)(n => Literal(n) +: children)
+
+  /**
+   * The scalar function call this transform stands for, over its arguments as 
they are. `None`
+   * when the bound function is not a [[ScalarFunction]], and also when a join 
reduced this
+   * expression's keys, since then the call no longer computes them. 
Evaluating it to place a row
+   * would send the row to a partition it does not belong to. That second arm 
is a local gate. No
+   * caller reaches it today, because every consumer of a reduced partitioning 
refuses it first,
+   * and the write path never sees one. The write path 
(`DistributionAndOrderingUtils`) casts the
+   * arguments to the function's input types itself. `eval` uses 
[[evaluableFunction]] instead.
+   */
+  lazy val resolvedFunction: Option[Expression] =
+    scalarFunction.map(V2ExpressionUtils.resolveScalarFunction(_, 
callArguments))
+
+  /**
+   * The call `eval` runs: [[resolvedFunction]], with each argument at the 
type the function
+   * declares for it in `inputTypes()`, see `atDeclaredType` for which 
arguments suit. `None` when
+   * an argument does not, when there is another number of arguments, when the 
call fails to
+   * resolve, and wherever `resolvedFunction` is `None`. `eval` rethrows a 
failure to resolve. A
+   * storage-partitioned join shuffles instead of evaluating such a transform, 
so each case but
+   * reduced keys is logged once, see `logNotScalar`, `logArgumentsMismatch` 
and
+   * `logCannotResolve`.
+   */
+  def evaluableFunction: Option[Expression] = evaluableFunctionAttempt match {
+    case Success(call) => call
+    case _ => None
+  }
+
+  /**
+   * The call, or why it failed to resolve, e.g. a `ScalarFunction` that 
inherits `produceResult`
+   * from a base class, connector code that throws, or a `LinkageError` for a 
connector class whose
+   * dependency is missing, which the planner would otherwise hit for a layout 
it does not pick.
+   * Computed and logged once, since a `lazy val` whose initializer throws 
runs it again on each
+   * access. Not serialized, so an executor resolves it again rather than 
receiving the call (or
+   * the failure) the driver resolved while planning.
+   */
+  @transient private lazy val evaluableFunctionAttempt: 
Try[Option[Expression]] =
+    try Success(resolveEvaluableFunction()) catch {
+      case e @ (NonFatal(_) | _: LinkageError) =>
+        TransformExpression.logCannotResolve(function, e)
+        Failure(e)
+    }
+
+  private def resolveEvaluableFunction(): Option[Expression] = scalarFunction 
match {
+    case None =>
+      // Reduced keys are the planner's own doing, so only a function Spark 
cannot call is logged.
+      if (!function.isInstanceOf[ScalarFunction[_]]) 
TransformExpression.logNotScalar(function)

Review Comment:
   **[36] Nit: the not-scalar line names a storage-partitioned join even where 
none evaluates the transform.**
   
   `eval` now goes through `evaluableFunctionAttempt` (L261-265), so this line 
runs for any evaluation, not only SPJ's. A V2 write whose required distribution 
clusters on a `bucket` bound to a function that is not a `ScalarFunction` keeps 
the raw `TransformExpression`, since `resolvedFunction` is `None` there 
(`DistributionAndOrderingUtils.scala:97-98`). The shuffle's projection falls 
back to interpreted evaluation, so the first task on each executor logs "The 
partition transform bucket (...) is not a ScalarFunction, so a 
storage-partitioned join does not evaluate it", and then fails with 
`cannotEvaluateExpressionError`. The failure is as on master; only the line is 
new. Could the wording leave the caller out, e.g. "so Spark does not evaluate 
it"?



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/ShuffleSpecSuite.scala:
##########
@@ -705,6 +713,246 @@ class ShuffleSpecSuite extends SparkFunSuite with 
SQLHelper {
     }
   }
 
+  test("SPARK-60522: KeyedShuffleSpec refuses a transform Spark cannot 
evaluate") {
+    // A connector may bind its partition transform to a `BoundFunction` that 
is not a
+    // `ScalarFunction`, or to a `ScalarFunction` whose `produceResult` is 
inherited, which
+    // resolving it does not find. `TransformExpression.eval` cannot run 
either, so an identity
+    // side is not reduced onto it and no other child is shuffled onto it. The 
gates answer that
+    // without throwing, since they are asked of candidates that may not be 
chosen.
+    val nonScalarBucket = NonScalarBucketFunction
+    abstract class BucketBase extends ScalarFunction[Int] {
+      override def produceResult(input: InternalRow): Int = input.getInt(1)
+    }
+    // Declares the bucket count too, so that only the inherited 
`produceResult` refuses it.
+    val inheritedBucket = new BucketBase {
+      override def inputTypes(): Array[DataType] = Array(IntegerType, 
IntegerType)
+      override def resultType(): DataType = IntegerType
+      override def name(): String = "bucket"
+      override def canonicalName(): String = "test.bucket"
+    }
+    val a = $"a".int
+    def spec(expression: Expression): KeyedShuffleSpec = KeyedShuffleSpec(
+      KeyedPartitioning(Seq(expression), Seq(InternalRow(1))), 
ClusteredDistribution(Seq(a)))
+    val identity = spec(a)
+
+    Seq(
+      ("scalar", TestBucketFunction, true),
+      ("non-scalar", nonScalarBucket, false),
+      ("inherited produceResult", inheritedBucket, false)
+    ).foreach {
+      case (name, fn, evaluable) =>
+        val bucket = spec(TransformExpression(fn, Seq(a), Some(4)))
+        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") {
+          assert(identity.areKeysCompatible(bucket, allowReduce = true) == 
evaluable, name)
+          assert(bucket.areKeysCompatible(identity, allowReduce = true) == 
evaluable, name)
+        }
+        withSQLConf(SQLConf.V2_BUCKETING_SHUFFLE_ENABLED.key -> "true") {
+          assert(bucket.canCreatePartitioning, s"$name: a layout as it stands")
+          assert(bucket.canEvaluatePartitioning == evaluable, name)
+        }
+    }
+  }
+
+  test("SPARK-60027: KeyedShuffleSpec refuses a transform whose arguments miss 
its input types") {
+    // Nothing casts a transform's arguments, the bucket count included, to 
its function's
+    // `inputTypes()` after analysis, so the call would get the raw values. So 
the gates require
+    // the arguments to suit the input types in number and type: types stored 
alike go as they
+    // are, and a narrower numeric argument, integral or floating-point, is 
cast, which gives the
+    // value Java's widening gave a magic `invoke`. Anything else is refused.
+    def bucketFunction(declared: DataType*): ScalarFunction[Int] = new 
ScalarFunction[Int] {
+      override def inputTypes(): Array[DataType] = declared.toArray
+      override def resultType(): DataType = IntegerType
+      override def name(): String = "bucket"
+      override def canonicalName(): String = "test.bucket"
+      override def produceResult(input: InternalRow): Int = 0
+    }
+    def spec(expression: Expression, key: InternalRow): KeyedShuffleSpec = 
KeyedShuffleSpec(
+      KeyedPartitioning(Seq(expression), Seq(key)),
+      ClusteredDistribution(expression.references.toSeq))
+
+    // (the function's input types, the column's type, whether Spark can 
evaluate the transform)
+    Seq(
+      (Seq(IntegerType, LongType), LongType, true),
+      (Seq(IntegerType, LongType), IntegerType, true),
+      (Seq(IntegerType, LongType), ShortType, true),
+      // A wider floating-point type too, which a magic `invoke` got from 
Java's widening.
+      (Seq(IntegerType, DoubleType), IntegerType, true),
+      (Seq(IntegerType, DoubleType), LongType, true),
+      (Seq(IntegerType, IntegerType), DoubleType, false),
+      (Seq(IntegerType, IntegerType), LongType, false),
+      (Seq(IntegerType, StringType), IntegerType, false),
+      (Seq(LongType, LongType), LongType, true),
+      (Seq(ShortType, LongType), LongType, false),
+      (Seq(LongType), LongType, false),
+      (Seq(IntegerType, LongType, LongType), LongType, false),
+      // A `CHAR`, `VARCHAR` or `STRING` is held as a string of its collation, 
so it suits any of
+      // them of that collation. Not another collation, which compares strings 
differently.
+      (Seq(IntegerType, StringType), VarcharType(10), true),
+      (Seq(IntegerType, StringType), CharType(5), true),
+      (Seq(IntegerType, VarcharType(5)), StringType, true),
+      (Seq(IntegerType, StringType), StringType("UTF8_LCASE"), false),
+      (Seq(IntegerType, StringType("UTF8_LCASE")), VarcharType(10), false),
+      // A decimal suits a declared decimal of its scale, so that its unscaled 
digits are what a
+      // function reads, at the top level at any precision. Not one of another 
scale.
+      (Seq(IntegerType, DecimalType(38, 2)), DecimalType(10, 2), true),
+      (Seq(IntegerType, DecimalType(38, 18)), DecimalType(10, 2), false),
+      (Seq(IntegerType, DecimalType(10, 2)), DecimalType(5, 0), false),
+      // A `DATE` and a `TIMESTAMP` are held as an `INT` and a `BIGINT`, so 
they suit those.
+      (Seq(IntegerType, IntegerType), DateType, true),
+      (Seq(IntegerType, LongType), TimestampType, true),
+      (Seq(IntegerType, DecimalType(10, 2)), DecimalType(38, 18), false),
+      (Seq(IntegerType, DecimalType(10, 4)), DecimalType(10, 2), false)
+    ).foreach { case (declared, columnType, evaluable) =>
+      val name = s"${declared.mkString("(", ", ", ")")} over $columnType"
+      val column = AttributeReference("k", columnType)()
+      val bucket = spec(
+        TransformExpression(bucketFunction(declared: _*), Seq(column), 
Some(4)), InternalRow(1))
+      val identityKey = columnType match {

Review Comment:
   **[41] Nit: `identityKey` gives some column types a value of another type.**
   
   The `SHORT` row (L780) falls to `case _ => InternalRow(1)`, an `Int`, and 
every decimal column gets `Decimal(1)`, which is a `DECIMAL(10,0)`. The test is 
still right, since nothing reads the value: `areKeysCompatible` compares 
partition keys only for unknown keys (`partitioning.scala:2363`). But the match 
reads as if the values mattered. 
`InternalRow(Literal.default(columnType).value)` would give a value of each 
column's type, or the plain `InternalRow(1)` that L812 and L846 use would say 
it is a placeholder. Either drops L813-819 and the `Decimal` and `UTF8String` 
imports, which only this match uses.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/TransformExpressionSuite.scala:
##########
@@ -112,4 +122,589 @@ class TransformExpressionSuite extends SparkFunSuite {
     assert(!b12.hasSameReducedKeys(left))
     assert(!b12.hasSameReducedKeys(b8), "nor do two unreduced ones")
   }
+
+  test("SPARK-60027: eval casts only a narrower numeric argument to the 
function's input type") {
+    // Reads the value at the declared `BIGINT`, so it fails on an `INT` that 
is not cast.
+    val longBucket = new ScalarFunction[Int] {
+      override def inputTypes(): Array[DataType] = Array(IntegerType, LongType)
+      override def resultType(): DataType = IntegerType
+      override def name(): String = "bucket"
+      override def canonicalName(): String = "test.bucket"
+      override def produceResult(input: InternalRow): Int =
+        Math.floorMod(input.getLong(1), input.getInt(0).toLong).toInt
+    }
+    Seq(Literal(7), Literal(7L), Literal(7.toShort)).foreach { value =>
+      val transform = bucket(longBucket, value)
+      assert(transform.evaluableFunction.isDefined, value.dataType)
+      assert(transform.eval(InternalRow.empty) == 3, value.dataType)
+    }
+    // A wider floating-point type too, as a magic `invoke` got it from Java's 
widening.
+    val doubleBucket = new ScalarFunction[Int] {
+      override def inputTypes(): Array[DataType] = Array(IntegerType, 
DoubleType)
+      override def resultType(): DataType = IntegerType
+      override def name(): String = "bucket"
+      override def canonicalName(): String = "test.bucket"
+      override def produceResult(input: InternalRow): Int =
+        Math.floorMod(input.getDouble(1).toLong, input.getInt(0).toLong).toInt
+    }
+    Seq(Literal(7), Literal(7L), Literal(7.0f)).foreach { value =>
+      val transform = bucket(doubleBucket, value)
+      assert(transform.evaluableFunction.isDefined, value.dataType)
+      assert(transform.eval(InternalRow.empty) == 3, value.dataType)
+    }
+
+    // Wider than declared, not numeric, or the wrong number of arguments: 
refused.
+    val intBucket = new ScalarFunction[Int] {
+      override def inputTypes(): Array[DataType] = Array(IntegerType, 
IntegerType)
+      override def resultType(): DataType = IntegerType
+      override def name(): String = "bucket"
+      override def canonicalName(): String = "test.bucket"
+      override def produceResult(input: InternalRow): Int = input.getInt(1)
+    }
+    Seq(
+      bucket(intBucket, Literal(7L)),
+      bucket(longBucket, Literal("7")),
+      TransformExpression(longBucket, Seq(Literal(7L))),
+      TransformExpression(longBucket, Seq(Literal(7L), Literal(7L)), Some(4))
+    ).foreach { transform =>
+      assert(transform.evaluableFunction.isEmpty, transform)
+      intercept[SparkException](transform.eval(InternalRow.empty))
+    }
+
+    // A decimal that a declared decimal of its scale can hold, and a 
`VARCHAR` against a plain
+    // string, go as they are, with the value a function read before this 
check.
+    val decimalBucket = new ScalarFunction[Int] {
+      override def inputTypes(): Array[DataType] = Array(IntegerType, 
DecimalType(38, 2))
+      override def resultType(): DataType = IntegerType
+      override def name(): String = "bucket"
+      override def canonicalName(): String = "test.bucket"
+      override def produceResult(input: InternalRow): Int =
+        input.getDecimal(1, 38, 2).toUnscaledLong.toInt
+    }
+    val decimal = bucket(decimalBucket, Literal(Decimal(BigDecimal("12.34"), 
10, 2)))
+    assert(!decimal.evaluableFunction.get.exists(_.isInstanceOf[Cast]))
+    assert(decimal.eval(InternalRow.empty) == 1234, "the unscaled digits at 
the declared scale")
+    // At another scale its unscaled digits would be another number, so it is 
refused.
+    assert(bucket(decimalBucket, Literal(Decimal(BigDecimal("12.3"), 10, 1)))
+      .evaluableFunction.isEmpty)
+    val stringBucket = new ScalarFunction[Int] {
+      override def inputTypes(): Array[DataType] = Array(IntegerType, 
StringType)
+      override def resultType(): DataType = IntegerType
+      override def name(): String = "bucket"
+      override def canonicalName(): String = "test.bucket"
+      override def produceResult(input: InternalRow): Int = 
input.getUTF8String(1).numChars()
+    }
+    val varchar = bucket(stringBucket,
+      Literal.create(UTF8String.fromString("abc"), VarcharType(10)))
+    assert(!varchar.evaluableFunction.get.exists(_.isInstanceOf[Cast]))
+    assert(varchar.eval(InternalRow.empty) == 3)
+
+    // The write path coerces the arguments itself, so it keeps the uncast 
call.
+    val stringArgument = bucket(longBucket, Literal("7"))
+    assert(stringArgument.resolvedFunction.isDefined)
+    assert(!stringArgument.resolvedFunction.get.collectFirst { case c: Cast => 
c }.isDefined)
+  }
+
+  test("SPARK-60027: an argument is taken as it is when it is stored as the 
declared type is") {
+    // A function declaring `declared` reads a value of `argumentType` as it 
is, field by field and
+    // by position, when the two are stored alike, as it did before the input 
type check. The
+    // value is read from an unsafe row, as a one-side shuffle reads it, since 
that is where a
+    // nested decimal is stored by its precision.
+    class IntUDT extends UserDefinedType[Integer] {
+      override def sqlType: DataType = IntegerType
+      override def serialize(obj: Integer): Any = obj
+      override def deserialize(datum: Any): Integer = 
datum.asInstanceOf[Integer]
+      override def userClass: Class[Integer] = classOf[Integer]
+    }
+    def function(declared: DataType)(read: InternalRow => Int): 
ScalarFunction[Int] =
+      new ScalarFunction[Int] {
+        override def inputTypes(): Array[DataType] = Array(IntegerType, 
declared)
+        override def resultType(): DataType = IntegerType
+        override def name(): String = "bucket"
+        override def canonicalName(): String = "test.bucket"
+        override def produceResult(input: InternalRow): Int =
+          Math.floorMod(read(input), input.getInt(0))
+      }
+    def struct(field: String, dataType: DataType): StructType =
+      new StructType().add(field, dataType)
+    val structField = (row: InternalRow) => row.getStruct(1, 1).getInt(0)
+    val fiveCents = Decimal(BigDecimal("0.05"), 10, 2)
+    def unscaled(decimal: InternalRow => Decimal): InternalRow => Int =
+      row => decimal(row).toUnscaledLong.toInt
+    // (what, the argument's type, the declared type, the value, how the 
function reads it,
+    //  whether it is taken)
+    Seq(
+      ("a field name in another case", struct("a", IntegerType), struct("A", 
IntegerType),
+        InternalRow(5), structField, true),
+      ("a renamed field", struct("x", IntegerType), struct("y", IntegerType), 
InternalRow(5),
+        structField, true),
+      ("a DATE field against an INT one", struct("d", DateType), struct("d", 
IntegerType),
+        InternalRow(5), structField, true),
+      ("a user-defined type against its sqlType", new IntUDT, IntegerType, 5,
+        (row: InternalRow) => row.getInt(1), true),
+      // At the top level the function gets the `Decimal` itself, so a key of 
the declared scale
+      // with more precision, e.g. a cogroup's, is taken.
+      ("a decimal with more precision at the declared scale",
+        DecimalType(12, 2), DecimalType(10, 2), Decimal(BigDecimal("123.45"), 
12, 2),
+        unscaled(_.getDecimal(1, 10, 2)), true),
+      // Nested in an unsafe row, a decimal of up to 18 digits is a `long`, 
and a wider one bytes,
+      // and it is read at the declared precision. So it is taken only with no 
more precision than
+      // declared, and on the same side of 18 digits.
+      ("a nested decimal with more precision on the long side",
+        struct("d", DecimalType(10, 2)), struct("d", DecimalType(18, 2)), 
InternalRow(fiveCents),
+        unscaled(_.getStruct(1, 1).getDecimal(0, 18, 2)), true),
+      ("an array element decimal with more precision on the long side",
+        ArrayType(DecimalType(10, 2)), ArrayType(DecimalType(18, 2)),
+        new GenericArrayData(Array[Any](fiveCents)),
+        unscaled(_.getArray(1).getDecimal(0, 18, 2)), true),
+      ("a map value decimal with more precision on the long side",
+        MapType(IntegerType, DecimalType(10, 2)), MapType(IntegerType, 
DecimalType(18, 2)),
+        ArrayBasedMapData(Map(1 -> fiveCents)),
+        unscaled(_.getMap(1).valueArray().getDecimal(0, 18, 2)), true),
+      ("a nested decimal across the long and the bytes storage",
+        struct("d", DecimalType(10, 2)), struct("d", DecimalType(38, 2)), 
InternalRow(fiveCents),
+        structField, false),
+      ("an array element decimal across the long and the bytes storage",
+        ArrayType(DecimalType(10, 2)), ArrayType(DecimalType(38, 2)),
+        new GenericArrayData(Array[Any](fiveCents)), structField, false),
+      ("a map value decimal across the long and the bytes storage",
+        MapType(IntegerType, DecimalType(10, 2)), MapType(IntegerType, 
DecimalType(38, 2)),
+        ArrayBasedMapData(Map(1 -> fiveCents)), structField, false),
+      ("a nested decimal with more precision than declared",
+        struct("d", DecimalType(12, 2)), struct("d", DecimalType(10, 2)),
+        InternalRow(Decimal(BigDecimal("0.05"), 12, 2)), structField, false),
+      ("a field of another physical type", struct("d", DateType), struct("d", 
LongType),
+        InternalRow(5), structField, false),
+      ("a struct with another number of fields", struct("a", IntegerType),
+        struct("a", IntegerType).add("b", IntegerType), InternalRow(5), 
structField, false)
+    ).foreach { case (what, argumentType, declared, value, read, taken) =>
+      val argument = BoundReference(0, argumentType, nullable = true)
+      val transform = TransformExpression(function(declared)(read), 
Seq(argument), Some(4))
+      assert(transform.evaluableFunction.isDefined == taken, what)
+      if (taken) {
+        val unsafe = 
UnsafeProjection.create(Seq(argument)).apply(InternalRow(value))
+        assert(transform.eval(unsafe) == 1, what)
+      }
+    }
+  }
+
+  test("SPARK-60027: a user-defined type is refused where a magic invoke 
cannot take it") {
+    // A user-defined type goes as its `sqlType`, and `resolveScalarFunction` 
finds a magic
+    // `invoke` from the declared types. But `Invoke` and `StaticInvoke` look 
the method up again
+    // from the arguments' classes, a user-defined type's being `Object`, so 
that call cannot be
+    // made and is refused, as the argument mismatch it is: logged at info 
level, not warned about
+    // as a call that fails to resolve. A `produceResult` reads the row, so it 
takes the value.
+    class IntUDT extends UserDefinedType[Integer] {
+      override def sqlType: DataType = IntegerType
+      override def serialize(obj: Integer): Any = obj
+      override def deserialize(datum: Any): Integer = 
datum.asInstanceOf[Integer]
+      override def userClass: Class[Integer] = classOf[Integer]
+    }
+    val withInvoke = new ScalarFunction[Int] {
+      override def inputTypes(): Array[DataType] = Array(IntegerType, 
IntegerType)
+      override def resultType(): DataType = IntegerType
+      override def name(): String = "udt_bucket"
+      override def canonicalName(): String = "test.bucket"
+      def invoke(numBuckets: Int, value: Int): Int = Math.floorMod(value, 
numBuckets)
+    }
+    val withProduceResult = new ScalarFunction[Int] {
+      override def inputTypes(): Array[DataType] = Array(IntegerType, 
IntegerType)
+      override def resultType(): DataType = IntegerType
+      override def name(): String = "bucket"
+      override def canonicalName(): String = "test.bucket"
+      override def produceResult(input: InternalRow): Int =
+        Math.floorMod(input.getInt(1), input.getInt(0))
+    }
+    val argument = BoundReference(0, new IntUDT, nullable = true)
+    val appender = new LogAppender("a user-defined type a magic invoke cannot 
take")
+    withLogAppender(appender, loggerNames = transformLogger, level = 
Some(Level.INFO)) {
+      assert(bucket(withInvoke, argument).evaluableFunction.isEmpty, "a magic 
invoke")
+    }
+    val logged = appender.loggingEvents
+      .filter(_.getMessage.getFormattedMessage.contains("udt_bucket"))
+    assert(logged.map(_.getLevel) == Seq(Level.INFO), 
logged.map(_.getMessage.getFormattedMessage))
+    val message = logged.head.getMessage.getFormattedMessage
+    // The arguments suit the input types, so the line says the method cannot 
be reached with
+    // them, names the user-defined type by its class, not as the `int` of its 
`sqlType`, and ends
+    // with the lookup's own text, without the condition and SQL state that 
would read as a Spark
+    // bug.
+    assert(message.contains("but the method its call resolves to cannot be 
invoked with " +
+      s"arguments of types (int, ${argument.dataType.getClass.getName}(int)), 
since it or its " +
+      "class is not public or it does not take their Java classes"), message)
+    assert(message.contains("does not evaluate it: Couldn't find method 
invoke"), message)
+    assert(!message.contains("INTERNAL_ERROR") && 
!message.contains("SQLSTATE"), message)
+    val transform = bucket(withProduceResult, argument)
+    assert(transform.evaluableFunction.isDefined, "produceResult")
+    assert(transform.eval(InternalRow(5)) == 1)
+  }
+
+  test("SPARK-60027: cogroup keys are stored alike when their key rows compare 
alike") {
+    // A cogroup pairs the groups of its two sides by comparing their key 
rows, so a key shuffled
+    // onto a layout has to be stored as the layout's column is: apart from 
nullability and field
+    // names, and, for a decimal of one scale, its precision, while both are 
stored as a `long` or
+    // both as bytes. The answer does not depend on which side is which.
+    class IntUDT extends UserDefinedType[Integer] {
+      override def sqlType: DataType = IntegerType
+      override def serialize(obj: Integer): Any = obj
+      override def deserialize(datum: Any): Integer = 
datum.asInstanceOf[Integer]
+      override def userClass: Class[Integer] = classOf[Integer]
+    }
+    Seq[(DataType, DataType, Boolean)](
+      (IntegerType, IntegerType, true),
+      (DateType, IntegerType, true),
+      (TimestampNTZType, TimestampType, true),
+      (StringType, VarcharType(5), true),
+      (new IntUDT, IntegerType, true),
+      (new StructType().add("x", IntegerType, nullable = false),
+        new StructType().add("y", IntegerType, nullable = true), true),
+      (ArrayType(IntegerType, containsNull = false), ArrayType(IntegerType), 
true),
+      (DecimalType(10, 2), DecimalType(12, 2), true),
+      (DecimalType(20, 2), DecimalType(38, 2), true),
+      (ArrayType(DecimalType(10, 2)), ArrayType(DecimalType(18, 2)), true),
+      (MapType(IntegerType, DecimalType(10, 2)), MapType(IntegerType, 
DecimalType(15, 2)), true),
+      (new StructType().add("d", DecimalType(10, 2)),
+        new StructType().add("d", DecimalType(15, 2)), true),
+      (IntegerType, LongType, false),
+      (ShortType, IntegerType, false),
+      (IntegerType, DoubleType, false),
+      (StringType, StringType("UTF8_LCASE"), false),
+      (DecimalType(10, 2), DecimalType(20, 2), false),
+      (DecimalType(10, 2), DecimalType(10, 3), false),
+      (new StructType().add("x", IntegerType), new StructType().add("x", 
LongType), false),
+      (ArrayType(IntegerType), ArrayType(LongType), false),
+      (new StructType().add("x", IntegerType),
+        new StructType().add("x", IntegerType).add("y", IntegerType), false)
+    ).foreach { case (one, other, alike) =>
+      assert(TransformExpression.keysStoredAlike(one, other) == alike, s"$one 
and $other")
+      assert(TransformExpression.keysStoredAlike(other, one) == alike, 
s"$other and $one")
+    }
+  }
+
+  test("SPARK-60027: a transform whose call fails to resolve is not evaluable, 
and says why") {
+    // Connector code can throw while Spark resolves the call. That counts as 
cannot evaluate, and
+    // the answer is kept, so the connector is asked once. `eval` rethrows 
what it threw.
+    var calls = 0
+    val failing = new ScalarFunction[Int] {
+      override def inputTypes(): Array[DataType] = {
+        calls += 1
+        throw new IllegalStateException("connector bug")
+      }
+      override def resultType(): DataType = IntegerType
+      override def name(): String = "bucket"
+      override def canonicalName(): String = "test.bucket"
+      override def produceResult(input: InternalRow): Int = 0
+    }
+    val transform = bucket(failing, Literal(7))
+    assert(transform.evaluableFunction.isEmpty)
+    assert(transform.evaluableFunction.isEmpty)
+    assert(calls == 1, "asked once")
+    val e = intercept[IllegalStateException](transform.eval(InternalRow.empty))
+    assert(e.getMessage == "connector bug")
+  }
+
+  test("SPARK-60027: a function whose call fails to resolve is warned about 
once") {
+    // The planner asks this of layouts it does not pick, on every query, so 
another transform
+    // over the same function class is not warned about again.
+    val failing = new ScalarFunction[Int] {
+      override def inputTypes(): Array[DataType] = throw new 
IllegalStateException("connector bug")
+      override def resultType(): DataType = IntegerType
+      override def name(): String = "bucket"
+      override def canonicalName(): String = "test.bucket"
+      override def produceResult(input: InternalRow): Int = 0
+    }
+    val appender = new LogAppender("cannot resolve a partition transform call")
+    withLogAppender(appender, loggerNames = transformLogger, level = 
Some(Level.WARN)) {
+      Seq(Literal(1), Literal(2), Literal(3)).foreach { value =>
+        assert(bucket(failing, value).evaluableFunction.isEmpty)
+      }
+    }
+    val warnings = appender.loggingEvents
+      .filter(_.getLevel == Level.WARN)
+      .map(_.getMessage.getFormattedMessage)
+    assert(warnings.size == 1, warnings)
+    assert(warnings.head.contains("connector bug"))
+  }
+
+  test("SPARK-60027: a function that cannot be linked is not evaluable, nor 
fails the logging") {
+    // A connector class whose dependency is missing throws a `LinkageError` 
while Spark looks up
+    // its methods, which `Try` would let through, and its `name()` can throw 
too.
+    val unlinked = new ScalarFunction[Int] {
+      override def inputTypes(): Array[DataType] = {
+        // scalastyle:off throwerror
+        throw new NoClassDefFoundError("missing/Dep")
+        // scalastyle:on throwerror
+      }
+      override def resultType(): DataType = IntegerType
+      override def name(): String = throw new IllegalStateException("no name")
+      override def canonicalName(): String = "test.bucket"
+      override def produceResult(input: InternalRow): Int = 0
+    }
+    val transform = bucket(unlinked, Literal(7))
+    assert(transform.evaluableFunction.isEmpty)
+    intercept[NoClassDefFoundError](transform.eval(InternalRow.empty))
+  }
+
+  test("SPARK-60027: a function whose name and failure cannot be linked still 
logs its failure") {
+    // `name()` and the failure's message are connector code too, and a 
missing dependency can make
+    // them throw a `LinkageError`. The warning falls back to the class names 
instead.
+    class UnlinkedFailure extends IllegalStateException {
+      override def getMessage: String = {
+        // scalastyle:off throwerror
+        throw new NoClassDefFoundError("missing/Message")
+        // scalastyle:on throwerror
+      }
+    }
+    val unlinked = new ScalarFunction[Int] {
+      override def inputTypes(): Array[DataType] = throw new UnlinkedFailure
+      override def resultType(): DataType = IntegerType
+      override def name(): String = {
+        // scalastyle:off throwerror
+        throw new NoClassDefFoundError("missing/Name")
+        // scalastyle:on throwerror
+      }
+      override def canonicalName(): String = "test.bucket"
+      override def produceResult(input: InternalRow): Int = 0
+    }
+    val appender = new LogAppender("partition transform call failure with 
unlinked text")
+    withLogAppender(appender, loggerNames = transformLogger, level = 
Some(Level.WARN)) {
+      assert(bucket(unlinked, Literal(7)).evaluableFunction.isEmpty)
+    }
+    val warnings = appender.loggingEvents
+      .filter(_.getLevel == Level.WARN)
+      .map(_.getMessage.getFormattedMessage)
+    assert(warnings.size == 1, warnings)
+    assert(warnings.head.contains(unlinked.getClass.getName), warnings.head)
+    assert(warnings.head.contains(classOf[UnlinkedFailure].getName), 
warnings.head)
+  }
+
+  test("SPARK-60027: arguments that do not suit the input types are logged 
once per types") {
+    // A mismatch makes a storage-partitioned join shuffle where it would not 
otherwise, so it is
+    // logged, once per function class and argument types.
+    class IntBucket extends ScalarFunction[Int] {
+      override def inputTypes(): Array[DataType] = Array(IntegerType, 
IntegerType)
+      override def resultType(): DataType = IntegerType
+      override def name(): String = "int_bucket"
+      override def canonicalName(): String = "test.bucket"
+      override def produceResult(input: InternalRow): Int = 0
+    }
+    val appender = new LogAppender("partition transform argument mismatches")
+    withLogAppender(appender, loggerNames = transformLogger, level = 
Some(Level.INFO)) {
+      Seq(Literal(7L), Literal(8L), Literal("7")).foreach { value =>
+        assert(bucket(new IntBucket, value).evaluableFunction.isEmpty, 
value.dataType)
+      }
+      assert(bucket(new IntBucket, Literal(7)).evaluableFunction.isDefined, 
"matching types")
+    }
+    val logged = appender.loggingEvents
+      .filter(_.getLevel == Level.INFO)
+      .map(_.getMessage.getFormattedMessage)
+    assert(logged.size == 2, logged)
+    assert(logged.exists(m => m.contains("int_bucket") && m.contains("(int, 
int)") &&
+      m.contains("(int, bigint)")), logged)
+    assert(logged.exists(_.contains("(int, string)")), logged)
+  }
+
+  test("SPARK-60027: a function that is not a ScalarFunction is logged once 
per class") {
+    // A class of its own, since the set of classes logged for is shared by 
the JVM.
+    class NotScalar extends BoundFunction {
+      override def inputTypes(): Array[DataType] = Array(IntegerType, LongType)
+      override def resultType(): DataType = IntegerType
+      override def name(): String = "bucket"
+      override def canonicalName(): String = "test.bucket"
+    }
+    val appender = new LogAppender("partition transform that is not a 
ScalarFunction")
+    withLogAppender(appender, loggerNames = transformLogger, level = 
Some(Level.INFO)) {
+      Seq(Literal(1L), Literal(2L)).foreach { value =>
+        assert(bucket(new NotScalar, value).evaluableFunction.isEmpty)
+      }
+    }
+    val logged = appender.loggingEvents
+      .filter(_.getLevel == Level.INFO)
+      .map(_.getMessage.getFormattedMessage)
+      .filter(_.contains("is not a ScalarFunction"))
+    assert(logged.size == 1, logged)
+  }
+
+  test("SPARK-60027: a mismatch is logged once per argument and declared 
types") {
+    // One class can declare other input types per instance, e.g. one per 
column type, so each
+    // declared signature a mismatch is logged for gets its own line.
+    class TypedBucket(valueType: DataType) extends ScalarFunction[Int] {
+      override def inputTypes(): Array[DataType] = Array(IntegerType, 
valueType)
+      override def resultType(): DataType = IntegerType
+      override def name(): String = "typed_bucket"
+      override def canonicalName(): String = "test.bucket"
+      override def produceResult(input: InternalRow): Int = 0
+    }
+    val appender = new LogAppender("partition transform mismatches per 
declared types")
+    withLogAppender(appender, loggerNames = transformLogger, level = 
Some(Level.INFO)) {
+      Seq(StringType, BinaryType, StringType).foreach { declared =>
+        assert(bucket(new TypedBucket(declared), 
Literal(7L)).evaluableFunction.isEmpty)
+      }
+    }
+    val logged = appender.loggingEvents
+      .filter(_.getLevel == Level.INFO)
+      .map(_.getMessage.getFormattedMessage)
+      .filter(_.contains("typed_bucket"))
+    assert(logged.size == 2, logged)
+    assert(logged.exists(_.contains("(int, string)")) && 
logged.exists(_.contains("(int, binary)")))
+  }
+
+  test("SPARK-60027: an argument mismatch line carries an error only for a 
lookup failure") {
+    // What a structured log gets: the `error` field holds what the lookup 
says, alone, and a
+    // mismatch the declared types explain has no `error` field at all. The 
line's context is
+    // filled only with structured logging on.
+    val structured = Logging.isStructuredLoggingEnabled
+    Logging.enableStructuredLogging()
+    try checkArgumentsMismatchLines()
+    finally if (!structured) Logging.disableStructuredLogging()
+  }
+
+  private def checkArgumentsMismatchLines(): Unit = {

Review Comment:
   **[40] Nit: this helper sits among the tests.**
   
   The suite's other members are all above the first test (L34-57), and this is 
the only one below it. It takes no parameters and only holds the body of the 
test above (L551-559), so that body could go straight into the test's `try`, 
and the member would go away. This is the same kind of thing as [item 
27](https://github.com/apache/spark/pull/59760#discussion_r4532209431), from 
the AGENTS.md rule on putting a new member with the code it belongs with.



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