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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveWithCTE.scala:
##########
@@ -303,22 +329,179 @@ 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): IndexedSeq[(DataType, Boolean)] =
+    plan.output.map(a => (a.dataType, a.nullable)).toIndexedSeq
+
+  // 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, predicted on copies until nothing widens, and 
rebuilds the loop from
+  // the original definition. `defs` are the CTE definitions the loop can 
reference.
+  // 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,
+      defs: collection.Map[Long, CTERelationDef]): CTERelationDef = {
+    val loop = if (cteDef.hasSelfReferenceAsUnionLoopRef) {
+      cteDef.child.collectFirst { case l: UnionLoop if l.id == cteDef.id => l }
+    } else {
+      None
+    }
+    loop.filter(l => l.resolved && !isVerified(l)) match {
+      case Some(l) =>
+        val refTypes = cteDef.child.collectFirstWithSubqueries {
+          case r: UnionLoopRef if r.loopId == cteDef.id => outputTypes(r)
+        }.get
+        val innerDefs = cteDef.child.collectWithSubqueries { case w: WithCTE 
=> w.cteDefs }
+        val visibleDefs = defs ++ innerDefs.flatten.map(d => d.id -> d)
+        val anchorTypes = laterOutputTypes(l.anchor, cteDef.id, refTypes, 
visibleDefs)
+        @tailrec def fixpoint(types: Seq[(DataType, Boolean)]): Seq[(DataType, 
Boolean)] = {
+          val next = merge(
+            types, anchorTypes, laterOutputTypes(l.recursion, cteDef.id, 
types, visibleDefs))
+          if (next == types) types else fixpoint(next)
+        }
+        val widened = fixpoint(refTypes)
+        if (widened == refTypes) {
+          l.setTagValue(VERIFIED_CHILDREN, (l.anchor, l.recursion))

Review Comment:
   **Blocking (P1):** The verdict recorded here comes from whichever analysis 
resolves the loop first. For a recursive CTE in a scalar, IN, EXISTS or LATERAL 
subquery, that is the subquery's nested analysis, whose `ResolveWithCTE` starts 
with an empty definition map. It predicts the self-reference without the 
enclosing WITH's definitions, so a reference to an enclosing CTE keeps its 
resolution-time type, from before UDF null handling, and the loop is tagged as 
verified. The outer pass, which can see the enclosing CTE, then skips the loop 
(line 375): the tag is keyed only on the anchor and recursion instances, which 
the nested run's later batches leave unchanged when neither contains an `Alias`.
   
   By this review's reading of the code, take `spark.udf.register("f", (v: 
Long) => v + 1)` and a view `edges(a, b)` over `VALUES (1L, CAST(NULL AS 
BIGINT)), (0L, 5L)`:
   
   ```sql
   WITH x AS (SELECT a AS src, f(b) AS dst FROM edges)
   SELECT (SELECT count(*) FROM (
     WITH RECURSIVE t AS (
       SELECT id FROM range(1, 2)
       UNION ALL
       SELECT x.dst FROM t JOIN x ON t.id = x.src)
     SELECT id FROM t))
   ```
   
   Level 1 writes `dst = NULL` into `id`, which the self-reference declares 
`BIGINT NOT NULL`. Level 2 reads that NULL as 0, joins the `(0, 5)` edge, and 
the count is 3. On the base branch the self-reference is nullable, so it reads 
NULL and the count is 2. Nested values from the same placement, such as 
`ARRAY(f(b))` defined in `x`, are still read back as 0. No test puts a 
recursive CTE in a subquery expression under an enclosing WITH: the `UDFSuite` 
enclosing-WITH case uses a FROM-clause subquery, which one analyzer run 
resolves.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60061#issuecomment-6664983350), 
[2](https://github.com/apache/spark/pull/60061#discussion_r4510531222), 
[3](https://github.com/apache/spark/pull/60061#pullrequestreview-5779476661).
   
   **Recommended change:** Record a loop as verified only for the definitions 
its prediction actually saw: when the anchor or recursion, including their 
subquery plans, references a CTE whose definition is not visible to the 
application running the widening, do not record the verdict, or record the 
missing definition ids with it and re-check once they are visible, so the outer 
analysis predicts the loop again with the enclosing definition and restores it 
when that definition writes NULLs; add Scala UDF tests that place an alias-free 
recursive CTE in scalar, IN and LATERAL subqueries under an enclosing WITH 
whose primitive UDF writes NULLs, at the top level and inside an array.
   
   **Why this works:** The verdict then covers the same definitions as the 
prediction behind it. In the nested subquery analysis the loop stays 
unverified, so the outer ResolveWithCTE predicts it again with the enclosing 
definition, finds the wider types and restores the definition; the subquery 
becomes unresolved, ResolveSubquery analyzes it again from the restored 
definition with its recorded wider types, and the outer pass then verifies it.
   
   **Scope:** Make the widening's stability verdict depend on the CTE 
definitions it could see, and cover recursive CTEs in subquery expressions 
under an enclosing WITH.
   
   **Risks:** A loop that reads an enclosing CTE from inside a subquery 
expression is now predicted again in the outer analysis and, when it widens, 
its subquery is analyzed a second time, adding analysis work for that shape 
only.
   
   **Constraints:** Still record the verdict for loops whose referenced 
definitions were all visible, so stable loops are not predicted again on every 
pass. Count references inside the anchor's and recursion's subquery plans, 
which the prediction already follows.
   
   **Success:** A recursive CTE in a scalar, IN, EXISTS or LATERAL subquery 
that reads a primitive Scala UDF's NULLs through an enclosing WITH declares 
those positions nullable in its self-reference, and later iterations read the 
NULLs back as NULL, at the top level and in nested positions. Loops whose 
referenced definitions are all visible are still verified once and not 
predicted again.
   
   **Verification:**
   - **Regression:** With f a primitive Long => Long UDF and an edges view 
holding (1, NULL) and (0, 5), WITH x AS (SELECT a AS src, f(b) AS dst FROM 
edges) around a scalar subquery that counts the rows of WITH RECURSIVE t AS 
(SELECT id FROM range(1, 2) UNION ALL SELECT x.dst FROM t JOIN x ON t.id = 
x.src) returns 2, as on the base branch, so the NULL id is not read as 0 and 
does not join the edge whose src is 0.
   - **Regression:** The same placement inside IN and LATERAL subqueries, and 
with the UDF value wrapped in an array that the recursion reads back, returns 
NULL at every later level on materialized steps.
   - **Compatibility:** Recursive CTEs outside subquery expressions, and those 
whose referenced CTEs are all visible, keep the self-reference and result types 
they have with the current change.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveWithCTE.scala:
##########
@@ -303,22 +329,179 @@ 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): IndexedSeq[(DataType, Boolean)] =
+    plan.output.map(a => (a.dataType, a.nullable)).toIndexedSeq
+
+  // 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, predicted on copies until nothing widens, and 
rebuilds the loop from
+  // the original definition. `defs` are the CTE definitions the loop can 
reference.
+  // 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,
+      defs: collection.Map[Long, CTERelationDef]): CTERelationDef = {
+    val loop = if (cteDef.hasSelfReferenceAsUnionLoopRef) {
+      cteDef.child.collectFirst { case l: UnionLoop if l.id == cteDef.id => l }
+    } else {
+      None
+    }
+    loop.filter(l => l.resolved && !isVerified(l)) match {
+      case Some(l) =>
+        val refTypes = cteDef.child.collectFirstWithSubqueries {
+          case r: UnionLoopRef if r.loopId == cteDef.id => outputTypes(r)
+        }.get
+        val innerDefs = cteDef.child.collectWithSubqueries { case w: WithCTE 
=> w.cteDefs }
+        val visibleDefs = defs ++ innerDefs.flatten.map(d => d.id -> d)
+        val anchorTypes = laterOutputTypes(l.anchor, cteDef.id, refTypes, 
visibleDefs)
+        @tailrec def fixpoint(types: Seq[(DataType, Boolean)]): Seq[(DataType, 
Boolean)] = {
+          val next = merge(
+            types, anchorTypes, laterOutputTypes(l.recursion, cteDef.id, 
types, visibleDefs))
+          if (next == types) types else fixpoint(next)
+        }
+        val widened = fixpoint(refTypes)
+        if (widened == refTypes) {
+          l.setTagValue(VERIFIED_CHILDREN, (l.anchor, l.recursion))
+          cteDef
+        } else {
+          l.getTagValue(LOOP_ORIGIN) match {
+            case Some(child) =>
+              val restored = cteDef.copy(child = child)
+              restored.setTagValue(SELF_REFERENCE_TYPES, widened)
+              restored
+            case None =>
+              throw SparkException.internalError("The self-reference of 
recursive CTE " +
+                s"${cteDef.id} needs wider types 
${widened.map(_._1.sql).mkString(", ")}, but " +
+                "the loop has no origin to rebuild it from.")
+          }
+        }
+      case None => cteDef
+    }
+  }
+
+  // Whether the loop's self-reference types were found stable for its current 
children.
+  private def isVerified(loop: UnionLoop): Boolean =
+    loop.getTagValue(VERIFIED_CHILDREN).exists { case (anchor, recursion) =>
+      (anchor eq loop.anchor) && (recursion eq loop.recursion)
+    }
+
+  private def merge(
+      types: Seq[(DataType, Boolean)],
+      outputs: IndexedSeq[(DataType, Boolean)]*): Seq[(DataType, Boolean)] =
+    types.zipWithIndex.map { case (t, i) =>
+      outputs.foldLeft(t) { case ((dt, nullable), output) =>
+        (StructType.unionLikeMerge(dt, output(i)._1), nullable || output(i)._2)
+      }
+    }
+
+  // The output types of `plan` once later analysis adds nullability (see 
withLaterNullability),
+  // with `refTypes` for the self-reference of loop `loopId` and the later 
output types of the CTEs
+  // in `defs` that it references. Fully nullable if the copy does not resolve.
+  private def laterOutputTypes(
+      plan: LogicalPlan,
+      loopId: Long,
+      refTypes: Seq[(DataType, Boolean)],
+      defs: collection.Map[Long, CTERelationDef]): IndexedSeq[(DataType, 
Boolean)] = {
+    val defTypes = mutable.HashMap.empty[Long, IndexedSeq[(DataType, Boolean)]]
+    def predict(p: LogicalPlan): IndexedSeq[(DataType, Boolean)] = {
+      val copy = p.transformUpWithSubqueries {
+        case r: UnionLoopRef if r.loopId == loopId =>
+          r.copy(output = r.output.zip(refTypes).map { case (a, (dt, 
nullable)) =>
+            a.withNullability(nullable).withDataType(dt)
+          })
+        case r: CTERelationRef if !r.recursive && 
defs.get(r.cteId).exists(_.resolved) =>
+          val types = defTypes.getOrElse(r.cteId, {
+            defTypes.put(r.cteId, outputTypes(r))
+            val t = predict(defs(r.cteId).child)
+            defTypes.put(r.cteId, t)
+            t
+          })
+          r.copy(output = r.output.zip(types).map { case (a, (dt, nullable)) =>
+            widenAttribute(a, dt, nullable)
+          })
+      }
+      val handled = withLaterNullability(copy)
+      if (handled.resolved) {
+        outputTypes(handled)
+      } else {
+        p.output.map(a => (a.dataType.asNullable, true)).toIndexedSeq
+      }
+    }
+    predict(plan)
+  }
+
+  // Applies to a copy the nullability that later analysis adds: primitive 
Scala UDFs only become
+  // nullable in the "ScalaUDF Null Handling" batch, and references keep the 
types they were
+  // resolved with. So the self-reference also covers those NULLs.
+  private def withLaterNullability(plan: LogicalPlan): LogicalPlan = {
+    val handled = refreshAttributeTypes(HandleNullInputsForUDF(plan))
+    if (handled.fastEquals(plan)) plan else withLaterNullability(handled)
+  }
+
+  // Like UpdateAttributeNullability, but also takes the data type of the 
child's output attribute
+  // where it is more nullable. A cast carries NULLs through, so its target 
takes the nullability of
+  // a more nullable input instead of rejecting it.
+  private def refreshAttributeTypes(plan: LogicalPlan): LogicalPlan = 
plan.transformUp {

Review Comment:
   **Blocking (P1):** `refreshAttributeTypes` uses `plan.transformUp`, and 
`HandleNullInputsForUDF` uses `resolveOperatorsUp`, so neither enters a 
subquery expression's plan. `predict()` does widen a CTE reference inside a 
LATERAL subquery, because it uses `transformUpWithSubqueries`. But the 
subquery's own operators above that reference keep their resolution-time 
attribute types, and `LateralJoin.output` takes the lateral plan's output 
unchanged for inner and cross joins, so the widened type never reaches the 
predicted recursion output.
   
   By this review's reading of the code, take `spark.udf.register("f", (x: 
Long) => x + 1)`:
   
   ```sql
   WITH RECURSIVE x AS (SELECT f(CAST(NULL AS BIGINT)) AS v),
   t(lvl, v) AS (
     SELECT 0, 0L
     UNION ALL
     SELECT t.lvl + 1, IF(t.lvl = 0, l.v, t.v)
     FROM t, LATERAL (SELECT v FROM x) l WHERE t.lvl < 2)
   SELECT lvl, v IS NULL FROM t
   ```
   
   The self-reference keeps `v BIGINT NOT NULL`. Level 1 still writes x's NULL, 
because the optimizer inlines the CTE and refreshes the rewritten lateral plan. 
Level 2 reads that NULL as 0, so `v IS NULL` is false there; on the base branch 
the self-reference is nullable and it is true. A nested value read the same 
way, or through a scalar subquery whose type comes from its plan's unrefreshed 
output, stays narrow too. No test reads a UDF-computed CTE column through a 
LATERAL subquery in the recursion.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60061#issuecomment-6664983350), 
[2](https://github.com/apache/spark/pull/60061#discussion_r4488922777), 
[3](https://github.com/apache/spark/pull/60061#discussion_r4510531222), 
[4](https://github.com/apache/spark/pull/60061#pullrequestreview-5779476661).
   
   **Recommended change:** Make the prediction refresh subquery plans too: 
apply UDF null handling and the attribute refresh to every subquery expression 
plan inside the copies, bottom-up, before the operators that read them, so a 
LATERAL join or a scalar subquery over a widened CTE reference reports the 
wider type; add Scala UDF tests in which the recursion reads a primitive UDF's 
NULLs from a CTE through a LATERAL subquery and through a scalar subquery, at 
the top level and inside an array.
   
   **Why this works:** Refreshing a subquery plan bottom-up gives its output 
attributes the widened types of the CTE references inside it; LateralJoin and 
ScalarSubquery derive their outputs from that plan, so the predicted recursion 
output, and with it the merged self-reference type, becomes nullable wherever 
the subquery can carry the UDF's NULL.
   
   **Scope:** Extend the self-reference prediction's nullability refresh into 
the subquery plans of its copies, and cover CTE values read through LATERAL and 
scalar subqueries.
   
   **Risks:** Columns fed through subquery plans by values that later analysis 
makes nullable become nullable in the self-reference and can widen result 
types, like other UDF-written columns.
   
   **Constraints:** Change only the prediction's copies; the live plan's 
subquery plans keep their analysis. Rely on HandleNullInputsForUDF staying 
idempotent on subquery plans the nested analysis already handled.
   
   **Success:** A recursion that reads, through a LATERAL or scalar subquery, a 
CTE value that a primitive Scala UDF computes from a nullable input declares 
that position nullable in its self-reference, and later iterations read the 
NULL back as NULL. Recursions without subquery expressions keep the 
self-reference types they have with the current change.
   
   **Verification:**
   - **Regression:** With f a primitive Long => Long UDF, WITH RECURSIVE x AS 
(SELECT f(CAST(NULL AS BIGINT)) AS v), t(lvl, v) AS (SELECT 0, 0L UNION ALL 
SELECT t.lvl + 1, IF(t.lvl = 0, l.v, t.v) FROM t, LATERAL (SELECT v FROM x) l 
WHERE t.lvl < 2) SELECT lvl, v IS NULL FROM t returns true at levels 1 and 2.
   - **Regression:** A recursion that reads ARRAY(f(...)) from a CTE through a 
LATERAL subquery or a scalar subquery reads the NULL element back as NULL at 
the next level on materialized steps.
   - **Compatibility:** Recursive CTEs whose subqueries carry no later 
nullability keep the same self-reference and result types.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveWithCTE.scala:
##########
@@ -303,22 +329,179 @@ 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): IndexedSeq[(DataType, Boolean)] =
+    plan.output.map(a => (a.dataType, a.nullable)).toIndexedSeq
+
+  // 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, predicted on copies until nothing widens, and 
rebuilds the loop from
+  // the original definition. `defs` are the CTE definitions the loop can 
reference.
+  // 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,
+      defs: collection.Map[Long, CTERelationDef]): CTERelationDef = {
+    val loop = if (cteDef.hasSelfReferenceAsUnionLoopRef) {
+      cteDef.child.collectFirst { case l: UnionLoop if l.id == cteDef.id => l }
+    } else {
+      None
+    }
+    loop.filter(l => l.resolved && !isVerified(l)) match {
+      case Some(l) =>
+        val refTypes = cteDef.child.collectFirstWithSubqueries {
+          case r: UnionLoopRef if r.loopId == cteDef.id => outputTypes(r)
+        }.get
+        val innerDefs = cteDef.child.collectWithSubqueries { case w: WithCTE 
=> w.cteDefs }
+        val visibleDefs = defs ++ innerDefs.flatten.map(d => d.id -> d)
+        val anchorTypes = laterOutputTypes(l.anchor, cteDef.id, refTypes, 
visibleDefs)
+        @tailrec def fixpoint(types: Seq[(DataType, Boolean)]): Seq[(DataType, 
Boolean)] = {
+          val next = merge(

Review Comment:
   **Blocking (P1):** This merge reads only declared nullability. 
`ArrayInsert`, which `array_append` and `array_prepend` become, types its 
result as `first.dataType.asNullable`. A constant-index read such as `arr[0]` 
over anything but an array literal is always typed nullable, even under ANSI 
mode, where an out-of-range index fails instead of returning NULL. So a 
recursion that writes such a value into a column widens that column's 
self-reference although no NULL can arrive there, and a column that copies or 
derives from it widens a round later and keeps the wider type in the CTE's 
result.
   
   By this review's reading of the code, this view never writes a NULL element:
   
   ```sql
   CREATE VIEW v AS WITH RECURSIVE t(n, path, prev) AS (
     SELECT 1, ARRAY(1), ARRAY(1)
     UNION ALL
     SELECT n + 1, array_append(path, n + 1), path FROM t WHERE n < 3
   ) SELECT * FROM t
   ```
   
   On 4.1 to 4.3, as on the base branch, `prev` is `ARRAY<INT>` with non-null 
elements, and the view stores that type. With this change `path` widens in the 
first round and `prev` in the second, so `prev`'s result type gains nullable 
elements. Reading `v` then wraps `prev` in an ANSI cast or an UpCast to the 
stored type; both reject nullable elements into non-null ones, so `SELECT * 
FROM v` stops resolving. Casts of such a column to a NOT NULL nested type fail 
the same way, and a stateful streaming query that keys or stores it from a 
batch-side recursive CTE fails its state schema check on restart. The TODO 
above `widenSelfReference` acknowledges the widening, but these columns were 
typed correctly before, and no setting restores the old types.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60061#issuecomment-6664983350), 
[2](https://github.com/apache/spark/pull/60061#discussion_r4488922764), 
[3](https://github.com/apache/spark/pull/60061#pullrequestreview-5779476661).
   
   **Recommended change:** In the copies the prediction types, give 
array_append and array_prepend results under the default negative-index 
setting, and constant-index element reads (arr[i], element_at) under ANSI mode, 
the nested nullability their inputs allow, so the merge widens only positions a 
NULL can reach and copies of those values keep the base branch's types; narrow 
the TODO above widenSelfReference to whatever still widens, and add recursive 
CTE analyzer tests and SQL golden cases for recursions that never write a NULL 
but copy such values.
   
   **Why this works:** Before the merge, the prediction retypes these 
expressions in its copies by what their inputs allow: an insert at position 1, 
or at -1 without the legacy negative-index setting, never pads the array, so 
its elements are nullable only when the source's elements or the item are, and 
an ANSI constant-index read fails instead of returning NULL when the index is 
out of range, so it is nullable only when the array or its elements are. Only 
the discarded copies change, so the live plan, its declared types and its 
results stay as they are, while the self-reference and its copies keep the 
anchor's types.
   
   **Scope:** Teach the copy-based self-reference type prediction the nested 
nullability that append, prepend and ANSI constant-index reads can actually 
produce, and cover never-NULL recursions that copy them.
   
   **Risks:** If the precise rule admits an input that can produce a NULL, the 
self-reference is declared narrower than what the recursion writes and later 
iterations read that NULL as 0; for example array_append over an empty array 
pads a NULL under spark.sql.legacy.negativeIndexInArrayInsert, so that setting 
must keep the declared nullability.
   
   **Constraints:** Retype only in the prediction's copies; the live plan keeps 
the original expressions and types. Apply the retyping wherever the prediction 
refreshes types, including inside subquery plans, so a value read through a 
subquery is typed the same way. Keep the declared nullability under 
spark.sql.legacy.negativeIndexInArrayInsert, for positions other than 1 and -1, 
and with ANSI mode off, since those can produce NULLs.
   
   **Exclusions:**
   - Other expressions that Spark types as nullable whatever their inputs, if 
any besides these turn up, still widen the columns that copy them; each needs 
the same precise typing in the prediction, and the TODO and the migration note 
keep naming them.
   
   **Success:** A recursion that never writes a NULL and copies an array_append 
or array_prepend result, or an ANSI constant-index read, keeps the base 
branch's result types, so views created on 4.1 to 4.3 over it still read and 
NOT NULL nested casts of the copies still analyze. A recursion that can write a 
NULL into those positions, including under the legacy negative-index setting or 
with ANSI mode off, still widens the self-reference and reads the NULL back as 
NULL.
   
   **Verification:**
   - **Regression:** A recursive CTE whose recursion writes array_append(path, 
n + 1) with non-null inputs and copies path into another column keeps 
non-nullable elements in the self-reference and the result for both columns, 
and a persisted view created with those types still reads; the same holds for 
array_prepend and for ARRAY(arr[0]) and element_at with ANSI mode on.
   - **Behavior:** With spark.sql.legacy.negativeIndexInArrayInsert enabled, 
array_append over an empty array in the recursion still widens the 
self-reference and the padded NULL reads back as NULL at the next level; with 
ANSI mode off, a constant-index read past the end still widens and its NULL 
reads back as NULL.
   - **Compatibility:** Recursions that write a NULL into nested positions, and 
queries outside recursive CTEs that use array_append, array_prepend or element 
reads, keep the types and results they have with the current change.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveWithCTE.scala:
##########
@@ -303,22 +329,179 @@ 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): IndexedSeq[(DataType, Boolean)] =
+    plan.output.map(a => (a.dataType, a.nullable)).toIndexedSeq
+
+  // 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, predicted on copies until nothing widens, and 
rebuilds the loop from
+  // the original definition. `defs` are the CTE definitions the loop can 
reference.
+  // 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,
+      defs: collection.Map[Long, CTERelationDef]): CTERelationDef = {
+    val loop = if (cteDef.hasSelfReferenceAsUnionLoopRef) {
+      cteDef.child.collectFirst { case l: UnionLoop if l.id == cteDef.id => l }
+    } else {
+      None
+    }
+    loop.filter(l => l.resolved && !isVerified(l)) match {
+      case Some(l) =>
+        val refTypes = cteDef.child.collectFirstWithSubqueries {
+          case r: UnionLoopRef if r.loopId == cteDef.id => outputTypes(r)
+        }.get
+        val innerDefs = cteDef.child.collectWithSubqueries { case w: WithCTE 
=> w.cteDefs }
+        val visibleDefs = defs ++ innerDefs.flatten.map(d => d.id -> d)
+        val anchorTypes = laterOutputTypes(l.anchor, cteDef.id, refTypes, 
visibleDefs)
+        @tailrec def fixpoint(types: Seq[(DataType, Boolean)]): Seq[(DataType, 
Boolean)] = {
+          val next = merge(
+            types, anchorTypes, laterOutputTypes(l.recursion, cteDef.id, 
types, visibleDefs))
+          if (next == types) types else fixpoint(next)
+        }
+        val widened = fixpoint(refTypes)
+        if (widened == refTypes) {
+          l.setTagValue(VERIFIED_CHILDREN, (l.anchor, l.recursion))
+          cteDef
+        } else {
+          l.getTagValue(LOOP_ORIGIN) match {
+            case Some(child) =>
+              val restored = cteDef.copy(child = child)

Review Comment:
   **Blocking (P1):** `LOOP_ORIGIN` holds the definition's child as it was when 
the loop was first built, and the transforms that later change the live tree 
only carry the tag along. Suppose an inner recursive CTE in the recursion of an 
enclosing one references it, and the inner anchor resolves in an earlier 
Resolution iteration. The inner loop is built first, and its snapshot keeps the 
raw `CTERelationRef(o, recursive = true)`. Building the enclosing loop then 
replaces that reference with a `UnionLoopRef` in the live tree only (lines 
341-348). If the inner self-reference widens, at the top level or in a nested 
position, this restore brings the raw reference back. The enclosing 
definition's child is by then a `SubqueryAlias` over 
`UnresolvedSubqueryColumnAliases` over a `UnionLoop`. So 
`hasSelfReferenceAsCTERef` is true, but no build arm matches, because 
`UnionLoop` is not a `Union`, and the next pass throws `INVALID_RECURSIVE_CTE` 
(lines 298-305).
   
   By this review's reading of the code, this query now fails analysis with 
`INVALID_RECURSIVE_CTE`:
   
   ```sql
   WITH RECURSIVE o(lvl) AS (
     SELECT id FROM range(1)
     UNION ALL
     SELECT m FROM (
       WITH RECURSIVE i(m) AS (
         SELECT 1L
         UNION ALL
         SELECT IF(o.lvl > 0, NULL, o.lvl + 2) FROM i JOIN o ON i.m = 1 WHERE 
o.lvl < 2)
       SELECT m FROM i) WHERE m > 1)
   SELECT * FROM o
   ```
   
   `i`'s literal anchor resolves before `o`'s anchor over `range`, and `i` 
widens, because its recursion can write a NULL into a column its anchor typed 
`BIGINT NOT NULL`. The base branch never restores a loop, and it returns 0 and 
2. For nested NULL writes, which the base branch read back as 0, the change 
replaces that wrong result with this error instead of fixing it. No test nests 
a recursive CTE that references its enclosing one.
   
   **Recommended change:** When rewriteRecursiveCTERefs replaces an enclosing 
CTE's recursive reference, apply the same replacement to the LOOP_ORIGIN of 
every UnionLoop it rebuilds on the way, so an inner loop restored later keeps 
the enclosing UnionLoopRef; add a recursive CTE SQL golden case with an inner 
recursive CTE whose recursion references the enclosing one, whose anchor 
resolves first, and whose recursion can write a NULL.
   
   **Why this works:** A restore then reproduces the inner definition as the 
live tree means it: its reference to the enclosing CTE is already the enclosing 
loop's UnionLoopRef with that build's types, so the enclosing definition never 
regains a raw recursive reference and keeps matching its own loop; every later 
build of the enclosing loop applies the rewrite again with its new types.
   
   **Scope:** Keep inner loops' rebuild snapshots consistent with an enclosing 
loop's rewrite of its recursive reference, and cover nested recursive CTEs that 
reference their enclosing one.
   
   **Risks:** A snapshot the rewrite misses brings the analysis error back, and 
one rewritten with the wrong types would rebuild the inner loop against stale 
enclosing types until the next enclosing build rewrites it again.
   
   **Constraints:** Rewrite snapshots with the same self-reference types the 
enclosing build uses, and only on the rebuilt nodes, never on instances an 
enclosing snapshot still holds. Leave snapshots that hold no recursive 
reference to the enclosing CTE unchanged.
   
   **Success:** A recursive CTE nested in the recursion of another that it 
references analyzes and returns the base branch's rows, also when its anchor 
resolves before the enclosing anchor and its self-reference widens. Restoring a 
loop never reintroduces a recursive reference to an enclosing CTE whose loop is 
already built.
   
   **Verification:**
   - **Regression:** WITH RECURSIVE o(lvl) AS (SELECT id FROM range(1) UNION 
ALL SELECT m FROM (WITH RECURSIVE i(m) AS (SELECT 1L UNION ALL SELECT IF(o.lvl 
> 0, NULL, o.lvl + 2) FROM i JOIN o ON i.m = 1 WHERE o.lvl < 2) SELECT m FROM 
i) WHERE m > 1) SELECT * FROM o analyzes and returns 0 and 2.
   - **Regression:** The same nesting where the inner recursion writes a NULL 
into an array element reads that NULL back as NULL at the inner loop's next 
level.
   - **Compatibility:** Nested recursive CTEs whose inner loop does not 
reference the enclosing one, such as the existing inner-loop golden cases, keep 
their results and types.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveWithCTE.scala:
##########
@@ -49,7 +63,9 @@ object ResolveWithCTE extends Rule[LogicalPlan] {
       cteDefMap: mutable.HashMap[Long, CTERelationDef]): LogicalPlan = {
     plan.resolveOperatorsDownWithPruning(_.containsAllPatterns(CTE)) {
       case withCTE @ WithCTE(_, cteDefs) =>
-        val newCTEDefs = cteDefs.map {
+        // The enclosing and sibling definitions that a recursive CTE can 
reference.
+        val visibleDefs = cteDefMap ++ cteDefs.map(d => d.id -> d)

Review Comment:
   **Nit (P3):** Three parts of the widening do work that cannot change its 
result.
   
   - This line copies `cteDefMap` and the siblings for every `WithCTE` on every 
`ResolveWithCTE` pass, including in queries without recursive CTEs. Only 
`widenSelfReference`'s branch for a resolved, unverified loop reads the map, 
and that branch copies it again (line 381).
   - Each `laterOutputTypes` call starts a fresh `defTypes` memo (line 431), so 
every fixpoint round re-predicts each enclosing or sibling CTE the recursion 
references. Only the loop's own definition holds its `UnionLoopRef`, so those 
predictions are the same in every round, and a 150-link copy chain like the new 
suite test runs about 150 rounds.
   - The fixpoint runs even when every self-reference position is already 
nullable, which `merge` can never widen.
   
   **Verification:**
   - **Compatibility:** Every existing recursive CTE widening case, including 
pass-through, copy chains, inner WITH, column lists, CTE references and Scala 
UDFs, keeps the same self-reference and result types.
   - **Inspection:** The visible-definition map is built only where the 
widening reads it, the memo for definitions outside the loop is shared across 
fixpoint rounds, and the fixpoint is skipped for self-references that are 
nullable everywhere.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveWithCTE.scala:
##########
@@ -303,22 +329,179 @@ 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): IndexedSeq[(DataType, Boolean)] =
+    plan.output.map(a => (a.dataType, a.nullable)).toIndexedSeq
+
+  // 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, predicted on copies until nothing widens, and 
rebuilds the loop from
+  // the original definition. `defs` are the CTE definitions the loop can 
reference.
+  // 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,
+      defs: collection.Map[Long, CTERelationDef]): CTERelationDef = {
+    val loop = if (cteDef.hasSelfReferenceAsUnionLoopRef) {
+      cteDef.child.collectFirst { case l: UnionLoop if l.id == cteDef.id => l }
+    } else {
+      None
+    }
+    loop.filter(l => l.resolved && !isVerified(l)) match {
+      case Some(l) =>
+        val refTypes = cteDef.child.collectFirstWithSubqueries {
+          case r: UnionLoopRef if r.loopId == cteDef.id => outputTypes(r)
+        }.get
+        val innerDefs = cteDef.child.collectWithSubqueries { case w: WithCTE 
=> w.cteDefs }
+        val visibleDefs = defs ++ innerDefs.flatten.map(d => d.id -> d)
+        val anchorTypes = laterOutputTypes(l.anchor, cteDef.id, refTypes, 
visibleDefs)
+        @tailrec def fixpoint(types: Seq[(DataType, Boolean)]): Seq[(DataType, 
Boolean)] = {
+          val next = merge(
+            types, anchorTypes, laterOutputTypes(l.recursion, cteDef.id, 
types, visibleDefs))
+          if (next == types) types else fixpoint(next)
+        }
+        val widened = fixpoint(refTypes)
+        if (widened == refTypes) {
+          l.setTagValue(VERIFIED_CHILDREN, (l.anchor, l.recursion))
+          cteDef
+        } else {
+          l.getTagValue(LOOP_ORIGIN) match {
+            case Some(child) =>
+              val restored = cteDef.copy(child = child)

Review Comment:
   **Non-blocking (P2):** Each widening restores the definition from 
`LOOP_ORIGIN`, which holds the definition as it was when the loop was first 
built, and resolves its recursion again. That adds two costs the base branch, 
which built each loop once, did not have.
   
   First, because the self-reference no longer starts nullable at the top 
level, a recursion that only writes a top-level NULL into a column the anchor 
typed non-nullable now resolves its recursion twice for the same rows, 
including the subquery expressions on it. Examples are the new golden case 
`IF(lvl = 0, NULL, n + 1)` over `id FROM range(3)`, and a literal seed joined 
to a nullable table column.
   
   Second, an enclosing loop's snapshot holds its inner recursive CTEs either 
unbuilt or built with their narrow self-reference. So restoring the enclosing 
loop makes every inner level that widens build, widen and rebuild again. The 
work roughly doubles with each nesting level that widens, and a deep enough 
nest reaches the Resolution batch's `spark.sql.analyzer.maxIterations` limit 
and fails analysis. By this review's reading of the code, a cycle takes about 
five Resolution iterations, so four or five nested levels that each widen 
approach the default limit of 100. Nothing measures this yet.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60061#discussion_r4488922764).
   
   **Recommended change:** When restoring a definition, carry the 
self-reference types that each recursive CTE nested inside it has reached, read 
by definition id from the current child, onto the matching definitions in the 
restored snapshot, and restore any inner loop that the snapshot holds already 
built from that loop's own recorded origin, so each inner loop is built with 
its widened types at once instead of resolving narrow and widening again. Keep 
the single rebuild a top-level-only widening takes, which commit 225b08ffefb 
introduced to keep copies of never-NULL values narrow, and add a comment at the 
restore saying why it stays: patching nullability into the resolved recursion 
in place could leave outer references and other bound attributes narrower than 
the data. Add analyzer tests with three nested recursive CTEs that each write a 
NULL, one where every inner anchor resolves after its enclosing anchor and one 
where the inner anchors resolve first.
   
   **Why this works:** Inner definitions in the restored snapshot then start 
from the types they already widened to, whether the snapshot held them unbuilt 
or already built, so restoring an enclosing loop re-resolves them once without 
another widening or restore, and nesting no longer multiplies the rebuilds; the 
top-level rebuild remains one extra resolution for each loop that widens.
   
   **Scope:** Carry inner recursive CTEs' widened types across an enclosing 
restore, including into inner loops the snapshot holds already built, document 
the remaining top-level rebuild, and cover nested widening in analyzer tests.
   
   **Risks:** A carried type that is stale costs another widening round; it 
never narrows a self-reference, because the merge only adds nullability.
   
   **Constraints:** Match inner definitions by definition id and carry only the 
types that same definition has reached. Build the restored child from new 
definition and loop instances; never write tags on instances that another 
loop's snapshot still holds. Leave an inner loop that has no recorded origin as 
it is, so it widens through its own restore as before. Keep the single rebuild 
for a top-level-only widening; do not patch nullability into the resolved 
recursion.
   
   **Exclusions:**
   - A recursive CTE whose recursion writes a top-level NULL into a 
non-nullable anchor column still resolves its recursion twice; removing that 
would mean patching the resolved recursion in place, which could leave bound 
attributes narrower than the data.
   
   **Success:** Nested recursive CTEs that each widen rebuild every inner loop 
at most once per rebuild of its enclosing loop, without widening it again, 
whichever of their anchors resolves first, so the Resolution iterations they 
need grow linearly with nesting depth. The results and final types of every 
recursive CTE are unchanged by this repair. The restore explains in a comment 
why a top-level-only widening rebuilds the loop.
   
   **Verification:**
   - **Regression:** Three nested recursive CTEs whose recursions each write a 
NULL analyze with every inner loop widened only once, both when each enclosing 
anchor resolves first and when the inner anchors resolve first, such as literal 
inner anchors under an enclosing anchor over a table-valued function; they end 
with nullable self-reference types where NULLs are written and finish well 
within the Resolution batch's default iteration limit.
   - **Behavior:** A recursion writing IF(lvl = 0, NULL, n + 1) into a column 
whose anchor is BIGINT NOT NULL still ends with a nullable self-reference and 
returns the same rows.
   - **Inspection:** The restore carries a comment explaining why a 
top-level-only widening rebuilds the loop instead of patching nullability in 
place.



##########
docs/sql-migration-guide.md:
##########
@@ -75,6 +75,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 that pass through or copy a value built by a Scala UDF 
with primitive parameters, including one built in a CTE that the recursive CTE 
reads. 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 CT
 E 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 TYPE EVOLUTION`. Result columns that can never be `NULL` may now be 
reported as non-nullable, at the top level and in nested types such as 
`ARRAY(n)` over such a column.

Review Comment:
   **Nit (P3):** The opening sentences say a recursive CTE now returns the 
`NULL`s its anchor or recursive term writes into array elements, map values or 
struct fields, but that holds only for reads through the self-reference. Take a 
column the recursive term builds itself with a primitive Scala UDF, such as 
`ARRAY(f(IF(lvl = 0, CAST(NULL AS BIGINT), arr[0])))` in `UDFSuite`. The outer 
query's reference to the CTE keeps the types it was resolved with, from before 
UDF null handling, so an outer `SELECT arr[0] IS NULL FROM t` still returns 
false, as before.
   
   The list of changed types also applies "or derive their nested type from" 
only to columns derived from a column that actually receives a `NULL`. A column 
derived from a copy of an always-nullable value, such as `CONCAT(a, ARRAY(2))` 
where the recursion writes `ARRAY(a[0])` into `a`, changes type without 
matching any listed category, and so does a column derived from a UDF-built 
pass-through column. A user whose view or cast fails can miss the column that 
changed, and a user reading UDF-built nested values in the outer query is 
promised `NULL`s that still read as 0.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60061#discussion_r4510531270).
   
   **Verification:**
   - **Inspection:** Each category of result column the entry names as changing 
type does change in the analyzer, each column that changes type falls under a 
named category, and the claim about returned NULLs holds for reads through the 
self-reference and is qualified for outer reads of UDF-built nested values.



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