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


##########
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)
+        val widened = refTypes.zipWithIndex.map { case (refType, i) =>
+          childOutputs.foldLeft(refType) { case ((dt, nullable), output) =>
+            (StructType.unionLikeMerge(dt, output(i).dataType), nullable || 
output(i).nullable)

Review Comment:
   **Nit (P3):** `childOutputs` holds the plain output `Seq`s, and for a 
`Project` those are `List`s, so each `output(i)` here walks `i` cells. With two 
lookups per column per child, a check costs about `2 * k^2` list steps for a 
`k`-column CTE, and it reruns on every remaining Resolution iteration: 
negligible at typical widths, noticeable only for very wide recursive CTEs. 
Converting once, for example `Seq(l.anchor, 
l.recursion).map(withLaterNullability(_).output.toIndexedSeq)`, gives the same 
types in the same merge order.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60061#discussion_r4488922792).
   
   **Verification:**
   - **Compatibility:** Every existing widening case keeps the same 
self-reference and result types, including pass-through, copy-chain, inner 
WITH, column-list and Scala UDF cases.
   - **Inspection:** The merge reads each child's predicted output through an 
indexed sequence rather than a linear list.



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