spark-test commented on code in PR #60683:
URL: https://github.com/apache/spark/pull/60683#discussion_r4624720019
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -1058,7 +1058,69 @@ object ConvertToCatalyst extends Rule[LogicalPlan] {
e.containsPattern(TRANSPILED_PYTHON_UDF) &&
e.exists(_.isInstanceOf[TranspiledPythonUDF])
} => p
- case p => convertOperator(p)
+ case p => convertOperator(keepCartesianGuard(p))
+ }
+ }
+
+ /**
+ * With `spark.sql.crossJoin.enabled=false`, hands back to Python every call
that spans both
+ * sides of a join with no other condition spanning them, so
CheckCartesianProducts still fails
+ * the query (SPARK-58780).
+ *
+ * Interpreted, such a call cannot be evaluated by the join, so
ExtractPythonUDFFromJoinCondition
+ * pulls it out into a Filter above a join with no condition, and the check
raises. Lowered, it is
+ * a native expression that reads both sides, which is all the check looks
for -- but no join key
+ * can be extracted from it, so the planner still picks a CartesianProduct
and the query runs
+ * quadratic in silence. Keeping the Python UDF keeps the error users asked
for.
+ *
+ * Covers the call in the join's own condition and in a Filter above it
(`join(...).where(...)`,
+ * or a comma join in SQL), which predicate pushdown later moves into the
join. A key that only
+ * arrives from further away, e.g. a Filter above this one, is not seen
here, so that call stays
+ * interpreted when it could have been lowered: slower, but no different
from transpilation off.
+ */
+ private def keepCartesianGuard(p: LogicalPlan): LogicalPlan = {
+ // The join types CheckCartesianProducts checks. An explicit Cross join is
allowed to be one.
+ def checked(j: Join): Boolean = j.joinType match {
+ case Inner | LeftOuter | RightOuter | FullOuter => true
Review Comment:
**Non-blocking (P2):** Including the outer types here sends an outer join's
cross-side call back to Python, but ExtractPythonUDFFromJoinCondition pulls a
Python UDF out of an inner join only; for any other join type it throws
UNSUPPORTED_FEATURE.PYTHON_UDF_IN_ON_CLAUSE (joins.scala:282-289). Reading the
code, `left.join(right, u('a', 'b'), 'left_outer')` with `u` transpiled from
`lambda a, b: a == b` runs as a nested-loop join on the base branch, and with
this change and `spark.sql.crossJoin.enabled=false` it fails at planning; right
and full outer joins fail the same way. CheckCartesianProducts has already
accepted these joins because the condition reads both sides, so keeping the
call interpreted protects nothing. The error's only advice, a CROSS JOIN
rewrite, is for inner joins, and it never mentions the cross-join setting. The
base branch's own TranspiledUDFParameterSuite.scala:163-168 pins that a
read-once cross-side call lowers in a LEFT OUTER join and the join runs. An oute
r join that a null-rejecting filter above turns inner does still need the
guard, because with transpilation off it gets the cartesian error.
**Recommended change:** In ConvertToCatalyst's keepCartesianGuard
(Optimizer.scala:1081-1124), hand back a cross-side call in an outer join only
when a filter above will make that join inner before
ExtractPythonUDFFromJoinCondition runs, and otherwise leave the call lowered;
inner joins keep today's handling. Decide this from every filter above the
join, not only from one that holds a transpiled call: the fast path in
ConvertToCatalyst.apply (Optimizer.scala:1057-1059) passes the guard only
operators that hold a call, so a plain `where(col('b') > 0)` never reaches the
Filter arm today. With cross joins disabled, either let such a filter reach the
guard or make the decision in one pass over the plan before conversion. Ask
EliminateOuterJoin's own null-rejection test (buildNewJoinType,
joins.scala:185-205, opened to the optimizer package instead of copied) about
each filter over the outer join, directly or through projections and subquery
aliases, with its references resolved throug
h their aliases and its own transpiled calls left out, since an interpreted
Python UDF never counts as rejecting nulls there (joins.scala:171). For a join
that the test makes inner, hand back both the filter's cross-side calls and the
cross-side calls in the join's own condition; for an outer join that stays
outer, do neither. In the join tests, flip the outer-join expectation of the
first new cross join guard test (ConvertToCatalystSuite.scala:740-747), add a
case under a null-rejecting filter that holds no transpiled call, and add
end-to-end PySpark cases for both outcomes.
**Why this works:** With transpilation off and cross joins disabled, a
Python UDF that reads both sides of an outer join's condition raises the
implicit cartesian product error only when a filter above makes the join inner,
because only then does ExtractPythonUDFFromJoinCondition pull it out of the
join; otherwise the extractor raises the unsupported-feature error whatever the
cross-join setting. EliminateOuterJoin makes that decision from the filter's
conjuncts, and the filter that makes it usually holds no Python UDF at all.
Asking the same test about every filter above the join, leaving out the
filter's own calls, which transpilation off cannot count as rejecting nulls
either, keeps the call interpreted exactly in the first case, so that the
cartesian error survives, and lowered in the second, so that the outer join
runs as it does on the base branch.
**Compatibility:** Inner joins that only a transpiled call links, in their
own condition or under a filter, still fail with the implicit cartesian product
error under spark.sql.crossJoin.enabled=false, unless the lowered call gives
the join an equi-join key, which the fix for those keys keeps lowered.
**Risks:** A null-rejecting filter that reaches the outer join only through
rewrites the decision does not follow, such as pushdown through an inner join
above it, leaves the join's call lowered. Once made inner, that join runs as a
nested-loop join, as on the base branch, where the pull request as it stands
raises the cartesian error. The same happens when a filter's only
null-rejecting conjunct is a transpiled call, which the test cannot evaluate
before lowering. Setting spark.sql.crossJoin.enabled=true still turns the guard
off entirely.
**Constraints:** Call EliminateOuterJoin's null-rejection test rather than
copying it, so the guard and that rule cannot disagree about when an outer join
becomes inner. Read the filter's references through any projections between it
and the join in the same way as the fix for calls that reach a join through
projections, pushdown or join reordering, so both fixes see the filter
identically.
**Exclusions:**
- CheckCartesianProducts and ExtractPythonUDFFromJoinCondition keep their
current behavior for native and interpreted conditions.
**Verification:**
- **Regression:** With cross joins disabled and transpilation and ANSI on, a
left outer, a right outer and a full outer join whose only cross-side condition
is a transpiled `a == b` call run end to end and return the rows they return
with cross joins enabled.
- **Behavior:** With cross joins disabled, a left outer join on such a call
under a `where` that rejects nulls from its right side and holds no transpiled
call, such as `where(col('b') > 0)`, fails with the implicit cartesian product
error, as the same query does with transpilation off.
- **Behavior:** At the rule level, the guard keeps a lone cross-side call
lowered in an outer join with no filter above, hands it back to Python when a
filter above rejects nulls from the padded side, whether or not that filter
holds a transpiled call, and still hands it back in an inner join.
- **Compatibility:** A full outer join under a filter that rejects nulls
from only one side, which therefore stays a left or right outer join, keeps its
call lowered and runs.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -1058,7 +1058,69 @@ object ConvertToCatalyst extends Rule[LogicalPlan] {
e.containsPattern(TRANSPILED_PYTHON_UDF) &&
e.exists(_.isInstanceOf[TranspiledPythonUDF])
} => p
- case p => convertOperator(p)
+ case p => convertOperator(keepCartesianGuard(p))
+ }
+ }
+
+ /**
+ * With `spark.sql.crossJoin.enabled=false`, hands back to Python every call
that spans both
+ * sides of a join with no other condition spanning them, so
CheckCartesianProducts still fails
+ * the query (SPARK-58780).
+ *
+ * Interpreted, such a call cannot be evaluated by the join, so
ExtractPythonUDFFromJoinCondition
+ * pulls it out into a Filter above a join with no condition, and the check
raises. Lowered, it is
+ * a native expression that reads both sides, which is all the check looks
for -- but no join key
+ * can be extracted from it, so the planner still picks a CartesianProduct
and the query runs
+ * quadratic in silence. Keeping the Python UDF keeps the error users asked
for.
+ *
+ * Covers the call in the join's own condition and in a Filter above it
(`join(...).where(...)`,
+ * or a comma join in SQL), which predicate pushdown later moves into the
join. A key that only
+ * arrives from further away, e.g. a Filter above this one, is not seen
here, so that call stays
+ * interpreted when it could have been lowered: slower, but no different
from transpilation off.
+ */
+ private def keepCartesianGuard(p: LogicalPlan): LogicalPlan = {
+ // The join types CheckCartesianProducts checks. An explicit Cross join is
allowed to be one.
+ def checked(j: Join): Boolean = j.joinType match {
+ case Inner | LeftOuter | RightOuter | FullOuter => true
+ case _ => false
+ }
+ def spans(e: Expression, j: Join): Boolean =
+ e.references.exists(j.left.outputSet.contains) &&
+ e.references.exists(j.right.outputSet.contains)
+ def keepPython(cond: Expression, joins: Seq[Join], joinConds:
Seq[Expression]): Expression = {
+ val conjuncts = splitConjunctivePredicates(cond)
+ // The joins that only a Python UDF ties together, transpiled or not.
Interpreted, a conjunct
+ // holding one is pulled out of the join, so it is no key to the check
either way.
+ val unkeyed = joins.filter { j =>
+ !(conjuncts ++ joinConds).exists(c => spans(c, j) && !c.exists { e =>
+ isScalarPythonUDF(e) && spans(e, j)
+ })
+ }
+ // Only the call itself goes back to Python. Its arguments are left for
`convertOperator`,
+ // which may still lower a nested call that reads one side.
+ def strip(e: Expression): Expression = e match {
+ case s: TranspiledPythonUDF if unkeyed.exists(spans(s, _)) =>
s.pythonUDFExpr
Review Comment:
**Non-blocking (P2):** This hands the call back before NullPropagation,
BooleanSimplification, SimplifyConditionals and SimplifyCasts run. For `a == b`
over two non-nullable integral or string columns, as in
`spark.range(3).join(spark.range(3).withColumnRenamed('id', 'b'), u('id',
'b'))` with `u` transpiled from `lambda a, b: a == b`, those rules reduce the
lowered CASE WHEN to `id = b`. Reading the code, the base branch plans that
join as a hash join on the key and returns three rows, while with the call kept
in Python ExtractPythonUDFFromJoinCondition pulls it out of the join and the
check after UDF extraction raises 'Detected implicit cartesian product'. A body
such as `a1 == b1 and a2 == b2` over such columns lowers to a conjunction of
two keys and fails the same way. These joins were never cartesian products, so
failing them goes beyond the problem the PR fixes, and the doc comment's
statement that no join key can be extracted from a lowered call does not hold
for them; the s
uite's fixture option `EqualTo(pref(0), pref(1))`
(ConvertToCatalystSuite.scala:724-727) is itself such a key. This needs
`spark.sql.crossJoin.enabled=false`, an internal setting, with transpilation on.
**Recommended change:** In keepCartesianGuard (Optimizer.scala:1101-1106),
before handing a cross-side call back, lower it with its selected option and
arguments, then simplify the result as the optimizer will for those arguments'
nullability. Reuse the optimizer's own null-propagation, boolean, conditional
and cast simplification for this rather than a copy. If the result, or any of
its conjuncts, is an equality between an expression of one side and an
expression of the other, the form equi-join key extraction takes as a key
(patterns.scala:199-203), keep the call lowered and count it as that join's
key. Correct the doc comment (Optimizer.scala:1070-1074) and the suite's
section comment (ConvertToCatalystSuite.scala:716-720), which say a lowered
call gives no join key. Change the suite's cross-side fixture
(ConvertToCatalystSuite.scala:724-727), whose option is a bare equality and so
is itself a key, to the null-guarded form the transpiler emits for nullable
arguments. Add join t
ests for both outcomes.
**Why this works:** A join keyed by an equality between its two sides is
planned as a hash or sort-merge join and passes CheckCartesianProducts on the
base branch, so it has no cartesian product to report, and equi-join key
extraction finds such an equality among the condition's conjuncts. Applying the
simplification the optimizer applies later shows whether the lowered call is,
or contains as a conjunct, such a key. Keeping those calls lowered restores the
base branch's plan for them, while every call that remains a non-key condition
is still handed back and keeps the cartesian product error.
**Compatibility:** Calls whose lowered form is not a join key keep failing
with the implicit cartesian product error, as with transpilation off.
**Risks:** If later optimizer rewrites ever stopped turning the simplified
equality into an equi-join key, a call kept lowered would let a nested-loop
join run silently again; reusing the same rules keeps the guard and the final
plan in step, and spark.sql.crossJoin.enabled=true remains the rollback for the
guard as a whole.
**Constraints:** The exemption applies only to a call whose simplified form
gives the join an equi-join key, an equality with one expression per side,
alone or as one of its conjuncts; every other lowered form is handed back as
before. The guard must keep one notion of a keyed join across this exemption
and the fixes for outer joins and for calls that reach a join through
projections, pushdown or join reordering, so a call kept lowered as a key also
counts as its join's key.
**Exclusions:**
- Calls whose arguments become non-nullable only through later rewrites keep
failing as with transpilation off.
**Verification:**
- **Regression:** With cross joins disabled and transpilation and ANSI on,
joining two range-based frames on a transpiled `a == b` call over their
non-nullable id columns, and on a call whose body is `a1 == b1 and a2 == b2`
over non-nullable long columns, runs, plans an equi-join with no Python
evaluation, and returns the matching rows.
- **Behavior:** The same call fails with the implicit cartesian product
error over nullable long columns, and over non-nullable double columns, whose
NaN guard remains.
- **Behavior:** At the rule level, a cross-side call whose option simplifies
to an equality of one column per side, alone or in a conjunction, stays
lowered, and the null-guarded fixture over nullable columns is still handed
back to Python in every join-condition and filter case.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/ConvertToCatalystSuite.scala:
##########
@@ -712,4 +712,92 @@ class ConvertToCatalystSuite extends PlanTest {
condition = "INVALID_UDF_PARAMETER_PLACEHOLDER_INDEX",
parameters = Map("index" -> "2", "numParams" -> "1"))
}
+
+ // ---- Cross join guard (SPARK-58780) ----
+ //
+ // With cross joins disabled, a call that is the only thing tying a join's
two sides together
+ // stays Python, so CheckCartesianProducts still raises as it does without
transpilation. Lowered,
+ // it would read both sides and pass the check, while giving the planner no
key to join on.
+
+ private val attrB = $"b".long
+
+ // `a == b` across the join: a two-argument call whose option reads both
sides.
+ private def matchCall(left: Expression = attrA): TranspiledPythonUDF =
+ makeTPUDF(PythonUDF("match", null, BooleanType, Seq(left, attrB),
+ PythonEvalType.SQL_BATCHED_UDF, udfDeterministic = true),
EqualTo(pref(0), pref(1)))
+
+ private def join(
+ condition: Option[Expression],
+ joinType: JoinType = Inner): Join =
+ Join(LocalRelation(attrA), LocalRelation(attrB), joinType, condition,
JoinHint.NONE)
+
+ private def crossJoinOff[T](block: => T): T =
+ transpileOn { withSQLConf(SQLConf.CROSS_JOINS_ENABLED.key -> "false") {
block } }
+
+ private def keptPython(plan: LogicalPlan): Boolean =
+ plan.expressions.exists(_.exists(_.isInstanceOf[PythonUDF]))
+
+ test("keeps the only join condition Python while cross joins are off") {
+ crossJoinOff {
+ Seq(Inner, LeftOuter, RightOuter, FullOuter).foreach { joinType =>
+ val converted = convert(join(Some(matchCall()), joinType))
Review Comment:
**Nit (P3):** Every new case that keeps a call in Python passes the
cross-side call as the whole condition, as here, and the multi-conjunct cases
are all keyed, so the guard's descent into an enclosing expression
(`other.mapChildren(strip)`, Optimizer.scala:1103) never runs in a test.
Deleting it would leave every new Scala and Python test green while
`left.join(right, u('a', 'b') & (col('a') > 0))` or
`left.join(right).where(~u('a', 'b'))` lowers the call and runs a silent
cartesian product again. Likewise, no test pins that left semi and left anti
joins keep the call lowered, so adding them to the guarded join types would
break a working semi join unnoticed.
**Verification:**
- **Regression:** With cross joins disabled, a cross-side call inside a
conjunction with a one-side predicate, or inside a negation, in an inner join's
condition or in a filter over an unkeyed inner join, is handed back to Python
at the rule level, and the conjunction case fails end to end with the implicit
cartesian product error.
- **Regression:** With cross joins disabled, a left semi join and a left
anti join whose only condition is a cross-side call keep the call lowered at
the rule level.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -1058,7 +1058,69 @@ object ConvertToCatalyst extends Rule[LogicalPlan] {
e.containsPattern(TRANSPILED_PYTHON_UDF) &&
e.exists(_.isInstanceOf[TranspiledPythonUDF])
} => p
- case p => convertOperator(p)
+ case p => convertOperator(keepCartesianGuard(p))
+ }
+ }
+
+ /**
+ * With `spark.sql.crossJoin.enabled=false`, hands back to Python every call
that spans both
+ * sides of a join with no other condition spanning them, so
CheckCartesianProducts still fails
+ * the query (SPARK-58780).
+ *
+ * Interpreted, such a call cannot be evaluated by the join, so
ExtractPythonUDFFromJoinCondition
+ * pulls it out into a Filter above a join with no condition, and the check
raises. Lowered, it is
+ * a native expression that reads both sides, which is all the check looks
for -- but no join key
+ * can be extracted from it, so the planner still picks a CartesianProduct
and the query runs
+ * quadratic in silence. Keeping the Python UDF keeps the error users asked
for.
+ *
+ * Covers the call in the join's own condition and in a Filter above it
(`join(...).where(...)`,
+ * or a comma join in SQL), which predicate pushdown later moves into the
join. A key that only
+ * arrives from further away, e.g. a Filter above this one, is not seen
here, so that call stays
+ * interpreted when it could have been lowered: slower, but no different
from transpilation off.
+ */
+ private def keepCartesianGuard(p: LogicalPlan): LogicalPlan = {
Review Comment:
**Non-blocking (P2):** Reading the code, this guard still misses calls that
become a join's only condition through a path it does not model, so under
`spark.sql.crossJoin.enabled=false` transpilation on keeps running a silent
nested-loop join or cartesian product where transpilation off fails with
'Detected implicit cartesian product'. It matches a call by its own references,
examines only Join and Filter operators, judges a join condition only against
its own join, and counts any conjunct reading both sides of a join as that
join's key. Examples: `left.join(right).select(col('a').alias('x'),
col('b').alias('y')).where(u('x', 'y'))`, where x and y belong to neither side;
`left.join(right).withColumn('m', u('a', 'b')).where('m')`, where the Project's
call is lowered and its cheap alias pushed into the join; `a.join(b).join(c,
u(a.p, b.q) & (a.k == c.k))`, where the call is pushed into Join(a, b) as its
only condition; `SELECT * FROM a, b, c WHERE u(a.p, b.q) AND a.x + b.y = c.z`, w
here the conjunct counted as the key of Join(a, b) lands in the upper join;
and `SELECT * FROM A, B, C WHERE u(A.a, C.c) AND B.b = C.c`, which ReorderJoin
rebuilds as (A JOIN C ON u) JOIN B. With transpilation off the interpreted UDF
follows the same pushdown and is pulled back out of that join, so the check
raises. The doc comment defers only a key that arrives from further away, which
errs toward keeping Python, not these shapes.
**Recommended change:** Rework how keepCartesianGuard
(Optimizer.scala:1081-1124) decides that a cross-side call has no key, so that
it judges the join the call will sit in on the final plan. Resolve a call's
references through the projections between it and the joins below, aliases and
computed columns included. Treat a transpiled call in a Project above an
unkeyed inner join like a filter's call. In the Join arm, judge a condition's
one-side conjuncts against the joins inside that side, where pushdown will put
them. Count a conjunct as a call's key only when it is deterministic, holds no
cross-side Python UDF, and reads the same base relations as the call, so
pushdown and join reordering cannot separate them. Where the guard cannot tell,
keep the call interpreted. Update the doc comment (Optimizer.scala:1065-1080)
to describe the rule, and add join tests at the rule level and end to end for
each traced shape.
**Why this works:** On the final plan, CheckCartesianProducts rejects an
inner join that only a Python UDF links once ExtractPythonUDFFromJoinCondition
has pulled the UDF out. A call that reads several base relations of an
inner-join group ends up in the condition of the first join that covers those
relations, whichever operator or projection it started in, and a deterministic,
Python-free conjunct reading exactly those relations lands in that same join.
Judging the call by its base relations, and requiring such a key, therefore
predicts the check's outcome across projections, pushdown and reordering, and
keeping the call interpreted when no such key exists reproduces the error
transpilation off gives.
**Compatibility:** Joins with a real key on the same relations as the call
keep the call lowered, and with spark.sql.crossJoin.enabled=true or an explicit
CROSS JOIN every call is lowered as on the base branch.
**Risks:** Calls whose key sits in a different filter, whose only key reads
other relations than the call does, as in a three-way join keyed by `b.m = c.m`
next to a call over a and c, or that the rule cannot place, stay interpreted
under spark.sql.crossJoin.enabled=false even where the guard lowers them today,
so those joins evaluate the Python function per joined row instead of natively;
results are unchanged, and setting spark.sql.crossJoin.enabled=true turns the
guard off and restores lowering.
**Constraints:** The rule must not hand back a call in an outer join that
stays outer, or a call whose lowered form gives its join an equi-join key; the
fixes for outer joins and for equi-join keys define those exemptions, and all
three must share one notion of when a join is keyed. Resolving references
through projections must follow each projection's own alias definitions, so
that a computed column is judged by the columns it reads.
**Exclusions:**
- A key that reaches the join only from another filter stays unseen, as the
comment at Optimizer.scala:1076-1079 already accepts, so such calls stay
interpreted rather than lowered.
**Verification:**
- **Regression:** With cross joins disabled and transpilation and ANSI on,
each traced shape fails end to end with the implicit cartesian product error,
as it does with transpilation off: a where over aliased or renamed join columns
or over a derived table, a where on a column the call computes, a call in a
parent join's condition that reads only the child join's sides, a call whose
only both-sides conjunct also reads a third relation or is nondeterministic,
and a three-way comma join that join reordering regroups.
- **Behavior:** At the rule level, the guard hands the call back to Python
in each of those shapes, and keeps it lowered when a deterministic conjunct
reading the same relations keys the join, either in the same condition or in a
join below a filter.
- **Compatibility:** A join keyed by a native equality on the same relations
as the call still runs with no Python evaluation and returns the same rows as
with cross joins enabled.
--
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]