cloud-fan commented on code in PR #60403:
URL: https://github.com/apache/spark/pull/60403#discussion_r4584688573
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2281,10 +2285,12 @@ object InferFiltersFromConstraints extends
Rule[LogicalPlan]
}
private def inferFilters(plan: LogicalPlan): LogicalPlan =
plan.transformWithPruning(
- _.containsAnyPattern(FILTER, JOIN)) {
+ _.containsAnyPattern(FILTER, JOIN, AS_OF_JOIN)) {
case filter @ Filter(condition, child) =>
+ val canAdd: Expression => Boolean =
+ if (filter.getTagValue(asOfInputFilterTag).isDefined) canBeAsOfFilter
else canBeFilter
Review Comment:
**Non-blocking (P2):** The as-of check here depends on the tag still being
on the Filter that holds the as-of-derived predicates, which holds only within
one run of the Once batch. Two later rewrites move those predicates into a
Filter without the tag: PushPredicateThroughNonJoin pushes the marked Filter
below a Project as a new Filter, and transformDown copies the tag onto the
returned Project (TreeNode.scala:596); and when a filter is pushed onto the
marked Filter, CombineFilters builds a merged Filter that takes the tags of the
outer, unmarked one. A correlated scalar or lateral subquery body goes through
this rule twice: OptimizeSubqueries runs the whole optimizer on it, and
RewriteCorrelatedScalarSubquery or RewriteLateralSubquery then inlines it
before the main plan's Infer Filters batch.
From reading the code, two outcomes follow:
- With ANSI mode and spark.sql.legacy.inferFailableFiltersFromConstraints
on, take a correlated scalar subquery over `(SELECT id, k, a, ts FROM l WHERE
10 / a > 0) l2 ASOF JOIN r MATCH_CONDITION (l2.ts >= r.ts) ON l2.k = r.k AND
r.k = l2.a`. The subquery's own run adds the tagged `l2.k = l2.a` above the
Project and correctly rejects `10 / l2.k > 0`. The next batch merges that
Filter with `10 / a > 0` below the Project, untagged, and the main plan's run
then adds `10 / k > 0` through canBeFilter, ahead of the original condition. A
left row with k = 0 and a = 5 now raises DIVIDE_BY_ZERO, while the base branch
never adds `k = a` and returns rows. The input's own cast equality can do the
same in the other direction: `CAST(s AS INT) = y` rewrites an added `y > 5`
into `CAST(s AS INT) > 5`.
- With the flag off, in `FROM o, LATERAL (SELECT l.k, l.a, r.v FROM l ASOF
JOIN r ... ON l.k = r.k AND r.k = l.a WHERE l.id = o.id) lat WHERE lat.a NOT IN
(SELECT x FROM s)`, the main plan pushes the NOT IN into the as-of left input
after the subquery's own run added `l.k = l.a`, CombineFilters merges the two
untagged, and the main plan's run derives `l.k NOT IN (SELECT x FROM s)`, so
that input runs two anti joins where the base branch runs one.
Both need the internal, default-off sort-merge as-of settings, and the first
also the internal, default-off legacy flag. None of the new tests moves a
tagged Filter into an untagged one before another run of the rule.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60403#discussion_r4562643184).
**Recommended change:** Two parts, both in InferFiltersFromConstraints.
First, do not run the AsOfJoin case when the plan the rule gets is rooted at a
correlated Subquery, as InjectRuntimeFilter does: the main plan inlines a
correlated scalar or lateral subquery body before its own Infer Filters batch
and runs the case there once, after any filter from the outer query has been
pushed in. Second, while spark.sql.legacy.inferFailableFiltersFromConstraints
is on, make inferAsOfInputFilter add only IS NOT NULL predicates to either
input; IS NOT NULL takes no part in the substitution through equalities and
literal bindings, so no later run can derive a filter that can fail from what
the case added. Keep the tag and the Filter case, which still stop the same-run
rewrite of an input's own IN or NOT IN filter, explain both parts in code
comments, and add a TODO at the correlated-Subquery check naming the
uncorrelated LATERAL subquery, which RewriteLateralSubquery also inlines. In
the filt
er-inference plan tests, the legacy-flag test then expects only IS NOT NULL
from the as-of case, so its third case expects no `lk = la`, and a new case
runs the rule on a plan rooted at a correlated Subquery; the sort-merge as-of
SQL tests get the subquery cases listed under verification.
**Why this works:** A correlated scalar or lateral subquery body then gets
its as-of filters only from the main plan's single run of the Once batch, where
the tag still marks the Filters the case adds when the Filter case visits them,
and no later run of the rule follows. Under the legacy flag, the case adds only
IS NOT NULL, which inferAdditionalConstraints and
inferConstraintsFromLiteralBindings skip, so any later run, on any route,
derives only from predicates the base branch also has there.
**Risks:** With the legacy flag on, as-of inputs get only IS NOT NULL from
the ON keys, so the key equalities, literal bindings and range filters the
current version infers, such as `q.symbol = 'MSFT'`, are not inferred, and
those inputs shuffle and sort more rows; with the flag off this part changes
nothing. As-of joins inside a correlated EXISTS or IN subquery get no inferred
filters, as on the base branch, because the optimizer inlines those bodies only
after its filter-inference batch; as-of joins inside correlated scalar and
lateral subqueries get theirs from the main plan's run instead. An uncorrelated
LATERAL subquery still goes through the rule twice, so an IN or NOT IN filter
that the outer query pushes into its inner as-of left input can still be
derived a second time there; with the second part, nothing that can fail is
derived there.
**Constraints:** Keep the tag and the Filter case, which stop an input's own
IN or NOT IN filter from being rewritten with an added equality or literal
within one run. Keep canBeFilter, the regular Join cases and Filters the
AsOfJoin case did not add following the legacy flag as on the base branch. Keep
running the AsOfJoin case on the main plan and on uncorrelated subquery bodies.
Apply the IS NOT NULL restriction only while the legacy flag is on.
**Exclusions:**
- An uncorrelated LATERAL subquery, whose Subquery root is not marked
correlated, still goes through the rule twice, so a pushed-in IN or NOT IN
filter can still be derived a second time there; a TODO at the
correlated-Subquery check names it.
**Verification:**
- **Regression:** With ANSI mode, the legacy flag and SQL ASOF JOIN on, each
of these queries returns the rows it returns with InferFiltersFromConstraints
excluded instead of failing: an inner as-of join inside a correlated scalar
subquery whose left input keeps a Project over `10 / a > 0`, with ON `l.k = r.k
AND r.k = l.a` and a left row where k is 0 and a is 5; the same join inside a
lateral subquery whose `a <> 0 AND 10 / a > 0` filter comes from the outer
WHERE; and an inner as-of join inside a correlated scalar subquery with ON `l.y
= r.k`, a right filter `r.k > 5`, and a left input that filters on `kind =
'num' AND CAST(s AS INT) = y` over a row whose kind is 'text' and whose s is
'abc'.
- **Regression:** With the legacy flag off, a correlated lateral subquery
whose inner as-of join has ON `l.k = r.k AND r.k = l.a`, under an outer `WHERE
lat.a NOT IN (SELECT x FROM s)`, has exactly one join below the as-of left
input and returns the same rows as with InferFiltersFromConstraints excluded.
- **Behavior:** In the filter-inference plan tests, with the legacy flag on,
the as-of case adds only IS NOT NULL to either input, so the third case of the
legacy-flag test expects no `lk = la` on the left input, and on a plan rooted
at a correlated Subquery the as-of case adds no filter.
- **Compatibility:** With the legacy flag off, an as-of join inside a
correlated scalar subquery still has the inferred key filters on its inputs in
the optimized plan, now added when the main plan runs the rule over the inlined
body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2315,6 +2321,32 @@ object InferFiltersFromConstraints extends
Rule[LogicalPlan]
case _ => join
}
+
+ // A right row that fails the ON condition is never the match of any left
row, so a filter
+ // that follows from the left constraints and the ON condition can drop it
before the join.
+ // An inner join also drops the left rows without a match, so its left
side gets one too.
+ case j: AsOfJoin if conf.inferFiltersAcrossAsOfJoinEnabled =>
+ val allConstraints = getAllConstraints(j.left, j.right, j.condition)
+ val newLeft = j.joinType match {
+ case Inner => inferAsOfInputFilter(j.left, allConstraints)
+ case LeftOuter => j.left
+ case other =>
+ throw SparkException.internalError(s"Unexpected as-of join type:
$other")
+ }
+ // The join reads the right input lazily and reads one row past each key
group. A right
+ // filter changes which rows it reads, so a right ON key or a right
input expression that
+ // can fail could fail on a row the join did not read before.
+ val rightKeys =
+ j.condition.toSeq.flatMap(AsOfJoin.extractEquiJoinKeys(_, j.left,
j.right)._2)
+ val newRight = if (rightKeys.forall(cannotFail) &&
cannotFailAnywhere(j.right)) {
Review Comment:
**Non-blocking (P2):** This check decides the right input on its own, while
an inner join's left input is always filtered at Optimizer.scala:2331. In an
inner self join such as `WITH q AS (SELECT sym, ts, (ask - bid) / bid AS spread
FROM quotes) SELECT ... FROM q a ASOF JOIN q b MATCH_CONDITION (a.ts > b.ts) ON
a.sym = b.sym` with ANSI on and a nullable sym, the division makes the right
copy fail cannotFailAnywhere and keep its base plan, while the left copy gets
`isnotnull(sym)` as a data filter of its scan. From reading the planner code,
the two exchanges then no longer canonicalize to the same plan, so quotes is
scanned and shuffle-written twice instead of once, the same loss you measured
for the LEFT ASOF case. The PR description and the comment at
Optimizer.scala:2346-2348 state that cost only for a left outer self join, and
an earlier review comment on this PR said an inner self join keeps its reuse,
which this check now makes untrue for such inputs. No test or benchmark loo
ks at exchange reuse for an as-of self join.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60403#discussion_r4562643206).
**Recommended change:** Extend the comment at Optimizer.scala:2346-2348 to
cover an inner as-of self join whose right input fails the right-input check:
only the left copy gets a filter, so the two copies no longer share one
exchange; leaving the left input unfiltered as well when the right input stays
unfiltered and both inputs are the same plan would keep the reuse, and the
change keeps the left filter for the same reason as in the left outer case.
State the same cost, alternative and reason in the self-join paragraph of the
PR description. The right-input check that creates this case was added in
commit 9834ac087a8b.
**Why this works:** Stating the cost together with the rejected alternative
and the reason makes it a cost the author accepts, as the left outer one
already is, so readers of the code and of the PR description see both self-join
costs.
**Risks:** The extra scan and shuffle stay: an inner as-of self join whose
shared input fails the right-input check still reads and shuffle-writes that
input twice; only the statement of the cost changes.
**Constraints:** Keep the left outer statement and its reason unchanged.
**Exclusions:**
- Changing the plan of an inner as-of self join is left out; leaving its
left input unfiltered when both inputs are the same plan is the alternative the
new statement names.
**Verification:**
- **Inspection:** The self-join comment in the AsOfJoin case of
InferFiltersFromConstraints and the PR description say that in an inner as-of
self join whose right input fails the right-input check only the left copy is
filtered, so the two copies no longer share an exchange, name the alternative
of leaving the left input unfiltered too when both inputs are the same plan,
and give the reason for keeping the left filter.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -1866,6 +1866,18 @@ object SQLConf {
.booleanConf
.createWithDefault(false)
+ val INFER_FILTERS_ACROSS_AS_OF_JOIN_ENABLED =
+ buildConf("spark.sql.optimizer.inferFiltersAcrossAsOfJoin.enabled")
+ .internal()
+ .doc("When true, the query optimizer infers filters for the inputs of an
AS-OF join from " +
+ "its ON condition and its other input, such as `q.k = 7` from `ON t.k
= q.k` and " +
+ "`t.k = 7`. When false, it infers no filter for the inputs of an AS-OF
join, while " +
+ "other joins keep their inferred filters.")
Review Comment:
**Nit (P3):** With this setting false, only the AsOfJoin case is skipped:
the Filter and Join cases still infer filters inside each input from its own
constraints, which is why the plan test 'as-of joins: no filter is inferred
across them with the flag off' expects IsNotNull(lk) on the left input. Only
sort-merge as-of joins reach that case, because RewriteAsOfJoin turns every
other AsOfJoin into a correlated subquery first. As-of inputs also ignore
spark.sql.legacy.inferFailableFiltersFromConstraints (canBeAsOfFilter at
Optimizer.scala:2403-2404), but the legacy flag's doc still says true infers
filters that can fail, and this doc does not mention the exemption. Saying both
here would fix it:
```suggestion
.doc("When true, the query optimizer infers filters for the inputs of
a sort-merge " +
"AS-OF join from its ON condition and its other input, such as `q.k
= 7` from " +
"`ON t.k = q.k` and `t.k = 7`, but never a filter that can fail,
whatever " +
"spark.sql.legacy.inferFailableFiltersFromConstraints says. When
false, it infers no " +
"filter across such a join, while each input keeps the filters
inferred from its own " +
"constraints and other joins keep theirs.")
```
**Verification:**
- **Inspection:** The doc of
spark.sql.optimizer.inferFiltersAcrossAsOfJoin.enabled states that it covers
sort-merge AS-OF joins, that with it false each input still gets the filters
inferred from its own constraints, and that no filter that can fail is inferred
onto as-of inputs whatever spark.sql.legacy.inferFailableFiltersFromConstraints
says.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -2315,6 +2321,32 @@ object InferFiltersFromConstraints extends
Rule[LogicalPlan]
case _ => join
}
+
+ // A right row that fails the ON condition is never the match of any left
row, so a filter
+ // that follows from the left constraints and the ON condition can drop it
before the join.
+ // An inner join also drops the left rows without a match, so its left
side gets one too.
+ case j: AsOfJoin if conf.inferFiltersAcrossAsOfJoinEnabled =>
+ val allConstraints = getAllConstraints(j.left, j.right, j.condition)
Review Comment:
**Nit (P3):** For a left outer join the left input is never filtered
(Optimizer.scala:2332), so when the right input fails the check at
Optimizer.scala:2341, this constraint set, the union of both inputs'
constraints and the ON conjuncts with transitivity and literal-binding
inference over it, is built and discarded with the plan unchanged. On the base
branch the rule does not visit the as-of join at all. Making it lazy builds it
only on the paths that pass it to an input filter, without changing any plan:
```suggestion
lazy val allConstraints = getAllConstraints(j.left, j.right,
j.condition)
```
**Verification:**
- **Inspection:** In the AsOfJoin case of InferFiltersFromConstraints the
constraint set is built only on paths that pass it to an input filter, and a
left outer join whose right input fails the right-input check returns without
building it.
--
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]