spark-test commented on code in PR #60647:
URL: https://github.com/apache/spark/pull/60647#discussion_r4609049802
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/constraints.scala:
##########
@@ -466,6 +466,9 @@ case class CheckInvariant(
override def children: Seq[Expression] = child +: columnExtractors.map(_._2)
override def dataType: DataType = BooleanType
override def nullable: Boolean = false
+ // A violating row fails the write, so the optimizer must not evaluate this
on rows that are
+ // not written, e.g. by pushing it below a join.
+ override lazy val throwable: Boolean = true
Review Comment:
**Blocking (P1):** With `throwable = true`, join pushdown no longer pushes a
check over one input's columns into that input. For a write whose query
inner-joins three or more inputs, `ReorderJoin` then folds the check's Filter
into the join conditions, `createOrderedJoin` puts the check into a lower
join's condition (`joins.scala:85-101`), and the join-condition case of
`PushPredicateThroughJoin` keeps it there (`Optimizer.scala:3468-3481`). With
`spark.sql.cbo.enabled` and `spark.sql.cbo.joinReorder.enabled` on and row
counts on every input, `CostBasedJoinReorder` collects the check with the other
join conditions, but `JoinReorderDP.buildJoin` gives each candidate join only
the conditions that reference both of its sides
(`CostBasedJoinReorder.scala:289-309`), and `search` adds nothing back for a
condition no join took (`CostBasedJoinReorder.scala:172-192`). A check over one
input can be evaluated on one side of every candidate join, so, reading the
code, the reordered plan carri
es no check at all.
For example, with `t (id INT, value INT, CONSTRAINT positive_id CHECK (id >
0))`, `s` holding `(-1, 10)`, `u1(value)` and `u2(value)` each holding `10`,
and row-count statistics on all three, `INSERT INTO t SELECT s.id, s.value FROM
s JOIN u1 ON s.value = u1.value JOIN u2 ON s.value = u2.value` would write
`(-1, 10)` without an error. On the base branch the non-throwable check is
pushed into `s`, stays part of that join input through the reordering, and the
write fails with `CHECK_CONSTRAINT_VIOLATION`. Both configs are public, though
off by default, so a table can silently end up holding rows its constraints
forbid; this applies to every check whose columns come from a single join
input, including the checks of generated-column values.
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/subquery.scala:
##########
@@ -149,15 +149,18 @@ object RewritePredicateSubquery extends Rule[LogicalPlan]
with PredicateHelper {
val (withSubquery, withoutSubquery) =
splitConjunctivePredicates(condition)
.partition(SubqueryExpression.hasInOrCorrelatedExistsSubquery)
+ // A throwable conjunct stays above the joins that the subqueries are
rewritten to, so that
+ // it is not evaluated on the rows they remove.
+ val (stayUp, pushDown) = withoutSubquery.partition(_.throwable)
Review Comment:
**Blocking (P1):** Partitioning by `throwable` alone drops the written order
of the conjuncts, which the base branch kept by leaving every conjunct without
a subquery in one Filter below the joins, where `FilterExec` stops at the first
FALSE conjunct. Two orders now invert. A non-throwable conjunct written after a
throwable one now runs first, on every row; and a throwable conjunct written
before an IN or correlated EXISTS predicate now runs after that subquery's
join, whose condition (the IN values or the correlated predicates) then sees
the rows the throwable conjunct used to reject. Reading the plan, with ANSI
mode on, `SELECT * FROM t WHERE CASE WHEN x < 0 THEN raise_error('negative x')
ELSE x > 5 END AND 10 / (x - 3) > 1 AND y IN (SELECT y FROM u)` now raises
`DIVIDE_BY_ZERO` on a row with `x = 3`, which the base branch skips because the
CASE is false there; likewise `SELECT * FROM t WHERE CASE WHEN b = 0 THEN false
WHEN b < 0 THEN raise_error('negative b') ELSE true END AND
a / b IN (SELECT x FROM s)` now computes `1 / 0` in the semi join for the row
`(1, 0)` and raises `DIVIDE_BY_ZERO`.
A view's or inner query's filter that `CombineFilters` merges ahead of an
outer IN reaches the same shape, and a nondeterministic conjunct such as
`rand(42) < 0.5` written after a throwable one now runs on the rows it rejects,
which changes a seeded sample. Nothing restores the order later: the rest of
the RewriteSubquery batch, and the later batch that pushes filters again
(`SparkOptimizer.scala:100-101`), keep a throwable conjunct above the join.
CHECK writes are not hit, because a check is never false and the DSv2 scan
pushdown merges it last, but these are queries, not only writes, that succeed
today. It is the same kind of reordering that SPARK-60980 removed from
`CombineFilters`.
**Recommended change:** Lift a conjunct without a subquery into the Filter
above the subquery joins only when it is deterministic and throwable, is
written after the last conjunct that holds an IN or correlated EXISTS subquery,
and is followed by no non-throwable conjunct that
ExprUtils.canEvaluateUnconditionally rejects, that is, one that can fail or is
nondeterministic. Keep every other conjunct without a subquery in the Filter
below the joins, in written order, as the base branch does. Add a TODO at the
split naming the reordering by join pushdown that the exclusions describe, and
add subquery rewrite optimizer tests and end-to-end subquery query tests for
these orders.
**Why this works:** A lifted conjunct is throwable, so join pushdown, filter
combining and pushdown through other operators keep it above the joins, in this
batch and in the later ones that push filters again. Nothing that can fail
follows it, so what runs ahead of it is what is written before it and conjuncts
that cannot fail, which only reduce the rows it sees. Every other conjunct
stays in the Filter below the joins in written order, as on the base branch, so
the conjuncts, IN values and correlated predicates written after a throwable
conjunct that stays there run only on the rows it keeps. A write's CHECK
constraints are lifted, because the DSv2 scan pushdown merges them after every
conjunct of the source's filter.
**Compatibility:** A filter without a throwable conjunct, or whose throwable
conjuncts are all written before its last subquery predicate or followed by a
conjunct that can fail, is rewritten exactly as on the base branch.
**Risks:** The description's statement that a raise_error written together
with an IN or EXISTS subquery is no longer evaluated on rows the subquery
removes then holds only for a throwable conjunct written after the last
subquery predicate with nothing after it that can fail; any other one runs
below the joins as on the base branch, so it can still raise on a row a
subquery removes. Over a DSv2 source, whose scan pushdown moves a filter's
subquery predicates after its other conjuncts, a guard written in the same
WHERE clause as the predicate is never lifted; a CHECK constraint, or a guard
in an outer query's filter, which the scan pushdown merges afterwards, still
is. A lifted conjunct no longer runs before the joins of the subqueries written
before it, so their IN values, correlated predicates and subquery predicates in
a disjunction also run on the rows it rejects. A query in which one of those
fails on such a row succeeds on the base branch but now raises, as the base
branch al
ready does for the same condition written with an IN list instead of the
subquery, or as a WHERE clause over an explicit semi join; writing the guard
before the subquery predicate keeps the base behavior. No flag restores the
base placement, so reverting the change is the only rollback.
**Constraints:** Only a throwable conjunct may sit above a subquery join:
join pushdown, which runs right after the split in the same batch and again in
the later batch that pushes filters from partition pruning, moves any other
deterministic conjunct below the join whatever its written order. A write's
CHECK constraints stay liftable only while nothing that can fail follows them;
the DSv2 scan pushdown merges them after every conjunct of the source's filter.
**Exclusions:**
- Join pushdown's own reordering of non-throwable conjuncts ahead of a
throwable one above an explicit join is the base branch's behavior and stays as
it is.
- Over an explicit join, join pushdown leaves the conjuncts it can neither
push nor move into the join in a Filter with the throwable ones last, so the
split can see a throwable conjunct after an IN or EXISTS predicate over both
sides of that join even when it is written before it, and lifts it as the PR
does; keeping their written order there is a separate change to join pushdown,
which the TODO at the split names.
**Verification:**
- **Regression:** With ANSI mode on, a query filtering with a raise_error
CASE guard that is false on a row, then a division by zero on that row, then an
IN subquery, returns the rows the base branch returns instead of raising
DIVIDE_BY_ZERO.
- **Regression:** With ANSI mode on, a query filtering with a CASE guard
that drops the rows whose divisor is zero, then an IN subquery whose value
divides by that column, returns the rows the base branch returns.
- **Regression:** With ANSI mode on, a query filtering with an IN subquery,
then a raise_error CASE guard that is false on a row, then a division by zero
on that row, returns the rows the base branch returns, run end to end so that
the later optimizer batch that pushes filters from partition pruning also runs.
- **Behavior:** Rewriting a filter keeps below the subquery joins, in
written order, a throwable conjunct written before the last IN predicate and
one followed by a conjunct that can fail, and places above the joins a
throwable conjunct written after the last IN predicate that only conjuncts that
cannot fail follow.
- **Behavior:** A CHECK constraint written after an IN predicate in the same
filter stays above the semi join, and an INSERT whose query filters a DSv2
source with an IN subquery writes only the rows the subquery keeps, without
CHECK_CONSTRAINT_VIOLATION.
--
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]