spark-test commented on code in PR #60695:
URL: https://github.com/apache/spark/pull/60695#discussion_r4624209558
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UpdateAttributeNullability.scala:
##########
@@ -69,4 +70,18 @@ object UpdateAttributeNullability extends Rule[LogicalPlan] {
}
if (newOutput == m.output) m else m.copy(output = newOutput)
}
+
+ // Expand derives the nullability of its new output attributes from its
projections when it is
+ // built, for instance, for grouping sets or UNPIVOT. The projections may
become nullable later
+ // when this rule updates the attributes they reference, e.g., a column of a
Dataset that an
+ // outer join makes nullable, so widen the nullability of the output
attributes accordingly,
+ // keeping their expression IDs.
+ private def widenOutputNullability(e: Expand): Expand = {
+ val projections = e.projections.map(_.toIndexedSeq)
+ val newOutput = e.output.zipWithIndex.map { case (attr, index) =>
+ attr.withNullability(
Review Comment:
**Non-blocking (P2):** `withNullability` changes only the top-level flag, so
the output's data type keeps the nested nullability that `UnpivotTransformer`
or `GroupingAnalyticsTransformer` fixed when it built the `Expand`. Reading the
code, with the data of the new test,
```scala
left.join(right, left("a") === right("b"), "left_outer")
.unpivot(Array(left("a")), Array(struct(right("b")).as("s")), "col",
"value")
```
keeps `value` as `struct<b: int NOT NULL>`. `GetStructField.nullable` takes
the field's nullability from that type (complexTypeExtractors.scala:227), so
`$"value.b".isNull` folds to false and `$"value.b"` reads a non-NULL value such
as 0 for the unmatched row. An `array(right("b"))` value keeps `containsNull =
false` the same way. For a `groupingSets` key such as `struct(right("b"))`,
even the `Expand` projections keep the old type, because the main pass at lines
51-54 updates only the nullable flag of the alias they reference. The same
queries with the top-level column `right("b")` now return NULL, so the fix
looks complete while nested values still return the wrong result.
**Recommended change:** Extend the Expand widening in
UpdateAttributeNullability so that each output's data type also takes the
nested nullability of the projections at its position, merging struct field,
array element, and map value nullability the way the unpivot value type already
merges values, and only ever widening, while keeping the expression ID, name,
and metadata. In the rule's main pass, when a reference is updated from a child
output with the same expression ID, also take that output's data type when the
two differ only in nullability, so the projections of a grouping-sets Expand
and the operators above an Expand see the widened type. Add Dataset unpivot
tests for a struct value and an array value over a column that a left outer
join makes nullable, and a Dataset grouping-sets test that groups by a struct
of such a column.
**Why this works:** Once the rule has rewritten the projections' references,
each projection's type carries the nested nullability the outer join produces;
merging those types into the output makes the Expand declare what it emits, and
carrying the merged type to references by expression ID gives every parent a
struct field, array element, or map value that is nullable wherever the data
can be NULL, so NullPropagation no longer folds IS NULL on it and generated
code checks it.
**Compatibility:** The top-level widening this PR adds, the expression IDs
it keeps, and the schemas of the unpivot variable and id columns stay as they
are.
**Risks:** References in every operator, not only around an Expand, take a
child's wider nested nullability, so a plan that reads a struct, array, or map
built from a pre-resolved column on the null-supplying side of an outer join,
such as a Spark Connect plan analyzed at once, can report a nested field as
nullable where it reported NOT NULL before; that corrects the same kind of
wrong result, and no flag brings the old types back. A streaming query started
before Spark 4.3 that keeps such a nested column in its state fails to restart
in the same way as one that keeps a top-level column, so the streaming
migration note this review asks for should then name nested fields too. A DSv2
write of such a nested column into a NOT NULL nested field now checks that
field and fails for rows where it is NULL, instead of storing a non-NULL value.
**Constraints:** The merge only widens: it never turns a nullable struct
field, array element, or map value into NOT NULL, so the optimizer and AQE runs
of the rule cannot change a type between runs. A reference takes a child
output's data type only when the two have the same expression ID and differ in
nullability alone. With spark.sql.legacy.unpivot.useFirstValueNestedNullability
set to true, an unpivot value column keeps taking its nested nullability from
the first value, as that flag documents.
**Exclusions:**
- Generate outputs, such as the element of explode over an array built from
a column that an outer join makes nullable, keep their stale nullability; that
is a separate bug in a different operator.
- MergeRows outputs keep widening at the top level only.
**Verification:**
- **Regression:** Unpivoting struct(right("b")) after a left outer join,
with the data of the PR's test, reports the struct's field as nullable and
returns NULL for that field and true for its IS NULL on the unmatched row, and
unpivoting array(right("b")) returns a NULL element on that row when the value
is exploded.
- **Regression:** Dataset groupingSets over a left outer join that groups by
a struct of the null-supplying side's column reports the field of the struct
key as nullable and returns NULL in it for the unmatched row, which needs the
widened type to reach the aggregate above the Expand.
- **Compatibility:** With
spark.sql.legacy.unpivot.useFirstValueNestedNullability set to true, an unpivot
value column keeps the first value's nested nullability, and unpivots and
grouping sets whose nested values do not come from such a column keep their
data types.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UpdateAttributeNullability.scala:
##########
@@ -54,6 +54,7 @@ object UpdateAttributeNullability extends Rule[LogicalPlan] {
}
newPlan match {
case m: MergeRows => widenOutputNullability(m)
+ case e: Expand => widenOutputNullability(e)
Review Comment:
**Blocking (P1):** This arm also widens the `Expand` that
`EvaluateUnresolvedInlineTable.toExpand` builds for a VALUES list evaluated
when the query runs (`spark.sql.inlineTable.nonFoldableExpressions.enabled`, on
by default). That `Expand` takes each column's nullability from the values
before their cast (`nullable = column.exists(_.nullable)`,
EvaluateUnresolvedInlineTable.scala:221), so a cast that `Cast.forceNullable`
marks nullable, such as DATE to TIMESTAMP_NTZ, leaves a NOT NULL output over a
nullable projection.
Reading the code, with a DSv2 table `t (ts TIMESTAMP_NTZ NOT NULL, r
DOUBLE)` in a catalog that keeps NOT NULL:
```sql
INSERT INTO t VALUES (current_date(), rand()), (TIMESTAMP_NTZ'2020-01-01
00:00:00', 1.0D)
```
`ResolveOutputRelation` sees `col1` as NOT NULL in the Resolution batch and
adds no `AssertNotNull`. This arm then makes `col1` nullable in the `ScalaUDF
Null Handling` batch, `V2WriteCommand.outputResolved` turns false, and
`CheckAnalysis` throws `[INTERNAL_ERROR] Found the unresolved operator:
'AppendData` although no value is NULL. The base branch writes both rows, and
an insert-only MERGE from such a VALUES source fails the same way. Writes of an
already analyzed Dataset are not affected, because their query is widened
before the write is resolved. It is the ordering problem that SPARK-61935
removed for Scala UDFs.
The fix belongs in the producer: in `toExpand`, mark an output attribute
nullable when any row's value for that column, after its cast or constant
folding, is nullable. Write resolution then adds an `AssertNotNull` that
passes, and this arm changes nothing for that `Expand`.
**Verification:**
- **Regression:** An INSERT into a DSv2 table that keeps a NOT NULL
TIMESTAMP_NTZ column, from a VALUES list that has a runtime-evaluated value
such as rand() and mixes a non-constant DATE such as current_date() with a
TIMESTAMP_NTZ literal in that column, succeeds and stores both rows, where it
fails with an internal error about an unresolved AppendData before the repair.
- **Behavior:** A SELECT over the same VALUES list reports that column as
nullable and returns both rows with non-NULL values.
- **Compatibility:** VALUES lists that are evaluated during analysis, and
runtime-evaluated VALUES lists whose casts cannot return NULL, report the same
column nullability as on the base branch, such as a NOT NULL column whose
integer value is cast to BIGINT next to rand().
##########
sql/core/src/test/scala/org/apache/spark/sql/DatasetUnpivotSuite.scala:
##########
@@ -780,6 +780,16 @@ class DatasetUnpivotSuite extends SharedSparkSession {
}
}
+ test("SPARK-62051: unpivot of a column made nullable by an outer join") {
+ val left = Seq(1, 2).toDF("a")
+ val right = Seq(2).toDF("b")
+ // `right("b")` is resolved as non-nullable, and becomes nullable after
resolution
+ checkAnswer(
+ left.join(right, left("a") === right("b"), "left_outer")
+ .unpivot(Array(left("a")), Array(right("b")), "col", "value"),
Review Comment:
**Nit (P3):** With a single value, the `Expand` has one projection, so
`projections.exists(...)` (UpdateAttributeNullability.scala:83), a `forall`,
and a check of the first projection all agree, and this test passes under each
of them. A case with two values where only the second comes from the
null-supplying side tells them apart, for example with `left = Seq((1, 10), (2,
20)).toDF("a", "x")`:
```scala
left.join(right, left("a") === right("b"), "left_outer")
.unpivot(Array(left("a")), Array(left("x"), right("b")), "col", "value")
```
Its value column has to be nullable and the unmatched row's `b` value NULL;
a first-projection or all-projections check would keep the column NOT NULL and
return -1 or 0 for that row.
**Verification:**
- **Regression:** Unpivoting two values after a left outer join, where only
the second value comes from the null-supplying side, reports the value column
as nullable and returns NULL for that value on the unmatched row, which fails
on the base branch and would also fail if the widening looked only at the first
projection or required every projection to be nullable.
--
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]