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


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

Review Comment:
   **Blocking (P1):** The self-reference used to declare every column nullable 
at the top level. Here it now takes the nullability predicted from copies of 
the anchor and recursion that apply Scala UDF null handling, but those copies 
stop at references to other CTEs. A `CTERelationRef` copied its definition's 
output during resolution, before the later batch wraps a primitive-parameter 
UDF inside that definition in `If(IsNull(input), NULL, udf)`, and 
`UpdateAttributeNullability` skips leaves. So a column the anchor or recursion 
reads from such a CTE is declared non-nullable here, and later iterations, 
which read the previous level's rows through the self-reference's declared 
types, read its NULLs without a null check.
   
   With `spark.udf.register("f", (x: Long) => x + 1)`:
   
   ```sql
   WITH RECURSIVE x AS (SELECT f(IF(id = 0, CAST(NULL AS BIGINT), id)) AS v 
FROM range(3)),
   t(lvl, v) AS (SELECT 0, v FROM x UNION ALL SELECT lvl + 1, v FROM t WHERE 
lvl < 2)
   SELECT lvl, count_if(v IS NULL) FROM t GROUP BY lvl ORDER BY lvl
   ```
   
   The base branch counts one NULL at every level. With this change the counts 
are 1, 0 and 0, because levels 1 and 2 read the NULL as 0. This happens 
whenever the anchor or recursion reads such a UDF column through a CTE 
reference (a sibling `WITH RECURSIVE` entry, the definition's inner `WITH`, or 
an enclosing `WITH`), the CTE is inlined, which is the default for 
deterministic CTEs, and the recursion passes the column through or derives a 
value from it. The same boundary leaves nested NULLs from such a CTE, such as 
`ARRAY(f(c))` defined in `x`, unwidened. The new `UDFSuite` cases never put the 
UDF behind a CTE reference. 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 self-reference type prediction see the 
later nullability of the CTEs the loop reads. When computing the widened types, 
replace the output of each non-recursive CTE reference in the anchor and 
recursion copies with the output of a null-handled copy of its definition, 
found among the enclosing WITH's definitions, the definition's inner WITH, or 
the already resolved outer definitions. Add recursive CTE tests with a 
primitive Scala UDF in a sibling CTE, in an inner WITH and in a WITH that 
encloses the recursive CTE, read by the anchor and by the recursion, with its 
result used both directly and inside an array.
   
   **Why this works:** The copies' outputs then reflect the nullability the 
live plan has after UDF null handling and CTE inlining, including values read 
through CTE references. The existing merge widens the self-reference, at the 
top level and in nested types, exactly where such NULLs can arrive, so later 
iterations read them with null checks.
   
   **Scope:** Extend the recursive CTE self-reference type prediction to 
referenced CTEs, and add Scala UDF coverage for them.
   
   **Compatibility:** Self-reference columns that can never be NULL stay 
non-nullable, at the top level and in nested types built from them.
   
   **Risks:** Columns read from a CTE whose definition applies a primitive 
Scala UDF to a nullable input become nullable in the self-reference and can 
widen result types, like other UDF-written columns, so persisted views over 
them may need the remedies the migration note describes. Nullability that 
extension rules add after the Resolution batch stays invisible to the 
prediction, so NULLs those rules introduce are still not covered.
   
   **Constraints:** The prediction must only widen nullability and must not 
resolve or rewrite the live definitions; the definition copies are discarded 
once their types are read. A reference whose definition is not resolved yet 
must not block the check, since the loop cannot be resolved before its 
referenced definitions are.
   
   **Exclusions:**
   - The outer query's reference to the recursive CTE keeps the nested types 
fixed during analysis, as for any CTE; that general behavior is not changed 
here.
   
   **Success:** A NULL produced by a primitive Scala UDF in a CTE that the 
anchor or recursion reads, whether a sibling WITH RECURSIVE entry, an inner 
WITH or a WITH that encloses the recursive CTE, is read back as NULL by later 
iterations, at the top level and in nested positions. Recursive CTEs that read 
no such CTE keep the self-reference and result types they have before this 
repair.
   
   **Verification:**
   - **Regression:** A recursive CTE whose anchor reads, from a sibling WITH 
RECURSIVE entry, a column computed by a primitive Long => Long UDF over an 
input that is NULL for some rows returns NULL for that column at every level 
that passes it through, on both local-relation and materialized steps.
   - **Regression:** The same holds when the UDF is in an inner WITH of the 
definition or in a WITH that encloses the recursive CTE, when the recursion 
rather than the anchor reads the CTE, and when the UDF's result is wrapped in 
an array whose NULL element a later level reads back as NULL.
   - **Compatibility:** Recursive CTEs without CTE references keep exactly the 
self-reference and result types they have before this repair.



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