spark-test commented on code in PR #60651:
URL: https://github.com/apache/spark/pull/60651#discussion_r4610831131
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ScalaUDF.scala:
##########
@@ -52,12 +52,19 @@ case class ScalaUDF(
inputEncoders: Seq[Option[ExpressionEncoder[_]]] = Nil,
outputEncoder: Option[ExpressionEncoder[_]] = None,
udfName: Option[String] = None,
- nullable: Boolean = true,
+ udfNullable: Boolean = true,
udfDeterministic: Boolean = true)
extends Expression with NonSQLExpression with UserDefinedExpression {
override lazy val deterministic: Boolean = udfDeterministic &&
children.forall(_.deterministic)
+ // The analyzer makes the UDF return null for a null input of a primitive
parameter (see
+ // `HandleNullInputsForUDF`) only after resolution, so the nullability
covers that case for the
+ // rules that run before, e.g. the ones adding NOT NULL checks to table
writes.
+ override def nullable: Boolean = udfNullable ||
inputPrimitives.zip(children).exists {
Review Comment:
**Nit (P3):** Because `nullable` is a `def`, every call on a UDF with
`udfNullable = false` (any typed UDF with a primitive return type, or one
marked `asNonNullable`) allocates a new `inputPrimitives.zip(children)`
collection and rereads the primitive children's nullability. Planning calls it
often: `Project.output` maps `Alias.toAttribute`, which reads `child.nullable`
on each call (basicLogicalOperators.scala:75, namedExpressions.scala:204-206),
so a plan projecting many such UDF columns, or a nested unwrapped chain like
`plus1(plus1(plus1(id)))`, repeats the walk throughout analysis and
optimization. The value cannot change for an immutable expression, and
`InvokeLike` caches the same primitive-argument check in lazy vals
(objects.scala:76-78), as this class already does for `deterministic` and
`inputPrimitives`. A private lazy val for the input-derived term, walking
`inputPrimitives` and `children` without an intermediate collection, keeps the
result identical. This is planni
ng cost only; generated code and execution are unchanged.
**Verification:**
- **Inspection:** The input-derived term of ScalaUDF.nullable is computed
once per instance without an intermediate collection, and udfNullable still
short-circuits it.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ScalaUDF.scala:
##########
@@ -52,12 +52,19 @@ case class ScalaUDF(
inputEncoders: Seq[Option[ExpressionEncoder[_]]] = Nil,
outputEncoder: Option[ExpressionEncoder[_]] = None,
udfName: Option[String] = None,
- nullable: Boolean = true,
+ udfNullable: Boolean = true,
udfDeterministic: Boolean = true)
extends Expression with NonSQLExpression with UserDefinedExpression {
override lazy val deterministic: Boolean = udfDeterministic &&
children.forall(_.deterministic)
+ // The analyzer makes the UDF return null for a null input of a primitive
parameter (see
+ // `HandleNullInputsForUDF`) only after resolution, so the nullability
covers that case for the
+ // rules that run before, e.g. the ones adding NOT NULL checks to table
writes.
+ override def nullable: Boolean = udfNullable ||
inputPrimitives.zip(children).exists {
Review Comment:
**Non-blocking (P2):** This reads each primitive argument's nullability as
it is when a rule asks, but in the Resolution batch
`ResolveRowLevelCommandAssignments`, `RewriteUpdateTable` and
`RewriteMergeIntoTable` (Analyzer.scala:799-802) run before `typeCoercionRules`
(Analyzer.scala:805), in the same iteration in which `ResolveFunctions` creates
the UDF. `ScalaUDF` has no input type check, so with `plus1 = (x: Int) => x +
1` and `dep` a `NOT NULL STRING`, `UPDATE t SET salary = plus1(dep) WHERE pk =
1` is aligned while the argument is still the bare `dep`: `nullable` is false
here and `checkNullability` adds no `AssertNotNull`
(TableOutputResolver.scala:635-652). Only afterwards does `ImplicitTypeCasts`
turn the argument into `CAST(dep AS INT)`, which is nullable by type in every
non-try mode (Cast.scala:919-920). With `spark.sql.ansi.enabled=false` that
cast returns NULL for a value like `'hr'`, `HandleNullInputsForUDF` makes the
UDF return NULL, and the `ReplaceData` or `WriteD
elta` row projection keeps the non-nullable schema it captured at rewrite time
(RewriteRowLevelCommand.scala:346-355), so following the code, NULL is written
into `salary` without `NOT_NULL_ASSERT_VIOLATION`. `MERGE ... WHEN MATCHED THEN
UPDATE SET salary = plus1(s.dep)` takes the same path when `s.dep` is a
non-nullable STRING. INSERT and insert-only MERGE are fine because their writes
are checked after coercion, and with ANSI on the cast fails instead of
returning NULL. The base branch writes NULL for these statements too, so this
is the failure the PR fixes, still open for arguments that become nullable only
through the UDF's implicit input cast.
**Recommended change:** Make ScalaUDF.nullable also count a primitive
parameter whose argument does not yet have the parameter's input type and whose
implicit cast to that type can return NULL. For primitive parameter i, with
argument c and input type t taken from inputTypes (ScalaUDF.scala line 117),
treat the parameter as nullable when c.nullable is true, or when c.dataType
differs from t and Cast.forceNullable(c.dataType, t) is true. Add UPDATE and
MERGE cases to the DSv2 row-level operation tests that, with
spark.sql.ansi.enabled set to false, write a typed Int => Int UDF over a NOT
NULL STRING value into a NOT NULL column. A row whose string does not parse
must fail with NOT_NULL_ASSERT_VIOLATION, and a row whose string parses must
write the computed value.
**Why this works:** Once coercion runs, the argument becomes a cast to t,
whose nullability is the argument's nullability or
Cast.forceNullable(c.dataType, t) for a non-try cast (Cast.scala lines
919-920). Predicting that value before coercion gives ScalaUDF.nullable the
same answer before and after ImplicitTypeCoercion (TypeCoercionHelper.scala
lines 800-814). Row-level alignment then adds AssertNotNull for such an
assignment (TableOutputResolver.scala lines 635-652), and the frozen
ReplaceData or WriteDelta projection records the asserted, non-nullable value,
matching the If wrapper the null-input rewrite adds later.
**Compatibility:** Generated code and evaluation stay as on the PR head, and
a UDF whose primitive arguments already have the parameter's input type reports
the same nullability as on the PR head.
**Risks:** An argument whose implicit cast can return NULL by type but never
does at runtime now reports nullable before coercion as well as after. Examples
are a fractional argument to an integral parameter in LEGACY mode, and a STRING
argument with ANSI on, where the cast fails instead of returning NULL. Rules
that run before coercion then add a NOT NULL check that never fails and record
nullable attributes. On the PR head these UDFs already report nullable once
coercion has run, so only plans recorded in that window change, and reverting
the change restores them.
**Constraints:** Keep the prediction equal to the nullability of the non-try
cast that ImplicitTypeCoercion inserts for a primitive parameter, which is the
parameter's input type, and do not consult spark.sql.ansi.enabled, because
Cast.forceNullable does not depend on it. Leave udfNullable as the flag code
generation reads for Option unwrapping.
**Verification:**
- **Regression:** With spark.sql.ansi.enabled set to false, an UPDATE and a
MERGE with a WHEN MATCHED UPDATE clause set a NOT NULL INT column to a typed
Int => Int UDF applied to a NOT NULL STRING value. They must fail with
NOT_NULL_ASSERT_VIOLATION when the string does not parse and write the computed
value when it parses, for both group-based and delta-based row-level writes.
- **Behavior:** A UDF with udfNullable = false and an Int parameter over a
non-nullable STRING argument reports nullable both before coercion and after
it, over the resulting cast, while the same UDF over a non-nullable INT
argument stays non-nullable.
- **Compatibility:** With ANSI on, the same UPDATE still fails with the cast
error for a string that does not parse, and assignments whose UDF arguments
already have the parameter type keep the nullability they have on the PR head.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/AnalysisSuite.scala:
##########
@@ -2203,7 +2203,7 @@ class AnalysisSuite extends AnalysisTest with Matchers {
function = (i: Int) => i + 1,
dataType = IntegerType,
children = $"a" :: Nil,
- nullable = false,
+ udfNullable = false,
Review Comment:
**Non-blocking (P2):** After the rename this test no longer exercises the
batch it was written for: the UDF over the nullable `testRelation` column `a`
is already nullable at resolution, so `u` and the outer reference are nullable
before the `ScalaUDF Null Handling` batch runs, and the assertion holds even
without its `UpdateAttributeNullability`. UDFSuite's `SPARK-47927: ScalaUDF
null handling` (UDFSuite.scala:1272-1277), the test that needed the batch's
second pass on the base branch, is masked the same way, since the lateral alias
it reads is now nullable at resolution. The struct-input `SPARK-47927:
Correctly pass null values derived from join to UDF` test
(UDFSuite.scala:1200-1209) still catches dropping `UpdateAttributeNullability`,
but never needs a second wrap. So, reading the code, if the batch were changed
to run once, all of these tests would still pass, while a typed `Int => Int`
UDF applied to a resolved non-nullable Dataset column from the null-supplying
side of a le
ft outer join would be left unwrapped and return 1 instead of NULL for an
unmatched row. A test of that shape that checks the NULL result would restore
the signal.
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ScalaUDFSuite.scala:
##########
@@ -139,4 +139,16 @@ class ScalaUDFSuite extends SparkFunSuite with
ExpressionEvalHelper {
val code = udf.genCode(new CodegenContext).code.toString
assert(!code.contains("fieldName") && !code.contains("udfName") &&
!code.contains("outputName"))
}
+
+ test("SPARK-61935: nullable when the input of a primitive parameter is
nullable") {
Review Comment:
**Nit (P3):** All three assertions use one-parameter UDFs, so they cannot
tell the per-parameter pairing in the override from a wrong one. Replacing its
body with `inputPrimitives.headOption.contains(true) &&
children.head.nullable`, or with `inputPrimitives.contains(true) &&
children.exists(_.nullable)`, would still pass them, although the first reports
an `(Int, Int)` UDF whose only nullable input is the second one as
non-nullable, and the second reports a `(String, Int)` UDF whose only nullable
input is the String as nullable. The existing multi-parameter tests do not
cover this either: the AnalysisSuite ones keep the default `udfNullable =
true`, and UDFSuite's SPARK-24891 tests check results that
`HandleNullInputsForUDF` produces on its own. Those two two-parameter cases
would close the gap.
**Verification:**
- **Behavior:** For a UDF with udfNullable = false, two Int parameters and
only the second argument nullable, nullable is true. For a String and an Int
parameter with only the String argument nullable, nullable is false.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ScalaUDF.scala:
##########
@@ -41,7 +41,7 @@ import org.apache.spark.util.Utils
* @param outputEncoder ExpressionEncoder for the return type of function.
It's only defined when
* this is a typed Scala UDF.
* @param udfName The user-specified name of this UDF.
- * @param nullable True if the UDF can return null value.
+ * @param udfNullable True if the UDF can return null value.
Review Comment:
**Nit (P3):** After the split, `udfNullable` is only the declared
nullability of the function's result: it is what `toScalaUDF` passes from
`UserDefinedFunction.nullable`, and what code generation reads to decide Option
unwrapping. The expression's `nullable` is also true for a null primitive
input, which the new ScalaUDFSuite test asserts for `udfNullable = false`. The
kept description says `false` means the UDF cannot return null, which now
describes `nullable` instead. Suggested wording:
```suggestion
* @param udfNullable True if the function itself can return null.
`nullable` is also true when
* a primitive parameter's input can be null.
```
**Verification:**
- **Inspection:** The udfNullable description no longer says that a false
value means the UDF cannot return null, and it points to nullable for arguments
of primitive parameters.
--
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]