spark-test commented on code in PR #60074:
URL: https://github.com/apache/spark/pull/60074#discussion_r4483199873
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/ExistingRDD.scala:
##########
@@ -213,13 +214,15 @@ object LogicalRDD extends Logging {
)(originDataset.sparkSession, stats, constraints, fromCheckpoint)
}
+ // Associate outputs with matching names and compatible nested nullability
for metadata rewriting.
Review Comment:
**Nit (P3):** "for metadata rewriting" here means statistics and
constraints, but the comment four lines below uses "metadata" for
`Attribute.metadata`, which this match deliberately ignores, so the header
reads as if the map rewrote attribute metadata. Wording such as "for rewriting
statistics and constraints" would remove the ambiguity.
**Verification:**
- **Inspection:** The comments on the LogicalRDD association helpers
describe them as rewriting statistics and constraints and use the word metadata
only for attribute metadata.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveWithCTE.scala:
##########
@@ -311,10 +312,14 @@ object ResolveWithCTE extends Rule[LogicalPlan] {
columnNames: Option[Seq[String]]) = {
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)
+ // Later iterations can introduce nulls at any depth, even with a
non-null anchor.
+ val useAnchorNullability =
+
conf.getConf(SQLConf.LEGACY_RECURSIVE_CTE_USE_ANCHOR_NESTED_NULLABILITY)
+ val output = anchor.output.map { attr =>
+ val dataType = if (useAnchorNullability) attr.dataType else
attr.dataType.asNullable
Review Comment:
**Blocking (P1):** `asNullable` widens every nested position of the
recursive reference, including positions that no iteration can make null. For a
column the recursive term only passes through, such as `a` in
```sql
WITH RECURSIVE r(n, a) AS (
SELECT 0, array(1)
UNION ALL
SELECT n + 1, a FROM r WHERE n < 2
)
SELECT * FROM r
```
the base branch's typing (`ARRAY<INT>` with non-null elements) was already
correct, but the `UnionLoop` output now reports nullable elements. That
regresses queries whose results were already correct:
- A persisted view created before the upgrade stored the non-null element
type. When a session reads it with the new setting unset, the default `SCHEMA
COMPENSATION` mode wraps the column in an ANSI `Cast` to the stored type, and
`canAnsiCast` rejects a nullable-to-non-null element, so the view stops
resolving until it is recreated or the reader sets
`spark.sql.legacy.recursiveCTE.useAnchorNestedNullability` to `true`. `SCHEMA
BINDING` fails the same way through `UpCast`. A SQL function whose inferred
return type has a `NOT NULL` struct field over such a CTE fails the same check
when called, which the migration note does not mention.
- `id NOT IN (SELECT x FROM r LATERAL VIEW explode(a) t AS x)` against a
non-nullable `id` no longer folds `IsNull(id = x)`, so it is planned as a
`BroadcastNestedLoopJoin` instead of an equi anti join: the CTE side's size
estimate is never broadcastable, which rules out the null-aware broadcast hash
join. When the outer side is also above the broadcast threshold, the whole CTE
result is broadcast. `sort_array`'s primitive fast path, the `count(x)` to
`count(1)` rewrite, and `IsNull`/`IsNotNull` folding are lost as well.
Columns that iterations can make null, including one that copies another
column's nullable value from the previous iteration, still need the widening.
These consequences were traced through the source, not run.
**Recommended change:** Under the default setting, give each
recursive-reference column the nested nullability that iterations can actually
produce instead of the anchor type's fully nullable form. Start from the
anchor's types; once the recursive term is resolved, merge the nested
nullability of its output into the reference type, and whenever that widens a
position, rebuild the recursive term from its original unresolved form with the
widened reference types and resolve it again, until the reference type covers
the recursive output. Keep the legacy setting's anchor typing unchanged, update
the recursive CTE analyzer expectations for pass-through columns, say in the
migration note that only columns iterations can make null become more nullable,
and add coverage for views, SQL functions and NOT IN planning over pass-through
recursive CTEs.
**Why this works:** Nested nullability only grows from one step to the next
and is bounded by the fully nullable form, so the loop terminates, normally
after zero or one extra resolution. A position ends up nullable exactly when
some iteration's recursive output can carry a null there, including a column
that copies another column's nullable value from the previous iteration, so the
PR's corrected null predicates still hold, while pass-through positions keep
the anchor's types. Stored view and SQL function schemas then still cast, and
nullability-gated optimizations such as the equi anti join for NOT IN, the
primitive sort_array path and null-check folding apply as on the base branch.
**Scope:** Make recursive-reference typing precise at its producer, keep
UnionLoop unresolved until the reference type is stable, and cover views, SQL
functions and plans over pass-through recursive CTEs.
**Compatibility:** Recursions that introduce nested nulls keep the PR's
nullable types and corrected results, and the legacy setting keeps the base
branch's analysis.
**Risks:** Each widening step resolves the recursive term again, adding
analysis time proportional to the number of nested positions that become
nullable, which is usually zero or one. Rebuilding the recursive term assigns
new expression IDs inside it; UnionLoop's output IDs must stay stable, and
parents must not resolve against an intermediate loop output or they will carry
stale types. Columns that iterations can make null keep the nullable types this
PR gives them, so views over those columns still need recreation or the legacy
setting, as the migration note says.
**Constraints:** With the legacy setting enabled, analysis must match the
base branch exactly. Keep the PR's corrected results for recursions that
introduce nested nulls, its preservation of the anchor's struct field spelling,
and its errors when a recursive term widens the anchor's element or field
types. The re-typing must terminate for every input and must not leave the
unresolved recursive term in the analyzed plan. Keep the recursive coercion
keyed to structural type compatibility rather than to the loop's resolved
state, so that pending re-typing does not make it fire on every analyzer pass.
**Exclusions:**
- Views and SQL functions whose stored schema was already wrong on the base
branch, because a column copies another column's nullable value from the
previous iteration, still need recreation or the legacy setting; that failure
is the intended correction.
- The scope and rollback of the relaxed LogicalRDD statistics matching,
which a separate repair handles.
**Success:** Under the default setting, a recursive CTE column that the
recursive term only passes through, or rebuilds without introducing a null,
keeps the anchor's nested nullability in the reference, the loop output and the
CTE result. A column that any iteration can make null at a nested position,
including one that copies another column's nullable value from the previous
iteration, is nullable at that position, and the PR's corrected results for
those queries are unchanged. A view or SQL function created on the base branch
over a recursive CTE that only passes nested non-null columns through resolves
and returns the same rows after the change. NOT IN on an element unnested from
such a pass-through column against a non-nullable key is planned as an equi
anti join as on the base branch, and sort_array over it keeps its primitive
fast path.
**Verification:**
- **Behavior:** Analyzer coverage asserts reference, loop and output types
for array, struct, map and struct-map-key anchors, with and without CTE column
aliases: pass-through columns keep the anchor's nested nullability,
null-introducing columns and columns that copy another column's nullable value
from the previous iteration become nullable at the right positions, and a chain
of such copies converges.
- **Regression:** A view created with the base branch's schema over a
recursive CTE that passes a nested non-null column through resolves and returns
the same rows under the default setting, in both the default compensation mode
and SCHEMA BINDING, and a SQL function whose inferred return type has a NOT
NULL struct field over such a CTE can be called.
- **Regression:** NOT IN on an element exploded from a pass-through
recursive CTE column, against a non-nullable key, is planned as an equi anti
join rather than a broadcast nested loop join, with the same result rows.
- **Compatibility:** With the legacy setting enabled, recursive reference
types and recursive coercion match the base branch, and the existing
nested-nullability golden results (null predicates, struct field spelling and
widening errors) are unchanged with ANSI mode on and off.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -7251,6 +7251,18 @@ object SQLConf {
.intConf
.createWithDefault(100)
+ val LEGACY_RECURSIVE_CTE_USE_ANCHOR_NESTED_NULLABILITY =
+ buildConf("spark.sql.legacy.recursiveCTE.useAnchorNestedNullability")
+ .internal()
+ .doc("When true, recursive CTE references inherit the anchor's nested
nullability " +
+ "and recursive type coercion uses the legacy rules. This can return
incorrect results " +
+ "or fail when later iterations introduce null array elements, map
values, or struct " +
+ "fields. When false, recursive references allow nested nulls.")
+ .version("4.4.0")
+ .withBindingPolicy(ConfigBindingPolicy.SESSION)
Review Comment:
**Nit (P3):** The documented restore path for views depends on this
`SESSION` binding: a view created before this change has no saved value for the
key, so only the reading session's value decides how its body resolves. No
changed test creates or reads a persisted view or SQL function over a recursive
CTE; `ResolveRecursiveCTESuite`, `CTEInlineSuite` and the new golden file run
direct queries only. With `PERSISTED`, such a view would always resolve with
the default and the documented workaround would stop working while every suite
stays green. A `PersistedViewTestSuite` case for a view stored with the
previous schema, read with the setting unset and with it set to `true`, would
pin both behaviors.
**Verification:**
- **Compatibility:** A persisted view over a recursive CTE whose stored
schema has the base branch's non-null nested type for a column that copies
another column's nullable value from the previous iteration, and which has no
saved value for the legacy setting, fails to resolve when the reading session
leaves the setting unset and resolves with the stored schema when the reading
session sets it to true.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/ExistingRDD.scala:
##########
@@ -213,13 +214,15 @@ object LogicalRDD extends Logging {
)(originDataset.sparkSession, stats, constraints, fromCheckpoint)
}
+ // Associate outputs with matching names and compatible nested nullability
for metadata rewriting.
private[sql] def buildOutputAssocForRewrite(
source: Seq[Attribute],
destination: Seq[Attribute]): Option[Map[Attribute, Attribute]] = {
- // We check the name and type, allowing nullability, exprId, metadata,
qualifier be different
- // E.g. This could happen during optimization phase.
+ // Optimization can change exprId, metadata, and qualifier. Recursive
references can also
+ // widen nested nullability; narrowing it would not preserve the source's
type guarantees.
val rewrite = source.zip(destination).flatMap { case (attr1, attr2) =>
- if (attr1.name == attr2.name && attr1.dataType == attr2.dataType) {
+ if (attr1.name == attr2.name &&
+ DataType.equalsIgnoreCompatibleNullability(attr1.dataType,
attr2.dataType)) {
Review Comment:
**Nit (P3):** This relaxation applies to every caller of these helpers, not
only recursive CTE substitution, and
`spark.sql.legacy.recursiveCTE.useAnchorNestedNullability` does not control it.
`LogicalRDD.fromDataset` also backs `Dataset.checkpoint`/`localCheckpoint` and
`ForeachBatchSink`: for example, checkpointing
`df.select(col("arr").cast(ArrayType(IntegerType, containsNull = true)))` over
a non-null-element `arr` now keeps statistics and constraints, because
`SimplifyCasts` removes the nullability-only cast, where the base branch
dropped them with the warning. With the legacy setting on, an iteration whose
data are narrower than the anchor-typed reference also keeps statistics now, so
the flag does not restore the previous planning. Results are unaffected, but
join selection and constraint-based filter inference can change on paths that
neither the PR description nor the migration note mentions. Making compatible
matching an explicit option that only `UnionLoopExec` enables
when the legacy setting is off would keep the other callers as they were.
**Verification:**
- **Compatibility:** With the legacy setting enabled, a recursion whose
later iterations have narrower nested nullability than the anchor-typed
reference drops statistics and constraints and logs the mismatch warning on the
LogicalRDD path, as on the base branch.
- **Compatibility:** Checkpointing a Dataset whose optimized output has
narrower nested nullability than its analyzed output gives the same statistics
and constraints as on the base branch.
- **Regression:** With the default setting, a recursion above the
local-relation threshold with nested non-null anchor types keeps statistics and
constraints on every iteration and logs no mismatch warning.
##########
sql/core/src/test/scala/org/apache/spark/sql/CTEInlineSuite.scala:
##########
@@ -32,6 +33,38 @@ abstract class CTEInlineSuiteBase
import testImplicits._
+ // More than 100 rows per iteration exercises recursive reference
substitution through LogicalRDD.
+ test("SPARK-60860: nested nulls in recursive CTEs with an RDD-backed
anchor") {
+ for {
+ localRelationLimit <- Seq(0, 100, 200)
+ legacy <- Seq(false, true)
+ } {
+ withSQLConf(
+ SQLConf.LEGACY_RECURSIVE_CTE_USE_ANCHOR_NESTED_NULLABILITY.key ->
legacy.toString,
+
SQLConf.CTE_RECURSION_ANCHOR_ROWS_LIMIT_TO_CONVERT_TO_LOCAL_RELATION.key ->
+ localRelationLimit.toString) {
+ val appender = new LogAppender("recursive nested nullability")
+ withLogAppender(appender, loggerNames =
Seq(classOf[LogicalRDD].getName)) {
+ val result = sql(
+ """WITH RECURSIVE r(id, n, a, saw_null) AS (
+ | SELECT id, 0, array(1), false FROM range(101)
+ | UNION ALL
+ | SELECT id, n + 1, array(CAST(NULL AS INT)), exists(a, x -> x
IS NULL)
+ | FROM r WHERE n < 2
+ |)
+ |SELECT n, saw_null, count(*) FROM r GROUP BY n, saw_null
+ |""".stripMargin)
+ checkAnswer(result, Seq(Row(0, false, 101L), Row(1, false, 101L),
Row(2, !legacy, 101L)))
+ }
+ // The legacy schema can still require narrowing nested nullability in
later iterations.
+ if (!legacy) {
Review Comment:
**Nit (P3):** This absent-warning check is the test's only
`LogicalRDD`-specific assertion, so it can pass without exercising that path.
With `localRelationLimit = 200`, the 101-row anchor and every iteration become
a `LocalRelation` (`count <= localRelationLimit` in `UnionLoopExec`), so that
run never reaches `LogicalRDD.fromDataset`. At 0 and 100 the check would still
pass if a later change routed those runs elsewhere or the appender stopped
capturing `LogicalRDD` warnings, and the test name ("RDD-backed anchor") and
comment overstate the 200 case. The legacy runs at 0 and 100 do log the warning
from the second iteration on, because the reference keeps the anchor's non-null
elements while that iteration's data are nullable, so asserting it there would
give the test a positive control.
**Verification:**
- **Regression:** Reverting the compatible-nullability association for
recursive substitution fails the default-setting runs at thresholds 0 and 100,
and routing those runs away from the LogicalRDD path fails the legacy-setting
assertion.
--
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]