peter-toth commented on code in PR #60671:
URL: https://github.com/apache/spark/pull/60671#discussion_r4630672370
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PushdownPredicatesAndPruneColumnsForCTEDef.scala:
##########
@@ -65,9 +65,15 @@ object PushdownPredicatesAndPruneColumnsForCTEDef extends
Rule[LogicalPlan] with
private def gatherPredicatesAndAttributes(plan: LogicalPlan, cteMap:
CTEMap): Unit = {
plan match {
case WithCTE(child, cteDefs) =>
- cteDefs.zipWithIndex.foreach { case (cteDef, precedence) =>
+ cteDefs.foreach { cteDef =>
gatherPredicatesAndAttributes(cteDef.child, cteMap)
- cteMap.put(cteDef.id, (cteDef, precedence, Seq.empty,
AttributeSet.empty))
+ // The precedence is the visiting order across all scopes, not the
index within
+ // this WithCTE: a definition visited later is either a later
sibling (a real
+ // forward reference) or lives in a nested scope, and an earlier
definition
+ // cannot see either. (A definition nested in an earlier sibling
sorts lower
+ // yet is also invisible, but no reference site can see both it and
the
+ // current definition, so that case never reaches the guard.)
+ cteMap.put(cteDef.id, (cteDef, cteMap.size, Seq.empty,
AttributeSet.empty))
Review Comment:
**Finding 3.** `cteMap.size` is a visiting order only while every id is new,
and `gatherPredicatesAndAttributes` visits some scopes twice. The reference
case walks `plan.subqueriesAll`, which already includes nested subqueries, and
each of those walks its own subqueries again. On the second visit the ids
already exist, the size stays flat, and every definition of that `WithCTE` gets
the same precedence. So `>=` reads a reference to an earlier sibling as a
forward one. Master's index within the `WithCTE` stays the same on every visit.
```sql
with x as materialized (select id from t2)
select count(*) from x
where id > (select max(id) - 60 from t2 where id < (
with c1 as materialized (select id from small),
c2 as materialized (select id from t2)
select count(*) from c2 where id > (select min(id) + 50 from c1)))
```
Both return `100`. On master three CTE bodies in the optimized plan carry a
filter with a subquery, and on this head one does. `c2`'s reference reads its
earlier sibling `c1`, so `c2` is now materialized unfiltered. A counter that
always increases restores it, back to three:
```scala
// in apply
gatherPredicatesAndAttributes(plan, cteMap, Iterator.from(0))
// in the WithCTE case
cteMap.put(cteDef.id, (cteDef, precedences.next(), Seq.empty,
AttributeSet.empty))
```
Here `precedences: Iterator[Int]` is passed through the recursion. That also
makes the comment above true. Measured with the suites listed in 1.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PushdownPredicatesAndPruneColumnsForCTEDef.scala:
##########
@@ -86,7 +92,8 @@ object PushdownPredicatesAndPruneColumnsForCTEDef extends
Rule[LogicalPlan] with
case r: CTERelationRef =>
// If the ref's ID does not exist in the map or if ref's
corresponding precedence
// is bigger than that of the current CTE we are pushing
predicates for, it
- // indicates a forward reference and we should exclude this
predicate.
+ // indicates a forward reference (a later sibling, or a
definition in a nested
Review Comment:
**Finding 1.** This says a reference into a nested scope excludes the
predicate, but the check only sees references among the subquery's own
operators. `s.plan.find` at line 91 does not descend into subqueries nested
inside `s.plan`. On master that left some crashes in place. With the new order
it also lets through one that master stopped: a nested definition now takes a
predicate that reads an outer CTE, and whatever that predicate hides one level
down comes with it.
Measured on master and on this head, with `t2 = range(100)` plus `k = id %
10`, and `small = range(5)`:
```sql
with u as materialized (select id, k from t2 where k < 6)
select (with c1 as materialized (select id from small),
c2 as materialized (select id from small where id > 0)
select min(id) from c1
where id >= (select min(u.id) from u
where u.id >= (select min(id) from c2))) x
```
Master returns `[1]`, and this head fails with `NoSuchElementException: key
not found: 2`. The SPARK-61957 query with its reference one subquery deeper,
`id > (select min(id) from small where id >= (select min(id) from c))`, fails
with `key not found: 2` on both.
Walking the nested subqueries too fixes both, which then return `[1]` and
`[59,95]`:
```scala
case s: SubqueryExpression =>
// Definitions the subquery brings along travel with the predicate.
val definedInside = s.plan.collectWithSubqueries {
case WithCTE(_, defs) => defs.map(_.id)
}.flatten.toSet
s.plan.collectFirstWithSubqueries {
case r: CTERelationRef if !definedInside.contains(r.cteId) &&
(!cteMap.contains(r.cteId) || cteMap(r.cteId)._2 >= precedence) => r
}.nonEmpty
```
With this and the changes from 2 and 3, these pass:
- `CTEInlineSuite`, AQE off and on (99 tests);
- the `cte` cases of `SQLQueryTestSuite` (18);
- `InlineCTESuite` and `PushdownPredicatesForCTEDefStalenessSuite` (19).
The two shapes would make good tests next to the new one.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PushdownPredicatesAndPruneColumnsForCTEDef.scala:
##########
@@ -65,9 +65,15 @@ object PushdownPredicatesAndPruneColumnsForCTEDef extends
Rule[LogicalPlan] with
private def gatherPredicatesAndAttributes(plan: LogicalPlan, cteMap:
CTEMap): Unit = {
plan match {
case WithCTE(child, cteDefs) =>
- cteDefs.zipWithIndex.foreach { case (cteDef, precedence) =>
+ cteDefs.foreach { cteDef =>
Review Comment:
**Finding 2.** The rule keys its state by def id, but `InlineCTE` can leave
the same `WithCTE` in two places, with one id and different exprIds. That
happens for a non-materialized CTE that holds a nested `MATERIALIZED` one and
is referenced twice. The second registration then replaces the first, and its
predicate is pushed into both copies. Master kept that predicate out of the
nested definition (`0 >= 0`), so the query ran. This head admits it:
```sql
with r as materialized (select id from small),
w as (select (with x as materialized (select id from t2)
select count(*) from x where id > (select max(id) from
r)) cnt
from range(2))
select p.cnt, q.cnt from w p, w q
```
Master returns four rows of `[95,95]`. This head fails with
`INTERNAL_ERROR_ATTRIBUTE_NOT_FOUND`: `Could not find id#20L in [id#0L]`. I
measured this in a plain JVM. Inside Spark's test harness, master and this head
both fail earlier, with `Once strategy's idempotence is broken for batch Inline
CTE`. So a test for this has to drive the rule directly, e.g. a `PlanTest` on
the plan that `InlineCTE` returns.
Leaving alone an id that two different definitions register fixes it, and
gives four rows of `[95,95]`, as with the rule excluded:
```scala
// in gatherPredicatesAndAttributes, before the put
cteMap.get(cteDef.id).foreach { case (seen, _, _, _) =>
if (!(seen eq cteDef)) duplicated += cteDef.id
}
// in pushdownPredicatesAndAttributes
case cteDef @ CTERelationDef(child, id, originalPlanWithPredicates, _, _, _,
_)
if !duplicated.contains(id) => ...
case cteRef @ CTERelationRef(cteId, _, output, _, _, _, _, _)
if !duplicated.contains(cteId) => ...
```
Here `duplicated` is a `mutable.Set[Long]` created next to `cteMap` in
`apply`. A `WithCTE` that is merely visited twice (3) is the same instance, so
this does not affect it.
The same guard also fixes a wrong result that master has too. `with w as
(select (with x as materialized (select id, k, id * 2 as d from t2) select
max(d) from x) m from range(2)) select p.m, q.m from w p, w q` returns `99`
instead of `198` on master and on this head, and `198` with this rule excluded
or with the guard. I found no ticket for it, so if the guard does not land
here, please file one.
##########
sql/core/src/test/scala/org/apache/spark/sql/CTEInlineSuite.scala:
##########
@@ -1104,6 +1105,40 @@ abstract class CTEInlineSuiteBase
}
}
+ test("SPARK-61957: predicate referencing a nested MATERIALIZED CTE stays in
its scope") {
+ withTempView("t2", "small") {
+ spark.range(100).selectExpr("id", "id % 10 as
k").createOrReplaceTempView("t2")
+ spark.range(5).createOrReplaceTempView("small")
+
+ // Each scalar subquery keeps `c` in its own nested WithCTE, which the
outer `u`
+ // cannot see. The predicate on the reference to `u` mentions `c` only
inside that
+ // nested scope, so PushdownPredicatesAndPruneColumnsForCTEDef must keep
it at the
+ // reference; pushing it into `u`'s definition plants a reference to `c`
outside
+ // `c`'s scope, which used to crash the rule's next pass with a
key-not-found error.
+ val df = sql(
+ s"""with
+ |u0 as materialized (select id from t2),
+ |u as materialized (select id, k from t2 where k < 6)
+ |select (with c as materialized (select id from small)
+ | select count(*) from u where id > (select min(id) from c))
x,
+ | (with c as materialized (select id from small)
+ | select max(id) from u where id > (select min(id) from c)) y
+ |from u0 limit 1
+ """.stripMargin)
+ checkAnswer(df, Row(59, 95) :: Nil)
+
+ // No definition may absorb a predicate that references another scope's
CTE.
+ val defsWithSubquery =
df.queryExecution.optimizedPlan.collectWithSubqueries {
+ case d: CTERelationDef
+ if d.child.collect {
+ case p if
p.expressions.exists(_.exists(_.isInstanceOf[ScalarSubquery])) => p
+ }.nonEmpty => d
Review Comment:
**Finding 5.** `optimizedPlan` holds no `CTERelationDef` here.
`ReplaceCTERefWithRepartition`, one of the last batches of `SparkOptimizer`,
replaces every reference with its definition's body under a
`RepartitionOperation`, and drops the `WithCTE`. So this collect returns
nothing, and the assertion holds whatever was pushed. On this query,
`optimizedPlan.collectWithSubqueries { case d: CTERelationDef => d }` is empty
at this head. The test still fails on master, but only through the crash. The
description says the test "verifies that no CTE definition absorbs a
predicate", and this is the check that would have to do it.
The other pushdown tests in this file look under `RepartitionOperation`
(e.g. line 374), which holds the definition bodies after the replacement. The
same check on those does see a pushed predicate:
```suggestion
case r: RepartitionOperation
if r.child.collect {
case p if
p.expressions.exists(_.exists(_.isInstanceOf[ScalarSubquery])) => p
}.nonEmpty => r
```
With it, this test passes at this head. On the query in 4, where this PR
does push a predicate with a subquery into a definition, the same check finds
that body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/PushdownPredicatesAndPruneColumnsForCTEDef.scala:
##########
@@ -65,9 +65,15 @@ object PushdownPredicatesAndPruneColumnsForCTEDef extends
Rule[LogicalPlan] with
private def gatherPredicatesAndAttributes(plan: LogicalPlan, cteMap:
CTEMap): Unit = {
plan match {
case WithCTE(child, cteDefs) =>
- cteDefs.zipWithIndex.foreach { case (cteDef, precedence) =>
+ cteDefs.foreach { cteDef =>
gatherPredicatesAndAttributes(cteDef.child, cteMap)
- cteMap.put(cteDef.id, (cteDef, precedence, Seq.empty,
AttributeSet.empty))
+ // The precedence is the visiting order across all scopes, not the
index within
Review Comment:
**Finding 4.** Besides keeping predicates out, the new order lets new ones
in. On master the first definition of a nested `WithCTE` has index 0, so `0 >=
0` kept out every predicate at its references that reads a CTE, and a later one
took it only when the outer CTE's own index was lower. Now a nested definition
takes any predicate that reads an outer CTE:
```sql
with x as materialized (select id from small)
select (with n as materialized (select id from t2)
select count(*) from n where id > (select min(id) + 50 from x)) z
```
Both return `49`. Master materializes `n` in full, and this head puts the
filter with the subquery into it. That pushdown is valid, since `x` is visible
where `n` is defined, and it is the path that 1 and 2 go through. The
description only talks about preventing pushdowns, so it should mention this
one. A test should pin it too, with the check from 5, along with the
earlier-sibling pushdown from 3, which no test covers either.
##########
sql/core/src/test/scala/org/apache/spark/sql/CTEInlineSuite.scala:
##########
@@ -1104,6 +1105,40 @@ abstract class CTEInlineSuiteBase
}
}
+ test("SPARK-61957: predicate referencing a nested MATERIALIZED CTE stays in
its scope") {
Review Comment:
**Finding 6.** The bug reaches back to 4.0. SPARK-48307 (4.0.0) made
`InlineCTE` keep not-inlined definitions in their own `WithCTE`, so nested ones
reach this rule since then. Before it, every such definition was hoisted into
one top-level `WithCTE`, as on branch-3.5, so the local index was a global one.
`MATERIALIZED` only exists since 4.4.0 (SPARK-59372), but it is not needed: a
non-deterministic CTE referenced twice is not inlined either. This variant
fails with `key not found: 2` with the master rule, and returns `[59,95]` on
this head:
```sql
with u0 as (select id, rand() r from t2),
u as (select id, k, rand() r from t2 where k < 6)
select (with c as (select id, rand() r from small)
select count(*) from u
where id > (select min(id) from c) and id > (select max(id) - 4 from
c)) x,
(with c as (select id, rand() r from small)
select max(id) from u
where id > (select min(id) from c) and id > (select max(id) - 4 from
c)) y
from u0 a join u0 b on a.id = b.id limit 1
```
As a second test, it would also run on the maintenance branches, where this
test does not parse. I checked the older branches by reading only: branch-4.0
to branch-4.3 have the same rule and keep nested definitions in place.
--
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]