spark-test commented on code in PR #60198:
URL: https://github.com/apache/spark/pull/60198#discussion_r4525854829


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala:
##########
@@ -0,0 +1,526 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import java.util.{Collections, IdentityHashMap}
+
+import scala.annotation.tailrec
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, 
AttributeMap,
+  AttributeSet, Coalesce, EqualNullSafe, EqualTo, Expression, ExprUtils,
+  ExternalUserDefinedFunction, Literal, NamedExpression, PredicateHelper, 
PythonUDF}
+import org.apache.spark.sql.catalyst.optimizer.ReplaceUpdateFieldsExpression
+import org.apache.spark.sql.catalyst.planning.ScanOperation
+import org.apache.spark.sql.catalyst.plans.{Inner, LeftAnti, LeftOuter, 
LeftSemi}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupFilter, 
ExternalLookupJoin,
+  ExternalLookupJoinShapes, ExternalLookupProject, ExternalLookupTransform, 
Filter, LogicalPlan,
+  LookupKeyComparison, PreparedExternalLookupJoin, Project}
+import org.apache.spark.sql.catalyst.rules.Rule
+import 
org.apache.spark.sql.catalyst.trees.TreePattern.{DATA_SOURCE_V2_RELATION, 
EXTERNAL_LOOKUP_JOIN}
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.connector.catalog.{SupportsRead, TableCapability}
+import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, 
FieldReference}
+import org.apache.spark.sql.connector.expressions.filter.{Predicate => 
V2Predicate}
+import org.apache.spark.sql.connector.read.{LookupParameter, 
SupportsExternalLookup,
+  SupportsPushDownRequiredColumns}
+import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
+import org.apache.spark.sql.execution.datasources.DataSourceStrategy
+import org.apache.spark.sql.types.{ArrayType, BooleanType, DataType, MapType, 
StructType}
+
+/** Finalizes an optimized external lookup side immediately before ordinary V2 
scan preparation. */
+object PrepareExternalLookupJoin extends Rule[LogicalPlan] with PredicateHelper
+  with QueryErrorsBase {
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    val prepared = 
plan.transformUpWithPruning(_.containsPattern(EXTERNAL_LOOKUP_JOIN)) {
+      case join: ExternalLookupJoin if provablyEmpty(join) => 
emptyJoinResult(join)
+      case join: ExternalLookupJoin => prepare(join)
+    }
+    // Prepared lookup joins no longer contain their lookup relation, so a 
lookup-only table that
+    // is still read here cannot run.
+    if (prepared.containsPattern(DATA_SOURCE_V2_RELATION)) {
+      prepared.foreach { node =>
+        ExternalLookupRelations.lookupOnlyTable(node).foreach { table =>
+          throw QueryCompilationErrors.unsupportedBatchReadError(table)
+        }
+      }
+    }
+    prepared
+  }
+
+  // The optimizer folds `WHERE false` on the lookup side into an empty 
relation, and a condition
+  // such as `s.id = r.id AND false` into `false`. Such a join needs no 
connector call.
+  private def provablyEmpty(join: ExternalLookupJoin): Boolean =
+    join.right.maxRows.contains(0L) || (join.condition match {
+      case Some(Literal(value, BooleanType)) => value == null || value == false
+      case _ => false
+    })
+
+  private def emptyJoinResult(join: ExternalLookupJoin): LogicalPlan = {
+    val nullLookupColumns = join.right.output.map { attr =>
+      Alias(Literal(null, attr.dataType), attr.name)(attr.exprId)
+    }
+    val unmatched = Project(join.left.output ++ nullLookupColumns, join.left)
+    join.joinType match {
+      case LeftOuter => unmatched
+      case LeftAnti => join.left
+      // The stream side is kept under a false filter rather than replaced by 
an empty relation,
+      // so that its sources, watermarks and stateful operators still run in 
every micro-batch.
+      // PruneFilters decides whether a streaming subplan may be pruned.
+      case LeftSemi => Filter(Literal.FalseLiteral, join.left)
+      case _ => Filter(Literal.FalseLiteral, unmatched)
+    }
+  }
+
+  private def prepare(join: ExternalLookupJoin): LogicalPlan = {
+    // Analysis already rejects a lookup side with a stage that cannot be 
evaluated, or with another
+    // operator; this is a fallback.
+    val hasUnevaluableStage = join.right.exists {
+      case node @ (_: Project | _: Filter) =>
+        
!node.expressions.forall(ExternalLookupJoinShapes.canEvaluateInLookupStage)
+      case _ => false
+    }
+    // The lookup-side stages are built here, and no later rule reaches them. 
withField and
+    // dropFields values cannot be evaluated until 
ReplaceUpdateFieldsExpression, in the
+    // optimizer's last batch, lowers them, so the same rule lowers them now, 
and the current time
+    // of a micro-batch takes its value now too.
+    val lookupPlan = (if (hasUnevaluableStage) None else {
+      extractLookupPlan(ReplaceUpdateFieldsExpression(
+        ExternalLookupJoinShapes.withBatchTimestampValues(join.right)))
+    }).getOrElse {
+      throw 
QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN")
+    }
+    val relation = lookupPlan.relation
+    val tableName = relation.table.name()
+    val supportsRead = relation.table match {
+      case table: SupportsRead
+          if table.capabilities().contains(TableCapability.EXTERNAL_LOOKUP) => 
table
+      case _ =>
+        throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+          "TABLE", Map("table" -> toSQLId(tableName)))
+    }
+    val conjuncts = join.condition.toSeq.flatMap(splitConjunctivePredicates)
+    // A Python or external UDF over lookup columns cannot run in the 
residual. The rules that move
+    // one out of a join condition match only Join and run later, so this rule 
does it: an inner
+    // join evaluates the conjunct in a filter above the join, and other join 
types are rejected.
+    if (join.joinType != Inner) {
+      conjuncts.flatMap(lookupSideUDF(join, _)).headOption.foreach {
+        case _: ExternalUserDefinedFunction =>
+          throw 
QueryCompilationErrors.useExternalUDFInJoinConditionUnsupportedError(join.joinType)
+        case _ =>
+          throw 
QueryCompilationErrors.usePythonUDFInJoinConditionUnsupportedError(join.joinType)
+      }
+    }
+    val conditionCandidates = conjuncts.zipWithIndex.flatMap { case (conjunct, 
index) =>
+      ExternalLookupJoinShapes.lookupComparison(
+        conjunct, join.left.outputSet, join.right.outputSet).flatMap { 
comparison =>
+        tableColumn(comparison.lookupField, lookupPlan).map { column =>
+          OfferedLookupPredicate(comparison.parameter, column, Some(index), 
comparison.comparison)
+        }
+      }
+    }
+    // Predicate pushdown moves a comparison of a lookup column with a 
constant onto the lookup
+    // side, as for an ordinary join, so the source receives it as a pushed 
filter. A source may
+    // need it in its access path, as the constant tenant of a composite key, 
so it is offered as
+    // well. The filter stays, and Spark evaluates it on the returned rows 
either way.
+    val lookupSideOutput = AttributeSet(lookupPlan.relation.output ++
+      lookupPlan.fields.map(_.toAttribute) ++ 
lookupPlan.upperStages.flatMap(_.output))
+    val filterCandidates = lookupFilterConjuncts(lookupPlan).flatMap { 
conjunct =>
+      ExternalLookupJoinShapes.lookupComparison(conjunct, AttributeSet.empty, 
lookupSideOutput)
+        .filter(_.parameter.isInstanceOf[Literal])

Review Comment:
   **Non-blocking (P2):** This filter keeps a lookup-side comparison only when 
its value is a `Literal`. Predicate pushdown, however, moves any deterministic 
comparison of a lookup column with a value that reads no column out of the join 
condition, for every join type. A deterministic Scala or Java UDF over literals 
is such a value: `ScalaUDF` does not override `foldable`, so `ConstantFolding` 
leaves it as written, and `canEvaluateInLookupStage` lets it move.
   
   By this review's reading of the code, take the suite's 
`CompositeExternalLookupDataSource`, which selects its predicates only when it 
is offered `tenant = ?` together with an `id` predicate, and 
`people.join(directory, directory("tenant") === tenantOf(lit(1)) && 
directory("id") === people("id"))`, where `tenantOf` is a deterministic Scala 
UDF. With `PushDownPredicates` excluded, the condition offers `tenant = ?` and 
`id = ?`, and the query plans. With the rule, the tenant comparison moves onto 
the lookup side and is dropped here. The source is offered only `id = ?`, 
selects nothing, and the query stops when it starts with `NO_LOOKUP_PREDICATE`. 
When that comparison is the condition's only conjunct, the error is 
`MISSING_JOIN_CONDITION` instead. The new `selectLookupPredicates` paragraph 
promises this offer for a comparison with any constant. The failure is 
explicit, and literal constants keep working.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60198#issuecomment-6756317204), 
[2](https://github.com/apache/spark/pull/60198#issuecomment-6758519302), 
[3](https://github.com/apache/spark/pull/60198#discussion_r4515402927), 
[4](https://github.com/apache/spark/pull/60198#discussion_r4515402938), 
[5](https://github.com/apache/spark/pull/60198#pullrequestreview-5829371635).
   
   **Recommended change:** Drop the Literal-only filter from 
PrepareExternalLookupJoin's lookup candidates from the lookup side's filters, 
so that every comparison lookupComparison accepts there, whose value reads no 
column, is offered as the same comparison is from the join condition, and 
update the comment above it. eed15e59faa added that filter when it stopped 
keeping comparisons with a constant in the join condition, where 5b687f33a48 
kept every such comparison and ec65b23afb5 one that could be the only key, so 
that they move as for an ordinary join and are offered again from the lookup 
side. This repair completes that offer and does not bring back the earlier 
rule. Add end-to-end lookup join tests with the composite-key source and a 
constant tenant computed by a deterministic Scala UDF over a literal.
   
   **Why this works:** Without the Literal check, lookupComparison's own rule 
decides, as it does for the join condition: with no stream columns available, a 
value qualifies only when it reads no column, and isOfferedOn still requires a 
range value that cannot fail. Spark evaluates a selected parameter on each 
stream row with the projection it uses for every parameter, so a deterministic 
constant expression gives the value it gives in the join condition. The 
lookup-side filter stays: it is still pushed to the connector when it 
translates, and still checked on the returned rows.
   
   **Scope:** Lookup planning again offers a comparison that predicate pushdown 
moved onto the lookup side, whatever form its constant takes after 
optimization, as it offers the same comparison from the join condition. Tests 
cover a source that needs such a constant in its key.
   
   **Compatibility:** Comparisons with literal constants keep their candidates, 
pushed filters and request batching, and nothing new moves onto the lookup side.
   
   **Risks:** A source that selects more predicates when it is offered more may 
now select a comparison whose constant is computed, so its requests and the 
plan change for queries that already planned. The rows do not change, since 
Spark checks every selected predicate and the lookup-side filter on the 
returned rows. Restoring the Literal check rolls this back. A selected constant 
computed by a UDF is evaluated on each stream row, as it already is when the 
comparison stays in the join condition, which costs more per row than a literal.
   
   **Constraints:** A value must still read no column: a comparison whose value 
reads a lookup column stays an ordinary lookup-side filter. The lookup-side 
filter stays on the lookup side, is still pushed to the connector when it 
translates, and is still checked on the returned rows.
   
   **Success:** A streaming lookup join over a source that needs a constant in 
its key plans when that constant is a deterministic expression that 
optimization leaves unfolded, such as a Scala UDF over a literal. Written in 
the join condition, the comparison gives the same rows with and without 
PushDownPredicates; written in a filter above an inner join, which only 
predicate pushdown moves onto the lookup side, it is offered from there as a 
literal constant is, and gives the rows of the join-condition form. Lookup 
planning offers a comparison from the lookup side's filters exactly when 
lookupComparison accepts it with no stream columns, the same value rule as for 
constants in the join condition.
   
   **Verification:**
   - **Regression:** For every comparison of a lookup column with a 
deterministic value that reads no column but is not a literal after 
optimization, with a deterministic Scala UDF over a literal as the example, a 
lookup join whose source selects its predicates only when it is offered that 
comparison together with a predicate on another key column plans, is offered 
and selects the same predicates, and returns the same rows with and without 
PushDownPredicates when the comparison is written in the join condition, and 
plans with predicate pushdown and returns the rows of the join-condition form 
when the comparison is written in a filter above an inner join.
   - **Regression:** A lookup join whose only conjunct compares a lookup key 
column with such a value, over a source that can serve that key alone, plans 
and returns the same rows with and without PushDownPredicates instead of 
failing for want of a lookup candidate.
   - **Compatibility:** Comparisons with literal constants are offered, pushed 
as filters and checked on the returned rows as before, a selected range whose 
value reads no column still keeps requests batched and cached, and a range 
whose value can fail is still not offered.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3195,6 +3211,27 @@ object PushPredicateThroughJoin extends 
Rule[LogicalPlan] with PredicateHelper {
     (leftEvaluateCondition, rightEvaluateCondition, commonCondition ++ stayUp)
   }
 
+  /**
+   * [[split]] for an external lookup join. A conjunct over lookup columns 
that a lookup-side stage
+   * cannot evaluate, such as one with a Python UDF or a subquery, is neither 
pushed nor moved into
+   * the condition, so it is left out of the result. 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. A comparison of a lookup column with a constant moves as 
for a join; lookup
+   * planning still offers it to the connector as a lookup candidate.
+   *
+   * @return (canEvaluateInLeft, canEvaluateInRight, haveToEvaluateInBoth)
+   */
+  private def splitLookupJoin(condition: Seq[Expression], join: 
ExternalLookupJoin) = {
+    val movable = condition.filterNot { cond =>
+      cond.references.exists(join.right.outputSet.contains) &&

Review Comment:
   **Non-blocking (P2):** This check applies the lookup-side stage rule to 
every conjunct that reads a lookup column, including one over both sides, which 
can only go into the join condition. `canEvaluateInLookupStage` rejects a 
Python UDF, an external UDF or a subquery anywhere in the conjunct, even when 
the UDF reads only stream columns. The ordinary join's `Inner` branch moves 
such a conjunct into the condition, because `canEvaluateWithinJoin` accepts a 
Python UDF.
   
   By this review's reading of the code, the streaming `SELECT s.door, 
d.department FROM badge_swipes s, employee_directory d WHERE d.id = 
normalize(s.badge)`, with a registered Python UDF `normalize`, forms an inner 
lookup join without a condition. `PushDownPredicates` leaves the key above the 
join, so lookup planning finds no candidate. The query then stops when it 
starts with `MISSING_JOIN_CONDITION`, whose message tells the user to compare 
the columns in a WHERE clause above an inner join, which the query does. 
Written in `ON`, the same key stays in the condition and is offered with the 
UDF as a stream-side parameter, the form that 'a stream-only Python UDF in a 
lookup join's residual or lookup parameter' runs. The `CROSS JOIN` and 
`crossJoin().where(...)` spellings fail the same way, and `JOIN ... ON TRUE` 
fails with `NO_LOOKUP_CANDIDATE`. With another key in `ON`, the WHERE 
comparison is never offered. The exception's stated reason, that the lookup 
side cannot evaluate the conj
 unct, holds only for a conjunct that goes onto the lookup side. The failure is 
explicit, and writing the key in `ON` works around it.
   
   **Recommended change:** Judge each conjunct by the place it can reach. In 
splitLookupJoin, apply canEvaluateInLookupStage only to a conjunct that reads 
lookup columns alone, the one that can go onto the lookup side, and keep a 
conjunct over both sides out of every move only when it holds a subquery. In 
the Inner branch of the filter case for lookup joins, accept an external UDF in 
a conjunct over both sides as canEvaluateWithinJoin accepts a Python UDF, 
keeping the checks for nondeterministic and throwing conjuncts. Update the 
splitLookupJoin comment, which gives the lookup side's limits as the reason for 
the exception. The exception dates from 5b687f33a48, before a key written in 
WHERE planned; eed15e59faa and d3477aa9bb5 made such keys plan without 
revisiting it. Add plan tests to the predicate pushdown tests for external 
lookup joins, planning tests of lookup joins with an external UDF, and 
end-to-end lookup join tests with a Python UDF in the key's stream-side value.
   
   **Why this works:** A conjunct over both sides can only go into the join 
condition, and for an inner join lookup planning already plans every Python or 
external UDF there: as a stream-side parameter or residual when the UDF reads 
only stream columns, later evaluated on the stream side, and in a filter above 
the join when it reads lookup columns. Judging such a conjunct by the 
condition's rules rather than the lookup-side stage's moves the WHERE key into 
the condition, where lookup planning offers it as it does when the key is 
written in ON. A conjunct over lookup columns alone keeps the lookup-stage 
check, so nothing new reaches a lookup-side stage.
   
   **Scope:** Predicate pushdown moves a lookup key written in WHERE into an 
inner lookup join's condition even when its stream-side value calls a Python or 
external UDF, so the key plans as it does in ON. What goes onto either side of 
the join is unchanged.
   
   **Compatibility:** What moves onto either side of a lookup join, and 
everything a left outer, semi or anti lookup join does with a filter above it, 
stays as it is, and throwing and nondeterministic conjuncts still stay above an 
inner lookup join.
   
   **Risks:** A conjunct over both sides whose Python or external UDF reads 
lookup columns now enters an inner lookup join's condition, and lookup planning 
moves it back into a filter above the join, so its plan takes one more step 
with the same rows. Restoring the pin rolls this back. A UDF over stream 
columns in a key moved from WHERE now runs as a lookup parameter or in the 
residual. External UDF planning extracts an external UDF there as it does from 
any other operator, but no test runs that route yet; were the extraction to 
miss it, an inner join with another key in ON and such a conjunct in WHERE, 
which runs now with the conjunct above the join, would fail to plan, which the 
planning verification below checks.
   
   **Constraints:** A conjunct over lookup columns alone keeps the lookup-stage 
check, so no lookup-side stage receives a Python UDF, an external UDF, a 
subquery or a nondeterministic expression. A conjunct that can throw, or that 
is nondeterministic, still stays above an inner lookup join. Left outer, left 
semi and left anti lookup joins still move nothing from a filter above into 
their condition.
   
   **Exclusions:**
   - A comparison in WHERE whose stream-side value holds a subquery still stays 
above the join, as it does now, so a join whose only key it is still fails to 
plan: the same key written in ON is refused with SUBQUERY_IN_JOIN_CONDITION, so 
there is no ON form for it to match.
   
   **Success:** Every inner lookup join whose lookup key is written in a filter 
above it, as a comma join, CROSS JOIN, crossJoin() with where() or JOIN ... ON 
TRUE, plans and returns the same rows as the same key written in ON when the 
key's stream-side value calls a Python or external UDF over stream columns. 
With another key in ON, such a comparison written in WHERE is offered to the 
connector as it is when written in ON. A conjunct over lookup columns alone 
with a Python UDF, an external UDF or a subquery, and a conjunct over both 
sides with a subquery, stay where they are today.
   
   **Verification:**
   - **Regression:** For a comma join, a CROSS JOIN, crossJoin() with where() 
and a JOIN ... ON TRUE whose only lookup key is written in WHERE with a Python 
UDF over a stream column in its stream-side value, the streaming query starts 
and returns the same rows as the same key written in ON, and with another key 
in ON the comparison written in WHERE is among the offered lookup candidates.
   - **Regression:** After predicate pushdown, a conjunct over both sides in a 
filter above an inner lookup join moves into the join condition when it holds a 
Python or external UDF, over stream columns or over lookup columns, while a 
conjunct over lookup columns alone with such a UDF or a subquery, a conjunct 
over both sides with a subquery, and a throwing or nondeterministic conjunct 
stay above the join.
   - **Behavior:** A lookup key whose stream-side value calls an external UDF 
over stream columns, written in ON or moved from WHERE, is offered as a lookup 
candidate, and external UDF planning then evaluates the UDF on the stream side, 
leaving no external UDF in the prepared lookup join's parameters or residual.
   - **Compatibility:** A conjunct over both sides whose Python UDF reads 
lookup columns, written in WHERE above an inner lookup join with a key in ON, 
returns the same rows as before the change, and filters above left outer, semi 
and anti lookup joins keep their plans.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -3289,6 +3326,63 @@ 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, commonFilterCondition) 
=
+        splitLookupJoin(conjuncts, j)
+      val (newJoinConditions, rightFilterConditionsToPush) = j.joinType match {
+        case Inner =>
+          // don't push throwable expressions into join condition
+          (commonFilterCondition.filter(cond => canEvaluateWithinJoin(cond) && 
!cond.throwable),

Review Comment:
   **Nit (P3):** `split` leaves every throwing conjunct with the common ones, 
and `splitLookupJoin` adds the conjuncts without references to them too. This 
`!cond.throwable` is therefore the only check that keeps a throwing conjunct of 
a filter above an inner lookup join out of its condition. No test reaches it. 
The filter tests of `PushPredicateThroughExternalLookupJoinSuite` use no 
throwing conjunct. Every `raise_error` in `ExternalLookupJoinSuite` is in a 
join condition or a lookup-side projection. `FilterPushdownSuite` pins this 
guard only for an ordinary join.
   
   By this review's reading of the code, without the check `t.k = CASE WHEN s.x 
< 0 THEN raise_error('bad') ELSE s.x END` would move into the condition and be 
offered as `k = ?`. A source that selects it would make Spark evaluate the 
`CASE` on every stream row, so the query would fail on rows with no match. A 
plan test that puts such a conjunct next to a non-throwing one over both sides, 
and asserts that only the latter moves into the condition, would catch the 
guard's removal.
   
   **Verification:**
   - **Regression:** After predicate pushdown, a throwing conjunct over both 
sides in a filter above an inner lookup join stays in that filter while a 
non-throwing conjunct over both sides in the same filter moves into the join 
condition, so the test fails when the throwable check is removed.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/ExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,5828 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import java.nio.charset.StandardCharsets
+import java.util.concurrent.{ConcurrentLinkedQueue, CountDownLatch, TimeUnit}
+import java.util.concurrent.atomic.{AtomicBoolean, AtomicInteger, AtomicLong, 
AtomicReference}
+
+import scala.collection.mutable
+import scala.concurrent.duration._
+import scala.jdk.CollectionConverters._
+import scala.reflect.{classTag, ClassTag}
+
+import com.google.common.base.Ticker
+
+import org.apache.spark.{SparkException, SparkIllegalArgumentException, 
SparkRuntimeException,
+  SparkThrowable, SparkUnsupportedOperationException, TaskContext}
+import org.apache.spark.rdd.DeterministicLevel
+import org.apache.spark.sql.{AnalysisException, Column, DataFrame, Encoders, 
Row, SaveMode,
+  SQLContext}
+import org.apache.spark.sql.IntegratedUDFTestUtils.{shouldTestPythonUDFs, 
TestPythonUDF}
+import org.apache.spark.sql.QueryTest
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.analysis.{ExternalLookupJoinEligibility,
+  FormExternalLookupJoin, NoSuchTableException}
+import org.apache.spark.sql.catalyst.expressions.{Add, Attribute, 
AttributeMap, AttributeReference,
+  Cast, EqualTo, Expression, GenericInternalRow, LessThan, Literal, Rand, 
SubqueryExpression,
+  UnsafeProjection}
+import org.apache.spark.sql.catalyst.optimizer.{EliminateOuterJoin, 
PushDownPredicates}
+import org.apache.spark.sql.catalyst.plans.{Inner, LeftOuter, QueryPlan}
+import org.apache.spark.sql.catalyst.plans.logical.{Deduplicate, 
ExternalLookupCacheOptions,
+  ExternalLookupProject, Filter, LeafNode, LogicalPlan, 
PreparedExternalLookupJoin}
+import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData, GenericArrayData}
+import org.apache.spark.sql.classic.Dataset
+import org.apache.spark.sql.connector.catalog.{Identifier, InMemoryBaseTable,
+  InMemoryTableCatalog, MetadataColumn, SupportsMetadataColumns, SupportsRead, 
Table,
+  TableCapability, TableCatalog, TableChange,
+  TableProvider}
+import org.apache.spark.sql.connector.catalog.TableCapability.{BATCH_READ, 
EXTERNAL_LOOKUP}
+import org.apache.spark.sql.connector.expressions.{NamedReference, Transform}
+import org.apache.spark.sql.connector.expressions.filter.Predicate
+import org.apache.spark.sql.connector.metric.{CustomMetric, CustomSumMetric, 
CustomTaskMetric}
+import org.apache.spark.sql.connector.read.{Batch, ExternalLookup, 
ExternalLookupReader,
+  ExternalLookupReaderFactory, ExternalLookupResultCursor, InputPartition, 
LookupParameter,
+  PartitionReader, PartitionReaderFactory, Scan, ScanBuilder, 
SupportsExternalLookup,
+  SupportsPushDownRequiredColumns, SupportsPushDownV2Filters}
+import org.apache.spark.sql.execution.{CoalesceExec, LocalTableScanExec}
+import org.apache.spark.sql.execution.datasources.{FileFormat, 
SaveIntoDataSourceCommand}
+import org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation, 
ExternalLookupRelation,
+  FileDataSourceV2, StreamingDataSourceV2ScanRelation, TableCapabilityCheck}
+import org.apache.spark.sql.execution.exchange.ShuffleExchangeExec
+import org.apache.spark.sql.execution.joins.ExternalLookupJoinExec
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.StreamingDeduplicateExec
+import org.apache.spark.sql.execution.streaming.runtime.{IncrementalExecution, 
MemoryStream,
+  StreamingQueryWrapper}
+import org.apache.spark.sql.execution.streaming.sources.LowLatencyMemoryStream
+import org.apache.spark.sql.execution.vectorized.OnHeapColumnVector
+import org.apache.spark.sql.functions.{broadcast, coalesce, col, concat, 
count, current_date,
+  current_timestamp, date_from_unix_date, expr, length, lit, max, raise_error, 
rand, struct,
+  to_json, upper, when}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.sources.{BaseRelation, CreatableRelationProvider, 
InsertableRelation,
+  RelationProvider, SchemaRelationProvider}
+import org.apache.spark.sql.streaming.{StreamingQueryException, 
StreamRealTimeModeE2ESuiteBase}
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{ArrayType, DataType, Decimal, DecimalType, 
DoubleType,
+  IntegerType, MapType, StringType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+import org.apache.spark.sql.vectorized.ColumnarBatch
+import org.apache.spark.unsafe.types.UTF8String
+
+class ExternalLookupJoinSuite extends QueryTest with SharedSparkSession {
+
+  import testImplicits._
+
+  private val EXTERNAL_LOOKUP_CATALOG_NAME = "external_lookup_cat"
+  // The supportedJoinTypes parameter of a JOIN_TYPE error.
+  private val SUPPORTED_JOIN_TYPES = "INNER, LEFT OUTER, LEFT SEMI, LEFT ANTI"
+
+  private val streamRunCount = new AtomicInteger()
+
+  override def beforeEach(): Unit = {
+    super.beforeEach()
+    SimpleExternalLookupDataSource.resetCounters()
+    SemanticKeyExternalLookupDataSource.requestSizes.clear()
+  }
+
+  /** The rows of `df` as a streaming DataFrame: one micro-batch, in 
`numPartitions` partitions. */
+  private def streamOf(df: DataFrame, numPartitions: Int = 1): DataFrame = {
+    val input = MemoryStream[Row](numPartitions)(Encoders.row(df.schema), 
spark.sqlContext)
+    input.addData(df.collect().toSeq)
+    input.toDF()
+  }
+
+  private case class StreamRun(rows: Seq[Row], execution: 
IncrementalExecution) {
+    def plan: LogicalPlan = execution.optimizedPlan
+    def lookupJoin: ExternalLookupJoinExec = 
execution.executedPlan.collectFirst {
+      case exec: ExternalLookupJoinExec => exec
+    }.get
+  }
+
+  /** Runs the streaming `df` on a memory sink until it has processed all of 
its input. */
+  private def runStream(df: DataFrame, outputMode: String = "append"): 
StreamRun = {
+    val queryName = 
s"external_lookup_stream_${streamRunCount.incrementAndGet()}"
+    val query =
+      
df.writeStream.format("memory").outputMode(outputMode).queryName(queryName).start()
+    try {
+      query.processAllAvailable()
+      StreamRun(
+        spark.table(queryName).collect().toSeq,
+        query.asInstanceOf[StreamingQueryWrapper].streamingQuery.lastExecution)
+    } finally {
+      query.stop()
+      spark.catalog.dropTempView(queryName)
+    }
+  }
+
+  /**
+   * Runs the lookup join of the streaming `joined` again, over stream rows 
with the given ids, in
+   * one task, with [[ExternalLookupTestTicker]] as the clock of its cache.
+   */
+  private def runWithTestTicker(joined: DataFrame, ids: Seq[Int]): 
Seq[InternalRow] = {
+    val lookupJoin = runStream(joined).lookupJoin
+    SimpleExternalLookupDataSource.resetCounters()
+    val streamRows =
+      CoalesceExec(1, LocalTableScanExec(lookupJoin.child.output, 
ids.map(InternalRow(_)), None))
+    lookupJoin.copy(child = streamRows, cacheTicker = ExternalLookupTestTicker)
+      .executeCollect().toSeq
+  }
+
+  // Excludes the optimizer rules that push predicates through joins.
+  private val withoutPredicatePushdown =
+    Seq(SQLConf.OPTIMIZER_EXCLUDED_RULES.key -> PushDownPredicates.ruleName)
+
+  private def checkStream(df: DataFrame, expected: Seq[Row]): Unit =
+    QueryTest.sameRows(expected, runStream(df).rows).foreach(fail(_))
+
+  /** The error that the streaming `df` fails with, when it starts or in a 
micro-batch. */
+  private def streamFailure[T <: Throwable : ClassTag](df: DataFrame): T = {
+    val cause = try {
+      runStream(df)
+      fail("The streaming query did not fail")
+    } catch {
+      case e: StreamingQueryException => e.getCause
+      case e: Throwable with SparkThrowable => e
+    }
+    assert(classTag[T].runtimeClass.isInstance(cause), cause)
+    cause.asInstanceOf[T]
+  }
+
+  test("a stream whose scan is pruned at the start reads the columns of its 
lookup joins") {
+    withSQLConf(
+        "spark.sql.catalog.stream_cat" -> 
classOf[InMemoryTableCatalog].getName,
+        SQLConf.STREAMING_V2_COLUMN_PRUNING_ENABLED.key -> "true") {
+      withTable("stream_cat.ns.badge_swipes") {
+        sql("CREATE TABLE stream_cat.ns.badge_swipes (employee INT, door 
STRING, minute INT) " +
+          s"TBLPROPERTIES ('${InMemoryBaseTable.STREAMING_COLUMN_PRUNING}' = 
'true')")
+        sql("INSERT INTO stream_cat.ns.badge_swipes VALUES (1, 'lobby', 10), 
(3, 'garage', 20)")
+        val swipes = spark.readStream.table("stream_cat.ns.badge_swipes")
+        val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+        checkStream(
+          swipes.join(lookup, swipes("employee") === lookup("id"))
+            .select(swipes("door"), lookup("department")),
+          Seq(Row("lobby", "engineering"), Row("lobby", "research")))
+        // An aggregate over a left outer lookup join that also counts lookup 
values, so the join
+        // runs, and the pruned scan still reads the stream column that the 
aggregate reads.
+        val latestByDoor = swipes.join(lookup, swipes("employee") === 
lookup("id"), "left_outer")
+          .groupBy(swipes("door")).agg(max(swipes("minute")), 
count(lookup("department")))
+        val run = runStream(latestByDoor, "complete")
+        assert(run.plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+        QueryTest.sameRows(
+          Seq(Row("lobby", 10, 2L), Row("garage", 20, 0L)), 
run.rows).foreach(fail(_))
+      }
+    }
+  }
+
+  test("a stream whose scan gets the query's filters joins its lookup joins as 
without them") {
+    // The stream drops the rows that fail the filters that its scan builder 
took when the query
+    // started, so a micro-batch that does not apply one of them fails.
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    def results(pushdown: Boolean): (Seq[Seq[Row]], Seq[Seq[Expression]]) = {
+      var result: (Seq[Seq[Row]], Seq[Seq[Expression]]) = null
+      withSQLConf(
+          "spark.sql.catalog.stream_cat" -> 
classOf[InMemoryTableCatalog].getName,
+          SQLConf.STREAMING_V2_FILTER_PUSHDOWN_ENABLED.key -> 
pushdown.toString) {
+        withTable("stream_cat.ns.badge_swipes") {
+          sql("CREATE TABLE stream_cat.ns.badge_swipes (employee INT, door 
STRING, minute INT) " +
+            s"TBLPROPERTIES ('${InMemoryBaseTable.STREAMING_FILTER_PUSHDOWN}' 
= 'true', " +
+            s"'${InMemoryBaseTable.SIMULATE_STREAMING_FILTERS}' = 'true')")
+          sql("INSERT INTO stream_cat.ns.badge_swipes VALUES " +
+            "(1, 'lobby', 10), (2, 'garage', 20), (3, 'dock', 30), (1, 
'garage', 40)")
+          val swipes = spark.readStream.table("stream_cat.ns.badge_swipes")
+          val onEmployee = swipes("employee") === lookup("id")
+          val runs = Seq(
+            // A filter on stream columns below the join, and above an inner 
and a left outer join.
+            runStream(swipes.where(swipes("minute") > 15).join(lookup, 
onEmployee)),
+            runStream(swipes.join(lookup, onEmployee).where(swipes("minute") > 
15)),
+            runStream(swipes.join(lookup, onEmployee, "left_outer")
+              .where(swipes("door") === "garage")),
+            // A filter on both sides, which predicate pushdown can move into 
the join condition.
+            runStream(swipes.join(lookup, onEmployee)
+              .where(swipes("door") =!= lookup("department") && 
swipes("minute") < 35)),
+            // An aggregate that ignores duplicates needs no ordinary left 
outer join, which the
+            // optimizer removes, with its filters pushed to the stream. A 
lookup join stays.

Review Comment:
   **Nit (P3):** By this review's reading of the code, this run no longer has a 
lookup join. `PushDownPredicates` moves `minute > 15` below the left outer join 
and `ColumnPruning` projects `door` and `minute`. This PR's 
`EliminateOuterJoin` case then drops the join through `LeftOuterJoinLeftSide`, 
since `max` ignores duplicates. The same happens in the `left_outer` iteration 
of 'an aggregate over a filtered lookup join runs' (lines 4000-4006), whose 
comment places the lookup join below the aggregate's exchange. So this comment 
is now false, and neither run can fail for a left outer lookup join regression.
   
   Counting a lookup value in both aggregates, as eed15e59faa did for the test 
of a stream whose scan is pruned, keeps the join. Asserting that each left 
outer run's plan holds a lookup join would then restore their coverage. A 
separate run of the present shape could pin the removal itself: no lookup join 
in its plan, no request to the source, and the rows of the same query with 
`EliminateOuterJoin` excluded.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60198#discussion_r4515402967).
   
   **Verification:**
   - **Regression:** Each left outer run of the two tests fails when its plan 
holds no lookup join, so removing the join again, or a regression in a left 
outer lookup join under streaming filter pushdown or exchange reuse, turns them 
red.
   - **Behavior:** An aggregate that reads only stream columns through 
duplicate-agnostic functions over a left outer lookup join plans no lookup 
join, sends no request to the source, and returns the same rows as with 
EliminateOuterJoin excluded.



-- 
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]

Reply via email to