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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2570,24 +2610,49 @@ 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 {
+    case t: TransformExpression => canEvaluate(t)
+    case _ => true
+  }
+
   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, so that answers for what is built too. 
A Pandas or Arrow
+    // cogroup's need not (SPARK-60782), e.g. a `BIGINT` key or a string of 
another collation, and
+    // falling back to a hash shuffle would pair its groups wrongly. So such a 
child fails here,
+    // while planning, with an error that names the key's type.
+    newExpressions.foreach {
+      case t: TransformExpression if t.evaluableFunction.isEmpty =>

Review Comment:
   **[17] A cogroup key narrower than the layout's column passes this check 
through the new widening `Cast`, and the cogroup then pairs its groups wrongly 
where master failed.**
   
   This loop only asks whether the layout's function can take the shuffled key. 
Since `atDeclaredType` widens a narrower numeric argument 
(`TransformExpression.scala:381-382`), a Pandas or Arrow cogroup key that is 
narrower than the layout's column gets through. For example, with 
`spark.sql.sources.v2.bucketing.shuffle.enabled=true`:
   
   - `t1` has `id BIGINT` and reports `bucket(4, id)`, bound to a function that 
declares `(INT, BIGINT)` and implements only `produceResult`, like the test 
catalog's `BucketFunction`.
   - `t1.groupby("id").cogroup(df2.groupby("id")).applyInPandas(...)` runs with 
`df2.id` as `INT`, holding negative ids.
   
   `t1`'s layout is picked, and `df2` is shuffled onto `bucket(4, CAST(id AS 
BIGINT))`, which Spark can evaluate, so no error is raised and every row lands 
in the right partition. But `CoGroupedIterator` orders the keys by the left 
side's types (`CoGroupedIterator.scala:35-36`) and pairs groups by comparing 
the key rows (`CoGroupedIterator.scala:61`). `UnsafeRowWriter` writes an `INT` 
into a zeroed 8-byte slot (`UnsafeRowWriter.java:165-169`), so at `BIGINT` a 
right key `-1` reads as `4294967295`. In a partition that holds a negative 
right key, no group pairs: with the keys `[-5, -1, 3, 7]` on both sides, the 
UDF gets 8 half-groups instead of 4 pairs, and a left `4294967295` would pair 
with a right `-1`. An integral key onto a `FLOAT` or `DOUBLE` layout, which the 
widening from [item 
2](https://github.com/apache/spark/pull/59760#discussion_r4433579770) also 
admits, leaves every nonzero key unpaired.
   
   On master the same query failed in every shuffle task: 
`ApplyFunctionExpression` puts the `Integer` into a `MutableLong` slot, whose 
`update` casts it (`SpecificInternalRow.scala:148-151`). So this turns a task 
failure into wrong groups. The reply at 
[r4433782711](https://github.com/apache/spark/pull/59760#discussion_r4433782711)
 and the comment at L2641-2644 cover the other direction, a `BIGINT` key 
against a function declaring `INT`, which is still refused here. A magic 
`invoke(int, long)` and the default hash shuffle already return such groups on 
master, which is SPARK-60782, so I'm not asking about those.
   
   Could this loop also refuse a shuffled key that is not stored the way the 
template's column is, e.g. with a `storedAlike`-style check between the key's 
type and the type of the column `te` is over? For a join, the key at that 
position is the column's equi-join partner, so its type matches up to 
nullability and field names, and no join plan changes. The `DECIMAL(12,2)` key 
onto a `DECIMAL(10,2)` layout that `EnsureRequirementsSuite` pins would still 
pass.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2570,24 +2610,49 @@ 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 {
+    case t: TransformExpression => canEvaluate(t)
+    case _ => true
+  }
+
   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, so that answers for what is built too. 
A Pandas or Arrow
+    // cogroup's need not (SPARK-60782), e.g. a `BIGINT` key or a string of 
another collation, and
+    // falling back to a hash shuffle would pair its groups wrongly. So such a 
child fails here,

Review Comment:
   **[18] Nit: this says a cogroup child with a key of another type fails here, 
but the check below covers transform positions only.**
   
   L2641-2644 says such a child "fails here, while planning, with an error that 
names the key's type". Two cases never reach that error:
   
   - An identity position (L2634) is rebuilt over the other key whatever its 
type. A `STRING COLLATE UTF8_LCASE` key shuffled onto an identity `STRING` 
layout raises nothing, and a `BIGINT` key shuffled onto an identity `INT` 
layout typically fails in the map task with a `ClassCastException`.
   - A layout Spark cannot evaluate never gets here, so its cogroup takes the 
hash shuffle.
   
   Both behave as on master and belong to SPARK-60782, so this is only about 
the wording. Could the comment say that it covers transform positions, and that 
identity positions and the hash fallback are left to SPARK-60782?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -202,4 +361,63 @@ 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.
+   */
+  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
+    }
+
+  /**
+   * Whether a value of type `from` is stored the way one of type `to` is, so 
that a function
+   * declaring `to` reads it as it is:
+   *  - two types with one physical type, e.g. a `VARCHAR` and a string of the 
same collation, a
+   *    `DATE` and an `INT`, or a `TIMESTAMP` and a `BIGINT`. A user-defined 
type is stored as its
+   *    `sqlType`;
+   *  - two structs, arrays or maps whose fields, elements, keys and values 
are stored alike, by
+   *    position. Field names and nullability do not change how a value is 
stored. A function
+   *    declaring a non-nullable field gets the values a nullable one holds;
+   *  - two decimals of one scale, so that the unscaled digits a function 
reads are the same. At the
+   *    top level the function gets the `Decimal` itself, whatever precision 
it declares, e.g. a
+   *    `DECIMAL(12,2)` key of a cogroup against a function declaring 
`DECIMAL(10,2)`, which a

Review Comment:
   **[19] Nit: this copy, and the one at `EnsureRequirementsSuite.scala:1800`, 
still say "a cogroup".**
   
   e1684e5 narrowed the same statement to "A Pandas or Arrow cogroup" at 
`partitioning.scala:1895-1897`, `partitioning.scala:2443-2447`, 
`partitioning.scala:2641-2644` and `EnsureRequirementsSuite.scala:1839`, but 
not here or in the `EnsureRequirementsSuite` test that pins the `DECIMAL(12,2)` 
key. A typed Dataset cogroup cannot have keys of different types, since 
`CoGroup.apply` requires both grouping schemas to be equal 
(`object.scala:774`). Could these two say "a Pandas or Arrow cogroup" as well? 
The explanation now lives in five places, and copies of it drifted before 
([finding 
9](https://github.com/apache/spark/pull/59760#discussion_r4435873409), [finding 
15](https://github.com/apache/spark/pull/59760#discussion_r4457220586)), so 
keeping it once, in `createPartitioning`, and referring to it from the others 
would also help.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/ShuffleSpecSuite.scala:
##########
@@ -865,7 +1113,7 @@ class ShuffleSpecSuite extends SparkFunSuite with 
SQLHelper {
     // A stand-in for a connector partition function such as `bucket`: only 
the canonical name

Review Comment:
   **[23] The positive control at L1159-1160 now passes only through the mixin 
forwarder from finding 2, and this comment no longer holds.**
   
   This PR changed `bucketFn`'s input types (L1116) and added `canEvaluate(t)` 
to the identity-vs-transform arm (`partitioning.scala:2408-2411`). So "unmarked 
identity-vs-transform pairs remain admissible" now also asks whether Spark can 
evaluate `bucketFn`, which has neither `produceResult` nor `invoke`. It passes 
because Scala gives the anonymous class a forwarder to the default 
`produceResult`, as [finding 
2](https://github.com/apache/spark/pull/59760#discussion_r4370153116) described 
for `TestBucketFunction` (`javap` on the master build of this fixture shows 
one), and calling it throws `SCALAR_FUNCTION_NOT_COMPATIBLE`. If the lookup gap 
in the `V2ExpressionUtils.scala:277-280` TODO is closed, this unknown-keys test 
fails for a reason unrelated to unknown keys. `TestBucketFunction` got a 
`produceResult` for this; could `bucketFn` get one too, and could this comment 
say that more than the canonical name matters now?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -167,30 +175,181 @@ 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]].
+   */
+  private def scalarFunction: Option[ScalarFunction[_]] = function match {
+    case scalarFunc: ScalarFunction[_] if reducedWith.isEmpty => 
Some(scalarFunc)
+    case _ => None
+  }
+
+  /** 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`.
    */
-  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))
+  def evaluableFunction: Option[Expression] = evaluableFunctionAttempt match {
+    case Success(call) => call
     case _ => None
   }
 
-  override def eval(input: InternalRow): Any = resolvedFunction match {
-    case Some(fn) => fn.eval(input)
-    case None => throw QueryExecutionErrors.cannotEvaluateExpressionError(this)
+  /**
+   * 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 NonFatal(e) => cannotResolve(e)
+      case e: LinkageError => cannotResolve(e)
+    }
+
+  private def cannotResolve(e: Throwable): Try[Option[Expression]] = {
+    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)
+      }
+      val call = if (arguments.length == declaredTypes.length && 
typed.forall(_.isDefined)) {
+        Some(V2ExpressionUtils.resolveScalarFunction(scalarFunc, 
typed.flatten))
+          .filter(TransformExpression.methodTakesArguments)
+      } else {
+        None
+      }
+      if (call.isEmpty) {
+        TransformExpression.logArgumentsMismatch(scalarFunc, 
arguments.map(_.dataType),
+          declaredTypes)
+      }
+      call
+  }
+
+  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`, 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
+
+  /**
+   * `text`, or `fallback` when it throws. `name()` 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(text: => String, fallback: String): String =
+    try text catch { case NonFatal(_) | _: LinkageError => fallback }
+
+  /**
+   * Whether the method `call` invokes takes its arguments. `Invoke` and 
`StaticInvoke` look it up
+   * again from the arguments' classes, a user-defined type's being `Object`, 
so a magic `invoke`
+   * the declared types found may not take them. Looked up here, so that such 
a call is refused as
+   * the argument mismatch it is, rather than failing in `eval`.
+   */
+  private def methodTakesArguments(call: Expression): Boolean =
+    try {
+      call match {
+        case i: objects.Invoke => i.method
+        case s: objects.StaticInvoke => s.method

Review Comment:
   **[22] No test reaches this `StaticInvoke` arm.**
   
   `resolveScalarFunction` builds a `StaticInvoke` only when the magic method 
is static (`V2ExpressionUtils.scala:264-268`), and every magic `invoke` in this 
PR's fixtures is an instance method of a Scala object or an anonymous class. So 
deleting this line keeps every test green, and a connector with a static 
`invoke` and a UDT argument would pass the check and fail in tasks again. 
Static magic methods are the common Java shape; Iceberg's `bucket` functions 
use them. Could a test cover it with a Java function that has a static 
`invoke`, e.g. `JavaLongAdd.JavaLongAddStaticMagic` in sql/core's test sources, 
over UDT arguments whose `sqlType` is `BIGINT`?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala:
##########
@@ -357,27 +357,57 @@ case class EnsureRequirements(
     // consider the minimum parallelism iff ALL children need to be 
re-shuffled.
     //
     // A child needs to be re-shuffled iff either of the following is true:
-    //   1. It can't create partitioning by itself, i.e., 
`canCreatePartitioning` returns false
-    //      (as for the case of `RangePartitioning`), therefore it needs to be 
re-shuffled
-    //      according to another child's shuffle spec.
+    //   1. It can't create partitioning by itself, i.e., no member of its 
spec can serve as the
+    //      layout (`canServe` below, as for the case of `RangePartitioning`), 
therefore it needs
+    //      to be re-shuffled according to another child's shuffle spec.
     //   2. It already has `ShuffleExchangeLike`, so we can re-use existing 
shuffle without
     //      introducing extra shuffle.
     //
     // On the other hand, in scenarios such as:
     //   HashPartitioning(5) <-> HashPartitioning(6)
     // while `spark.sql.shuffle.partitions` is 10, we'll only re-shuffle the 
left side and make it
     // HashPartitioning(6).
-    val shouldConsiderMinParallelism = children.zip(specs).forall { case 
(child, spec) =>
-      spec.forall(!_.canCreatePartitioning) || 
child.isInstanceOf[ShuffleExchangeLike]
+    //
+    // A member of a child serves as the layout when it can create a 
partitioning, and either Spark
+    // can evaluate that partitioning or no child has to be shuffled onto it: 
every other
+    // co-partitioned child pairs with it as it stands, which evaluates 
nothing. One that cannot
+    // serve does not keep its child from being re-shuffled, so it counts 
towards neither the
+    // parallelism guard nor the ranking below.
+    //
+    // A `ShuffleSpecCollection` answers `isCompatibleWith` if *any* of its 
members does, so the
+    // winner alone does not say which member the sides agreed on. The 
projection pushed into a
+    // paired child and the partitioning built for a re-shuffled child both 
have to come from one
+    // member, otherwise the sides end up grouped on different keys, or on a 
key set the child does
+    // not even have. So what is picked here is the pairing, not a member per 
side.
+    //
+    // Per child, each member of its spec with the member each child pairs 
with it, in child order.
+    // The pairing compares partition keys, so it is worked out when first 
asked for, and once: for
+    // a member that cannot be evaluated by `canServe`, and for the winner's 
members below.
+    val childMembers: Seq[Seq[LeafShuffleSpec]] = 
specs.map(_.toSeq.flatMap(_.flatten))
+    final class Pairing(val member: LeafShuffleSpec, index: Int) {
+      lazy val paired: Seq[Option[LeafShuffleSpec]] =
+        childMembers.map(_.find(member.isCompatibleWith))
+      // `canEvaluatePartitioning` first: it is kept by the spec, while the 
pairing compares keys.
+      lazy val canServe: Boolean =
+        member.canCreatePartitioning && (member.canEvaluatePartitioning ||
+          paired.zip(specs).zipWithIndex.forall { case ((pairedMember, spec), 
j) =>
+            j == index || spec.isEmpty || pairedMember.isDefined
+          })
+    }
+    val pairings: Seq[Seq[Pairing]] = childMembers.zipWithIndex.map { case 
(members, index) =>
+      members.map(new Pairing(_, index))
+    }
+    val shouldConsiderMinParallelism = children.zip(pairings).forall { case 
(child, members) =>

Review Comment:
   **[28] Nit: the comment that explains this guard is now 30 lines above it.**
   
   On the base, the comment that starts "Whether we should consider 
`spark.sql.shuffle.partitions`" (L355-369) sat right on 
`shouldConsiderMinParallelism`. Now the new paragraphs and `childMembers`, 
`Pairing` and `pairings` (L371-399) come in between, so it reads as if it 
documented `childMembers`. Could L355-369 move down to this line?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -167,30 +175,181 @@ 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]].
+   */
+  private def scalarFunction: Option[ScalarFunction[_]] = function match {
+    case scalarFunc: ScalarFunction[_] if reducedWith.isEmpty => 
Some(scalarFunc)
+    case _ => None
+  }
+
+  /** 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`.
    */
-  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))
+  def evaluableFunction: Option[Expression] = evaluableFunctionAttempt match {
+    case Success(call) => call
     case _ => None
   }
 
-  override def eval(input: InternalRow): Any = resolvedFunction match {
-    case Some(fn) => fn.eval(input)
-    case None => throw QueryExecutionErrors.cannotEvaluateExpressionError(this)
+  /**
+   * 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 NonFatal(e) => cannotResolve(e)
+      case e: LinkageError => cannotResolve(e)
+    }
+
+  private def cannotResolve(e: Throwable): Try[Option[Expression]] = {
+    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)
+      }
+      val call = if (arguments.length == declaredTypes.length && 
typed.forall(_.isDefined)) {
+        Some(V2ExpressionUtils.resolveScalarFunction(scalarFunc, 
typed.flatten))
+          .filter(TransformExpression.methodTakesArguments)
+      } else {
+        None
+      }
+      if (call.isEmpty) {
+        TransformExpression.logArgumentsMismatch(scalarFunc, 
arguments.map(_.dataType),
+          declaredTypes)
+      }
+      call
+  }
+
+  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`, 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
+
+  /**
+   * `text`, or `fallback` when it throws. `name()` 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(text: => String, fallback: String): String =
+    try text catch { case NonFatal(_) | _: LinkageError => fallback }
+
+  /**
+   * Whether the method `call` invokes takes its arguments. `Invoke` and 
`StaticInvoke` look it up
+   * again from the arguments' classes, a user-defined type's being `Object`, 
so a magic `invoke`
+   * the declared types found may not take them. Looked up here, so that such 
a call is refused as
+   * the argument mismatch it is, rather than failing in `eval`.
+   */
+  private def methodTakesArguments(call: Expression): Boolean =

Review Comment:
   **[27] Nit: `methodTakesArguments` sits among the logging helpers.**
   
   It is between `orElse` and `logArgumentsMismatch`, while the rule it 
completes, `atDeclaredType` and `storedAlike` (L377, L403), is at the end of 
the object. The `evaluableFunction` doc points to `atDeclaredType` for which 
arguments suit, and that doc ends with "Anything else is refused", so the UDT 
refusal is in neither place it points to. Could it move next to 
`atDeclaredType`, with a line in that doc?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2570,24 +2610,49 @@ 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 {
+    case t: TransformExpression => canEvaluate(t)
+    case _ => true
+  }
+
   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, so that answers for what is built too. 
A Pandas or Arrow
+    // cogroup's need not (SPARK-60782), e.g. a `BIGINT` key or a string of 
another collation, and
+    // falling back to a hash shuffle would pair its groups wrongly. So such a 
child fails here,
+    // while planning, with an error that names the key's type.
+    newExpressions.foreach {
+      case t: TransformExpression if t.evaluableFunction.isEmpty =>
+        // `name()` and `inputTypes()` are connector code, which must not 
replace this error.
+        val functionClass = t.function.getClass.getName
+        val inputTypes =
+          try t.function.inputTypes().toSeq catch { case NonFatal(_) | _: 
LinkageError => Nil }
+        throw QueryExecutionErrors.storagePartitionJoinKeyTypeMismatchError(

Review Comment:
   **[21] Nit: `STORAGE_PARTITION_JOIN_KEY_TYPE_MISMATCH` names neither the key 
nor the bucket count.**
   
   `<transform>` gets only `name()`, and `<inputTypes>` includes the bucket 
count's type, which the query never mentions. For a Pandas cogroup on two 
`BIGINT` keys shuffled onto `[bucket(4, c1), bucket(8, c2)]`, where `bucket(4)` 
declares `(INT, INT)`, the message says "its partition transform bucket 
declares the input types ("INT", "INT"), which do not take the key of type 
"BIGINT"". "bucket" and "BIGINT" fit both keys, and nothing says that the first 
"INT" is the bucket count. Could `<transform>` include the count, e.g. 
`bucket(4)`, and the message name the key with `toSQLExpr`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -167,30 +175,181 @@ 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]].
+   */
+  private def scalarFunction: Option[ScalarFunction[_]] = function match {
+    case scalarFunc: ScalarFunction[_] if reducedWith.isEmpty => 
Some(scalarFunc)
+    case _ => None
+  }
+
+  /** 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`.
    */
-  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))
+  def evaluableFunction: Option[Expression] = evaluableFunctionAttempt match {
+    case Success(call) => call
     case _ => None
   }
 
-  override def eval(input: InternalRow): Any = resolvedFunction match {
-    case Some(fn) => fn.eval(input)
-    case None => throw QueryExecutionErrors.cannotEvaluateExpressionError(this)
+  /**
+   * 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 NonFatal(e) => cannotResolve(e)
+      case e: LinkageError => cannotResolve(e)
+    }
+
+  private def cannotResolve(e: Throwable): Try[Option[Expression]] = {
+    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)
+      }
+      val call = if (arguments.length == declaredTypes.length && 
typed.forall(_.isDefined)) {
+        Some(V2ExpressionUtils.resolveScalarFunction(scalarFunc, 
typed.flatten))
+          .filter(TransformExpression.methodTakesArguments)
+      } else {
+        None
+      }
+      if (call.isEmpty) {
+        TransformExpression.logArgumentsMismatch(scalarFunc, 
arguments.map(_.dataType),
+          declaredTypes)
+      }
+      call
+  }
+
+  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`, 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
+
+  /**
+   * `text`, or `fallback` when it throws. `name()` 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(text: => String, fallback: String): String =
+    try text catch { case NonFatal(_) | _: LinkageError => fallback }
+
+  /**
+   * Whether the method `call` invokes takes its arguments. `Invoke` and 
`StaticInvoke` look it up
+   * again from the arguments' classes, a user-defined type's being `Object`, 
so a magic `invoke`
+   * the declared types found may not take them. Looked up here, so that such 
a call is refused as
+   * the argument mismatch it is, rather than failing in `eval`.
+   */
+  private def methodTakesArguments(call: Expression): Boolean =
+    try {
+      call match {
+        case i: objects.Invoke => i.method
+        case s: objects.StaticInvoke => s.method
+        case _ =>
+      }
+      true
+    } catch {
+      case NonFatal(_) => false
+    }
+
+  /**
+   * Logs that `function`'s input types do not take `argumentTypes`, see 
`evaluableFunction`.
+   */
+  private def logArgumentsMismatch(
+      function: BoundFunction,
+      argumentTypes: Seq[DataType],
+      declaredTypes: Seq[DataType]): Unit = {
+    def typeList(types: Seq[DataType]): String = 
types.map(_.catalogString).mkString("(", ", ", ")")

Review Comment:
   **[20] The INFO line for a user-defined type refused here lists the same 
types on both sides, and drops the lookup failure that explains it.**
   
   This is about the code added for [item 
13](https://github.com/apache/spark/pull/59760#discussion_r4463685227). 
`typeList` (L314) renders types with `catalogString`, and 
`UserDefinedType.catalogString` is its `sqlType`'s. So for the `withInvoke` 
case in the new test, a UDT over `INT` against a `bucket` declaring `(INT, 
INT)` with `invoke(int, int)`, the line reads "declares the input types (int, 
int), which do not take arguments of types (int, int)". What actually fails, 
"Couldn't find method invoke with arguments (int, class java.lang.Object)", is 
dropped by `case NonFatal(_) => false` (L304). Two more effects:
   
   - A magic `invoke` that is not public gets the same line. 
`V2ExpressionUtils.findMethod` finds it with `getDeclaredMethod`, but 
`Invoke.method` looks it up with `getMatchingAccessibleMethod`, which only sees 
public methods.
   - Two UDTs with one `sqlType` share a log-once key per function class.
   
   The test checks only the level and "which do not take arguments" 
(`TransformExpressionSuite.scala:321-322`). Could `typeList` mark a UDT, e.g. 
by its class name or as `toSQLType` does in the new error (`UDT("INT")`), and 
could the line carry the lookup failure's message when `methodTakesArguments` 
is what refused the call?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -167,30 +175,181 @@ 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]].
+   */
+  private def scalarFunction: Option[ScalarFunction[_]] = function match {
+    case scalarFunc: ScalarFunction[_] if reducedWith.isEmpty => 
Some(scalarFunc)
+    case _ => None
+  }
+
+  /** 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`.
    */
-  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))
+  def evaluableFunction: Option[Expression] = evaluableFunctionAttempt match {
+    case Success(call) => call
     case _ => None
   }
 
-  override def eval(input: InternalRow): Any = resolvedFunction match {
-    case Some(fn) => fn.eval(input)
-    case None => throw QueryExecutionErrors.cannotEvaluateExpressionError(this)
+  /**
+   * 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 NonFatal(e) => cannotResolve(e)
+      case e: LinkageError => cannotResolve(e)
+    }
+
+  private def cannotResolve(e: Throwable): Try[Option[Expression]] = {
+    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)
+      }
+      val call = if (arguments.length == declaredTypes.length && 
typed.forall(_.isDefined)) {
+        Some(V2ExpressionUtils.resolveScalarFunction(scalarFunc, 
typed.flatten))
+          .filter(TransformExpression.methodTakesArguments)
+      } else {
+        None
+      }
+      if (call.isEmpty) {
+        TransformExpression.logArgumentsMismatch(scalarFunc, 
arguments.map(_.dataType),
+          declaredTypes)
+      }
+      call
+  }
+
+  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`, 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
+
+  /**
+   * `text`, or `fallback` when it throws. `name()` 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(text: => String, fallback: String): String =

Review Comment:
   **[26] Nit: a generic `orElse` would also cover the `inputTypes()` guard in 
`createPartitioning`.**
   
   [Item 14](https://github.com/apache/spark/pull/59760#discussion_r4463685235) 
made this `private[sql]`, but since it takes only a `String`, 
`createPartitioning` repeats the same `catch { case NonFatal(_) | _: 
LinkageError => Nil }` for `inputTypes()` (`partitioning.scala:2649-2650`) and 
imports `NonFatal` for that line alone. `orElse[T](value: => T, fallback: => 
T): T` would make it `orElse(t.function.inputTypes().toSeq, Nil)`. In the same 
spirit, the two catch arms at L225-227 could be one, `case e @ (NonFatal(_) | 
_: LinkageError) =>`, which would drop `cannotResolve`. Then one pattern 
decides which connector failures are swallowed.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/TransformExpressionSuite.scala:
##########
@@ -112,4 +117,404 @@ 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, level = Some(Level.INFO)) {

Review Comment:
   **[24] Nit: `withLogAppender` can scope the appender to this logger.**
   
   The seven log tests attach the appender to the root logger and then keep the 
events whose `getLoggerName` ends with "TransformExpression" (L319, L367, L418, 
L443, L466, L489, L515). Passing `loggerNames = 
Seq(classOf[TransformExpression].getName)`, as 
`EnsureRequirementsSuite.scala:1257` does, would replace those filters and keep 
other loggers' events out of the appender's 1000-event cap.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2415,6 +2433,27 @@ case class KeyedShuffleSpec(
   private def argumentsAreColumns(transform: TransformExpression): Boolean =
     transform.children.forall(_.isInstanceOf[Attribute])
 
+  /**
+   * Whether Spark can evaluate `transform`, see 
`TransformExpression.evaluableFunction`. An
+   * identity reduce evaluates it on the identity side's partition keys, and a 
one-side shuffle on
+   * each row of the side it shuffles, both after rebuilding it over the other 
side's key. An
+   * equi-join pairs two keys only when their types are equal apart from 
nullability and field
+   * names (`BinaryComparison.sameType`), which `evaluableFunction` does not 
tell apart either. So
+   * for a join, asking this of the reported transform answers it for the 
rebuilt one, and the
+   * reported one keeps the answer. A Pandas or Arrow cogroup does not coerce 
its keys, so a key of
+   * another type, e.g. a `BIGINT` against a transform over an `INT` column 
that declares `INT`,
+   * can still fail as it did before this check. A one-side shuffle fails 
while planning, in
+   * `createPartitioning`. A decimal key of the column's scale passes, since 
its precision does not
+   * change what the function reads.
+   *
+   * A Scala class or object that extends `ScalarFunction` directly gets a 
mixin forwarder to the
+   * default `produceResult`, which the lookup finds, so this is true even 
when the connector
+   * implements neither `produceResult` nor `invoke`. Evaluating it then throws
+   * `SCALAR_FUNCTION_NOT_COMPATIBLE`. Reflection cannot tell the forwarder 
from an override.
+   */
+  private def canEvaluate(transform: TransformExpression): Boolean =

Review Comment:
   **[25] Nit: taking any `Expression` here would remove two duplicated arms.**
   
   Since this takes only a `TransformExpression`:
   
   - the base's single alternative in `isExpressionCompatible` became two 
identical arms (L2408-2411);
   - `canEvaluatePartitioning` spells out the default (L2622-2625);
   - `createPartitioning` asks `t.evaluableFunction.isEmpty` directly (L2646).
   
   With `case t: TransformExpression => t.evaluableFunction.isDefined` and 
`case _ => true`, the arm can go back to the base's `(_: AttributeReference, _: 
TransformExpression) | (_: TransformExpression, _: AttributeReference)` with 
`allowReduce && canReduceKeys && canEvaluate(left) && canEvaluate(right)`, and 
the other two become `partitioning.expressions.forall(canEvaluate)` and 
`!canEvaluate(t)`, with the same results.



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