HeartSaVioR commented on code in PR #60198:
URL: https://github.com/apache/spark/pull/60198#discussion_r4520084625
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3199,6 +3215,49 @@ object PushPredicateThroughJoin extends
Rule[LogicalPlan] with PredicateHelper {
(leftEvaluateCondition, rightEvaluateCondition, commonCondition ++ stayUp)
}
+ /**
+ * [[split]] for an external lookup join, which also returns the conjuncts
that must not move.
+ * Moving a conjunct onto the lookup side must not turn a query that runs
without it into one
+ * that fails to plan:
+ * - A comparison of a lookup column with a constant, such as `t.tier >=
2`, that lookup
+ * planning could offer as a lookup candidate is returned apart. It moves
onto the lookup side
+ * like any other lookup-side conjunct when the join condition keeps
another key, as
+ * `hasStreamSideLookupKey` decides. Otherwise it is the join's only
possible key, and it
+ * stays in the join condition.
+ * - A conjunct over lookup columns that a lookup-side stage cannot
evaluate, such as one with
+ * a Python UDF or a subquery, is pinned: it is neither pushed nor moved
into the condition.
+ * - A conjunct without references, such as a literal, belongs to neither
side. It stays with
+ * the common conditions, so that a condition that folds to false keeps
its result without a
+ * lookup, instead of leaving a join whose stream side is empty.
+ *
+ * @return (canEvaluateInLeft, canEvaluateInRight, constantKeys,
haveToEvaluateInBoth, pinned)
+ */
+ private def splitLookupJoin(condition: Seq[Expression], join:
ExternalLookupJoin) = {
+ val (pinned, movable) = condition.partition { cond =>
+ cond.references.exists(join.right.outputSet.contains) &&
+ !ExternalLookupJoinShapes.canEvaluateInLookupStage(cond)
+ }
+ val (withoutReferences, withReferences) =
movable.partition(_.references.isEmpty)
+ val (left, right, common) = split(withReferences, join.left, join.right)
+ val (constantKeys, rightOnly) = right.partition { cond =>
+ ExternalLookupJoinShapes.lookupComparison(
+ cond, join.left.outputSet, join.right.outputSet).isDefined
+ }
+ (left, rightOnly, constantKeys, common ++ withoutReferences, pinned)
+ }
+
+ /**
+ * Whether `conjuncts` hold a comparison of a lookup column with a
stream-side value that lookup
+ * planning can offer as a lookup candidate. A join condition that holds one
still has a possible
+ * key when its comparisons with constants move onto the lookup side.
+ */
+ private def hasStreamSideLookupKey(
+ conjuncts: Seq[Expression],
+ join: ExternalLookupJoin): Boolean = conjuncts.exists { cond =>
+ ExternalLookupJoinShapes.lookupComparison(cond, join.left.outputSet,
join.right.outputSet)
+ .exists(_.parameter.references.nonEmpty)
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
Thanks. Fixed at the root in
[0c20a33fc99](https://github.com/apache/spark/commit/0c20a33fc9915847ea1418b0f9195b0dcc7a3b9a):
the pushdown no longer decides which constants are keys, so
`hasStreamSideLookupKey` is gone. Constant comparisons move as for an ordinary
join, and `PrepareExternalLookupJoin`, which knows the offered candidates, also
offers them as keys (see the next thread). Your example now plans with `id =
?`, and a regression test covers it.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3293,6 +3352,76 @@ object PushPredicateThroughJoin extends
Rule[LogicalPlan] with PredicateHelper {
case other =>
throw SparkException.internalError(s"Unexpected join type: $other")
}
+ // The same for an external lookup join. The conjuncts keep their written
order where they stay.
+ case f @ Filter(filterCondition, j: ExternalLookupJoin) =>
+ val conjuncts = splitConjunctivePredicates(filterCondition)
+ val (leftFilterConditions, rightFilterConditions, constantKeys,
commonFilterCondition, _) =
+ splitLookupJoin(conjuncts, j)
+ val (newJoinConditions, rightFilterConditionsToPush) = j.joinType match {
+ case Inner =>
+ // don't push throwable expressions into join condition
+ def canMoveIntoJoin(cond: Expression) = canEvaluateWithinJoin(cond)
&& !cond.throwable
+ val intoCondition = commonFilterCondition.filter(canMoveIntoJoin)
+ val joinConditions =
j.condition.toSeq.flatMap(splitConjunctivePredicates)
+ if (hasStreamSideLookupKey(joinConditions ++ intoCondition, j)) {
+ (intoCondition, rightFilterConditions ++ constantKeys)
+ } else {
+ ((constantKeys ++ commonFilterCondition).filter(canMoveIntoJoin),
+ rightFilterConditions)
+ }
+ // A filter on lookup columns above a left outer join also removes the
null-padded rows of
+ // stream rows without a match, so it stays above. EliminateOuterJoin
first makes the join
+ // inner when the filter rejects nulls. A semi or anti join outputs no
lookup column.
+ case LeftOuter | LeftSemi | LeftAnti => (Nil, Nil)
+ case other =>
+ throw SparkException.internalError(s"Unexpected external lookup join
type: $other")
+ }
+ val pushed = leftFilterConditions ++ rightFilterConditionsToPush ++
newJoinConditions
+ if (pushed.isEmpty) {
+ f
+ } else {
+ val newJoin = j.copy(
+ left = leftFilterConditions.
+ reduceLeftOption(And).map(Filter(_, j.left)).getOrElse(j.left),
+ right = rightFilterConditionsToPush.
+ reduceLeftOption(And).map(Filter(_, j.right)).getOrElse(j.right),
+ condition = (j.condition.toSeq ++
newJoinConditions).reduceLeftOption(And))
+ conjuncts.filterNot(pushed.contains).
+ reduceLeftOption(And).map(Filter(_, newJoin)).getOrElse(newJoin)
+ }
+
+ // Push the join filter of an external lookup join into its children.
+ case j: ExternalLookupJoin =>
+ val conjuncts =
j.condition.map(splitConjunctivePredicates).getOrElse(Nil)
+ val (leftJoinConditions, lookupSideConditions, constantKeys, _, _) =
+ splitLookupJoin(conjuncts, j)
+ val rightJoinConditions = if (hasStreamSideLookupKey(conjuncts, j)) {
+ conjuncts.filter(cond => lookupSideConditions.contains(cond) ||
constantKeys.contains(cond))
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
Agreed on the goal.
[0c20a33fc99](https://github.com/apache/spark/commit/0c20a33fc9915847ea1418b0f9195b0dcc7a3b9a)
reaches it a little differently, to stay closer to an ordinary join. Constant
comparisons, ranges included, move onto the lookup side exactly as for an
ordinary join. `PrepareExternalLookupJoin` then both pushes them as filters and
offers them as key candidates.
- A source without filter pushdown can still select `id = ?` or `tenant =
?`, so `s.dept = t.department AND t.id = 1` plans.
- A range with a constant bound keeps requests batched and cached.
- Tests use `CompositeExternalLookupDataSource` with a constant tenant. Each
such query also plans, with the same rows, with the pushdown rules excluded.
##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/SupportsExternalLookup.java:
##########
@@ -35,34 +41,58 @@ public interface SupportsExternalLookup extends ScanBuilder
{
* lookup-side {@link NamedReference} with a {@link LookupParameter}; the
array is never empty. In
* every offered comparison the reference is {@code children()[0]} and the
parameter is
* {@code children()[1]}: when the query writes the lookup column on the
right, Spark flips the
- * operator, so {@code s.ts < t.event_time} is offered as {@code event_time
> ?}. For example:
+ * operator, so {@code s.ts < t.event_time} is offered as {@code event_time
> ?}. When the join
+ * condition also has a comparison with a stream-side value that Spark can
offer, Spark usually
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
Rewritten in
[0c20a33fc99](https://github.com/apache/spark/commit/0c20a33fc9915847ea1418b0f9195b0dcc7a3b9a),
as its own paragraph. A constant comparison, from `ON` or from `WHERE`,
arrives as a pushed filter and is also offered as a candidate, and Spark checks
it on the returned rows either way.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3293,6 +3352,76 @@ object PushPredicateThroughJoin extends
Rule[LogicalPlan] with PredicateHelper {
case other =>
throw SparkException.internalError(s"Unexpected join type: $other")
}
+ // The same for an external lookup join. The conjuncts keep their written
order where they stay.
+ case f @ Filter(filterCondition, j: ExternalLookupJoin) =>
+ val conjuncts = splitConjunctivePredicates(filterCondition)
+ val (leftFilterConditions, rightFilterConditions, constantKeys,
commonFilterCondition, _) =
+ splitLookupJoin(conjuncts, j)
+ val (newJoinConditions, rightFilterConditionsToPush) = j.joinType match {
+ case Inner =>
+ // don't push throwable expressions into join condition
+ def canMoveIntoJoin(cond: Expression) = canEvaluateWithinJoin(cond)
&& !cond.throwable
+ val intoCondition = commonFilterCondition.filter(canMoveIntoJoin)
+ val joinConditions =
j.condition.toSeq.flatMap(splitConjunctivePredicates)
+ if (hasStreamSideLookupKey(joinConditions ++ intoCondition, j)) {
+ (intoCondition, rightFilterConditions ++ constantKeys)
+ } else {
+ ((constantKeys ++ commonFilterCondition).filter(canMoveIntoJoin),
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
This case is gone with the change above. Constants now move as for an
ordinary join, whatever the condition holds, and are offered from the lookup
side.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/joins.scala:
##########
@@ -205,19 +212,39 @@ object EliminateOuterJoin extends Rule[LogicalPlan] with
PredicateHelper {
}.forall(ae => ae.isDistinct ||
EliminateDistinct.isDuplicateAgnostic(ae.aggregateFunction))
}
+ /**
+ * The left side of a left outer join. An external lookup join returns every
stream row at least
+ * once as well, so a duplicate-agnostic aggregate over its stream side does
not need it either.
+ */
+ private object LeftOuterJoinLeftSide {
+ def unapply(plan: LogicalPlan): Option[LogicalPlan] = plan match {
+ case Join(left, _, LeftOuter, _, _) => Some(left)
+ case ExternalLookupJoin(left, _, LeftOuter, _, _, _) => Some(left)
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
We'd keep it. An ordinary join is removed in the same case, and we follow
the rule that a lookup join behaves as an ordinary join does, unless a lookup
makes that impossible. It costs the shared extractor, and it skips every lookup
for such a query. I fixed the stale comment, and that part of the test now also
reads a lookup value, so it still runs a lookup join
([0c20a33fc99](https://github.com/apache/spark/commit/0c20a33fc9915847ea1418b0f9195b0dcc7a3b9a)).
--
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]