viirya commented on code in PR #60198:
URL: https://github.com/apache/spark/pull/60198#discussion_r4515402938


##########
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:
   "Usually" leaves connector authors guessing. Please state when a constant is 
offered and when it arrives as a pushed filter, what a source that needs it as 
part of its key must do, and that it fails with `NO_LOOKUP_PREDICATE` 
otherwise. Comparisons from WHERE can be offered too, which this doesn't 
mention. This would read better as its own paragraph.



##########
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:
   `lookupComparison` only checks the shape, while 
`PrepareExternalLookupJoin.tableColumn` also requires the lookup column to 
trace back to a table column. A stream comparison on a computed lookup column 
counts as a key here but is never offered, and the constant that could have 
been the key has already moved:
   
   ```scala
   val lookup = base.select(col("id"), length(col("department")).as("len"), 
col("department"))
   left.join(lookup, left("k") === lookup("len") && lookup("id") === 1)
   ```
   
   This fails with `NO_LOOKUP_CANDIDATE`, and plans with `id = ?` without these 
rules, which the `splitLookupJoin` scaladoc rules out. The decision needs the 
same criterion as `tableColumn`: either trace aliases through the lookup side 
here, or decide in `PrepareExternalLookupJoin`, where the offered candidates 
are known. Please add a regression test.



##########
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:
   The batching and cache cost discussed for O3 comes from range predicates 
(`selectsRange`); a selected constant equality has no such cost. Moving `=` and 
`<=>` as well takes a key away from connectors without filter pushdown: with 
`s.dept = t.department AND t.id = 1` and a source that serves only `id`, the 
query now fails with `NO_LOOKUP_PREDICATE`, while it plans without these rules. 
A composite key such as `(tenant, id)` with a constant tenant has the same 
problem.
   
   Can we move only the range comparisons and keep equalities offered? An 
unselected constant equality would then not reach the source as a filter; if 
that matters, could Prepare both offer and push it? No test currently covers a 
source that depends on a constant key; the existing assertion was just changed 
to the new candidates.



##########
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:
   What is the use case for removing the join under an aggregate? It needs a 
streaming aggregate that reads no lookup column and ignores duplicates, which 
seems rare for a lookup join, and this extractor exists only for it. If it 
stays, the comment at `ExternalLookupJoinSuite.scala:165` ("A lookup join 
stays") is now wrong, and that part of the test no longer exercises a lookup 
join.



##########
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)

Review Comment:
   Both callers discard `pinned`. Please remove it from the tuple and the 
`@return`.



##########
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:
   With `ON t.v = 5 WHERE t.x = 'a'`, the condition already has a key, yet the 
WHERE constant still moves into it and can be offered, including as a range. 
Should this test for any candidate in the condition, rather than only a 
stream-side one?



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/PushPredicateThroughExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,288 @@
+/*
+ * 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.catalyst.optimizer
+
+import org.apache.spark.api.python.PythonEvalType
+import org.apache.spark.sql.catalyst.analysis.FormExternalLookupJoin
+import org.apache.spark.sql.catalyst.dsl.expressions._
+import org.apache.spark.sql.catalyst.dsl.plans._
+import org.apache.spark.sql.catalyst.expressions.{CreateNamedStruct, 
DropField, Expression,
+  Literal, PythonUDF, Rand, ScalarSubquery, UpdateFields, WithField}
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, 
LeftOuter, LeftSemi,
+  PlanTest}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, Join, 
JoinHint,
+  LocalRelation, LogicalPlan}
+import org.apache.spark.sql.catalyst.rules.RuleExecutor
+import org.apache.spark.sql.connector.catalog.{Table, TableCapability}
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import org.apache.spark.sql.types.{BooleanType, DoubleType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+class PushPredicateThroughExternalLookupJoinSuite extends PlanTest {
+  private object Optimize extends RuleExecutor[LogicalPlan] {
+    val batches = Batch("Push down predicates", FixedPoint(10), 
PushDownPredicates) :: Nil
+  }
+
+  // Operator optimization runs both rules.
+  private object OptimizeWithOuterJoinElimination extends 
RuleExecutor[LogicalPlan] {
+    val batches = Batch("Eliminate outer joins and push down predicates", 
FixedPoint(10),
+      EliminateOuterJoin, PushDownPredicates) :: Nil
+  }
+
+  private val stream = LocalRelation(Seq($"streamKey".int), isStreaming = true)
+  private val lookup = DataSourceV2Relation.create(
+    LookupOnlyTable, None, None, CaseInsensitiveStringMap.empty)
+  private val streamKey = stream.output.head
+  private val Seq(lookupKey, lookupValue, lookupScore, lookupName, lookupInfo) 
= lookup.output
+  private val keysEqual = streamKey === lookupKey
+  // A conjunct over both sides, which only the join condition can evaluate.
+  private val bothSidesConjunct = streamKey + lookupValue > 0
+  // A filter conjunct that is not deterministic never moves.
+  private val nonDeterministic = Rand(1L) > 0.5
+  // A lookup-side conjunct that is not a lookup candidate, so it can move 
onto the lookup side.
+  private val lookupNonCandidate = lookupValue + 1 > 2
+  private val lookupJoinTypes = Seq(Inner, LeftOuter, LeftSemi, LeftAnti)
+  private val booleanPythonUDF = (args: Seq[Expression]) =>
+    PythonUDF("udf", null, BooleanType, args, PythonEvalType.SQL_BATCHED_UDF, 
true)
+  private val scalarSubquery = 
ScalarSubquery(LocalRelation($"subqueryValue".int))
+
+  /** An external lookup join, as the optimizer forms it. */
+  private def lookupJoin(joinType: JoinType, conjuncts: Expression*): 
ExternalLookupJoin =
+    FormExternalLookupJoin(
+      Join(stream, lookup, joinType, Some(conjuncts.reduce(_ && _)), 
JoinHint.NONE))
+      .asInstanceOf[ExternalLookupJoin]
+
+  /** `join` with the given sides and condition conjuncts. */
+  private def expectedJoin(
+      join: ExternalLookupJoin,
+      streamSide: LogicalPlan = stream,
+      lookupSide: LogicalPlan = lookup,
+      conjuncts: Seq[Expression]): ExternalLookupJoin =
+    join.copy(left = streamSide, right = lookupSide, condition = 
Some(conjuncts.reduce(_ && _)))
+
+  test("push a filter above the join into the stream side and the join 
condition") {
+    Seq[(JoinType, Expression, ExternalLookupJoin => LogicalPlan)](
+      // The lookup-side conjunct goes through the join condition onto the 
lookup side, and the
+      // conjunct on both sides into the join condition.
+      (Inner, streamKey > 1 && lookupNonCandidate && bothSidesConjunct && 
nonDeterministic,
+        join => expectedJoin(join, stream.where(streamKey > 1), 
lookup.where(lookupNonCandidate),
+          Seq(keysEqual, bothSidesConjunct)).where(nonDeterministic)),
+      // Under a left outer join, a filter on lookup columns also removes the 
null-padded rows of
+      // stream rows without a match. On the lookup side or in the join 
condition it would keep
+      // those rows, so it stays above. EliminateOuterJoin, which this batch 
does not run, makes
+      // the join inner when the filter rejects nulls, and the filter can then 
move.
+      (LeftOuter, streamKey > 1 && lookupNonCandidate, join =>
+        expectedJoin(join, stream.where(streamKey > 1), conjuncts = 
Seq(keysEqual))
+          .where(lookupNonCandidate)),
+      (LeftSemi, streamKey > 1 && nonDeterministic, join =>
+        expectedJoin(join, stream.where(streamKey > 1), conjuncts = 
Seq(keysEqual))
+          .where(nonDeterministic)),
+      (LeftAnti, streamKey > 1 && nonDeterministic, join =>
+        expectedJoin(join, stream.where(streamKey > 1), conjuncts = 
Seq(keysEqual))
+          .where(nonDeterministic))).foreach {
+      case (joinType, filter, expected) =>
+        val join = lookupJoin(joinType, keysEqual)
+        comparePlans(Optimize.execute(join.where(filter)), expected(join))
+    }
+  }
+
+  test("push join condition conjuncts on one side into that side") {
+    val intoBothSides: ExternalLookupJoin => LogicalPlan = join =>
+      expectedJoin(join, stream.where(streamKey > 1), 
lookup.where(lookupNonCandidate),
+        Seq(keysEqual, bothSidesConjunct))
+    // A stream-side conjunct of a left outer or left anti join decides which 
stream rows find a
+    // match, so it stays in the condition. The join checks one that cannot 
fail, such as
+    // `streamKey > 1`, on each stream row before the lookup, and any other 
one on the joined rows.
+    val intoLookupSide: ExternalLookupJoin => LogicalPlan = join =>
+      expectedJoin(join, lookupSide = lookup.where(lookupNonCandidate),
+        conjuncts = Seq(keysEqual, streamKey > 1, bothSidesConjunct))
+    Seq(
+      Inner -> intoBothSides,
+      LeftSemi -> intoBothSides,
+      LeftOuter -> intoLookupSide,
+      LeftAnti -> intoLookupSide).foreach { case (joinType, expected) =>
+      val join =
+        lookupJoin(joinType, keysEqual, streamKey > 1, lookupNonCandidate, 
bothSidesConjunct)
+      comparePlans(Optimize.execute(join), expected(join))
+    }
+  }
+
+  test("leave a join without movable conjuncts unchanged") {
+    Seq(
+      lookupJoin(Inner, keysEqual),
+      lookupJoin(LeftOuter, keysEqual, bothSidesConjunct),
+      lookupJoin(LeftAnti, keysEqual, streamKey > 1),
+      lookupJoin(Inner, keysEqual, nonDeterministic),
+      // A literal belongs to neither side, so a condition that folds to false 
keeps its result.
+      lookupJoin(Inner, keysEqual, Literal(false))).foreach { join =>
+      assert(Optimize.execute(join) eq join)
+    }
+    val filtered = lookupJoin(LeftOuter, keysEqual).where(lookupNonCandidate 
&& nonDeterministic)
+    assert(Optimize.execute(filtered) eq filtered)
+  }
+
+  test("move a comparison with a constant onto the lookup side when the join 
keeps a key") {
+    // As for a join, a lookup-side conjunct goes onto the lookup side, where 
the connector receives
+    // it as a pushed filter. The join condition keeps `keysEqual` as the key.
+    val constantComparisons = Seq[Expression](
+      lookupValue === 5, lookupValue <=> 5, lookupValue < 5, lookupValue <= 5, 
lookupValue > 5,
+      lookupValue >= 5, Literal(5) === lookupValue, Literal(5) <=> lookupValue,
+      Literal(5) < lookupValue, Literal(5) >= lookupValue)
+    for (joinType <- lookupJoinTypes; comparison <- constantComparisons) {
+      val join = lookupJoin(joinType, keysEqual, comparison)
+      comparePlans(Optimize.execute(join),
+        expectedJoin(join, lookupSide = lookup.where(comparison), conjuncts = 
Seq(keysEqual)))
+    }
+    // A filter above an inner join moves there too. Under a left outer join 
it stays above.
+    val inner = lookupJoin(Inner, keysEqual)
+    for (comparison <- Seq(lookupValue === 5, lookupValue >= 5)) {
+      comparePlans(Optimize.execute(inner.where(comparison)),
+        expectedJoin(inner, lookupSide = lookup.where(comparison), conjuncts = 
Seq(keysEqual)))
+    }
+    val outer = lookupJoin(LeftOuter, keysEqual).where(lookupValue === 5)
+    assert(Optimize.execute(outer) eq outer)
+    // A comparison with a stream-side value in a filter above an inner join 
moves into the join
+    // condition, as for a join.
+    comparePlans(Optimize.execute(inner.where(streamKey < lookupValue)),
+      expectedJoin(inner, conjuncts = Seq(keysEqual, streamKey < lookupValue)))
+    // The shape is exact: only a bare column compared with a stream-side 
value or a constant is
+    // a lookup candidate.
+    val notCandidates = Seq[Expression](
+      lookupValue =!= 5, lookupValue + 1 > 5, lookupValue.in(1, 2), 
lookupValue.isNull)
+    for (conjunct <- notCandidates) {
+      val join = lookupJoin(Inner, keysEqual, conjunct)
+      comparePlans(Optimize.execute(join), expectedJoin(join, lookupSide = 
lookup.where(conjunct),
+        conjuncts = Seq(keysEqual)))
+    }
+  }
+
+  test("keep a comparison with a constant in the join condition when it is the 
only key") {
+    // A lookup join cannot run without a key, so a comparison with a constant 
stays a lookup
+    // candidate when no comparison with a stream-side value can be one.
+    for (joinType <- lookupJoinTypes; comparison <- Seq(lookupValue === 5, 
lookupValue >= 5)) {
+      val join = lookupJoin(joinType, comparison)
+      assert(Optimize.execute(join) eq join)
+    }
+    // An equality on a DOUBLE is never offered, so it is no key and the 
constant one stays.
+    val neverOffered = lookupScore === streamKey.cast(DoubleType)
+    val withoutKey = lookupJoin(Inner, neverOffered, lookupValue === 5)
+    assert(Optimize.execute(withoutKey) eq withoutKey)
+    // A filter above an inner join adds its comparison with a constant to the 
join condition.
+    val inner = lookupJoin(Inner, lookupValue === 5)
+    comparePlans(Optimize.execute(inner.where(lookupName === "x")),
+      expectedJoin(inner, conjuncts = Seq(lookupValue === 5, lookupName === 
"x")))
+  }
+
+  test("move a conjunct over withField or dropFields values like any 
lookup-side conjunct") {

Review Comment:
   This now follows the same path as any lookup-only conjunct, and the 
end-to-end test already covers it, so it can go. The test at L211 could join 
the existing `notCandidates` list. Also, the comment at L232 is imprecise: a 
reference-less scalar subquery above an inner join does move into the condition.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/ExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,4961 @@
+/*
+ * 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, 
AtomicReference}
+
+import scala.collection.mutable
+import scala.concurrent.duration._
+import scala.jdk.CollectionConverters._
+import scala.reflect.{classTag, ClassTag}
+
+import org.apache.spark.{SparkException, SparkIllegalArgumentException, 
SparkRuntimeException,
+  SparkThrowable, SparkUnsupportedOperationException, TaskContext}
+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.NoSuchTableException
+import org.apache.spark.sql.catalyst.expressions.{Add, Attribute, 
AttributeReference, Cast, EqualTo,
+  GenericInternalRow, LessThan, Literal, Rand}
+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, 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, 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.functions.{broadcast, coalesce, col, concat, 
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, DoubleType, 
IntegerType,
+  MapType, StringType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+import org.apache.spark.unsafe.types.UTF8String
+import org.apache.spark.util.{Clock, ManualClock}
+
+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 `body` with `clock` as the clock of the lookup cache TTL. */
+  private def withCacheClock[T](clock: Clock)(body: => T): T = {
+    val previous = ExternalLookupJoinExec.cacheClock
+    ExternalLookupJoinExec.cacheClock = clock
+    try body finally ExternalLookupJoinExec.cacheClock = previous
+  }
+
+  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 that reads only stream columns and ignores duplicates 
does not need a left
+        // outer join, so the optimizer removes an ordinary one. A lookup join 
stays.
+        val latestByDoor = swipes.join(lookup, swipes("employee") === 
lookup("id"), "left_outer")
+          .groupBy(swipes("door")).agg(max(swipes("minute")))
+        QueryTest.sameRows(
+          Seq(Row("lobby", 10), Row("garage", 20)),
+          runStream(latestByDoor, "complete").rows).foreach(fail(_))
+      }
+    }
+  }
+
+  test("external lookup capability produces a unary external lookup join") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    val joined = left.join(lookup, left("id") === lookup("id"), "inner")
+
+    val plan = runStream(joined).plan
+    assert(plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+    assert(!plan.toString.contains("SimpleExternalLookupScan"))
+  }
+
+  test("a dual-capability source keeps an ordinary join unless the hint opts 
in") {
+    val lookup = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    val expected = Seq(Row(1, 1, "engineering"), Row(1, 1, "research"))
+
+    assert(lookup.queryExecution.analyzed.isInstanceOf[DataSourceV2Relation])
+    assert(lookup.queryExecution.analyzed.isInstanceOf[ExternalLookupRelation] 
=== false)
+    SimpleExternalLookupDataSource.resetCounters()
+    val ordinary = left.join(lookup, left("id") === lookup("id"), "inner")
+    
assert(runStream(ordinary).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])
 === false)
+    checkStream(ordinary, expected)
+    assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+
+    SimpleExternalLookupDataSource.resetCounters()
+    val hinted = lookup.hint("external_lookup")
+    val lookupJoin = left.join(hinted, left("id") === hinted("id"), "inner")
+    
assert(runStream(lookupJoin).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+    checkStream(lookupJoin, expected)
+    assert(SimpleExternalLookupDataSource.requestCount.get() > 0)
+  }
+
+  test("a hinted or aliased lookup side follows the stream-static contract") {
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val lookupOnly = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val batch = Seq(1).toDF("id")
+    // Without the hint, a dual-capability table keeps an ordinary batch join.
+    checkAnswer(
+      batch.join(dual, batch("id") === dual("id")),
+      Seq(Row(1, 1, "engineering"), Row(1, 1, "research")))
+    // With it, the batch join fails: a hint the user wrote is never silently 
dropped.
+    Seq(
+      dual -> "`DualCapabilityExternalLookupTable`",
+      lookupOnly -> "`SimpleExternalLookupTable`").foreach { case (table, 
relation) =>
+      val hinted = table.hint("external_lookup")
+      checkError(
+        exception = intercept[AnalysisException] {
+          batch.join(hinted, batch("id") === hinted("id"))
+        },
+        condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.STATIC_LEFT_SIDE",
+        parameters = Map("relation" -> relation))
+    }
+    // A lookup-only table on the left side is found beneath an alias too.
+    val stream = streamOf(batch)
+    checkError(
+      exception = intercept[AnalysisException] {
+        lookupOnly.as("l").join(stream, $"l.id" === stream("id"))
+      },
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_TABLE_ON_LEFT",
+      parameters = Map("relation" -> "`SimpleExternalLookupTable`"))
+  }
+
+  test("a physical join strategy hint conflicts with the external lookup 
hint") {
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    Seq(
+      "broadcast" -> "BROADCAST",
+      "merge" -> "MERGE",
+      "shuffle_hash" -> "SHUFFLE_HASH",
+      "shuffle_replicate_nl" -> "SHUFFLE_REPLICATE_NL").foreach { case (hint, 
strategy) =>
+      val lookupSide = dual.hint("external_lookup").hint(hint)
+      val streamSide = left.hint(hint)
+      val hinted = dual.hint("external_lookup")
+      Seq(
+        () => left.join(lookupSide, left("id") === lookupSide("id")),
+        () => streamSide.join(hinted, streamSide("id") === 
hinted("id"))).foreach { query =>
+        checkError(
+          exception = intercept[AnalysisException] { 
query().queryExecution.analyzed },
+          condition = "INVALID_EXTERNAL_LOOKUP_HINT.CONFLICTING_JOIN_STRATEGY",
+          parameters = Map(
+            "strategy" -> strategy,
+            "relation" -> "`DualCapabilityExternalLookupTable`"))
+      }
+    }
+    // Both hints may name the same relation, in either order. A strategy hint 
is never merged
+    // into the lookup hint, so the conflict is still reported.
+    withTempView("external_lookup_left", "external_lookup_right") {
+      left.createOrReplaceTempView("external_lookup_left")
+      dual.createOrReplaceTempView("external_lookup_right")
+      Seq("EXTERNAL_LOOKUP(r), MERGE(r)", "MERGE(r), 
EXTERNAL_LOOKUP(r)").foreach { hints =>
+        checkError(
+          exception = intercept[AnalysisException] {
+            sql(s"SELECT /*+ $hints */ * FROM external_lookup_left l " +
+              "JOIN external_lookup_right r ON l.id = r.id")
+          },
+          condition = "INVALID_EXTERNAL_LOOKUP_HINT.CONFLICTING_JOIN_STRATEGY",
+          parameters = Map(
+            "strategy" -> "MERGE",
+            "relation" -> "`DualCapabilityExternalLookupTable`"))
+      }
+    }
+
+    // Without the lookup hint, the strategy hint plans the ordinary join it 
asks for.
+    SimpleExternalLookupDataSource.resetCounters()
+    val ordinary = left.join(dual.hint("merge"), left("id") === dual("id"))
+    
assert(runStream(ordinary).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])
 === false)
+    checkStream(ordinary, Seq(Row(1, 1, "engineering"), Row(1, 1, "research")))
+    assert(SimpleExternalLookupDataSource.requestCount.get() === 0)
+  }
+
+  test("a hinted dual-capability source fails when no lookup access path 
exists") {
+    val lookup = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val invoices = streamOf(Seq((1, "sales")).toDF("invoice", "costCenter"))
+
+    checkStream(
+      invoices.join(lookup, invoices("costCenter") === lookup("department")),
+      Seq(Row(1, "sales", 2, "sales")))
+    val hinted = lookup.hint("external_lookup")
+    checkError(
+      exception = streamFailure[AnalysisException](
+        invoices.join(hinted, invoices("costCenter") === 
hinted("department"))),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_PREDICATE",
+      parameters = Map("table" -> "`DualCapabilityExternalLookupTable`"))
+  }
+
+  test("a physical strategy hint on a lookup-only join is rejected") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 3).toDF("id"))
+    val withLookupHint = lookup.hint("external_lookup").hint("shuffle_hash")
+    Seq(
+      "BROADCAST" ->
+        (() => left.join(lookup.hint("broadcast"), left("id") === 
lookup("id"), "left_outer")),
+      "BROADCAST" ->
+        (() => left.join(broadcast(lookup), left("id") === lookup("id"), 
"left_outer")),
+      "MERGE" -> (() => left.hint("merge").join(lookup, left("id") === 
lookup("id"))),
+      "SHUFFLE_HASH" ->
+        (() => left.join(withLookupHint, left("id") === 
withLookupHint("id")))).foreach {
+      case (strategy, query) =>
+        checkError(
+          exception = intercept[AnalysisException] { 
query().queryExecution.analyzed },
+          condition = 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.CONFLICTING_JOIN_STRATEGY",
+          parameters = Map("strategy" -> strategy, "relation" -> 
"`SimpleExternalLookupTable`"))
+    }
+  }
+
+  test("an ordinary join over an enriched lookup join result stays ordinary") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val events = streamOf(Seq(1, 2).toDF("id"))
+    val enriched = events.join(lookup, events("id") === lookup("id"))
+      .select(events("id").as("event_id"), lookup("department"))
+    val base = Seq((1, "a"), (2, "b")).toDF("id", "tag")
+    val expected = Seq(
+      Row(1, "a", 1, "engineering"), Row(1, "a", 1, "research"), Row(2, "b", 
2, "sales"))
+    def lookupJoinCount(df: DataFrame): Int =
+      runStream(df).plan.collect { case j: PreparedExternalLookupJoin => j 
}.size
+
+    val joined = base.join(enriched, base("id") === enriched("event_id"))
+    assert(lookupJoinCount(joined) === 1)
+    checkStream(joined, expected)
+
+    withTempView("external_lookup_base", "external_lookup_events", 
"external_lookup_right") {
+      base.createOrReplaceTempView("external_lookup_base")
+      events.createOrReplaceTempView("external_lookup_events")
+      lookup.createOrReplaceTempView("external_lookup_right")
+      val sqlJoined = sql(
+        """
+          |SELECT b.id, b.tag, e.event_id, e.department
+          |FROM external_lookup_base b JOIN (
+          |  SELECT v.id AS event_id, r.department
+          |  FROM external_lookup_events v JOIN external_lookup_right r ON 
v.id = r.id) e
+          |ON b.id = e.event_id
+          |""".stripMargin)
+      assert(lookupJoinCount(sqlJoined) === 1)
+      checkStream(sqlJoined, expected)
+    }
+  }
+
+  test("an external lookup hint outside any join is ignored") {
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val expected = Seq(Row(1, "engineering"), Row(1, "research"), Row(2, 
"sales"))
+
+    checkAnswer(dual.hint("external_lookup"), expected)
+    assert(dual.hint("external_lookup", "cache_enabled=false").count() === 3)
+    withTempView("external_lookup_right") {
+      dual.createOrReplaceTempView("external_lookup_right")
+      checkAnswer(sql("SELECT /*+ EXTERNAL_LOOKUP */ * FROM 
external_lookup_right"), expected)
+      checkAnswer(sql("SELECT /*+ EXTERNAL_LOOKUP(r) */ * FROM 
external_lookup_right r"), expected)
+      checkAnswer(
+        sql("SELECT /*+ EXTERNAL_LOOKUP(r) */ id, count(*) FROM 
external_lookup_right r " +
+          "GROUP BY id"),
+        Seq(Row(1, 2), Row(2, 1)))
+    }
+  }
+
+  test("an empty lookup side does not call the connector") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 3).toDF("id"))
+    withTempView("empty_side_lookup", "empty_side_left") {
+      lookup.createOrReplaceTempView("empty_side_lookup")
+      left.createOrReplaceTempView("empty_side_left")
+      Seq("inner" -> "INNER", "left_outer" -> "LEFT OUTER").foreach { case 
(joinType, sqlJoin) =>
+        val expected =
+          if (joinType == "inner") Seq.empty[Row] else Seq(Row(1, null, null), 
Row(3, null, null))
+        val empty = lookup.where(lit(false))
+        Seq(
+          () => left.join(empty, left("id") === empty("id"), joinType),
+          () => sql(s"SELECT * FROM empty_side_left l $sqlJoin JOIN " +
+            "(SELECT * FROM empty_side_lookup WHERE 1 = 0) r ON l.id = 
r.id")).foreach { query =>
+          SimpleExternalLookupDataSource.resetCounters()
+          val joined = query()
+          assert(
+            
runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]) === 
false)
+          checkStream(joined, expected)
+          assert(SimpleExternalLookupDataSource.lookupCandidates.get() === 
Seq.empty)
+          assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+          assert(SimpleExternalLookupDataSource.requestCount.get() === 0)
+        }
+      }
+    }
+  }
+
+  test("a lookup side with another operator above the table fails when the 
DataFrame is built") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 3).toDF("id"))
+    val values = Seq(1).toDF("v")
+    // A lookup-only table, which no other join can read, and a hinted table 
that supports batch
+    // reads too. The join fails even where the optimizer would remove the 
operator. A subquery is
+    // planned apart from the lookup results, so a projection or filter with 
one cannot run either.
+    Seq(
+      lookup.limit(1),
+      lookup.distinct(),
+      dual.limit(1).hint("external_lookup"),
+      lookup.filter($"id".isin(values)),
+      lookup.filter(values.where(col("v") === 1).exists()),
+      lookup.filter($"id" < 
spark.range(2).select(max($"id")).scalar())).foreach { right =>
+      checkError(
+        exception = intercept[AnalysisException] {
+          left.join(right, left("id") === right("id"), "left_outer")
+        },
+        condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_PLAN",
+        parameters = Map.empty)
+    }
+    assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+  }
+
+  test("a USING join with the EXTERNAL_LOOKUP hint runs as an external lookup 
join") {
+    val left = streamOf(Seq(1, 3).toDF("id"))
+    Seq[Class[_]](
+      classOf[DualCapabilityExternalLookupDataSource],
+      classOf[SimpleExternalLookupDataSource]).foreach { source =>
+      val lookup = 
spark.read.format(source.getName).load().hint("external_lookup")
+      val joined = left.join(lookup, Seq("id"), "left_outer")
+      
assert(runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+      checkStream(joined, Seq(Row(1, "engineering"), Row(1, "research"), 
Row(3, null)))
+    }
+
+    // Without a condition the hinted join still fails, on the final plan.
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+      .hint("external_lookup")
+    checkError(
+      exception = streamFailure[AnalysisException](left.join(dual)),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION",
+      parameters = Map.empty)
+  }
+
+  test("an external lookup hint is found beneath an alias on either join 
side") {
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+
+    val aliased = dual.hint("external_lookup").as("r")
+    val joined = left.join(aliased, left("id") === $"r.id")
+    
assert(runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+    checkStream(joined, Seq(Row(1, 1, "engineering"), Row(1, 1, "research")))
+
+    checkError(
+      exception = intercept[AnalysisException] {
+        left.hint("external_lookup").as("l").join(dual, $"l.id" === dual("id"))
+          .queryExecution.analyzed
+      },
+      condition = "INVALID_EXTERNAL_LOOKUP_HINT.NOT_ON_LOOKUP_SIDE",
+      parameters = Map.empty)
+  }
+
+  test("a strategy hint on a nested join does not disable an outer lookup 
join") {
+    val left = streamOf(Seq((1, 10), (2, 20)).toDF("id", "k"))
+    val other = Seq((10, "a"), (20, "b")).toDF("k", "v")
+    val nested = left.join(other.hint("merge"), "k")
+    def usesLookup(df: DataFrame): Boolean =
+      runStream(df).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])
+
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+      .hint("external_lookup")
+    val dualJoin = nested.join(dual, nested("id") === dual("id"))
+    assert(usesLookup(dualJoin))
+    checkStream(dualJoin, Seq(
+      Row(10, 1, "a", 1, "engineering"), Row(10, 1, "a", 1, "research"),
+      Row(20, 2, "b", 2, "sales")))
+
+    // A lookup-only table on the outer join becomes a lookup join too, 
despite the nested join's
+    // MERGE hint.
+    val lookupOnly = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val lookupOnlyJoin = nested.join(lookupOnly, nested("id") === 
lookupOnly("id"))
+    assert(usesLookup(lookupOnlyJoin))
+    checkStream(lookupOnlyJoin, Seq(
+      Row(10, 1, "a", 1, "engineering"), Row(10, 1, "a", 1, "research"),
+      Row(20, 2, "b", 2, "sales")))
+  }
+
+  test("an explicit external lookup option marker rejects unsupported join 
shapes") {
+    val lookup = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+
+    checkError(
+      exception = intercept[AnalysisException] {
+        left.join(
+          lookup.hint("external_lookup", "cache_enabled=false"),
+          left("id") === lookup("id"),
+          "right_outer").queryExecution.analyzed
+      },
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE",
+      parameters = Map(
+        "joinType" -> "RIGHT OUTER",
+        "relation" -> "`DualCapabilityExternalLookupTable`",
+        "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES))
+
+    // A cross join fails with its join type while it is analyzed, before its 
missing condition.
+    checkError(
+      exception = 
intercept[AnalysisException](left.crossJoin(lookup.hint("external_lookup"))),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE",
+      parameters = Map(
+        "joinType" -> "CROSS",
+        "relation" -> "`DualCapabilityExternalLookupTable`",
+        "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES))
+
+    // A strategy hint on the same join conflicts before the join type is 
checked.
+    checkError(
+      exception = intercept[AnalysisException] {
+        left.join(
+          lookup.hint("external_lookup", "cache_enabled=false").hint("merge"),
+          left("id") === lookup("id"),
+          "right_outer").queryExecution.analyzed
+      },
+      condition = "INVALID_EXTERNAL_LOOKUP_HINT.CONFLICTING_JOIN_STRATEGY",
+      parameters = Map("strategy" -> "MERGE", "relation" -> 
"`DualCapabilityExternalLookupTable`"))
+  }
+
+  test("external lookup predicate negotiation includes type and null 
semantics") {
+    SimpleExternalLookupDataSource.resetCounters()
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq[java.lang.Integer](null, 1).toDF("id"))
+
+    runStream(left.join(lookup, left("id") <=> lookup("id"), "inner"))
+    assert(SimpleExternalLookupDataSource.lookupCandidates.get() ===
+      Seq(("<=>", "id", IntegerType)))
+  }
+
+  test("an external lookup hint on an ineligible join is rejected") {
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+      .hint("external_lookup")
+    val left = streamOf(Seq(1).toDF("id"))
+
+    // A cross join fails with its join type too, although it has no condition.
+    Seq[(() => DataFrame, String)](
+      (() => left.join(dual, left("id") === dual("id"), "right_outer"), "RIGHT 
OUTER"),
+      (() => left.crossJoin(dual), "CROSS")).foreach { case (joined, joinType) 
=>
+      val error = intercept[AnalysisException](joined())
+      assert(error.getCondition === 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE")
+      assert(error.getMessageParameters.get("joinType") === joinType)
+      assert(error.getMessageParameters.get("relation") === 
"`DualCapabilityExternalLookupTable`")
+    }
+  }
+
+  test("an external lookup join is a stream-static join with the lookup-only 
table on the right") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val batch = Seq(1).toDF("id")
+    // The left side must be a streaming query.
+    checkError(
+      exception = intercept[AnalysisException] {
+        batch.join(lookup, batch("id") === lookup("id"))
+      },
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.STATIC_LEFT_SIDE",
+      parameters = Map("relation" -> "`SimpleExternalLookupTable`"))
+    // The sides are never swapped.
+    val stream = streamOf(batch)
+    checkError(
+      exception = intercept[AnalysisException] {
+        lookup.join(stream, lookup("id") === stream("id"))
+      },
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_TABLE_ON_LEFT",
+      parameters = Map("relation" -> "`SimpleExternalLookupTable`"))
+  }
+
+  test("external lookup validates connector planning and request contracts") {
+    val left = streamOf(Seq(1).toDF("id"))
+    Seq(
+      ("nullKeySelection", "true", "NULL_RESULT",
+        Map("method" -> "SupportsExternalLookup.selectLookupPredicates()")),
+      ("selectionMode", "nullElement", "UNOFFERED_SELECTED_PREDICATE", 
Map("predicate" -> "null")),
+      ("selectionMode", "duplicate", "DUPLICATE_SELECTED_PREDICATE", 
Map("predicate" -> "id = ?")),
+      ("selectionMode", "copy", "UNOFFERED_SELECTED_PREDICATE", 
Map("predicate" -> "id = ?")),
+      ("maxBatchSize", "0", "NON_POSITIVE_MAX_PARAMETER_ROWS", Map("value" -> 
"0"))).foreach {
+      case (option, value, subClass, parameters) =>
+        val lookup = spark.read
+          .format(classOf[SimpleExternalLookupDataSource].getName)
+          .option(option, value)
+          .load()
+        checkError(
+          exception = streamFailure[AnalysisException](
+            left.join(lookup, left("id") === lookup("id"))),
+          condition = s"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.$subClass",
+          parameters = Map("table" -> "`SimpleExternalLookupTable`") ++ 
parameters)
+    }
+
+    def misconfigured(kind: String): DataFrame = spark.read
+      .format(classOf[MisconfiguredExternalLookupDataSource].getName)
+      .option("kind", kind)
+      .load()
+    val table = Map("table" -> "`MisconfiguredExternalLookupTable`")
+    Seq(
+      ("unknownField", "UNKNOWN_SCAN_FIELD", Map("field" -> "`unknown`")),
+      ("duplicateField", "DUPLICATE_SCAN_FIELD", Map("field" -> 
"`id`"))).foreach {
+      case (kind, subClass, parameters) =>
+        val lookup = misconfigured(kind)
+        checkError(
+          exception = streamFailure[AnalysisException](
+            left.join(lookup, left("id") === lookup("id"))),
+          condition = s"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.$subClass",
+          parameters = table ++ parameters)
+    }
+
+    val noExternalLookup = misconfigured("noExternalLookup")
+    checkError(
+      exception = streamFailure[SparkUnsupportedOperationException](
+        left.join(noExternalLookup, left("id") === noExternalLookup("id"))),
+      condition = "DATA_SOURCE_EXTERNAL_LOOKUP_NOT_SUPPORTED",
+      parameters = Map("description" -> "NoExternalLookupScan"))
+
+    // Violations found while the join runs are reported the same way, by the 
tasks.
+    val nullCursor = spark.read
+      .format(classOf[SimpleExternalLookupDataSource].getName)
+      .option("nullCursor", "true")
+      .load()
+    Seq(
+      (nullCursor, "NULL_RESULT", Map("table" -> "`SimpleExternalLookupTable`",
+        "method" -> "ExternalLookupReader.lookupBatch()")),
+      (misconfigured("nullReader"), "NULL_RESULT",
+        table ++ Map("method" -> 
"ExternalLookupReaderFactory.createReader()")),
+      (misconfigured("invalidOrdinal"), "INVALID_INPUT_ORDINAL",
+        table ++ Map("ordinal" -> "5", "numParameterRows" -> "1")),
+      // The ordinals just outside the request's parameter rows.
+      (misconfigured("negativeOrdinal"), "INVALID_INPUT_ORDINAL",
+        table ++ Map("ordinal" -> "-1", "numParameterRows" -> "1")),
+      (misconfigured("ordinalAtCount"), "INVALID_INPUT_ORDINAL",
+        table ++ Map("ordinal" -> "1", "numParameterRows" -> "1")),
+      (misconfigured("nullRow"), "NULL_RESULT",
+        table ++ Map("method" -> "ExternalLookupResultCursor.get()")),
+      // A value that breaks its column's type, which Spark relied on while it 
optimized.
+      (misconfigured("nullValue"), "NULL_IN_NOT_NULL_FIELD",
+        table ++ Map("field" -> "`department`")),
+      (misconfigured("nullUnderNotNullReadSchema"), "NULL_IN_NOT_NULL_FIELD",
+        table ++ Map("field" -> "`department`")),
+      (misconfigured("decimalOutOfRange"), "DECIMAL_OUT_OF_RANGE",
+        table ++ Map("field" -> "`amount`", "type" -> "\"DECIMAL(5,2)\"")),
+      // The same checks reach nested values: a decimal array element with too 
many digits, and
+      // a decimal map value that would need rounding.
+      (misconfigured("nestedDecimalOutOfRange"), "DECIMAL_OUT_OF_RANGE",
+        table ++ Map("field" -> "`amounts`.`element`", "type" -> 
"\"DECIMAL(5,2)\"")),
+      (misconfigured("nestedDecimalRounding"), "DECIMAL_OUT_OF_RANGE",
+        table ++ Map("field" -> "`rates`.`value`", "type" -> 
"\"DECIMAL(5,2)\"")),
+      // A map key is never null, whether it is a primitive or a struct.
+      (misconfigured("nullMapKey"), "NULL_IN_NOT_NULL_FIELD",
+        table ++ Map("field" -> "`labels`.`key`")),
+      (misconfigured("nullComplexMapKey"), "NULL_IN_NOT_NULL_FIELD",
+        table ++ Map("field" -> "`parts`.`key`"))).foreach {
+      case (lookup, subClass, parameters) =>
+        checkError(
+          exception = streamFailure[SparkRuntimeException](
+            left.join(lookup, left("id") === lookup("id"))),
+          condition = s"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.$subClass",
+          parameters = parameters)
+    }
+
+    // Planning failures that need no hint. A catalog can serve a table 
without SupportsRead.
+    val noLookupBuilder = misconfigured("noLookupBuilder")
+    val nonReadable = Dataset.ofRows(spark, DataSourceV2Relation.create(
+      NonReadableExternalLookupTable, None, None, 
CaseInsensitiveStringMap.empty))
+    val simple = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    Seq(
+      (noLookupBuilder, left("id") === noLookupBuilder("id"), "SCAN_BUILDER",
+        "MisconfiguredExternalLookupTable"),
+      (nonReadable, left("id") === nonReadable("id"), "TABLE", 
"NonReadableExternalLookupTable"),
+      (simple, simple("department") === "sales", "NO_LOOKUP_PREDICATE",
+        "SimpleExternalLookupTable")).foreach { case (lookup, condition, 
subClass, name) =>
+      checkError(
+        exception = streamFailure[AnalysisException](left.join(lookup, 
condition)),
+        condition = s"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.$subClass",
+        parameters = Map("table" -> s"`$name`"))
+    }
+    // A BIGINT stream key casts the INT lookup column, so Spark has no 
candidate to offer.
+    val bigintLeft = streamOf(Seq(1L).toDF("id"))
+    checkError(
+      exception = streamFailure[AnalysisException](
+        bigintLeft.join(simple, bigintLeft("id") === simple("id"))),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE",
+      parameters = Map("table" -> "`SimpleExternalLookupTable`"))
+  }
+
+  test("an external lookup hinted DataFrame can be reused by multiple joins") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+      .hint("external_lookup")
+
+    val first = streamOf(Seq(1).toDF("id"))
+    val second = streamOf(Seq(2).toDF("id"))
+    checkStream(first.join(lookup, first("id") === lookup("id")),
+      Seq(Row(1, 1, "engineering"), Row(1, 1, "research")))
+    checkStream(second.join(lookup, second("id") === lookup("id")),
+      Seq(Row(2, 2, "sales")))
+  }
+
+  test("external lookup finalizes expressions on the stream side after 
analysis") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq[java.lang.Integer](null, 1).toDF("id"))
+
+    checkStream(
+      left.join(
+        lookup,
+        coalesce(left("id"), lit(0)) === lookup("id"),
+        "inner"),
+      Seq(Row(1, 1, "engineering"), Row(1, 1, "research")))
+  }
+
+  test("external lookup prunes unused throwable lookup expressions") {
+    val rawLookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val lookup = rawLookup.select($"id", 
expr("raise_error('unused')").as("unused"))
+    val left = streamOf(Seq(1).toDF("id"))
+
+    checkStream(
+      left.join(lookup, left("id") === lookup("id"), "left_semi"),
+      Seq(Row(1)))
+
+    val projected = left.as("left").join(
+      lookup.as("lookup"),
+      $"left.id" === $"lookup.id",
+      "inner").select($"left.id")
+    checkStream(projected, Seq(Row(1), Row(1)))
+  }
+
+  test("external lookup rejects a non-deterministic lookup-side projection or 
filter") {
+    val rawLookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 1, 2).toDF("id"))
+    // The join evaluates the lookup-side stages on each returned row, so a 
random value could
+    // differ between two stream rows that join the same stored row.
+    Seq(
+      rawLookup.select($"id", $"department", rand(3).as("sample")),
+      rawLookup.filter(rand(3) >= 0.5)).foreach { lookup =>
+      checkError(
+        exception = intercept[AnalysisException] {
+          left.join(lookup, left("id") === lookup("id"), "inner")
+        },
+        condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_PLAN",
+        parameters = Map.empty)
+    }
+    assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+  }
+
+  test("external lookup hint rejects duplicate and malformed options") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val positiveInteger = Map("expected" -> "a positive integer")
+    val duration = Map("expected" -> "a non-negative duration, such as 500ms, 
5s, or 10m")
+    val supportedOptions = Map("supportedOptions" ->
+      "\"cache_enabled\", \"cache_max_entries\", \"cache_max_rows_per_key\", 
\"cache_ttl\"")
+    Seq(
+      (Seq("cache_enabled=true", "cache_enabled=false"), "cache_enabled", 
"DUPLICATE", Map()),
+      (Seq("cache_enabled=unknown"), "cache_enabled", "INVALID_VALUE",
+        Map("expected" -> "true or false")),
+      (Seq("cache_enabled="), "cache_enabled=", "INVALID_FORMAT", Map()),
+      (Seq("=true"), "=true", "INVALID_FORMAT", Map()),
+      (Seq("cache_mode=enabled"), "cache_mode", "UNSUPPORTED", 
supportedOptions),
+      (Seq("cache_max_entries=0"), "cache_max_entries", "INVALID_VALUE", 
positiveInteger),
+      (Seq("cache_max_entries=abc"), "cache_max_entries", "INVALID_VALUE", 
positiveInteger),
+      (Seq("cache_ttl=-1ms"), "cache_ttl", "INVALID_VALUE", duration),
+      (Seq("cache_ttl=abc"), "cache_ttl", "INVALID_VALUE", duration),
+      (Seq("cache_max_rows_per_key=0"), "cache_max_rows_per_key", 
"INVALID_VALUE",
+        positiveInteger),
+      (Seq("unknown_option=1"), "unknown_option", "UNSUPPORTED", 
supportedOptions)).foreach {
+      case (options, option, subClass, parameters) =>
+        checkError(
+          exception = intercept[AnalysisException] {
+            lookup.hint("external_lookup", options: _*).queryExecution.analyzed
+          },
+          condition = s"INVALID_EXTERNAL_LOOKUP_OPTION.$subClass",
+          parameters = Map("option" -> ("\"" + option + "\"")) ++ parameters)
+    }
+    checkError(
+      exception = intercept[AnalysisException] {
+        lookup.hint("external_lookup", 1).queryExecution.analyzed
+      },
+      condition = "INVALID_EXTERNAL_LOOKUP_HINT.UNSUPPORTED_PARAMETER",
+      parameters = Map("parameter" -> "\"1\""))
+    // A string without `=` is a relation name. When it names no relation, as 
an option without a
+    // value does, the error says how to write an option.
+    val noValue = intercept[AnalysisException] {
+      lookup.hint("external_lookup", "cache_enabled").queryExecution.analyzed
+    }
+    checkError(
+      exception = noValue,
+      condition = "INVALID_EXTERNAL_LOOKUP_HINT.RELATION_NOT_FOUND",
+      parameters = Map("relations" -> "`cache_enabled`"))
+    assert(noValue.getMessage.contains("Cannot find the relation(s) 
`cache_enabled` named by the " +
+      "hint. A string parameter that does not contain `=` is a relation name. 
Write a cache " +
+      "option as key=value, such as 'cache_enabled=false'."))
+  }
+
+  test("a hint can mix relation names and cache options given as strings") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      val catalogTable = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.dual"
+      val swipes = streamOf(Seq((1, "lobby"), (3, "garage")).toDF("employee", 
"door"))
+      val expected = Seq(Row(1, "lobby", "engineering"), Row(1, "lobby", 
"research"))
+      def checkCacheOptions(df: DataFrame, check: ExternalLookupCacheOptions 
=> Boolean): Unit = {
+        val run = runStream(df)
+        QueryTest.sameRows(expected, run.rows).foreach(fail(_))
+        val prepared = run.plan.collectFirst { case join: 
PreparedExternalLookupJoin => join }
+        assert(prepared.exists(join => check(join.cacheOptions)), prepared)
+      }
+
+      val directory = spark.table(catalogTable).as("r")
+      checkCacheOptions(
+        swipes.join(directory, swipes("employee") === $"r.id")
+          .hint("external_lookup", "r", "cache_enabled=false")
+          .select("employee", "door", "department"),
+        _.enabled === false)
+      withTempView("badge_swipes") {
+        swipes.createOrReplaceTempView("badge_swipes")
+        checkCacheOptions(
+          sql(
+            s"""
+              |SELECT /*+ EXTERNAL_LOOKUP('cache_ttl=2s', 'r') */ s.employee, 
s.door, r.department
+              |FROM badge_swipes s JOIN $catalogTable r ON s.employee = r.id
+              |""".stripMargin),
+          _.ttlMillis === 2000L)
+      }
+    }
+  }
+
+  test("the cache options of a hint in a WITH clause apply to its lookup 
join") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      withTempView("badge_swipes") {
+        streamOf(Seq((1, "lobby"), (3, "garage")).toDF("employee", "door"))
+          .createOrReplaceTempView("badge_swipes")
+        val run = runStream(sql(
+          s"""
+            |WITH lk AS (
+            |  SELECT /*+ EXTERNAL_LOOKUP('cache_enabled=false') */ *
+            |  FROM $EXTERNAL_LOOKUP_CATALOG_NAME.ns.dual)
+            |SELECT s.door, lk.department FROM badge_swipes s JOIN lk ON 
s.employee = lk.id
+            |""".stripMargin))
+        QueryTest.sameRows(
+          Seq(Row("lobby", "engineering"), Row("lobby", "research")), 
run.rows).foreach(fail(_))
+        val prepared = run.plan.collectFirst { case join: 
PreparedExternalLookupJoin => join }
+        assert(prepared.map(_.cacheOptions.enabled) === Some(false))
+      }
+    }
+  }
+
+  test("external lookup hint rejects invalid placement and relation targets") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+
+    checkError(
+      exception = intercept[AnalysisException] {
+        left.hint("external_lookup").join(lookup, left("id") === lookup("id"))
+          .queryExecution.analyzed
+      },
+      condition = "INVALID_EXTERNAL_LOOKUP_HINT.NOT_ON_LOOKUP_SIDE",
+      parameters = Map.empty)
+    checkError(
+      exception = intercept[AnalysisException] {
+        val hinted = lookup.hint("external_lookup").hint("external_lookup")
+        left.join(hinted, left("id") === hinted("id")).queryExecution.analyzed
+      },
+      condition = "INVALID_EXTERNAL_LOOKUP_HINT.MULTIPLE_HINTS",
+      parameters = Map.empty)
+
+    withTempView("external_lookup_left", "external_lookup_right") {
+      left.createOrReplaceTempView("external_lookup_left")
+      lookup.createOrReplaceTempView("external_lookup_right")
+      def query(hint: String): DataFrame = sql(
+        s"""
+          |SELECT /*+ $hint */ l.id, r.department
+          |FROM external_lookup_left l JOIN external_lookup_right r ON l.id = 
r.id
+          |""".stripMargin)
+      checkError(
+        exception = intercept[AnalysisException] {
+          query("EXTERNAL_LOOKUP(missing)").queryExecution.analyzed
+        },
+        condition = "INVALID_EXTERNAL_LOOKUP_HINT.RELATION_NOT_FOUND",
+        parameters = Map("relations" -> "`missing`"))
+      checkError(
+        exception = intercept[AnalysisException] {
+          query("EXTERNAL_LOOKUP(r, r)").queryExecution.analyzed
+        },
+        condition = "INVALID_EXTERNAL_LOOKUP_HINT.DUPLICATE_RELATION",
+        parameters = Map("relation" -> "`r`"))
+    }
+
+    val stream = MemoryStream[Int].toDF().toDF("id")
+    checkError(
+      exception = intercept[AnalysisException] {
+        left.join(stream.hint("external_lookup"), left("id") === stream("id"))
+          .queryExecution.analyzed
+      },
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.STREAMING_LOOKUP_SIDE",
+      parameters = Map.empty)
+  }
+
+  test("external lookup reports lookup sides and conditions it cannot plan") {
+    val claims = streamOf(Seq((1, "sales")).toDF("id", "costCenter"))
+    def planningError(lookup: DataFrame, condition: Column): AnalysisException 
=
+      streamFailure[AnalysisException](claims.join(lookup, condition))
+    def analysisError(lookup: DataFrame, condition: Column): AnalysisException 
=
+      intercept[AnalysisException](claims.join(lookup, condition))
+
+    // A hinted lookup side fails when the DataFrame is built: with 
LOOKUP_PLAN when it reads no
+    // DSv2 table, as a local relation does, and with TABLE for a DSv2 table 
that does not support
+    // external lookup.
+    val local = Seq(1).toDF("id").hint("external_lookup")
+    checkError(
+      exception = analysisError(local, claims("id") === local("id")),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.LOOKUP_PLAN",
+      parameters = Map.empty)
+
+    val batchOnly = spark.read
+      .format(classOf[MisconfiguredExternalLookupDataSource].getName)
+      .option("kind", "batchOnly")
+      .load()
+      .hint("external_lookup")
+    checkError(
+      exception = analysisError(batchOnly, claims("id") === batchOnly("id")),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.TABLE",
+      parameters = Map("table" -> "`MisconfiguredExternalLookupTable`"))
+
+    val noLookupBuilder = spark.read
+      .format(classOf[MisconfiguredExternalLookupDataSource].getName)
+      .option("kind", "noLookupBuilder")
+      .load()
+    checkError(
+      exception = planningError(noLookupBuilder, claims("id") === 
noLookupBuilder("id")),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.SCAN_BUILDER",
+      parameters = Map("table" -> "`MisconfiguredExternalLookupTable`"))
+
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    checkError(
+      exception = planningError(lookup, claims("costCenter") === 
lookup("department")),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_PREDICATE",
+      parameters = Map("table" -> "`SimpleExternalLookupTable`"))
+  }
+
+  test("external lookup maps a selected predicate to its own occurrence") {
+    val lookup = spark.read
+      .format(classOf[SimpleExternalLookupDataSource].getName)
+      .option("selectionMode", "last")
+      .load()
+      .hint("external_lookup", "cache_enabled=false")
+    val left = streamOf(Seq((1, 2), (2, 2), (2, 1)).toDF("a", "b"))
+
+    // Both candidates have the shape `id = ?`; only the second one, bound to 
`b`, is selected.
+    val joined =
+      left.join(lookup, lookup("id") === left("a") && lookup("id") === 
left("b"), "left_outer")
+    assert(runStream(joined).rows.toSet ===
+      Set(Row(1, 2, null, null), Row(2, 2, 2, "sales"), Row(2, 1, null, null)))
+    assert(SimpleExternalLookupDataSource.lookupCandidates.get() ===
+      Seq(("=", "id", IntegerType), ("=", "id", IntegerType)))
+    assert(SimpleExternalLookupDataSource.lookupCandidateDescriptions.get() ===
+      Seq("id = ?", "id = ?"))
+    assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === 
Seq(2, 1))
+
+    // Selected in reverse order, each parameter row is `(b, a)`.
+    SimpleExternalLookupDataSource.resetCounters()
+    val reversed = spark.read
+      .format(classOf[SimpleExternalLookupDataSource].getName)
+      .option("selectionMode", "reversed")
+      .load()
+    val condition = reversed("id") === left("a") && reversed("id") === 
left("b")
+    assert(runStream(left.join(reversed, condition, "left_outer")).rows.toSet 
===
+      Set(Row(1, 2, null, null), Row(2, 2, 2, "sales"), Row(2, 1, null, null)))
+    assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === 
Seq(2, 2, 1))
+  }
+
+  test("a parent projection of some lookup columns still plans an external 
lookup join") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 3).toDF("id"))
+    // Generic column pruning must not project the lookup relation, which 
would hide it from
+    // lookup planning; the join's requiredLookupOutput keeps it from doing so.
+    val joined = left.join(lookup, left("id") === lookup("id"), "left_outer")
+      .select(left("id"), lookup("department"))
+
+    
assert(runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+    // The source is asked for the lookup column that the projection reads, 
and for the key, which
+    // Spark checks on every returned row.
+    assert(SimpleExternalLookupDataSource.requiredColumns.get() === Seq("id", 
"department"))
+    checkStream(joined, Seq(Row(1, "engineering"), Row(1, "research"), Row(3, 
null)))
+  }
+
+  test("external lookup join supports inner and left outer joins") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq((1, "one"), (2, "two"), (3, "three")).toDF("id", 
"label"))
+
+    checkStream(
+      left.join(lookup, left("id") === lookup("id"), "inner"),
+      Seq(Row(1, "one", 1, "engineering"), Row(1, "one", 1, "research"),
+        Row(2, "two", 2, "sales")))
+    checkStream(
+      left.join(lookup, left("id") === lookup("id"), "left_outer"),
+      Seq(Row(1, "one", 1, "engineering"), Row(1, "one", 1, "research"),
+        Row(2, "two", 2, "sales"), Row(3, "three", null, null)))
+
+    // Only comparisons of a lookup field with a stream-side value are offered 
here. The connector
+    // selects `id = ?`, and Spark evaluates the other conjuncts: the 
stream-side one on each stream
+    // row before the lookup, and the two others on the lookup side. The join 
keeps `id = ?` as its
+    // key, so the comparison with a constant goes there too, as a pushed 
filter.
+    SimpleExternalLookupDataSource.resetCounters()
+    val flagged = streamOf(Seq((1, true), (2, true), (1, false)).toDF("id", 
"flag"))
+    checkStream(
+      flagged.join(
+        lookup,
+        flagged("id") === lookup("id") && flagged("flag") &&
+          lookup("department") === "engineering" && 
length(lookup("department")) > lookup("id"),
+        "left_outer"),
+      Seq(Row(1, true, 1, "engineering"), Row(2, true, null, null), Row(1, 
false, null, null)))
+    assert(SimpleExternalLookupDataSource.lookupCandidates.get() === Seq(("=", 
"id", IntegerType)))
+  }
+
+  test("a stream row that fails a stream-side conjunct of the condition is not 
looked up") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(
+      Seq((1, Some(true)), (2, Some(false)), (3, Some(true)), (4, 
None)).toDF("id", "flag"))
+    val key = left("id") === lookup("id")
+    // The join checks `flag` on each stream row before the lookup. A row 
where it is false or null
+    // cannot match, so its key is not requested: an inner or left semi join 
drops the row, a left
+    // outer join pads it with nulls, and a left anti join returns it.
+    val matched = Seq(Row(1, true, 1, "engineering"), Row(1, true, 1, 
"research"))
+    val unmatched =
+      Seq(Row(2, false, null, null), Row(3, true, null, null), Row(4, null, 
null, null))
+    Seq(
+      "inner" -> matched,
+      "left_outer" -> (matched ++ unmatched),
+      "left_semi" -> Seq(Row(1, true)),
+      "left_anti" -> Seq(Row(2, false), Row(3, true), Row(4, null))).foreach {
+      case (joinType, expected) =>
+        SimpleExternalLookupDataSource.resetCounters()
+        checkStream(left.join(lookup, key && left("flag"), joinType), expected)
+        assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === 
Seq(1, 3))
+    }
+
+    // A conjunct that can throw is not checked early: it is evaluated on the 
joined rows only, so
+    // never for id 3, which has no match, and every key is requested.
+    SimpleExternalLookupDataSource.resetCounters()
+    val throwing = when(left("id") === 3, raise_error(lit("evaluated for id 
3"))).otherwise(true)
+    checkStream(
+      left.join(lookup, key && throwing, "left_outer"),
+      matched ++ Seq(Row(2, false, 2, "sales"), Row(3, true, null, null), 
Row(4, null, null, null)))
+    assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === 
Seq(1, 2, 3, 4))
+
+    // A conjunct that is not deterministic is not checked early either. 
Analysis rejects one in a
+    // join condition, so the physical join gets one directly: `id + rand(0) < 
0`. It is false for
+    // every row, but it is evaluated on the joined rows only, so every key is 
requested.
+    val lookupJoin = runStream(left.join(lookup, key, "left_outer")).lookupJoin
+    val streamId = lookupJoin.child.output.head
+    val nonDeterministic =
+      LessThan(Add(Cast(streamId, DoubleType), Rand(Literal(0L))), 
Literal(0.0))
+    SimpleExternalLookupDataSource.resetCounters()
+    val rows = lookupJoin.copy(
+      residualCondition = Some(nonDeterministic),
+      child = LocalTableScanExec(
+        lookupJoin.child.output, Seq(InternalRow(1, true), InternalRow(2, 
false)), None))
+      .executeCollect()
+    assert(rows.map(row => row.getInt(0) -> row.isNullAt(2)).toSeq === Seq(1 
-> true, 2 -> true))
+    // Each row is in its own partition, so the order of the requests can vary.
+    assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq.sorted 
=== Seq(1, 2))
+  }
+
+  test("external lookup-only source joins without an explicit hint") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+
+    assert(lookup.queryExecution.analyzed.isInstanceOf[ExternalLookupRelation])
+    val joined = left.join(lookup, "id")
+    
assert(runStream(joined).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+    checkStream(joined, Seq(Row(1, "engineering"), Row(1, "research")))
+  }
+
+  test("an external lookup-only source cannot be read outside an eligible 
lookup join") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    checkError(
+      exception = intercept[AnalysisException] { 
lookup.queryExecution.optimizedPlan },
+      condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+      parameters = Map(
+        "tableName" -> "`SimpleExternalLookupTable`",
+        "operation" -> "batch scan"))
+    // A join that reads it but cannot be a lookup join fails with the reason. 
The condition must
+    // be written in the join, not in a later filter.
+    checkError(
+      exception = streamFailure[AnalysisException](
+        left.join(lookup).where(left("id") === lookup("id"))),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION",
+      parameters = Map.empty)
+    // An unsupported join type fails when the DataFrame is built, with or 
without a condition.
+    Seq[(() => DataFrame, String)](
+      (() => left.join(lookup, left("id") === lookup("id"), "full_outer"), 
"FULL OUTER"),
+      (() => left.crossJoin(lookup), "CROSS"),
+      (() => left.crossJoin(lookup).where(left("id") === lookup("id")), 
"CROSS")).foreach {
+      case (joined, joinType) =>
+        val error = intercept[AnalysisException](joined())
+        assert(error.getCondition === 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE")
+        assert(error.getMessageParameters.asScala.toMap === Map(
+          "joinType" -> joinType,
+          "relation" -> "`SimpleExternalLookupTable`",
+          "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES))
+    }
+  }
+
+  test("catalog-resolved tables follow the same lookup selection") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      withTempView("external_lookup_left") {
+        streamOf(Seq(1, 
3).toDF("id")).createOrReplaceTempView("external_lookup_left")
+        def query(table: String, hint: String = ""): DataFrame = sql(
+          s"""
+            |SELECT $hint l.id, r.department
+            |FROM external_lookup_left l
+            |LEFT JOIN $EXTERNAL_LOOKUP_CATALOG_NAME.ns.$table r ON l.id = r.id
+            |""".stripMargin)
+        val expected = Seq(Row(1, "engineering"), Row(1, "research"), Row(3, 
null))
+        def usesLookup(df: DataFrame): Boolean =
+          runStream(df).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])
+
+        SimpleExternalLookupDataSource.resetCounters()
+        val lookupOnly = query("lookup")
+        assert(usesLookup(lookupOnly))
+        checkStream(lookupOnly, expected)
+        assert(SimpleExternalLookupDataSource.requestCount.get() > 0)
+
+        SimpleExternalLookupDataSource.resetCounters()
+        val dual = query("dual")
+        assert(!usesLookup(dual))
+        checkStream(dual, expected)
+        assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+
+        val hintedDual = query("dual", "/*+ EXTERNAL_LOOKUP(r) */")
+        assert(usesLookup(hintedDual))
+        checkStream(hintedDual, expected)
+      }
+    }
+  }
+
+  test("a named external lookup hint marks every relation that it names") {
+    // As with join strategy hints, the name matches each unaliased reference 
to the table, so
+    // both joins read it through external lookup.
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      withTempView("external_lookup_left") {
+        streamOf(Seq(1, 
3).toDF("id")).createOrReplaceTempView("external_lookup_left")
+        val catalogTable = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.dual"
+        val twice = sql(
+          s"""
+            |SELECT /*+ EXTERNAL_LOOKUP(dual) */ *
+            |FROM external_lookup_left JOIN $catalogTable USING (id) JOIN 
$catalogTable USING (id)
+            |""".stripMargin)
+        val run = runStream(twice)
+        assert(run.plan.collect { case join: PreparedExternalLookupJoin => 
join }.size === 2)
+        QueryTest.sameRows(
+          Seq(Row(1, "engineering", "engineering"), Row(1, "engineering", 
"research"),
+            Row(1, "research", "engineering"), Row(1, "research", "research")),
+          run.rows).foreach(fail(_))
+      }
+    }
+  }
+
+  test("a named external lookup hint targets unaliased, multipart, and aliased 
relations") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      withTempView("external_lookup_left", "external_lookup_right") {
+        streamOf(Seq(1, 
3).toDF("id")).createOrReplaceTempView("external_lookup_left")
+        
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+          .createOrReplaceTempView("external_lookup_right")
+        val expected = Seq(Row(1, "engineering"), Row(1, "research"), Row(3, 
null))
+        def query(hintTarget: String, right: String, rightName: String): 
DataFrame = sql(
+          s"""
+            |SELECT /*+ EXTERNAL_LOOKUP($hintTarget) */ l.id, 
$rightName.department
+            |FROM external_lookup_left l LEFT JOIN $right ON l.id = 
$rightName.id
+            |""".stripMargin)
+
+        val catalogTable = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.dual"
+        Seq(
+          ("external_lookup_right", "external_lookup_right", 
"external_lookup_right"),
+          ("dual", catalogTable, "dual"),
+          ("ns.dual", catalogTable, "dual"),
+          (catalogTable, catalogTable, "dual"),
+          ("r", s"$catalogTable r", "r"),
+          ("s", "(SELECT * FROM external_lookup_right) s", "s")).foreach {
+          case (hintTarget, right, rightName) =>
+            val df = query(hintTarget, right, rightName)
+            
assert(runStream(df).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]),
+              hintTarget)
+            checkStream(df, expected)
+        }
+
+        // Like join strategy hints, a target name does not reach into an 
aliased subquery.
+        checkError(
+          exception = intercept[AnalysisException] {
+            query("external_lookup_right", "(SELECT * FROM 
external_lookup_right) s", "s")
+              .queryExecution.analyzed
+          },
+          condition = "INVALID_EXTERNAL_LOOKUP_HINT.RELATION_NOT_FOUND",
+          parameters = Map("relations" -> "`external_lookup_right`"))
+      }
+    }
+  }
+
+  test("a catalog-resolved lookup-only table in an ineligible join fails with 
the reason") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      val table = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.lookup"
+      val left = streamOf(Seq(1).toDF("id"))
+      val crossJoin = 
intercept[AnalysisException](left.crossJoin(spark.read.table(table)))
+      assert(crossJoin.getCondition === 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE")
+      assert(crossJoin.getMessageParameters.asScala.toMap === Map("joinType" 
-> "CROSS",
+        "relation" -> "`SimpleExternalLookupTable`", "supportedJoinTypes" -> 
SUPPORTED_JOIN_TYPES))
+      withTempView("external_lookup_left") {
+        left.createOrReplaceTempView("external_lookup_left")
+        val fullOuter = intercept[AnalysisException] {
+          sql(s"SELECT * FROM external_lookup_left l FULL OUTER JOIN $table r 
ON l.id = r.id")
+        }
+        assert(fullOuter.getCondition === 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE")
+        assert(fullOuter.getMessageParameters.asScala.toMap === Map(
+          "joinType" -> "FULL OUTER",
+          "relation" -> "`SimpleExternalLookupTable`",
+          "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES))
+      }
+    }
+  }
+
+  test("a catalog-resolved table can be composed into DataFrame joins") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      val left = streamOf(Seq(1, 3).toDF("id"))
+      val expected = Seq(Row(1, 1, "engineering"), Row(1, 1, "research"), 
Row(3, null, null))
+      def usesLookup(df: DataFrame): Boolean =
+        runStream(df).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])
+
+      val lookupOnly = spark.table(s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.lookup")
+      val lookupJoin = left.join(lookupOnly, left("id") === lookupOnly("id"), 
"left_outer")
+      assert(usesLookup(lookupJoin))
+      checkStream(lookupJoin, expected)
+
+      val dual = spark.table(s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.dual")
+      val ordinary = left.join(dual, left("id") === dual("id"), "left_outer")
+      assert(!usesLookup(ordinary))
+      checkStream(ordinary, expected)
+      val hinted = dual.hint("external_lookup")
+      val hintedJoin = left.join(hinted, left("id") === hinted("id"), 
"left_outer")
+      assert(usesLookup(hintedJoin))
+      checkStream(hintedJoin, expected)
+
+      checkError(
+        exception = intercept[AnalysisException] { lookupOnly.collect() },
+        condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+        parameters = Map(
+          "tableName" -> "`SimpleExternalLookupTable`",
+          "operation" -> "batch scan"))
+    }
+  }
+
+  test("a named external lookup hint accepts relation names given as strings") 
{
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      val catalogTable = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.dual"
+      val swipes = streamOf(Seq((1, "lobby"), (3, "garage")).toDF("employee", 
"door"))
+      val expected = Seq(Row(1, "lobby", "engineering"), Row(1, "lobby", 
"research"))
+      def checkLookupJoin(df: DataFrame, name: String): Unit = {
+        val run = runStream(df)
+        assert(run.plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]), 
name)
+        QueryTest.sameRows(expected, run.rows).foreach(fail(_))
+      }
+
+      // The Dataset API, which PySpark and Spark Connect use, passes a 
relation name as a string.
+      val aliased = spark.table(catalogTable).as("r")
+      val unaliased = spark.table(catalogTable)
+      Seq(
+        "r" -> swipes.join(aliased, swipes("employee") === $"r.id"),
+        catalogTable -> swipes.join(unaliased, swipes("employee") === 
unaliased("id")),
+        "ns.dual" -> swipes.join(unaliased, swipes("employee") === 
unaliased("id"))).foreach {
+        case (name, joined) =>
+          checkLookupJoin(
+            joined.hint("external_lookup", name).select("employee", "door", 
"department"), name)
+      }
+      checkError(
+        exception = intercept[AnalysisException] {
+          swipes.join(aliased, swipes("employee") === 
$"r.id").hint("external_lookup", 1)
+        },
+        condition = "INVALID_EXTERNAL_LOOKUP_HINT.UNSUPPORTED_PARAMETER",
+        parameters = Map("parameter" -> "\"1\""))
+
+      withTempView("badge_swipes") {
+        swipes.createOrReplaceTempView("badge_swipes")
+        Seq(
+          "'r'" -> s"$catalogTable r ON s.employee = r.id",
+          "'ns.dual'" -> s"$catalogTable ON s.employee = dual.id").foreach { 
case (name, join) =>
+          checkLookupJoin(
+            sql(s"SELECT /*+ EXTERNAL_LOOKUP($name) */ employee, door, 
department " +
+              s"FROM badge_swipes s JOIN $join"),
+            name)
+        }
+      }
+    }
+  }
+
+  test("with hints disabled, only a lookup-only table runs as an external 
lookup join") {
+    val swipes = streamOf(Seq((1, "lobby"), (3, "garage")).toDF("employee", 
"door"))
+    val expected = Seq(Row(1, "lobby", 1, "engineering"), Row(1, "lobby", 1, 
"research"))
+    withSQLConf(SQLConf.DISABLE_HINTS.key -> "true") {
+      // The hint is removed with the others, so the table that also supports 
batch reads keeps an
+      // ordinary join.
+      val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+        .hint("external_lookup")
+      val ordinary = runStream(swipes.join(dual, swipes("employee") === 
dual("id")))
+      assert(ordinary.plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]) 
=== false)
+      QueryTest.sameRows(expected, ordinary.rows).foreach(fail(_))
+      assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+
+      val lookupOnly = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+      val lookupJoin = runStream(swipes.join(lookupOnly, swipes("employee") 
=== lookupOnly("id")))
+      
assert(lookupJoin.plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+      QueryTest.sameRows(expected, lookupJoin.rows).foreach(fail(_))
+    }
+  }
+
+  test("a lookup side that reads a metadata column of the table is rejected") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      val table = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.versioned"
+      withTempView("badge_swipes") {
+        streamOf(Seq((1, "lobby"), (3, "garage")).toDF("employee", "door"))
+          .createOrReplaceTempView("badge_swipes")
+        val dataColumns =
+          sql(s"SELECT s.door, r.department FROM badge_swipes s JOIN $table r 
ON s.employee = r.id")
+        checkStream(dataColumns, Seq(Row("lobby", "engineering"), Row("lobby", 
"research")))
+        Seq(
+          s"SELECT s.door, r._version FROM badge_swipes s JOIN $table r ON 
s.employee = r.id",
+          s"""SELECT s.door FROM badge_swipes s JOIN $table r
+             |  ON s.employee = r.id AND r._version > 
0""".stripMargin).foreach { query =>
+          checkError(
+            exception = intercept[AnalysisException](sql(query)),
+            condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.METADATA_COLUMN",
+            parameters = Map("relation" -> "`VersionedExternalLookupTable`"))
+        }
+      }
+    }
+  }
+
+  test("a lookup side read through a WITH clause runs as an external lookup 
join") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      withTempView("badge_swipes") {
+        streamOf(Seq((1, "lobby"), (3, "garage")).toDF("employee", "door"))
+          .createOrReplaceTempView("badge_swipes")
+        val expected = Seq(Row(1, "lobby", "engineering"), Row(1, "lobby", 
"research"))
+        def query(table: String, hint: String = "", joinType: String = 
"JOIN"): DataFrame = sql(
+          s"""
+            |WITH lk AS (TABLE $EXTERNAL_LOOKUP_CATALOG_NAME.ns.$table)
+            |SELECT $hint s.employee, s.door, lk.department
+            |FROM badge_swipes s $joinType lk ON s.employee = lk.id
+            |""".stripMargin)
+        def usesLookup(df: DataFrame): Boolean =
+          runStream(df).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])
+
+        Seq(query("lookup"), query("dual", hint = "/*+ EXTERNAL_LOOKUP(lk) 
*/")).foreach { df =>
+          assert(usesLookup(df))
+          checkStream(df, expected)
+        }
+        val ordinary = query("dual")
+        assert(usesLookup(ordinary) === false)
+        checkStream(ordinary, expected)
+
+        val fullOuter =
+          intercept[AnalysisException](query("lookup", joinType = "FULL OUTER 
JOIN"))
+        assert(fullOuter.getCondition === 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE")
+        assert(fullOuter.getMessageParameters.asScala.toMap === Map(
+          "joinType" -> "FULL OUTER",
+          "relation" -> "`SimpleExternalLookupTable`",
+          "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES))
+      }
+    }
+  }
+
+  test("a WITH-clause lookup side that two lookup joins read") {
+    // The second reference to the CTE gets new attributes, so it is inlined 
under a projection to
+    // them, which a lookup side may have.
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      withTempView("badge_swipes") {
+        streamOf(Seq((1, 2), (3, 1)).toDF("employee", "escort"))
+          .createOrReplaceTempView("badge_swipes")
+        val run = runStream(sql(
+          s"""
+            |WITH lk AS (TABLE $EXTERNAL_LOOKUP_CATALOG_NAME.ns.lookup)
+            |SELECT s.employee, e.department, x.department
+            |FROM badge_swipes s JOIN lk e ON s.employee = e.id JOIN lk x ON 
s.escort = x.id
+            |""".stripMargin))
+        assert(run.plan.collect { case join: PreparedExternalLookupJoin => 
join }.size === 2)
+        QueryTest.sameRows(
+          Seq(Row(1, "engineering", "sales"), Row(1, "research", "sales")),
+          run.rows).foreach(fail(_))
+      }
+    }
+  }
+
+  test("cached data does not replace the lookup side of an external lookup 
join") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      val dualTable = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.dual"
+      val swipes = streamOf(Seq((1, "lobby"), (3, "garage")).toDF("employee", 
"door"))
+      val cachedRows = Seq(Row(1, "engineering"), Row(1, "research"))
+      val currentRows = Seq(Row(1, "legal"))
+      def join(directory: DataFrame): DataFrame =
+        swipes.join(directory, swipes("employee") === directory("id"))
+          .select(swipes("employee"), directory("department"))
+      def checkRun(df: DataFrame, lookupJoin: Boolean, expected: Seq[Row]): 
Unit = {
+        val run = runStream(df)
+        assert(run.plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]) === 
lookupJoin)
+        QueryTest.sameRows(expected, run.rows).foreach(fail(_))
+      }
+      // Changes the directory after the cache has read it.
+      def moveEmployeeToLegal(): Unit = 
SimpleExternalLookupDataSource.departmentsById.set(
+        Map(1 -> Seq("legal"), 2 -> Seq("sales")))
+
+      // A table that is cached, then hinted.
+      val dual = spark.table(dualTable).cache()
+      try {
+        assert(dual.count() === 3)
+        moveEmployeeToLegal()
+        checkRun(join(spark.table(dualTable)), lookupJoin = false, cachedRows)
+        checkRun(join(spark.table(dualTable).hint("external_lookup")), 
lookupJoin = true,
+          currentRows)
+        withTempView("badge_swipes") {
+          swipes.createOrReplaceTempView("badge_swipes")
+          checkRun(
+            sql(
+              s"""
+                |WITH lk AS (TABLE $dualTable)
+                |SELECT /*+ EXTERNAL_LOOKUP(lk) */ s.employee, lk.department
+                |FROM badge_swipes s JOIN lk ON s.employee = lk.id
+                |""".stripMargin),
+            lookupJoin = true,
+            currentRows)
+        }
+      } finally {
+        dual.unpersist(blocking = true)
+      }
+
+      // A hinted DataFrame that is cached.
+      SimpleExternalLookupDataSource.resetCounters()
+      val hinted = spark.table(dualTable).hint("external_lookup").cache()
+      try {
+        assert(hinted.count() === 3)
+        moveEmployeeToLegal()
+        checkRun(join(hinted), lookupJoin = true, currentRows)
+      } finally {
+        hinted.unpersist(blocking = true)
+      }
+
+      // A lookup-only table cannot be cached, as caching reads it with a 
batch scan.
+      val lookupOnly = spark.table(s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.lookup")
+      checkError(
+        exception = intercept[AnalysisException] { lookupOnly.cache() },
+        condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+        parameters = Map(
+          "tableName" -> "`SimpleExternalLookupTable`",
+          "operation" -> "batch scan"))
+      
assert(spark.sharedState.cacheManager.lookupCachedData(lookupOnly).isEmpty)
+      checkRun(join(lookupOnly), lookupJoin = true, currentRows)
+    }
+  }
+
+  test("a common expression in the join condition is evaluated in the lookup 
join") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq((1, "b"), (2, "c")).toDF("id", "code"))
+    val sameId = left("id") === lookup("id")
+    // BETWEEN evaluates its input once, and upper() is not cheap enough to 
repeat, so it would
+    // otherwise be computed in a projection below the join: over the lookup 
side, or the stream.
+    Seq(
+      expr("upper(department) BETWEEN 'F' AND 'Z'") ->
+        Seq(Row(1, "b", 1, "research"), Row(2, "c", 2, "sales")),
+      expr("upper(code) BETWEEN 'A' AND 'B'") ->
+        Seq(Row(1, "b", 1, "engineering"), Row(1, "b", 1, 
"research"))).foreach {
+      case (between, expected) =>
+        val run = runStream(left.join(lookup, sameId && between))
+        assert(run.plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+        QueryTest.sameRows(expected, run.rows).foreach(fail(_))
+    }
+  }
+
+  test("a subquery in the join condition of a lookup join is rejected") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq((1, 1)).toDF("id", "x"))
+    val values = Seq(1).toDF("v")
+    val sameId = left("id") === lookup("id")
+    // The optimizer rewrites such subqueries only in a Join, so they fail 
when the DataFrame is
+    // built, whether they read the stream side, the lookup side or neither. 
The scalar subquery
+    // references neither side, so it could be offered as a parameter.
+    Seq(
+      sameId && left("x").isin(values),
+      sameId && values.where(col("v") === 1).exists(),
+      lookup("id") === values.scalar(),
+      sameId && lookup("id").isin(values)).foreach { condition =>
+      checkError(
+        exception = intercept[AnalysisException](left.join(lookup, condition)),
+        condition = 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.SUBQUERY_IN_JOIN_CONDITION",
+        parameters = Map("relation" -> "`SimpleExternalLookupTable`"))
+    }
+  }
+
+  test("a SQL subquery over lookup columns in the join condition of a lookup 
join is rejected") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      withTempView("events", "codes") {
+        streamOf(Seq(1).toDF("id")).createOrReplaceTempView("events")
+        Seq(1).toDF("code").createOrReplaceTempView("codes")
+        // A correlated subquery cannot be written in a Dataset join 
condition, but can in SQL.
+        Seq(
+          "EXISTS (SELECT 1 FROM codes WHERE codes.code = l.id)",
+          "l.id IN (SELECT code FROM codes)").foreach { subquery =>
+          checkError(
+            exception = intercept[AnalysisException] {
+              sql(s"SELECT * FROM events e JOIN 
$EXTERNAL_LOOKUP_CATALOG_NAME.ns.lookup l " +
+                s"ON e.id = l.id AND $subquery")
+            },
+            condition = 
"EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.SUBQUERY_IN_JOIN_CONDITION",
+            parameters = Map("relation" -> "`SimpleExternalLookupTable`"))
+        }
+      }
+    }
+  }
+
+  test("Dataset join APIs that analyze a join plan lookup joins or fail with a 
named error") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq((1, 2)).toDF("sender", "receiver"))
+
+    val typed = left.joinWith(lookup, left("sender") === lookup("id"))
+    val typedRun = runStream(typed.toDF())
+    assert(typedRun.plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]))
+    QueryTest.sameRows(
+      Seq(Row(Row(1, 2), Row(1, "engineering")), Row(Row(1, 2), Row(1, 
"research"))),
+      typedRun.rows).foreach(fail(_))
+
+    // A lookup DataFrame reused in a second join is ambiguous, as any other 
DataFrame is.
+    def reusedJoinError(right: DataFrame): AnalysisException = 
intercept[AnalysisException] {
+      val enriched = left.join(right, left("sender") === right("id"))
+      enriched.join(right, enriched("receiver") === right("id"))
+    }
+    val ordinary = Seq((1, "engineering")).toDF("id", "department")
+    Seq("true", "false").foreach { autoResolve =>
+      withSQLConf(SQLConf.DATAFRAME_SELF_JOIN_AUTO_RESOLVE_AMBIGUITY.key -> 
autoResolve) {
+        val error = reusedJoinError(lookup)
+        assert(error.getCondition === reusedJoinError(ordinary).getCondition)
+        assert(error.getMessage.contains("ambiguous"), error)
+      }
+    }
+    // Loaded twice, the table enriches the stream with two lookup joins.
+    val receivers = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val enriched = left.join(lookup, left("sender") === lookup("id"))
+    val twice = enriched.join(receivers, enriched("receiver") === 
receivers("id"))
+    val twiceRun = runStream(twice)
+    assert(twiceRun.plan.collect { case join: PreparedExternalLookupJoin => 
join }.size === 2)
+    QueryTest.sameRows(
+      Seq(Row(1, 2, 1, "engineering", 2, "sales"), Row(1, 2, 1, "research", 2, 
"sales")),
+      twiceRun.rows).foreach(fail(_))
+
+    // An AS OF join reads the lookup-only table outside a lookup join.
+    checkError(
+      exception = 
streamFailure[AnalysisException](left.asInstanceOf[Dataset[Row]].joinAsOf(
+        lookup, left("sender"), lookup("id"), left("sender") === lookup("id"), 
"inner",
+        tolerance = null, allowExactMatches = true, direction = "backward")),
+      condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+      parameters = Map(
+        "tableName" -> "`SimpleExternalLookupTable`",
+        "operation" -> "batch scan"))
+
+    // A condition that is not boolean fails as for any other join.
+    val notBoolean = intercept[AnalysisException] {
+      left.join(lookup, left("sender") + lookup("id"))
+    }
+    assert(notBoolean.getCondition === "JOIN_CONDITION_IS_NOT_BOOLEAN_TYPE")
+  }
+
+  test("a catalog-resolved external lookup-only table cannot be read outside a 
lookup join") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      val table = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.lookup"
+      val left = Seq(1).toDF("id")
+      Seq[() => DataFrame](
+        () => spark.table(table),
+        () => sql(s"SELECT * FROM $table WHERE id = 1")).foreach {
+        df =>
+          checkError(
+            exception = intercept[AnalysisException] { 
df().queryExecution.optimizedPlan },
+            condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+            parameters = Map(
+              "tableName" -> "`SimpleExternalLookupTable`",
+              "operation" -> "batch scan"))
+      }
+    }
+  }
+
+  test("a command that reads a lookup-only table outside a lookup join fails 
before it writes") {
+    withSQLConf(
+        "spark.sql.catalog.testcat" -> classOf[InMemoryTableCatalog].getName,
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+      val catalogLookup = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.lookup"
+      def checkBatchScanError(write: () => Any): Unit = checkError(
+        exception = intercept[AnalysisException](write()),
+        condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+        parameters = Map(
+          "tableName" -> "`SimpleExternalLookupTable`",
+          "operation" -> "batch scan"))
+
+      // Each write would replace the archived assignment that its target 
holds.
+      withTable("testcat.ns.target", "v1_target") {
+        sql("CREATE TABLE testcat.ns.target (id INT, department STRING)")
+        sql("INSERT INTO testcat.ns.target VALUES (7, 'archive')")
+        sql("CREATE TABLE v1_target (id INT, department STRING) USING parquet")
+        sql("INSERT INTO v1_target VALUES (7, 'archive')")
+        Seq[(String, () => Any)](
+          "testcat.ns.target" ->
+            (() => 
lookup.write.mode("overwrite").saveAsTable("testcat.ns.target")),
+          "testcat.ns.target" -> (() => 
lookup.writeTo("testcat.ns.target").replace()),
+          "testcat.ns.target" -> (() =>
+            sql(s"REPLACE TABLE testcat.ns.target USING foo AS SELECT * FROM 
$catalogLookup")),
+          "testcat.ns.target" ->
+            (() => sql(s"INSERT OVERWRITE testcat.ns.target SELECT * FROM 
$catalogLookup")),
+          "v1_target" -> (() => 
lookup.write.mode("overwrite").saveAsTable("v1_target")),
+          "v1_target" -> (() => 
lookup.write.mode("overwrite").insertInto("v1_target")),
+          // A subquery of the query reads it.
+          "v1_target" -> (() => sql(
+            "INSERT OVERWRITE v1_target SELECT id, 'none' FROM VALUES (8) AS 
t(id) " +
+              s"WHERE id NOT IN (SELECT id FROM $catalogLookup)"))).foreach {
+          case (target, write) =>
+            checkBatchScanError(write)
+            checkAnswer(spark.table(target), Row(7, "archive"))
+        }
+      }
+
+      // V1 commands that hold their query outside their children.
+      RecordingV1WriteSource.writes.clear()
+      withTempView("recording_sink") {
+        sql("CREATE TEMPORARY VIEW recording_sink (id INT, department STRING) 
" +
+          s"USING ${classOf[RecordingV1WriteSource].getName}")
+        checkBatchScanError(() =>
+          
lookup.write.mode("overwrite").format(classOf[RecordingV1WriteSource].getName).save())
+        checkBatchScanError(() =>
+          sql(s"INSERT OVERWRITE TABLE recording_sink SELECT * FROM 
$catalogLookup"))
+      }
+      assert(RecordingV1WriteSource.writes.isEmpty)
+    }
+  }
+
+  test("a command reads a lookup-only table only through a lookup join, and a 
view not at all") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    def save(query: DataFrame): LogicalPlan = SaveIntoDataSourceCommand(
+      query.queryExecution.analyzed, new RecordingV1WriteSource, Map.empty, 
SaveMode.Overwrite)
+    TableCapabilityCheck(save(left.join(lookup, left("id") === lookup("id"))))
+    // A join of a command, which is analyzed in full, cannot gain a condition 
later.
+    checkError(
+      exception = 
intercept[AnalysisException](TableCapabilityCheck(save(left.join(lookup)))),
+      condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.MISSING_JOIN_CONDITION",
+      parameters = Map.empty)
+
+    withTempView("lookup_view", "enriched_view") {
+      lookup.createOrReplaceTempView("lookup_view")
+      left.join(lookup, left("id") === 
lookup("id")).createOrReplaceTempView("enriched_view")
+      checkStream(
+        spark.table("enriched_view"), Seq(Row(1, 1, "engineering"), Row(1, 1, 
"research")))
+      checkError(
+        exception = intercept[AnalysisException] {
+          spark.table("lookup_view").queryExecution.optimizedPlan
+        },
+        condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+        parameters = Map(
+          "tableName" -> "`SimpleExternalLookupTable`",
+          "operation" -> "batch scan"))
+    }
+  }
+
+  test("foreachBatch writes the micro-batches of a lookup join with batch 
commands") {
+    withSQLConf("spark.sql.catalog.testcat" -> 
classOf[InMemoryTableCatalog].getName) {
+      withTempPath { path =>
+        withTable("enriched_events") {
+          val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+          val events = streamOf(Seq(1, 2, 3).toDF("id"))
+          val enriched = events.join(lookup, events("id") === lookup("id"))
+            .select(events("id"), lookup("department"))
+          val v2Rows = new AtomicReference(Seq.empty[Row])
+          // Each micro-batch reaches the function as a plan that is already 
planned, so the batch
+          // commands over it read no lookup-only table.
+          val query = enriched.writeStream.foreachBatch { (batch: DataFrame, 
_: Long) =>
+            
batch.write.format("parquet").mode("append").save(path.getCanonicalPath)
+            batch.write.mode("append").saveAsTable("enriched_events")
+            // The function runs in the query's session, which has its own 
instance of the test
+            // catalog, so the V2 table is created and read there.
+            val session = batch.sparkSession
+            session.sql(
+              "CREATE TABLE IF NOT EXISTS testcat.ns.enriched_events (id INT, 
department STRING)")
+            batch.writeTo("testcat.ns.enriched_events").append()
+            
v2Rows.set(session.table("testcat.ns.enriched_events").collect().toSeq)
+          }.start()
+          try query.processAllAvailable() finally query.stop()
+          val expected = Seq(Row(1, "engineering"), Row(1, "research"), Row(2, 
"sales"))
+          checkAnswer(spark.read.parquet(path.getCanonicalPath), expected)
+          checkAnswer(spark.table("enriched_events"), expected)
+          QueryTest.sameRows(expected, v2Rows.get()).foreach(fail(_))
+          // Each write computes the micro-batch again, as batchDF is not 
persisted.
+          assert(SimpleExternalLookupDataSource.requestCount.get() === 3)
+        }
+      }
+    }
+  }
+
+  test("view definitions over a lookup-only table, in either view catalog, are 
not reads") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName,
+        "spark.sql.catalog.view_only" -> 
classOf[TestingViewOnlyCatalog].getName) {
+      val lookupTable = s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.lookup"
+      // ALTER VIEW of a session view, and CREATE VIEW and ALTER VIEW in a V2 
view catalog.
+      withTempView("departments") {
+        sql("CREATE TEMPORARY VIEW departments AS SELECT 1 AS id, 'none' AS 
department")
+        sql(s"ALTER VIEW departments AS SELECT * FROM $lookupTable")
+        assert(spark.table("departments").queryExecution.analyzed.exists {
+          case relation: DataSourceV2Relation => relation.table eq 
SimpleExternalLookupTable
+          case _ => false
+        })
+      }
+      val catalog = spark.sessionState.catalogManager.catalog("view_only")
+        .asInstanceOf[TestingViewOnlyCatalog]
+      sql(s"CREATE VIEW view_only.default.departments AS SELECT * FROM 
$lookupTable")
+      sql(s"ALTER VIEW view_only.default.pure_v AS SELECT * FROM $lookupTable")
+      Seq("departments", "pure_v").foreach { name =>
+        assert(catalog.loadView(Identifier.of(Array("default"), 
name)).queryText() ===
+          s"SELECT * FROM $lookupTable")
+      }
+    }
+  }
+
+  test("a stream-only Python UDF in a lookup join's residual or lookup 
parameter") {
+    assume(shouldTestPythonUDFs)
+    // The UDF returns its input, so each join has the same rows as the one 
with the column itself.
+    val pythonUDF = TestPythonUDF("stream_key")
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq((1, 1), (2, -1), (3, 1)).toDF("id", "shift"))
+    Seq[(Column => Column, String)](
+      (key => left("id") === lookup("id") && key > 0, "residual"),
+      (key => lookup("id") === key + left("id") - left("shift"), 
"parameter")).foreach {
+      case (condition, place) =>
+        Seq("inner", "left_outer").foreach { joinType =>
+          val withUDF = runStream(left.join(lookup, 
condition(pythonUDF(left("shift"))), joinType))
+          
assert(withUDF.plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]), place)
+          val builtIn = runStream(left.join(lookup, condition(left("shift")), 
joinType))
+          QueryTest.sameRows(builtIn.rows, withUDF.rows).foreach(error => 
fail(s"$place: $error"))
+        }
+    }
+  }
+
+  test("a table that also supports batch read is read as a batch scan outside 
a lookup join") {
+    withSQLConf(
+        s"spark.sql.catalog.$EXTERNAL_LOOKUP_CATALOG_NAME" ->
+          classOf[ExternalLookupTestCatalog].getName) {
+      Seq[() => DataFrame](
+        () => 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load(),
+        () => spark.table(s"$EXTERNAL_LOOKUP_CATALOG_NAME.ns.dual")).foreach { 
dual =>
+        val df = dual()
+        
assert(df.queryExecution.analyzed.exists(_.isInstanceOf[ExternalLookupRelation])
 === false)
+        checkAnswer(df, Seq(Row(1, "engineering"), Row(1, "research"), Row(2, 
"sales")))
+      }
+      assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+    }
+  }
+
+  test("a provider with a V1 read path cannot serve a lookup-only table") {
+    Seq(
+      classOf[RelationProviderExternalLookupDataSource],
+      classOf[SchemaRelationProviderExternalLookupDataSource],
+      classOf[FileFormatExternalLookupDataSource],
+      classOf[FileDataSourceV2ExternalLookupDataSource]).foreach { provider =>
+      val parameters = Map("table" -> "`SimpleExternalLookupTable`", 
"provider" -> provider.getName)
+      checkError(
+        exception = 
intercept[AnalysisException](spark.read.format(provider.getName).load()),
+        condition = 
"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.LOOKUP_ONLY_TABLE_WITH_V1_READ",
+        parameters = parameters)
+      withTempView("hybrid_view") {
+        checkError(
+          exception = intercept[AnalysisException] {
+            sql(s"CREATE TEMPORARY VIEW hybrid_view USING ${provider.getName}")
+          },
+          condition = 
"DATA_SOURCE_INVALID_EXTERNAL_LOOKUP.LOOKUP_ONLY_TABLE_WITH_V1_READ",
+          parameters = parameters)
+      }
+    }
+
+    // A provider without a V1 read path loads the table through both.
+    val provider = classOf[SimpleExternalLookupDataSource].getName
+    def readsLookupOnlyTable(df: DataFrame): Boolean =
+      df.queryExecution.analyzed.exists(_.isInstanceOf[ExternalLookupRelation])
+    assert(readsLookupOnlyTable(spark.read.format(provider).load()))
+    withTempView("lookup_view") {
+      sql(s"CREATE TEMPORARY VIEW lookup_view USING $provider")
+      assert(readsLookupOnlyTable(spark.table("lookup_view")))
+    }
+  }
+
+  test("external lookup join applies lookup-side projection and filter before 
joining") {
+    val rawLookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val lookup = rawLookup
+      .filter($"department" =!= "research")
+      .select($"id", upper($"department").as("department"))
+    val left = streamOf(Seq(1, 2).toDF("id"))
+
+    checkStream(
+      left.join(lookup, left("id") === lookup("id"), "inner"),
+      Seq(Row(1, 1, "ENGINEERING"), Row(2, 2, "SALES")))
+  }
+
+  test("external lookup rebinds projections after required-column pruning") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 2).toDF("id"))
+
+    val result = left.join(
+      lookup, left("id") === lookup("id"), "inner")
+      .select(upper(lookup("department")))
+
+    checkStream(result, Seq(Row("ENGINEERING"), Row("RESEARCH"), Row("SALES")))
+  }
+
+  test("external lookup join resolves a projected key alias") {
+    val rawLookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val lookup = rawLookup.select($"id".as("lookup_id"), $"department")
+    val left = streamOf(Seq(1, 3).toDF("id"))
+
+    checkStream(
+      left.join(
+        lookup, left("id") === lookup("lookup_id"), "left_outer"),
+      Seq(Row(1, 1, "engineering"), Row(1, 1, "research"), Row(3, null, null)))
+  }
+
+  test("external lookup join composes nested aliases and filters") {
+    val rawLookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val once = rawLookup.select($"id".as("lookup_id"), $"department")
+    val lookup = once.filter($"lookup_id" > 0).select($"lookup_id", 
$"department")
+    val left = streamOf(Seq(1, 3).toDF("id"))
+
+    checkStream(
+      left.join(
+        lookup, left("id") === lookup("lookup_id"), "left_outer"),
+      Seq(Row(1, 1, "engineering"), Row(1, 1, "research"), Row(3, null, null)))
+  }
+
+  test("an external lookup hint without relation names marks the whole query") 
{
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val dual = 
spark.read.format(classOf[DualCapabilityExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1).toDF("id"))
+    val expected = Seq(Row(1, "engineering"), Row(1, "research"))
+
+    // As with a join strategy hint, the hint applies to the plan it 
annotates, here the join
+    // itself rather than its lookup side, so it is ignored. A lookup-only 
table still needs no
+    // hint.
+    withTempView("external_lookup_left", "external_lookup_right", 
"external_lookup_dual") {
+      left.createOrReplaceTempView("external_lookup_left")
+      lookup.createOrReplaceTempView("external_lookup_right")
+      dual.createOrReplaceTempView("external_lookup_dual")
+      Seq("external_lookup_right" -> true, "external_lookup_dual" -> 
false).foreach {
+        case (right, usesLookup) =>
+          val df = sql(s"""
+            |SELECT /*+ EXTERNAL_LOOKUP */ l.id, r.department
+            |FROM external_lookup_left l JOIN $right r ON l.id = r.id
+            |""".stripMargin)
+          
assert(runStream(df).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin]) ===
+            usesLookup, right)
+          checkStream(df, expected)
+      }
+    }
+    val dataFrameJoin = left.join(dual, left("id") === 
dual("id")).hint("external_lookup")
+    assert(
+      
runStream(dataFrameJoin).plan.exists(_.isInstanceOf[PreparedExternalLookupJoin])
 === false)
+  }
+
+  test("SQL external lookup hint accepts cache options") {
+    SimpleExternalLookupDataSource.resetCounters()
+    val lookup = spark.read
+      .format(classOf[SimpleExternalLookupDataSource].getName)
+      .option("maxBatchSize", "1")
+      .load()
+    val left = streamOf(Seq(1, 2).toDF("id"))
+
+    withTempView("external_lookup_left", "external_lookup_right") {
+      left.createOrReplaceTempView("external_lookup_left")
+      lookup.createOrReplaceTempView("external_lookup_right")
+      val query = sql("""
+          |SELECT /*+ EXTERNAL_LOOKUP(
+          |  r,
+          |  'cache_enabled=false',
+          |  'cache_max_entries=123',
+          |  'cache_ttl=2s',
+          |  'cache_max_rows_per_key=5'
+          |) */ l.id, r.department
+          |FROM external_lookup_left l JOIN external_lookup_right r ON l.id = 
r.id
+          |""".stripMargin)
+      val run = runStream(query)
+      assert(QueryTest.sameRows(
+        Seq(Row(1, "engineering"), Row(1, "research"), Row(2, "sales")), 
run.rows).isEmpty)
+      val prepared = run.plan.collectFirst {
+        case externalLookup: PreparedExternalLookupJoin => externalLookup
+      }.get
+      assert(prepared.cacheOptions === ExternalLookupCacheOptions(
+        enabled = false,
+        maxEntries = 123,
+        ttlMillis = 2000,
+        maxRowsPerKey = 5))
+    }
+    assert(SimpleExternalLookupDataSource.requestCount.get() > 0)
+  }
+
+  test("external lookup pushes accepted filters and required columns to the 
source") {
+    SimpleExternalLookupDataSource.resetCounters()
+    val rawLookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val lookup = rawLookup.filter($"department" =!= "research").select($"id")
+    val left = streamOf(Seq(1, 2).toDF("id"))
+
+    checkStream(
+      left.join(lookup, left("id") === lookup("id"), "inner"),
+      Seq(Row(1, 1), Row(2, 2)))
+    // Spark evaluates the accepted filter again on the returned rows, so it 
asks for the column
+    // that the filter reads.
+    assert(SimpleExternalLookupDataSource.requiredColumns.get() === Seq("id", 
"department"))
+    assert(SimpleExternalLookupDataSource.pushedPredicateCount.get() > 0)
+  }
+
+  test("external lookup applies a pushed filter that the source accepts but 
does not apply") {
+    SimpleExternalLookupDataSource.resetCounters()
+    val lookup = spark.read
+      .format(classOf[SimpleExternalLookupDataSource].getName)
+      .option("ignoreAcceptedFilters", "true")
+      .load()
+      .filter($"department" =!= "research")
+    val left = streamOf(Seq(1, 2).toDF("id"))
+
+    checkStream(
+      left.join(lookup, left("id") === lookup("id"), "inner"),
+      Seq(Row(1, 1, "engineering"), Row(2, 2, "sales")))
+    assert(SimpleExternalLookupDataSource.pushedPredicateCount.get() > 0)
+  }
+
+  test("external lookup canonicalizes filters through a relation alias") {
+    SimpleExternalLookupDataSource.resetCounters()
+    val rawLookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+      .alias("lookup_source")
+    val lookup = rawLookup
+      .filter($"lookup_source.DEPARTMENT" =!= "research")
+      .select($"lookup_source.id")
+    val left = streamOf(Seq(1, 2).toDF("id"))
+
+    checkStream(
+      left.join(lookup, left("id") === lookup("id"), "inner"),
+      Seq(Row(1, 1), Row(2, 2)))
+    assert(SimpleExternalLookupDataSource.pushedPredicateFields.get() === 
Seq("department"))
+  }
+
+  test("an empty lookup side gives semi and anti join results without a 
connector call") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 3).toDF("id"))
+    val empty = lookup.where(lit(false))
+    Seq(
+      ("left_semi", Seq.empty[Row]),
+      ("left_anti", Seq(Row(1), Row(3)))).foreach { case (joinType, expected) 
=>
+      Seq(
+        () => left.join(empty, left("id") === empty("id"), joinType),
+        () => left.join(lookup, left("id") === lookup("id") && lit(false), 
joinType)).foreach {
+        query =>
+          SimpleExternalLookupDataSource.resetCounters()
+          val joined = query()
+          checkStream(joined, expected)
+          assert(SimpleExternalLookupDataSource.lookupCandidates.get() === 
Seq.empty)
+          assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+          assert(SimpleExternalLookupDataSource.requestCount.get() === 0)
+      }
+    }
+  }
+
+  test("lookup-side stages evaluate withField and dropFields values of a 
struct column") {
+    val lookup = readSchemaLookup("struct")
+    val left = streamOf(Seq(1, 2).toDF("id"))
+    // Whole-struct values, which the optimizer lowers only after the 
lookup-side stages are built.
+    val upgraded = lookup
+      .where($"info".dropFields("seats") === struct(lit("pro").as("plan")))
+      .select($"id", $"info".withField("seats", $"info.seats" + 1).as("info"))
+    val run = runStream(left.join(upgraded, left("id") === upgraded("id")))
+    QueryTest.sameRows(Seq(Row(1, 1, Row("pro", 11))), 
run.rows).foreach(fail(_))
+    assert(run.lookupJoin.lookupTransforms.nonEmpty)
+  }
+
+  test("external lookup pads CHAR columns as a batch read does") {
+    val lookup = spark.read
+      .format(classOf[ReadSchemaExternalLookupDataSource].getName)
+      .option("kind", "char")
+      .load()
+    val left = streamOf(Seq(1).toDF("id"))
+    // The connector returns "ab" for a CHAR(5) column; read-side padding 
makes it "ab   ".
+    checkStream(left.join(lookup, left("id") === lookup("id")), Seq(Row(1, 1, 
"ab   ")))
+  }
+
+  test("external lookup join supports left semi and left anti joins") {
+    SimpleExternalLookupDataSource.resetCounters()
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 2, 3).toDF("id"))
+
+    checkStream(
+      left.join(lookup, left("id") === lookup("id"), "left_semi"),
+      Seq(Row(1), Row(2)))
+    assert(SimpleExternalLookupDataSource.requiredColumns.get() === Seq("id"))
+    checkStream(
+      left.join(lookup, left("id") === lookup("id"), "left_anti"),
+      Seq(Row(3)))
+  }
+
+  test("semi and anti joins stop evaluating a stream row's residual at its 
first match") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 3).toDF("id"))
+    // Id 1 has two departments, returned in this order: engineering, then 
research. The residual
+    // would fail on research, so it must not be evaluated once engineering 
has matched.
+    val residual = when(lookup("department") === "research", 
raise_error(lit("evaluated")))
+      .otherwise(left("id") > 0)
+
+    Seq("left_semi" -> Seq(Row(1)), "left_anti" -> Seq(Row(3))).foreach {
+      case (joinType, expected) =>
+        SimpleExternalLookupDataSource.resetCounters()
+        checkStream(left.join(lookup, left("id") === lookup("id") && residual, 
joinType), expected)
+        // The cursor is still read to the end.
+        assert(SimpleExternalLookupDataSource.resultRowsRead.get() === 2)
+    }
+  }
+
+  test("external lookup reads only the key when no lookup column is read above 
the join") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq(1, 3).toDF("id"))
+
+    Seq("inner", "left_outer").foreach { joinType =>
+      SimpleExternalLookupDataSource.resetCounters()
+      val result = left.join(
+        lookup, left("id") === lookup("id"), joinType)
+        .select(left("id"))
+      val expected = if (joinType == "inner") Seq(Row(1), Row(1)) else {
+        Seq(Row(1), Row(1), Row(3))
+      }
+      checkStream(result, expected)
+      // Spark reads the key to check it on every returned row.
+      assert(SimpleExternalLookupDataSource.requiredColumns.get() === 
Seq("id"))
+    }
+  }
+
+  test("external lookup evaluates semi and anti residuals on the pruned 
response layout") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val claims = streamOf(Seq((1, "engineering"), (1, "missing"), (3, 
"missing"))
+      .toDF("id", "costCenter"))
+    val condition = claims("id") === lookup("id") &&
+      claims("costCenter") === lookup("department")
+
+    SimpleExternalLookupDataSource.resetCounters()
+    checkStream(
+      claims.join(lookup, condition, "left_semi"),
+      Seq(Row(1, "engineering")))
+    assert(SimpleExternalLookupDataSource.requiredColumns.get() === Seq("id", 
"department"))
+
+    SimpleExternalLookupDataSource.resetCounters()
+    checkStream(
+      claims.join(lookup, condition, "left_anti"),
+      Seq(Row(1, "missing"), Row(3, "missing")))
+    assert(SimpleExternalLookupDataSource.requiredColumns.get() === Seq("id", 
"department"))
+  }
+
+  test("external lookup join handles null, missing, duplicate, and partial 
batches") {
+    val lookup = spark.read
+      .format(classOf[SimpleExternalLookupDataSource].getName)
+      .option("maxBatchSize", "3")
+      .load()
+      .hint("external_lookup", "cache_enabled=false")
+    val left = streamOf(Seq[java.lang.Integer](1, 1, null, 3, 2).toDF("id"))
+
+    val run = runStream(left.join(lookup, left("id") === lookup("id"), 
"left_outer"))
+    val rows = run.rows
+    assert(rows.toSet === Set(
+      Row(1, 1, "engineering"),
+      Row(1, 1, "research"),
+      Row(null, null, null),
+      Row(3, null, null),
+      Row(2, 2, "sales")))
+    assert(rows.count(_.get(0) == 1) === 4)
+    assert(SimpleExternalLookupDataSource.requestSizes.asScala.toSeq === 
Seq(1, 2))
+    assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === 
Seq(1, 3, 2))
+    assert(SimpleExternalLookupDataSource.nullKeyRequests.get() === 0)
+    // Two batches, [1, 1, null] and [3, 2], send their 1 + 2 distinct 
requestable keys.
+    val metrics = run.lookupJoin.metrics
+    assert(Seq("numInputRows", "numInputBatches", "numLookupRequests", 
"numLookupParameterRows",
+      "numOutputRows").map(metrics(_).value) === Seq(5, 2, 2, 3, 7))
+    assert(metrics("lookupTime").value > 0)
+  }
+
+  test("external lookup join supports null-safe lookup keys") {
+    SimpleExternalLookupDataSource.resetCounters()
+    val lookup = spark.read
+      .format(classOf[SimpleExternalLookupDataSource].getName)
+      .load()
+    val left = streamOf(Seq[java.lang.Integer](1, null, 3).toDF("id"))
+
+    checkStream(
+      left.join(lookup, left("id") <=> lookup("id"), "left_outer"),
+      Seq(
+        Row(1, 1, "engineering"),
+        Row(1, 1, "research"),
+        Row(null, null, "unknown"),
+        Row(3, null, null)))
+    assert(SimpleExternalLookupDataSource.nullKeyRequests.get() > 0)
+  }
+
+  test("external lookup join supports complete composite equi-keys") {
+    val lookup = spark.read
+      .format(classOf[CompositeExternalLookupDataSource].getName)
+      .load()
+    val left = streamOf(Seq((1, 1), (1, 2), (2, 1)).toDF("tenant", "id"))
+
+    checkStream(
+      left.join(
+        lookup,
+        left("tenant") === lookup("tenant") && left("id") === lookup("id"),
+        "left_outer"),
+      Seq(Row(1, 1, 1, 1, "one-one"), Row(1, 2, null, null, null),
+        Row(2, 1, 2, 1, "two-one")))
+  }
+
+  test("external lookup combines equality and range predicates in one access 
path") {
+    CompositeExternalLookupDataSource.selectedLookupPredicates.set(Seq.empty)
+    val lookup = spark.read
+      .format(classOf[CompositeExternalLookupDataSource].getName)
+      .load()
+    // In tenant 1, the range from 0 covers the stored ids 1 and 3, so each of 
them joins two
+    // stream rows of the same tenant.
+    val left = streamOf(Seq(
+      (1, 1, 3),
+      (1, 0, 4),
+      (1, 2, 4),
+      (2, 0, 2),
+      (3, 0, 10)).toDF("tenant", "start", "end"))
+    val condition = lookup("tenant") === left("tenant") &&
+      lookup("id") >= left("start") &&
+      lookup("id") < left("end")
+
+    checkStream(
+      left.join(lookup, condition, "inner"),
+      Seq(
+        Row(1, 1, 3, 1, 1, "one-one"),
+        Row(1, 0, 4, 1, 1, "one-one"),
+        Row(1, 0, 4, 1, 3, "one-three"),
+        Row(1, 2, 4, 1, 3, "one-three"),
+        Row(2, 0, 2, 2, 1, "two-one")))
+    assert(CompositeExternalLookupDataSource.selectedLookupPredicates.get() 
=== Seq(
+      ("=", "tenant"),
+      (">=", "id"),
+      ("<", "id")))
+  }
+
+  test("external lookup join supports multiple range predicates on one field") 
{
+    SimpleExternalLookupDataSource.resetCounters()
+    val lookup = spark.read
+      .format(classOf[SimpleExternalLookupDataSource].getName)
+      .load()
+    val left = streamOf(Seq((1, 2), (1, 3)).toDF("start", "end"))
+
+    checkStream(
+      left.join(
+        lookup,
+        lookup("id") >= left("start") && lookup("id") < left("end"),
+        "inner"),
+      Seq(
+        Row(1, 2, 1, "engineering"),
+        Row(1, 2, 1, "research"),
+        Row(1, 3, 1, "engineering"),
+        Row(1, 3, 1, "research"),
+        Row(1, 3, 2, "sales")))
+    assert(SimpleExternalLookupDataSource.lookupCandidates.get() ===
+      Seq((">=", "id", IntegerType), ("<", "id", IntegerType)))
+
+    checkStream(
+      left.join(
+        lookup,
+        left("start") < lookup("id") && left("end") >= lookup("id"),
+        "inner"),
+      Seq(
+        Row(1, 2, 2, "sales"),
+        Row(1, 3, 2, "sales")))
+    assert(SimpleExternalLookupDataSource.lookupCandidates.get() ===
+      Seq((">", "id", IntegerType), ("<=", "id", IntegerType)))
+  }
+
+  test("external lookup sends one parameter row per request when it selects a 
range") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    // Three shifts that cover employee ids from 1, from 2 and from 3. Ids 1 
and 2 are stored, so
+    // id 2 is in the first two ranges. Each range is a request of its own, so 
the store returns
+    // id 2 once in each, and each shift joins it once.
+    val shifts = streamOf(Seq(("early", 1), ("late", 2), ("night", 
3)).toDF("shift", "firstId"))
+    val early = Seq(
+      Row("early", 1, 1, "engineering"),
+      Row("early", 1, 1, "research"),
+      Row("early", 1, 2, "sales"))
+    val late = Seq(Row("late", 2, 2, "sales"))
+
+    Seq(
+      "inner" -> (early ++ late),
+      "left_outer" -> (early ++ late :+ Row("night", 3, null, null)),
+      "left_semi" -> Seq(Row("early", 1), Row("late", 2)),
+      "left_anti" -> Seq(Row("night", 3))).foreach { case (joinType, expected) 
=>
+      SimpleExternalLookupDataSource.resetCounters()
+      checkStream(shifts.join(lookup, lookup("id") >= shifts("firstId"), 
joinType), expected)
+      assert(SimpleExternalLookupDataSource.requestSizes.asScala.toSeq === 
Seq(1, 1, 1), joinType)
+    }
+    // An equality-only lookup still sends the three ids in one request.
+    SimpleExternalLookupDataSource.resetCounters()
+    checkStream(
+      shifts.join(lookup, lookup("id") === shifts("firstId")),
+      Seq(
+        Row("early", 1, 1, "engineering"),
+        Row("early", 1, 1, "research"),
+        Row("late", 2, 2, "sales")))
+    assert(SimpleExternalLookupDataSource.requestSizes.asScala.toSeq === 
Seq(3))
+  }
+
+  test("a range on a widened stream column runs as an external lookup join") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    // Shifts that start at an employee id held as SMALLINT. Analysis casts it 
to the INT `id`,
+    // and the cast cannot fail, so Spark offers the range to the store 
instead of failing with
+    // NO_LOOKUP_CANDIDATE.
+    val shifts =
+      streamOf(Seq(("early", 1.toShort), ("late", 2.toShort)).toDF("shift", 
"firstId"))
+
+    checkStream(
+      shifts.join(lookup, lookup("id") >= shifts("firstId")),
+      Seq(
+        Row("early", 1.toShort, 1, "engineering"),
+        Row("early", 1.toShort, 1, "research"),
+        Row("early", 1.toShort, 2, "sales"),
+        Row("late", 2.toShort, 2, "sales")))
+    assert(SimpleExternalLookupDataSource.lookupCandidates.get() ===
+      Seq((">=", "id", IntegerType)))
+  }
+
+  test("a range with a cast that can fail is not offered, so an unmatched row 
does not fail") {
+    ValidityExternalLookupTable.offered.set(Seq.empty)
+    val rates = 
spark.read.format(classOf[ValidityExternalLookupDataSource].getName).load()
+    // An event on the last day that a DATE can hold. Its cast to 
TIMESTAMP_NTZ overflows, and no
+    // rate is stored for its id. A join evaluates the range only for the rows 
whose id matches,
+    // so this event must not fail the query.
+    val events = streamOf(Seq((2, Int.MaxValue)).toDF("id", "dayNumber"))
+      .select($"id", date_from_unix_date($"dayNumber").as("day"))
+    val condition = rates("id") === events("id") &&
+      rates("validFrom") >= events("day").cast("timestamp_ntz")
+
+    checkStream(
+      events.join(rates, condition, "left_outer").select(events("id"), 
rates("id")),
+      Seq(Row(2, null)))
+    assert(ValidityExternalLookupTable.offered.get() === Seq("id = ?"))
+  }
+
+  test("predicates move below an external lookup join as they do below a 
join") {
+    val lookup = 
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
+    val left = streamOf(Seq((1, true), (2, false), (3, true)).toDF("id", 
"flag"))
+    val key = left("id") === lookup("id")
+    def check(joined: DataFrame, expected: Set[Row], requestedKeys: Seq[Int]): 
Unit = {
+      SimpleExternalLookupDataSource.resetCounters()
+      assert(runStream(joined).rows.toSet === expected)
+      assert(SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq === 
requestedKeys)
+    }
+    val matched = Set(Row(1, true, 1, "engineering"), Row(1, true, 1, 
"research"))
+
+    // A filter above the join moves into the stream side, so the rows it 
rejects are not looked up.
+    Seq(
+      "inner" -> matched,
+      "left_outer" -> (matched + Row(3, true, null, null)),
+      "left_semi" -> Set(Row(1, true)),
+      "left_anti" -> Set(Row(3, true))).foreach { case (joinType, expected) =>
+      check(left.join(lookup, key, joinType).where(left("flag")), expected, 
Seq(1, 3))
+    }
+    // So does a stream-side conjunct of the join condition, except under a 
left outer or left
+    // anti join, where it decides which stream rows find a match and stays in 
the condition. Key 2
+    // is not requested there either: the join checks the conjunct on each 
stream row before the
+    // lookup, and a row that fails it cannot match.
+    Seq(
+      "inner" -> matched,
+      "left_semi" -> Set(Row(1, true)),
+      "left_outer" -> (matched + Row(2, false, null, null) + Row(3, true, 
null, null)),
+      "left_anti" -> Set(Row(2, false), Row(3, true))).foreach { case 
(joinType, expected) =>
+      check(left.join(lookup, key && left("flag"), joinType), expected, Seq(1, 
3))

Review Comment:
   This passes without the pushdown, because `splitResidualCondition` already 
checks `left("flag")` before the lookup. A conjunct that 
`canEvaluateUnconditionally` rejects would actually test the move.



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