spark-test commented on code in PR #60061:
URL: https://github.com/apache/spark/pull/60061#discussion_r4510531833


##########
docs/sql-migration-guide.md:
##########
@@ -67,6 +67,7 @@ license: |
 - Since Spark 4.4, 
`spark.sql.sources.v2.bucketing.preserveKeyOrderingOnCoalesce.enabled` defaults 
to `true`. When `GroupPartitionsExec` merges several input partitions that 
share one partition key value into a single output partition, it now keeps sort 
orders over the partition key expressions in the ordering it reports, since 
those expressions are constant within the merged partition. Sort orders over 
partition transforms such as `days(ts)` or `bucket(8, id)` are left out. Orders 
over other columns are still dropped, as the concatenation invalidates them, 
and a join that reduced the partition keys onto a common key space (see 
`spark.sql.sources.v2.bucketing.allowCompatibleTransforms.enabled`) reports no 
order, since the merged partitions then share only the reduced key. This can 
remove a `Sort` downstream of the merge. To restore the previous behavior, set 
`spark.sql.sources.v2.bucketing.preserveKeyOrderingOnCoalesce.enabled` to 
`false`.
 - Since Spark 4.4, when the `from_protobuf` option 
`unwrap.primitive.wrapper.types` is enabled, `from_protobuf` unwraps a present 
Protobuf primitive wrapper (such as `google.protobuf.Int32Value` or 
`StringValue`) whose inner `value` is unset or set to its default to the type's 
default value (`0`, `false`, `""`, or empty binary), regardless of the 
`emit.default.values` option. Previously such a wrapper unwrapped to `NULL` 
unless the `emit.default.values` option was enabled, which could also place a 
`NULL` into a non-nullable array element or map value. An absent wrapper field 
still unwraps to `NULL`.
 - Since Spark 4.4, the value columns of `UNPIVOT` and `Dataset.unpivot` merge 
the nested nullability (array element, map value, and struct field nullability) 
of all unpivoted values. Previously, a value column took the nested nullability 
of the first listed value, so a `NULL` array element, map value, or struct 
field of a later value could be returned as a non-`NULL` value such as `0`, and 
`IS NULL` on it returned `false`. A view created by an earlier Spark version 
over such an `UNPIVOT` may have recorded the non-nullable nested type in its 
schema and can fail to read; recreate it with `CREATE OR REPLACE VIEW`. To 
restore the previous behavior, set 
`spark.sql.legacy.unpivot.useFirstValueNestedNullability` to `true`.
+- Since Spark 4.4, a recursive CTE whose recursive term writes a `NULL` into 
an array element, map value or struct field of a column that the anchor built 
as non-nullable returns that `NULL`. Previously, the next iteration read such a 
value through the anchor's non-nullable nested type and could return a 
non-`NULL` value such as `0`, with `IS NULL` on it returning `false`, or fail 
with a `NullPointerException`. The nested type of such a column, and of columns 
that copy it, is now nullable in the result, so casting it to a type with a 
`NOT NULL` nested type fails. A view created by an earlier Spark version over 
such a recursive CTE may have recorded the non-nullable nested type in its 
schema and can fail to read; recreate it with `CREATE OR REPLACE VIEW`, or run 
`ALTER VIEW ... WITH SCHEMA EVOLUTION`. Columns that the recursive term only 
passes through keep their type.

Review Comment:
   Thanks for rewriting the entry; it now names the copied and derived columns. 
This review raises a few remaining inaccuracies in it.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4488922785","thread_id":"inline:4488922785","verdict_sha256":"5554de3ab396b0bdf55a7c6fbf310aedea616f56c75e136e5f3f3824dea1ce17"}
 -->



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveWithCTE.scala:
##########
@@ -303,22 +323,101 @@ object ResolveWithCTE extends Rule[LogicalPlan] {
   // Assumes that `anchor` is already resolved. If `columnNames` is set (which 
happens if an
   // UnresolvedSubqueryColumnAliases is atop a Union) also places an 
UnresolvedSubqueryColumnAliases
   // node above UnionLoopRef. At some later stage 
UnresolvedSubqueryColumnAliases gets resolved to
-  // a Project node.
+  // a Project node. `refTypes` overrides the anchor's data types and 
nullability for the
+  // UnionLoopRef output.
   private def rewriteRecursiveCTERefs(
       recursion: LogicalPlan,
       anchor: LogicalPlan,
       cteDefId: Long,
-      columnNames: Option[Seq[String]]) = {
+      columnNames: Option[Seq[String]],
+      refTypes: Option[Seq[(DataType, Boolean)]] = None) = {
+    val types = refTypes.getOrElse(outputTypes(anchor))
     recursion.transformUpWithSubqueriesAndPruning(_.containsPattern(CTE)) {
       case r: CTERelationRef if r.recursive && r.cteId == cteDefId =>
-        // We mark the output of UnionLoopRef as nullable as it may become 
NULL in the following
-        // iterations.
-        val ref =
-          UnionLoopRef(r.cteId, 
anchor.output.map(_.newInstance().withNullability(true)), false)
+        val output = anchor.output.zip(types).map { case (a, (dt, nullable)) =>
+          a.newInstance().withNullability(nullable).withDataType(dt)
+        }
+        val ref = UnionLoopRef(r.cteId, output, false)
         columnNames.map(UnresolvedSubqueryColumnAliases(_, ref)).getOrElse(ref)
     }
   }
 
+  private def outputTypes(plan: LogicalPlan): Seq[(DataType, Boolean)] =
+    plan.output.map(a => (a.dataType, a.nullable))
+
+  // The anchor's types, unless widenSelfReference has found wider ones.
+  private def selfReferenceTypes(
+      cteDef: CTERelationDef,
+      anchor: LogicalPlan): Seq[(DataType, Boolean)] =
+    cteDef.getTagValue(SELF_REFERENCE_TYPES).getOrElse(outputTypes(anchor))
+
+  // The self-reference starts with the anchor's types and nullability, but 
the recursion can
+  // write NULLs that they do not allow, e.g. ARRAY(CAST(NULL AS INT)) for an 
ARRAY(1) anchor. Once
+  // the loop is resolved, widens the self-reference's nullability, top-level 
and nested, to the
+  // anchor's and recursion's and rebuilds the loop from the original 
definition. This repeats
+  // until nothing widens.
+  // TODO: Copies of values that Spark types as nullable whatever their 
inputs, such as arr[0] or
+  // array_append results, still widen even if they never hold NULLs.
+  private def widenSelfReference(cteDef: CTERelationDef): CTERelationDef = {
+    val loop = if (cteDef.hasSelfReferenceAsUnionLoopRef) {
+      cteDef.child.collectFirst { case l: UnionLoop if l.id == cteDef.id => l }
+    } else {
+      None
+    }
+    loop.filter(_.resolved) match {
+      case Some(l) =>
+        val refTypes = cteDef.child.collectFirstWithSubqueries {
+          case r: UnionLoopRef if r.loopId == cteDef.id => outputTypes(r)
+        }.get
+        val childOutputs = Seq(l.anchor, 
l.recursion).map(withLaterNullability(_).output)

Review Comment:
   **Blocking (P1):** `withLaterNullability` wraps primitive-parameter UDFs in 
the copies, and `refreshAttributeTypes` then gives each reference its child's 
more nullable nested type, including references inside expressions that were 
type-checked against the narrower type. A cast whose target has non-null nested 
positions then fails `resolvableNullability`, `Alias.toAttribute` returns an 
`UnresolvedAttribute`, and reading `output(i).dataType` from the copy throws 
`UnresolvedException`.
   
   With `spark.udf.register("f", (x: Int) => x + 1)`:
   
   ```sql
   WITH RECURSIVE t(lvl, arr) AS (
     SELECT 0, ARRAY(CAST(1 AS BIGINT))
     UNION ALL
     SELECT lvl + 1, ARRAY(f(IF(lvl < 0, NULL, lvl))) FROM t WHERE lvl < 2
   )
   SELECT * FROM t
   ```
   
   Type coercion casts the recursion's `ARRAY<INT>` to `ARRAY<BIGINT>` with 
non-null elements, and the loop resolves. In the copy, `f` is wrapped, the 
array's elements become nullable, the cast stops resolving, and analysis fails 
with `[INTERNAL_ERROR] Invalid call to dataType on unresolved object`. On the 
base branch the live plan keeps the reference's nested type after UDF null 
handling, so the cast stays resolved and the query returns `[1]`, `[1]` and 
`[2]`. A user cast to a type with a NOT NULL nested field in the top projection 
of the anchor or recursion, over a value such a UDF builds, fails the same way. 
Traced from the source, not run.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60061#issuecomment-6664983350), 
[2](https://github.com/apache/spark/pull/60061#pullrequestreview-5779476661).
   
   **Recommended change:** Make the widening total over its copies. Predict 
each column's type from the refreshed copy without requiring type-checked 
expressions to stay resolved: treat a cast whose input became more nullable in 
nested positions as producing those nullable positions, since Spark's casts 
carry NULL elements, values and fields through at run time. Never read the type 
of an unresolved attribute, and if a column's prediction still cannot be 
evaluated, make that column's nested positions nullable instead of failing. Add 
tests in which a primitive UDF builds a nested value that needs a coercion 
cast, and in which a cast to a struct with a NOT NULL field reads a struct that 
such a UDF builds in a FROM subquery.
   
   **Why this works:** A cast in the live plan copies the NULLs its input 
receives into its output at run time, so predicting its output as at least as 
nullable as its refreshed input matches what later iterations read. Without a 
type check that can fail, the prediction is defined for every resolved loop, 
analysis no longer aborts, and the self-reference widens wherever the UDF can 
write NULLs.
   
   **Scope:** Make the recursive CTE self-reference type prediction tolerate 
casts whose inputs become more nullable, and cover UDF-built nested values 
behind casts with tests.
   
   **Risks:** Columns built by primitive UDFs behind casts become nullable in 
the self-reference, and later iterations read them with null checks. Casts are 
the type-checked expressions known to reject more nullable nested inputs; 
whether any other expression's type check does the same is not settled. If one 
does, the fallback makes that column's nested positions nullable, which can 
widen its result type even when it never holds a NULL.
   
   **Constraints:** The live plan keeps its casts unchanged; only the predicted 
types change. The prediction must still only widen nullability, so that the 
widening terminates.
   
   **Success:** Recursive CTEs whose anchor or recursion casts a nested value 
built by a primitive Scala UDF with a nullable input analyze without an 
internal error. When that UDF writes a NULL into the nested value, later 
iterations read it back as NULL.
   
   **Verification:**
   - **Regression:** A recursion that writes ARRAY(f(...)), with f a primitive 
Int => Int UDF over a nullable input, into a column whose anchor is 
ARRAY<BIGINT> analyzes, returns the base branch's rows when the input is never 
NULL, and returns NULL elements at later levels when it is.
   - **Regression:** An anchor or recursion whose top projection casts a struct 
built by such a UDF in a FROM subquery to a struct with a NOT NULL field 
analyzes without an internal error.
   - **Compatibility:** Recursive CTEs without primitive Scala UDFs keep the 
same self-reference and result types.



##########
docs/sql-migration-guide.md:
##########
@@ -67,6 +67,7 @@ license: |
 - Since Spark 4.4, 
`spark.sql.sources.v2.bucketing.preserveKeyOrderingOnCoalesce.enabled` defaults 
to `true`. When `GroupPartitionsExec` merges several input partitions that 
share one partition key value into a single output partition, it now keeps sort 
orders over the partition key expressions in the ordering it reports, since 
those expressions are constant within the merged partition. Sort orders over 
partition transforms such as `days(ts)` or `bucket(8, id)` are left out. Orders 
over other columns are still dropped, as the concatenation invalidates them, 
and a join that reduced the partition keys onto a common key space (see 
`spark.sql.sources.v2.bucketing.allowCompatibleTransforms.enabled`) reports no 
order, since the merged partitions then share only the reduced key. This can 
remove a `Sort` downstream of the merge. To restore the previous behavior, set 
`spark.sql.sources.v2.bucketing.preserveKeyOrderingOnCoalesce.enabled` to 
`false`.
 - Since Spark 4.4, when the `from_protobuf` option 
`unwrap.primitive.wrapper.types` is enabled, `from_protobuf` unwraps a present 
Protobuf primitive wrapper (such as `google.protobuf.Int32Value` or 
`StringValue`) whose inner `value` is unset or set to its default to the type's 
default value (`0`, `false`, `""`, or empty binary), regardless of the 
`emit.default.values` option. Previously such a wrapper unwrapped to `NULL` 
unless the `emit.default.values` option was enabled, which could also place a 
`NULL` into a non-nullable array element or map value. An absent wrapper field 
still unwraps to `NULL`.
 - Since Spark 4.4, the value columns of `UNPIVOT` and `Dataset.unpivot` merge 
the nested nullability (array element, map value, and struct field nullability) 
of all unpivoted values. Previously, a value column took the nested nullability 
of the first listed value, so a `NULL` array element, map value, or struct 
field of a later value could be returned as a non-`NULL` value such as `0`, and 
`IS NULL` on it returned `false`. A view created by an earlier Spark version 
over such an `UNPIVOT` may have recorded the non-nullable nested type in its 
schema and can fail to read; recreate it with `CREATE OR REPLACE VIEW`. To 
restore the previous behavior, set 
`spark.sql.legacy.unpivot.useFirstValueNestedNullability` to `true`.
+- Since Spark 4.4, a recursive CTE returns the `NULL`s that its anchor or 
recursive term writes into array elements, map values or struct fields. 
Previously, a later iteration could read such a `NULL` through a non-nullable 
nested type and return a non-`NULL` value such as `0`, with `IS NULL` on it 
returning `false`, or fail with a `NullPointerException`. The nested type of a 
result column is now nullable where it can hold such a `NULL`. This changes the 
type of columns that copy, or derive their nested type from, a column that the 
recursive term writes such a `NULL` into; of copies of values whose nested type 
Spark always declares nullable, such as `ARRAY(arr[0])` or `array_append` 
results; and of columns built by a Scala UDF with primitive parameters. Casting 
such a column to a type with a `NOT NULL` nested type fails, and a view created 
by an earlier Spark version over such a recursive CTE may have recorded the 
non-nullable nested type in its schema and can fail to read; recreate
  it with `CREATE OR REPLACE VIEW`, or run `ALTER VIEW ... WITH SCHEMA 
EVOLUTION`. Result columns that can never be `NULL` may now be reported as 
non-nullable.

Review Comment:
   **Nit (P3):** Three statements in this entry still don't match the code:
   
   - Nested types can narrow too. The self-reference no longer starts nullable, 
so `ARRAY(n)` over a never-NULL `n` now has non-null elements where the base 
branch had nullable ones (the new `ResolveRecursiveCTESuite` test asserts 
this), but the entry only mentions top-level narrowing.
   - A column that the recursion builds itself with a primitive Scala UDF keeps 
its result type, because `UnionLoop`'s output and the outer query's CTE 
reference are fixed during resolution, before UDF null handling. Only UDF-built 
columns that the self-reference passes through or copies change, so "columns 
built by a Scala UDF with primitive parameters" overstates it, and the outer 
query can still read such a NULL as non-NULL.
   - `CREATE VIEW` downgrades `SCHEMA EVOLUTION` to `SCHEMA TYPE EVOLUTION` for 
a view with a column list, but `ALTER VIEW ... WITH SCHEMA EVOLUTION` applies 
full schema evolution, which takes the column names from the query and can 
replace the declared ones.
   
   Saying that nested types can also narrow, limiting the UDF statement to 
columns that the self-reference passes through or copies, and recommending 
`CREATE OR REPLACE VIEW` or `ALTER VIEW ... WITH SCHEMA TYPE EVOLUTION` would 
fix it.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60061#discussion_r4488922785).
   
   **Verification:**
   - **Inspection:** Every kind of result column the entry says changes type 
does change in the analyzer, and every kind it says keeps its type keeps it, 
including nested types built from never-NULL self-reference columns and columns 
built by primitive Scala UDFs.
   - **Inspection:** The suggested view remedy preserves the declared column 
names of a view created with an explicit column list.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveWithCTE.scala:
##########
@@ -303,22 +323,78 @@ object ResolveWithCTE extends Rule[LogicalPlan] {
   // Assumes that `anchor` is already resolved. If `columnNames` is set (which 
happens if an
   // UnresolvedSubqueryColumnAliases is atop a Union) also places an 
UnresolvedSubqueryColumnAliases
   // node above UnionLoopRef. At some later stage 
UnresolvedSubqueryColumnAliases gets resolved to
-  // a Project node.
+  // a Project node. `refTypes` overrides the anchor's data types for the 
UnionLoopRef output.
   private def rewriteRecursiveCTERefs(
       recursion: LogicalPlan,
       anchor: LogicalPlan,
       cteDefId: Long,
-      columnNames: Option[Seq[String]]) = {
+      columnNames: Option[Seq[String]],
+      refTypes: Option[Seq[DataType]] = None) = {
+    val types = refTypes.getOrElse(anchor.output.map(_.dataType))
     recursion.transformUpWithSubqueriesAndPruning(_.containsPattern(CTE)) {
       case r: CTERelationRef if r.recursive && r.cteId == cteDefId =>
         // We mark the output of UnionLoopRef as nullable as it may become 
NULL in the following
         // iterations.
-        val ref =
-          UnionLoopRef(r.cteId, 
anchor.output.map(_.newInstance().withNullability(true)), false)
+        val output = anchor.output.zip(types).map { case (a, dt) =>
+          a.newInstance().withNullability(true).withDataType(dt)
+        }
+        val ref = UnionLoopRef(r.cteId, output, false)
         columnNames.map(UnresolvedSubqueryColumnAliases(_, ref)).getOrElse(ref)
     }
   }
 
+  // The anchor's types, unless widenSelfReference has found wider ones.
+  private def selfReferenceTypes(cteDef: CTERelationDef, anchor: LogicalPlan): 
Seq[DataType] =
+    
cteDef.getTagValue(SELF_REFERENCE_TYPES).getOrElse(anchor.output.map(_.dataType))
+
+  // A recursion can write NULLs into nested types that the self-reference 
declares non-nullable,
+  // e.g. ARRAY(CAST(NULL AS INT)) for an ARRAY(1) anchor. Once the loop is 
resolved, widens the
+  // nullability of such self-reference types to the anchor's and recursion's 
and rebuilds the
+  // loop from the original definition. This repeats until no type widens.
+  private def widenSelfReference(cteDef: CTERelationDef): CTERelationDef = {
+    val loop = if (cteDef.hasSelfReferenceAsUnionLoopRef) {
+      cteDef.child.collectFirst { case l: UnionLoop if l.id == cteDef.id => l }
+    } else {
+      None
+    }
+    loop.filter(_.resolved) match {
+      case Some(l) =>
+        val refTypes = cteDef.child.collectFirstWithSubqueries {
+          case r: UnionLoopRef if r.loopId == cteDef.id => 
r.output.map(_.dataType)
+        }.get
+        val children = Seq(l.anchor, l.recursion).map(withUdfNullHandling)
+        val widened = refTypes.zipWithIndex.map { case (dt, i) =>
+          children.foldLeft(dt)((t, c) => StructType.unionLikeMerge(t, 
c.output(i).dataType))

Review Comment:
   Thanks, each child's output is now read once per check. This review raises 
one remaining point about how those outputs are indexed.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4488922792","thread_id":"inline:4488922792","verdict_sha256":"5554de3ab396b0bdf55a7c6fbf310aedea616f56c75e136e5f3f3824dea1ce17"}
 -->



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