dongjoon-hyun commented on code in PR #59760:
URL: https://github.com/apache/spark/pull/59760#discussion_r4463685235
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/physical/partitioning.scala:
##########
@@ -2570,24 +2609,44 @@ 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 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 =>
+ throw QueryExecutionErrors.storagePartitionJoinKeyTypeMismatchError(
+ t.function.name(), t.function.inputTypes().toSeq,
t.children.head.dataType)
Review Comment:
**[14] Minor: the new error path calls connector code without the guard the
PR uses elsewhere.**
`t.function.name()` runs unguarded here. `TransformExpression.orElse`
(TransformExpression.scala:292-298) exists because `name()` is connector code
that can throw, e.g. a `NoClassDefFoundError` for a missing dependency, and the
mismatch log for this very transform already went through it
(TransformExpression.scala:311). If `name()` throws here, the user gets that
raw `Throwable` from planning instead of
`STORAGE_PARTITION_JOIN_KEY_TYPE_MISMATCH`.
Could this use the same fallback, the function class name, e.g. by making
`orElse` `private[sql]`?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -167,30 +175,173 @@ 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 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)
+ }
+ if (arguments.length == declaredTypes.length &&
typed.forall(_.isDefined)) {
+ val call = V2ExpressionUtils.resolveScalarFunction(scalarFunc,
typed.flatten)
+ // `Invoke` and `StaticInvoke` look the method up again from the
arguments' classes, a
+ // user-defined type's being `Object`, so look it up here, where a
failure is caught and
+ // logged, rather than in `eval`.
+ call match {
Review Comment:
**[13] A user-defined type refused here is warned about as an
`INTERNAL_ERROR`, not logged at INFO as an argument mismatch.**
This follows up on @peter-toth's finding 14. The lookup at L251-255 refuses
the UDT case as intended, but it does so by throwing: `Invoke.method` and
`StaticInvoke.method` call `findMethod`, which raises
`QueryExecutionErrors.methodNotFoundError`, a `SparkException.internalError`.
That lands in the `catch` of `evaluableFunctionAttempt` (L225-227), so
`logCannotResolve` warns "Cannot resolve a call of the partition transform
bucket ... does not evaluate it: org.apache.spark.SparkException:
[INTERNAL_ERROR] Couldn't find method invoke with arguments (int, class
java.lang.Object) ...". For the `withInvoke` function in the new
`TransformExpressionSuite` test (L285), that reads like a Spark or connector
bug, while the description says an argument mismatch is logged at INFO and only
a call that fails to resolve at WARN.
It also takes the `functionClass:SparkException` key in
`failuresWarnedAbout` (L335), so a later genuine resolution failure of the same
function class and kind is not warned about.
Could the lookup failure be caught here, logged through
`logArgumentsMismatch`, and return `None`, so that a UDT the magic `invoke`
cannot take is reported as the mismatch it is?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -202,4 +353,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) =>
Review Comment:
**[15] Nit: `atDeclaredType` still refuses a few lossless, time-zone-free
up-casts, so those layouts shuffle both sides.**
This follows up on [2]. L373 casts only what
`UpCastRule.legalNumericPrecedence` admits. Two other casts are lossless too
and need no time zone (`Cast.needsTimeZone` is false for both), but they fall
to `case _` at L375:
- `DATE` against a declared `TIMESTAMP_NTZ`, which is midnight on a fixed
UTC grid;
- an integral type against a `DECIMAL` wide enough for it (the
`to.isWiderThan(from)` arm of `UpCastRule.canUpCast`).
Master failed on both, since the physical types differ, so this is not a
regression, only plans the check could keep. `canUpCast(argumentType,
declaredType) && !Cast.needsTimeZone(argumentType, declaredType)` would cover
them, but it is too broad as it stands, since `canUpCast` also admits any
atomic type to `STRING`. So two explicit arms may be simpler. Not blocking, and
fine as a follow-up.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TransformExpression.scala:
##########
@@ -167,30 +175,173 @@ 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 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)
+ }
+ if (arguments.length == declaredTypes.length &&
typed.forall(_.isDefined)) {
+ val call = V2ExpressionUtils.resolveScalarFunction(scalarFunc,
typed.flatten)
+ // `Invoke` and `StaticInvoke` look the method up again from the
arguments' classes, a
+ // user-defined type's being `Object`, so look it up here, where a
failure is caught and
+ // logged, rather than in `eval`.
+ call match {
+ case i: objects.Invoke => i.method
+ case s: objects.StaticInvoke => s.method
+ case _ =>
+ }
+ Some(call)
+ } else {
+ TransformExpression.logArgumentsMismatch(scalarFunc,
arguments.map(_.dataType),
+ declaredTypes)
+ 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 {
+ /**
+ * The function classes and kinds of failure a failure to resolve a call was
logged as a warning
+ * for, as `functionClass:failureClass`. A function class that fails in
another way is warned
+ * about again.
+ */
+ private val failuresWarnedAbout: java.util.Set[String] =
ConcurrentHashMap.newKeySet[String]()
Review Comment:
**[16] Nit: the three log-once sets and their helpers could be one of each.**
`failuresWarnedAbout`, `mismatchesLogged` and `notScalarLogged` (L280-290)
differ only in their keys, and `logArgumentsMismatch`, `logNotScalar` and
`logCannotResolve` (L303-343) repeat one shape: add the key, then log with
`orElse(function.name(), functionClass)`. One set whose keys carry the kind
(e.g. `s"mismatch:$functionClass:$arguments:$declared"`,
`s"notScalar:$functionClass"`, `s"failure:$functionClass:$failureClass"`) and
one small log-once helper would keep the three messages and drop two sets and
their docs.
The three have already drifted a little: `logCannotResolve` computes
`functionName` before the check, since its `logDebug` runs on every call.
--
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]