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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -167,30 +175,172 @@ 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 =>
+            TransformExpression.logArgumentsMismatch(scalarFunc, 
arguments.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`, 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 }
+
+  /**
+   * Logs that `function`'s input types do not take `argumentTypes`, see 
`evaluableFunction`, with
+   * the failure to look up the method the call invokes, when that is what 
refused it. A
+   * user-defined type is named by its class, since its `catalogString` is its 
`sqlType`'s.
+   */
+  private def logArgumentsMismatch(
+      function: BoundFunction,
+      argumentTypes: Seq[DataType],
+      declaredTypes: Seq[DataType],
+      lookupFailure: Option[Throwable]): Unit = {
+    def typeName(dataType: DataType): String = dataType match {
+      case udt: UserDefinedType[_] => 
s"${udt.getClass.getName}(${udt.sqlType.catalogString})"
+      case other => other.catalogString
+    }
+    def typeList(types: Seq[DataType]): String = 
types.map(typeName).mkString("(", ", ", ")")
+    val functionClass = function.getClass.getName
+    val arguments = typeList(argumentTypes)
+    val reason = lookupFailure.map(e => s": ${orElse(e.toString, 
e.getClass.getName)}")

Review Comment:
   **[30] Nit: the INFO line for a refused user-defined type now ends with 
`[INTERNAL_ERROR]` again.**
   
   This is about the change for [item 
20](https://github.com/apache/spark/pull/59760#discussion_r4532209389). 
`reason` is the failure's `toString`, and the failure is what 
`InvokeLike.findMethod` throws, `QueryExecutionErrors.methodNotFoundError`, 
which is a `SparkException.internalError`. Its message carries the condition 
and the SQL state, so for the `withInvoke` case in `TransformExpressionSuite` 
the line now ends like this (wrapped):
   
   ```
   ... so a storage-partitioned join does not evaluate it: 
org.apache.spark.SparkException:
   [INTERNAL_ERROR] Couldn't find method invoke with arguments (int, class 
java.lang.Object)
   on class ... SQLSTATE: XX000
   ```
   
   That is the text [item 
13](https://github.com/apache/spark/pull/59760#discussion_r4463685227) took out 
of the WARN line, since it reads like a Spark bug, and a search of the logs for 
`INTERNAL_ERROR` now finds this INFO line. Could the line carry only the 
lookup's own text, e.g. the `message` parameter when the failure is a 
`SparkThrowable`? The new assertion at `TransformExpressionSuite.scala:329` 
checks only "Couldn't find method invoke", so it would keep passing.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -202,4 +352,112 @@ 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 value read at a 
smaller precision than
+   * it has is then read as it is, as a `long`, or fails, as bytes.

Review Comment:
   **[31] Nit: a decimal stored as a `long` and read at a smaller precision 
fails in an array, as bytes do.**
   
   L406-407 says such a value "is then read as it is, as a `long`, or fails, as 
bytes". That holds in a row: `UnsafeRow.getDecimal` reads a `long` with 
`Decimal.createUnsafe`, which checks nothing, at the top level and in a struct 
field. An array element, or a map's key or value, goes through 
`UnsafeArrayData.getDecimal` instead, which reads it with `Decimal.apply(long, 
precision, scale)`, and `set` throws when the value needs more digits than that 
precision.
   
   So for the pair the new test accepts at 
`TransformExpressionSuite.scala:357`, `ARRAY<DECIMAL(10,2)>` against 
`ARRAY<DECIMAL(18,2)>`, a cogroup whose left key is the narrower one fails in 
the task as soon as the other side holds an element of more than 10 digits. It 
never pairs groups wrongly, and after a hash shuffle the cogroup compares the 
keys the same way, so only the comment needs a word, e.g. "is then read as it 
is, as a `long` in a row, and fails in an array or a map, as it does as bytes".



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