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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala:
##########
@@ -0,0 +1,374 @@
+/*
+ * 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.analysis
+
+import scala.annotation.tailrec
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.SubqueryExpression
+import org.apache.spark.sql.catalyst.optimizer.{EliminateResolvedHint, 
InlineCTE}
+import org.apache.spark.sql.catalyst.plans.{Inner, LeftAnti, LeftOuter, 
LeftSemi}
+import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, 
CTERelationRef,
+  ExternalLookupCacheOptions, ExternalLookupHint, 
ExternalLookupHintCacheOptions,
+  ExternalLookupJoin, ExternalLookupJoinShapes, Filter, Join, 
JoinStrategyHint, LogicalPlan,
+  Project, ResolvedHint, SubqueryAlias, UnaryNode, View, WithCTE}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.{CTE, 
DATA_SOURCE_V2_RELATION,
+  EXTERNAL_LOOKUP_HINT, JOIN}
+import org.apache.spark.sql.catalyst.util.MetadataColumnHelper
+import org.apache.spark.sql.connector.catalog.TableCapability
+import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
+import org.apache.spark.sql.execution.datasources.v2.ExternalLookupRelations
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Classifies a join for external lookup. [[CheckExternalLookupJoin]] and 
[[FormExternalLookupJoin]]
+ * share it, so analysis rejects every join that the optimizer cannot convert, 
except one without
+ * a condition: see [[CheckExternalLookupJoin]].
+ *
+ * A join is an external lookup join when its right side reads a table that 
supports external
+ * lookup but not batch read, or when the right side carries an 
`EXTERNAL_LOOKUP` hint. A table
+ * that supports both keeps the ordinary join strategies unless the hint opts 
in. It must be a
+ * stream-static join: the left side is a streaming query, whose micro-batches 
tolerate lookup
+ * results that change between requests, and the lookup table is on the right 
side. The join reads
+ * the table directly, or through hints, aliases, views, and projections and 
filters that it can
+ * evaluate on the lookup results, so a join that must be a lookup join either 
runs as one or fails
+ * here, whatever the optimizer later does to its lookup side.
+ */
+object ExternalLookupJoinEligibility extends QueryErrorsBase {
+  sealed trait Eligibility
+  /**
+   * The join stays an ordinary join: it has no `EXTERNAL_LOOKUP` hint, and 
neither of its inputs is
+   * a lookup-only relation, directly or below unary operators. A lookup-only 
relation below another
+   * operator, such as a union, is not recognized, and fails later as a batch 
scan.
+   */
+  case object NotLookupJoin extends Eligibility
+  /** The join runs as an external lookup join. */
+  case object Eligible extends Eligibility
+  /**
+   * The join must run as an external lookup join, with a supported join type, 
but has no
+   * condition.
+   */
+  case object MissingCondition extends Eligibility
+  /** The join must run as an external lookup join but cannot. */
+  case class Ineligible(error: Throwable) extends Eligibility
+
+  private val SUPPORTED_JOIN_TYPES = Seq(Inner, LeftOuter, LeftSemi, LeftAnti)
+
+  def apply(join: Join): Eligibility = {
+    if (lookupHints(join.left).nonEmpty) {
+      return 
Ineligible(QueryCompilationErrors.invalidExternalLookupHintError("NOT_ON_LOOKUP_SIDE"))
+    }
+    // The lookup-only table must be on the right side; the sides are never 
swapped.
+    val leftLookupOnlyTable = 
ExternalLookupRelations.lookupOnlyTable(input(join.left))
+    if (leftLookupOnlyTable.isDefined) {
+      return ineligible("LOOKUP_TABLE_ON_LEFT", 
toSQLId(leftLookupOnlyTable.get.name()))
+    }
+    val markers = lookupHints(join.right)
+    val lookupOnly = 
ExternalLookupRelations.lookupOnlyTable(input(join.right)).isDefined
+    // A lookup-only table can be read only by a lookup join, and the hint 
opts a join in. Either
+    // way the join must run as an external lookup join, and the checks below 
apply.
+    if (!lookupOnly && markers.isEmpty) return NotLookupJoin
+    if (join.right.isStreaming) {
+      return 
Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError(
+        "STREAMING_LOOKUP_SIDE"))
+    }
+    // The DSv2 table that the lookup side reads through hints, aliases, 
views, and projections and
+    // filters that the lookup join can evaluate. There is none when another 
operator, or a stage
+    // that it cannot evaluate, stands in between, or the side reads no DSv2 
table.
+    val tableRelation = lookupRelation(join.right)
+    val table = ExternalLookupRelations.table(tableRelation) match {
+      case Some(table) => table
+      case None =>
+        return 
Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN"))
+    }
+    val relation = toSQLId(table.name())
+    if (!table.capabilities().contains(TableCapability.EXTERNAL_LOOKUP)) {
+      return 
Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError(
+        "TABLE", Map("table" -> relation)))
+    }
+    // A lookup returns the data columns of the table only. The relation 
outputs a metadata column
+    // only when the query reads one.
+    if (tableRelation.output.exists(_.isMetadataCol)) return 
ineligible("METADATA_COLUMN", relation)
+    if (!join.left.isStreaming) return ineligible("STATIC_LEFT_SIDE", relation)
+    // A join hint the user wrote is never silently dropped: an external 
lookup join cannot run a
+    // physical join strategy, and a lookup-only table has no batch scan for 
one.
+    joinStrategyHint(join) match {
+      // The user asked for a physical join, which an external lookup join 
cannot run.
+      case Some(strategy) =>
+        ineligible("CONFLICTING_JOIN_STRATEGY", relation,
+          Map("strategy" -> toSQLStmt(strategy.displayName)))
+      // No physical join was asked for: the join runs as an external lookup 
join unless a check
+      // below fails.
+      // Checked before the condition, so that a cross join fails while it is 
analyzed.
+      case None if !SUPPORTED_JOIN_TYPES.contains(join.joinType) =>

Review Comment:
   **Non-blocking (P2):** The previous review's WHERE-key finding is now fixed 
for a comma join and for JOIN ... ON TRUE, but this check still runs before the 
condition and rejects `Cross`, so the fix does not reach the CROSS JOIN 
spelling. By this review's reading of the code, `SELECT s.door, d.department 
FROM badge_swipes s, employee_directory d WHERE s.employee = d.id` runs as a 
lookup join, as the new test 'a lookup key written only in WHERE plans as for 
an ordinary join' checks. The same query written with `CROSS JOIN`, or as 
`swipes.crossJoin(directory).where(...)`, still fails during analysis with 
`EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.JOIN_TYPE`. For an ordinary join, `Cross` is 
`InnerLike`, so `PushPredicateThroughJoin` moves the WHERE key into the 
condition for both spellings. da6275df4f7 put the type check first so that a 
cross join over a lookup-only table failed at analysis instead of with 
MISSING_JOIN_CONDITION once optimization started. Back then a join without a 
condition 
 could never get a key, and this PR's pushdown removes that premise. The 
failure is explicit and no row is wrong, but FormExternalLookupJoinSuite and 
ExternalLookupJoinSuite still assert the rejection, including with a later 
filter.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60198#issuecomment-6756317204).
   
   **Recommended change:** In ExternalLookupJoinEligibility, treat a Cross join 
as an inner join: classify it by its condition, as MissingCondition without one 
and Eligible with one, while every other unsupported join type stays rejected 
with JOIN_TYPE before the condition is checked, and have FormExternalLookupJoin 
form it as an inner ExternalLookupJoin. Update the formation and end-to-end 
lookup join tests that now assert the JOIN_TYPE rejection of a cross join, with 
and without a later filter, to assert that it plans or fails as the comma join 
does. History: 2f216eb4625 classified a join without a condition before its 
type, which is the starting point for a cross join without a condition; 
da6275df4f7 moved the type check ahead so that a cross join over a lookup-only 
table fails with JOIN_TYPE during analysis rather than with 
MISSING_JOIN_CONDITION when optimization starts, a reason that assumed such a 
join could never get a key, which this PR's pushdown of WHERE keys removes. Unli
 ke the earlier order, the cross join must also be formed as Inner, because no 
later rule accepts Cross.
   
   **Why this works:** Normalizing Cross to Inner in the classifier that 
analysis, the command check and formation all share sends CROSS JOIN and 
crossJoin() down the same path as a comma join: analysis no longer rejects 
them, predicate pushdown moves a WHERE key into the formed inner lookup join, 
and lookup planning plans it or reports MISSING_JOIN_CONDITION when no key 
arrives, while every consumer keeps seeing only the four supported join types.
   
   **Scope:** Classify and form a cross join over a lookup table as an inner 
lookup join, so a key written in WHERE works for every spelling of an inner 
join without a condition.
   
   **Compatibility:** Every other unsupported join type keeps failing with 
JOIN_TYPE during analysis, and the comma join, JOIN ON TRUE and join() 
spellings plan as before.
   
   **Risks:** A cross join over a lookup table with no key anywhere now fails 
with MISSING_JOIN_CONDITION from lookup planning, at start() through the 
startup check or at the first micro-batch when that check is off, instead of 
with JOIN_TYPE during analysis; reverting the classification restores the 
earlier error.
   
   **Constraints:** The join type check must keep running before the condition 
check for right outer, full outer and the other unsupported join types, so they 
still fail with JOIN_TYPE during analysis. The formed lookup join must carry 
Inner, because the lookup join's optimizer, planning and execution accept only 
Inner, LeftOuter, LeftSemi and LeftAnti.
   
   **Exclusions:**
   - Supporting right outer or full outer lookup joins, which keep failing with 
JOIN_TYPE.
   
   **Success:** FROM s CROSS JOIN t WHERE s.id = t.id and 
s.crossJoin(t).where(s("id") === t("id")) over a lookup-only table or a hinted 
dual-capability table run as lookup joins and return the rows of the comma-join 
spelling. A cross join whose condition holds a lookup key, as join(t, 
condition, "cross"), plans as an inner lookup join. A cross join with no key 
fails with MISSING_JOIN_CONDITION, as a comma join without a key does. Right 
outer and full outer joins over a lookup table still fail with JOIN_TYPE during 
analysis.
   
   **Verification:**
   - **Regression:** A streaming query that writes its lookup key only in a 
WHERE clause above a CROSS JOIN in SQL, and one that filters a crossJoin() in 
the Dataset API, over a lookup-only table and over a hinted dual-capability 
table, runs as a lookup join and returns the same rows as the comma-join 
spelling of the same query.
   - **Behavior:** A cross join with a lookup key in its own condition plans as 
an inner lookup join, and a cross join with no key in its condition or in WHERE 
fails with MISSING_JOIN_CONDITION when the query starts, as a comma join 
without a key does.
   - **Compatibility:** A right outer or a full outer join over a lookup table 
still fails with JOIN_TYPE during analysis and lists the supported join types.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala:
##########
@@ -0,0 +1,472 @@
+/*
+ * 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.plans.logical
+
+import org.apache.spark.SparkException
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeSet, 
BinaryComparison,
+  Cast, CurrentBatchTimestamp, EqualNullSafe, EqualTo, Expression, ExprUtils,
+  ExternalUserDefinedFunction, GreaterThan, GreaterThanOrEqual, LessThan, 
LessThanOrEqual, Literal,
+  NamedExpression, PythonUDF, SubqueryExpression}
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, 
LeftOuter, LeftSemi}
+import org.apache.spark.sql.catalyst.trees.TreePattern.{CURRENT_LIKE, 
EXTERNAL_LOOKUP_HINT,
+  EXTERNAL_LOOKUP_JOIN, TreePattern}
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.connector.read.{ExternalLookupReaderFactory, Scan}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{BinaryType, BooleanType, ByteType, 
CharType, DataType,
+  DateType, DecimalType, IntegerType, IntegralType, LongType, ShortType, 
StringType,
+  TimestampNTZType, TimestampType, VarcharType}
+
+/**
+ * The cache settings of one external lookup join, from the
+ * `spark.sql.join.externalLookup.cache.*` configurations unless the join's 
`EXTERNAL_LOOKUP` hint
+ * overrides them. A cache lives within a task, per input partition, so these 
bound each such cache:
+ * its keys and their result rows take at most `maxBytes`, and each is kept 
for `ttlMillis` (0 keeps
+ * it until evicted). A key whose rows take more than a sixteenth of 
`maxBytes` is still joined but
+ * not cached, so that one large result cannot evict most of the cache. At 
present, a join that
+ * selects a range comparison (`<`, `<=`, `>`, `>=`) whose parameter reads a 
stream column caches
+ * nothing, whatever these settings say.
+ */
+case class ExternalLookupCacheOptions(
+    enabled: Boolean,
+    maxBytes: Long,
+    ttlMillis: Long)
+
+/**
+ * The cache options that one `EXTERNAL_LOOKUP` hint sets. An option that no 
hint of a join sets
+ * follows its `spark.sql.join.externalLookup.cache.*` configuration when the 
join is planned, not
+ * the one in effect when the hint was written.
+ */
+case class ExternalLookupHintCacheOptions(
+    enabled: Option[Boolean] = None,
+    maxBytes: Option[Long] = None,
+    ttlMillis: Option[Long] = None) {
+  /** These options, with the ones that they do not set taken from `other`. */
+  def orElse(other: ExternalLookupHintCacheOptions): 
ExternalLookupHintCacheOptions =
+    ExternalLookupHintCacheOptions(
+      enabled.orElse(other.enabled),
+      maxBytes.orElse(other.maxBytes),
+      ttlMillis.orElse(other.ttlMillis))
+
+  /** These options, with the configurations of `conf` for the ones that they 
do not set. */
+  def withDefaults(conf: SQLConf): ExternalLookupCacheOptions = 
ExternalLookupCacheOptions(
+    enabled = 
enabled.getOrElse(conf.getConf(SQLConf.JOIN_EXTERNAL_LOOKUP_CACHE_ENABLED)),
+    maxBytes = 
maxBytes.getOrElse(conf.getConf(SQLConf.JOIN_EXTERNAL_LOOKUP_CACHE_MAX_BYTES)),
+    ttlMillis = 
ttlMillis.getOrElse(conf.getConf(SQLConf.JOIN_EXTERNAL_LOOKUP_CACHE_TTL)))
+}
+
+/**
+ * Marks the plan below it as the lookup side that the `EXTERNAL_LOOKUP` hint 
asks an external
+ * lookup join to read, with the cache options that the hint sets. The 
external lookup join rules
+ * consume it when they form the join.
+ *
+ * Join strategy hints are [[ResolvedHint]] nodes with a [[JoinStrategyHint]]. 
This hint is not,
+ * because that representation cannot keep two of its guarantees:
+ *  - A strategy hint that conflicts with it must fail the query. [[HintInfo]] 
holds one strategy,
+ *    and `ResolveJoinStrategyHints` merges a strategy hint on an already 
hinted relation into the
+ *    existing [[ResolvedHint]] with `HintInfo.merge`, which keeps one 
strategy and only warns.
+ *  - It selects how the lookup side is read, not a physical join. 
`EliminateResolvedHint` moves
+ *    every [[ResolvedHint]] it can attach into `Join.hint`, for physical join 
selection.
+ */
+case class ExternalLookupHint(
+    child: LogicalPlan,
+    cacheOptions: ExternalLookupHintCacheOptions) extends UnaryNode {
+  override def output: Seq[Attribute] = child.output
+
+  final override val nodePatterns: Seq[TreePattern] = Seq(EXTERNAL_LOOKUP_HINT)
+
+  override protected def withNewChildInternal(newChild: LogicalPlan): 
ExternalLookupHint =
+    copy(child = newChild)
+}
+
+/**
+ * A lookup join retained through ordinary expression and operator 
optimization.
+ *
+ * @param requiredLookupOutput Lookup-side attributes still required above 
this join. They are
+ *   part of this node's references, so column pruning keeps them on the 
lookup side.
+ *   `ColumnPruning` narrows them to what the parent reads, and 
`PrepareExternalLookupJoin` prunes
+ *   the lookup scan to them.
+ */
+case class ExternalLookupJoin(
+    left: LogicalPlan,
+    right: LogicalPlan,
+    joinType: JoinType,
+    condition: Option[Expression],
+    cacheOptions: ExternalLookupCacheOptions,
+    requiredLookupOutput: Seq[Attribute]) extends BinaryNode {
+
+  final override val nodePatterns: Seq[TreePattern] = Seq(EXTERNAL_LOOKUP_JOIN)
+
+  override def output: Seq[Attribute] = joinType match {
+    case Inner => left.output ++ right.output
+    case LeftOuter => left.output ++ right.output.map(_.withNullability(true))
+    case LeftSemi | LeftAnti => left.output
+    case other => throw SparkException.internalError(s"Unexpected external 
lookup join type $other")
+  }
+
+  // As an ordinary join's: a semi or anti join returns at most its stream 
rows, and the other join
+  // types get the product of both sides' sizes.
+  override def stats: Statistics = joinType match {
+    case LeftSemi | LeftAnti => left.stats
+    case _ => super.stats
+  }
+
+  override def maxRows: Option[Long] = joinType match {
+    case LeftSemi | LeftAnti => left.maxRows
+    case _ => None
+  }
+
+  override protected def withNewChildrenInternal(
+      newLeft: LogicalPlan,
+      newRight: LogicalPlan): ExternalLookupJoin = copy(left = newLeft, right 
= newRight)
+}
+
+/**
+ * The join-condition and lookup-side shapes that an external lookup join can 
run. Analysis,
+ * lookup planning and the optimizer rules for lookup joins share them.
+ */
+object ExternalLookupJoinShapes {
+  /**
+   * A lookup candidate: a comparison of a lookup column with a value, written 
with the lookup
+   * column on the left.
+   */
+  case class LookupComparison(
+      lookupField: Attribute,
+      parameter: Expression,
+      comparison: LookupKeyComparison)
+
+  /**
+   * `conjunct` of the condition of a lookup join as a lookup candidate: `=`, 
`<=>`, `<`, `<=`, `>`
+   * or `>=` between a bare lookup column and a value, in either operand 
order. When the lookup
+   * column is written on the right, the comparison is rebuilt with it on the 
left, so
+   * `s.ts < t.event_time` is offered as `event_time > ?`.
+   *
+   * The value is the other operand, which Spark evaluates for each stream row 
to fill the
+   * comparison's parameter. It may read only stream columns, and it may read 
none, as a literal
+   * does. A value that reads lookup columns, as in `t.a = t.b`, cannot be a 
parameter.
+   *
+   * The lookup column must be one on which [[ExternalLookupKeyTypes]] lets 
Spark offer the
+   * comparison. A comparison on another column is an ordinary conjunct.
+   *
+   * @param streamOutput The output of the join's left side, the stream side.

Review Comment:
   **Nit (P3):** Since 0c20a33fc99, `PrepareExternalLookupJoin` also calls this 
helper on the conjuncts of lookup-side filters. It passes `AttributeSet.empty` 
as `streamOutput`, so that only a parameter reading no column qualifies, and 
the relation's output plus the segment's fields and the upper stages' outputs 
as `lookupOutput`. The doc still describes only a conjunct of the join 
condition and the join's left and right outputs. A reader could take the empty 
stream output for a bug, or miss that this shape check now also classifies 
lookup-side constants. Describing `streamOutput` as the attributes a parameter 
may read (none for a lookup-side constant) and `lookupOutput` as the 
lookup-side attributes the column may be would cover both callers.
   
   **Verification:**
   - **Inspection:** Each argument that lookup planning passes to the helper, 
for condition conjuncts and for lookup-side filter conjuncts, matches the 
documented meaning of the conjunct, streamOutput and lookupOutput.



##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -2855,6 +2918,79 @@
     ],
     "sqlState" : "42822"
   },
+  "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED" : {
+    "message" : [
+      "The join cannot be executed as an external lookup join:"
+    ],
+    "subClass" : {
+      "CONFLICTING_JOIN_STRATEGY" : {
+        "message" : [
+          "The join strategy hint <strategy> cannot be honored by an external 
lookup join over <relation>. Remove the <strategy> hint."
+        ]
+      },
+      "JOIN_TYPE" : {
+        "message" : [
+          "The join type <joinType> is not supported by an external lookup 
join over <relation>. Supported join types are <supportedJoinTypes>."
+        ]
+      },
+      "LOOKUP_PLAN" : {
+        "message" : [
+          "The lookup side must be a DSv2 table, optionally under projections 
and filters, which Spark evaluates on the lookup results. They cannot contain 
Python UDFs, external UDFs, subqueries or non-deterministic expressions: Spark 
evaluates them on each returned row, so a non-deterministic one could give one 
stored row different values for different stream rows. No other operator can be 
between the table and the join."
+        ]
+      },
+      "LOOKUP_TABLE_ON_LEFT" : {
+        "message" : [
+          "The lookup-only table <relation> must be on the right side of the 
join."
+        ]
+      },
+      "METADATA_COLUMN" : {
+        "message" : [
+          "An external lookup join over <relation> cannot read a metadata 
column of the table."
+        ]
+      },
+      "MISSING_JOIN_CONDITION" : {
+        "message" : [
+          "The join has no join condition, and predicate pushdown moved none 
into it from a later `WHERE` clause or filter. Compare a lookup column with a 
stream-side value in the join, such as in its `ON` clause or the condition 
argument of `join()`, or in a `WHERE` clause above an inner join."

Review Comment:
   **Nit (P3):** This text is now raised in cases it does not describe. By this 
review's reading of the code:
   1. The PR's pushdown moves every lookup-only conjunct of a condition onto 
the lookup side. So `stream.join(lookup, lookup("department") =!= "x")` ends 
with an empty condition and gets 'The join has no join condition'. Before these 
commits it reported `NO_LOOKUP_CANDIDATE` with the table name and the rules for 
a lookup predicate, and it still does with `PushDownPredicates` excluded.
   2. `TableCapabilityCheck` raises this error during analysis, before any 
pushdown, for a command whose query holds a streaming lookup join without a 
condition. For `INSERT ... SELECT ... FROM s, t WHERE s.id = t.id`, it says 
pushdown moved no key from a WHERE clause that holds one.
   3. `NO_LOOKUP_PREDICATE` still says Spark offered its predicates 'from the 
join condition', though the constant candidates added in 0c20a33fc99 come from 
lookup-side filters.
   
   The comments at `PrepareExternalLookupJoin`'s missing-condition decision 
('none was written in it') and at the command check ('the condition cannot be 
added later') make the same assumptions. Wording that holds everywhere, such as 
saying that the join has no condition from which Spark can plan a lookup, would 
keep the WHERE advice without these contradictions.
   
   **Verification:**
   - **Behavior:** The MISSING_JOIN_CONDITION error raised for a join whose 
only written conjunct reads lookup columns, such as ON t.department <> 'x', for 
a comma join with no key, and for a command whose query holds a lookup join 
without a condition, carries a message that neither denies the written 
condition nor says that predicate pushdown ran.
   - **Behavior:** The NO_LOOKUP_PREDICATE error raised when a source selects 
none of the predicates offered from a comparison of a lookup column with a 
constant in WHERE carries a message that does not attribute them to the join 
condition alone.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/PushPredicateThroughExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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.{Expression, Literal, 
PythonUDF, Rand,
+  ScalarSubquery}
+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) = 
lookup.output
+  private val keysEqual = streamKey === lookupKey
+  // A comparison with a stream-side value that is never offered: Spark offers 
no `=` on a DOUBLE.
+  private val neverOfferedKey = lookupScore === streamKey.cast(DoubleType)
+  // 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.

Review Comment:
   **Nit (P3):** Since 0c20a33fc99 a lookup candidate moves onto the lookup 
side too: 'move a comparison with a constant onto the lookup side as for a 
join' asserts it for `lookupValue === 5` and `lookupValue >= 5` under every 
join type. So 'not a lookup candidate, so it can move' now gives a reason that 
does not hold. Saying that the conjunct is not a candidate and moves as any 
deterministic lookup-side conjunct does would keep the fixture's point.
   
   **Verification:**
   - **Inspection:** The fixture comment's reason agrees with the suite's 
tests, which move lookup candidates such as comparisons with constants onto the 
lookup side as well.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/PushPredicateThroughExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,267 @@
+/*
+ * 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.{Expression, Literal, 
PythonUDF, Rand,
+  ScalarSubquery}
+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) = 
lookup.output
+  private val keysEqual = streamKey === lookupKey
+  // A comparison with a stream-side value that is never offered: Spark offers 
no `=` on a DOUBLE.
+  private val neverOfferedKey = lookupScore === streamKey.cast(DoubleType)
+  // 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 as for a join") 
{
+    // As for a join, a lookup-side conjunct goes onto the lookup side, where 
the connector receives
+    // it as a pushed filter. Lookup planning still offers it as a lookup 
candidate.
+    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)))
+    }
+    // So does one that is the join's only possible key, which lookup planning 
then offers from
+    // the lookup side.
+    for (joinType <- lookupJoinTypes; comparison <- Seq(lookupValue === 5, 
lookupValue >= 5)) {
+      val join = lookupJoin(joinType, comparison)
+      comparePlans(Optimize.execute(join),
+        join.copy(right = lookup.where(comparison), condition = None))
+    }
+    // A filter above an inner join moves there too, whatever key the 
condition keeps. 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 constantKey = lookupJoin(Inner, neverOfferedKey, lookupValue === 5)
+    comparePlans(Optimize.execute(constantKey.where(lookupName === "x")),
+      expectedJoin(constantKey, lookupSide = lookup.where(lookupValue === 5 && 
lookupName === "x"),
+        conjuncts = Seq(neverOfferedKey)))
+    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)))
+    // Any other lookup-side conjunct moves as well, including a comparison on 
a type that Spark
+    // never offers as a key: `=` or `<=>` on a DOUBLE, or a range on a STRING.
+    val notCandidates = Seq[Expression](
+      lookupValue =!= 5, lookupValue + 1 > 5, lookupValue.in(1, 2), 
lookupValue.isNull,
+      lookupScore === 5.0, lookupScore <=> 5.0, lookupName < "m", lookupName 
>= "a")
+    for (conjunct <- notCandidates) {
+      val join = lookupJoin(Inner, keysEqual, conjunct)
+      comparePlans(Optimize.execute(join), expectedJoin(join, lookupSide = 
lookup.where(conjunct),
+        conjuncts = Seq(keysEqual)))
+      comparePlans(Optimize.execute(inner.where(conjunct)),
+        expectedJoin(inner, lookupSide = lookup.where(conjunct), conjuncts = 
Seq(keysEqual)))
+    }
+  }
+
+  test("a comparison with a constant moves next to one on a computed lookup 
column") {
+    // `streamKey = computed` is never offered, as `computed` is no table 
column, and the
+    // comparison with a constant moves onto the lookup side as for a join, 
from where lookup
+    // planning offers it as the key.
+    val computed = (lookupValue + 1).as("computed")
+    val projected = lookup.select(lookupKey, lookupValue, computed)
+    val join = FormExternalLookupJoin(Join(stream, projected, Inner,
+      Some(streamKey === computed.toAttribute && lookupKey === 5), 
JoinHint.NONE))
+      .asInstanceOf[ExternalLookupJoin]
+    comparePlans(Optimize.execute(join), join.copy(
+      right = lookup.where(lookupKey === 5).select(lookupKey, lookupValue, 
computed),
+      condition = Some(streamKey === computed.toAttribute)))
+  }
+
+  test("keep a conjunct that a lookup-side stage cannot evaluate where it is") 
{
+    // The conjuncts read lookup columns, so a lookup-side stage would have to 
evaluate them, and
+    // a stage with a Python UDF or a subquery cannot be planned.
+    val pythonUDFs = Seq[Expression](
+      booleanPythonUDF(Seq(lookupValue)), booleanPythonUDF(Seq(streamKey, 
lookupValue)))
+    // A subquery over lookup columns cannot be in the condition of a lookup 
join, only in a filter
+    // above it, where it stays. One that reads no column moves into the 
condition of an inner join,

Review Comment:
   **Nit (P3):** This comment says that a subquery reading no column moves into 
an inner lookup join's condition. But the loop below asserts only that 
`lookupValue > scalarSubquery` stays above, and no end-to-end test runs such a 
query. By this review's reading of the code, `splitLookupJoin` keeps 
reference-less conjuncts with the common ones. The inner `Filter` case then 
moves them into the condition when `canEvaluateWithinJoin` accepts them, as it 
does for a non-correlated scalar subquery and for an uncorrelated EXISTS once 
`RewriteNonCorrelatedExists` has turned it into one. So `WHERE (SELECT max(v) 
FROM limits) > 0` above an inner lookup join is evaluated in 
`ExternalLookupJoinExec`'s residual. That path is new with these commits, since 
analysis rejects any subquery written in a lookup join's `ON`, and it relies on 
`PlanSubqueries` reaching `residualCondition` before execution. A regression in 
the move or in that evaluation would ship undetected.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60198#discussion_r4515402988).
   
   **Verification:**
   - **Regression:** The optimized plan of a filter with a reference-less 
scalar subquery above an inner lookup join holds the subquery in the join's 
condition and no filter above the join.
   - **Behavior:** A streaming query with WHERE (SELECT max(v) FROM limits) > 
0, and one with an uncorrelated EXISTS, above an inner lookup join runs and 
returns the same rows as with PushDownPredicates excluded, both when the 
subquery's predicate holds and when it does not.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/ExternalLookupJoinStartupCheck.scala:
##########
@@ -0,0 +1,96 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.streaming.runtime
+
+import scala.util.control.NonFatal
+
+import org.apache.spark.SparkThrowable
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.analysis.ExternalLookupJoinEligibility
+import org.apache.spark.sql.catalyst.streaming.WriteToStream
+import org.apache.spark.sql.classic.SparkSession
+import org.apache.spark.sql.execution.QueryExecution
+import org.apache.spark.sql.execution.streaming.checkpointing.OffsetSeqMetadata
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Plans the external lookup joins of a streaming query when it starts, in the 
thread that starts
+ * it, so that a join that cannot be planned fails `start()` instead of the 
first micro-batch that
+ * runs, which may come much later. Whether a join has a lookup predicate, and 
which ones the
+ * connector selects, depend on the condition as the optimizer leaves it, for 
example after it
+ * simplifies the condition. So the query is optimized once here, with the 
optimizer of its
+ * micro-batches and with their configuration, and the result is discarded.
+ *
+ * Only the lookup sides are planned. The other subtrees without a streaming 
relation, and the
+ * subtrees of subquery plans without an outer reference, become placeholders 
of their outputs, as
+ * in the optimization for the column pruning of streaming scans (see
+ * `StreamingV2ScanPushDown.forStartup`), so that their scans are neither 
built nor planned at the
+ * start, as for a query without a lookup join.
+ *
+ * Only the planning errors of the lookup join and of its connector contract 
fail the start. Any
+ * other error, such as one that an ordinary join raises too, is left to the 
micro-batch, which
+ * plans the query as before.
+ */
+private[sql] object ExternalLookupJoinStartupCheck extends Logging {
+  private val lookupErrorClasses = Set(
+    "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED",
+    "INVALID_EXTERNAL_LOOKUP_HINT",
+    "DATA_SOURCE_INVALID_EXTERNAL_LOOKUP",
+    // The default Scan.toExternalLookup() of a scan that does not override it.
+    "DATA_SOURCE_EXTERNAL_LOOKUP_NOT_SUPPORTED")
+
+  def apply(session: SparkSession, write: WriteToStream): Unit = {
+    val plan = write.inputQuery
+    if 
(!session.sessionState.conf.getConf(SQLConf.JOIN_EXTERNAL_LOOKUP_STARTUP_CHECK_ENABLED)
 ||
+        ExternalLookupJoinEligibility.lookupSidePlans(plan).isEmpty) {
+      return
+    }
+    session.withActive {
+      try {
+        SQLConf.withExistingConf(startupConf(session, write)) {
+          val normalized = QueryExecution.normalize(session, plan)
+          // The values that depend on when they are evaluated fold as in the 
first micro-batch.
+          session.sessionState.optimizer.execute(
+            StreamingV2ScanPushDown.forStartup(normalized, withStartupValues = 
false))

Review Comment:
   **Nit (P3):** At start this optimizes with `withStartupValues = false`, so 
`ComputeCurrentTime` folds `current_timestamp()`, `current_date()` and 
`localtimestamp()` into literals. Each micro-batch has already rewritten them 
to `CurrentBatchTimestamp`, which stays non-deterministic until optimization 
ends. With this PR's pushdown and lookup-side constant candidates, the two runs 
can now reach different lookup planning decisions. By this review's reading of 
the code, take `events.join(promotions).where(promotions("valid_from") <= 
current_timestamp() && promotions("valid_to") > current_timestamp())` over a 
connector that serves those ranges. At `start()` both conjuncts fold, move onto 
the lookup side and are offered, so the query starts. In the first micro-batch 
they stay above the join and nothing is offered, so it fails with 
`MISSING_JOIN_CONDITION`. The same holds for a connector that needs `valid_date 
= ?` next to an `ON` key, from `WHERE rates.valid_date = current_date()`, or `v
 alid_from <= ?` from `ON ... AND rates.valid_from <= current_timestamp()`. 
Each passes `start()` and fails the first micro-batch with 
`NO_LOOKUP_PREDICATE`. In the stacked PRs the WHERE cases failed at `start()`, 
and the ON range case already diverged this way. The failure is explicit, but 
it arrives at the first micro-batch, which may be much later, although the PR 
says such a join fails from `start()`. The comment above, 'fold as in the first 
micro-batch', holds for date and timestamp conversions but not for the current 
time, and no startup test covers a current-time key.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60198#issuecomment-6756317204).
   
   **Recommended change:** Before optimizing at start, rewrite 
current_timestamp(), current_date(), localtimestamp() and their nanosecond 
variants into CurrentBatchTimestamp exactly as MicroBatchExecution does for 
each batch, by moving that rewrite into a helper that both call, and correct 
the comment on the startup optimization to say that the current time is 
represented as in a micro-batch while date and timestamp conversions fold as in 
the first micro-batch. Add startup tests for a query whose only possible lookup 
key compares with the current time in WHERE, and for a connector that needs a 
comparison with the current time next to a stream-side key, written in WHERE or 
as a range in ON. ff67010628f added the check with withStartupValues = false so 
that the values that depend on when they are evaluated fold as in the first 
micro-batch, which holds for the conversions but not for the current time, 
which micro-batches never fold while optimizing.
   
   **Why this works:** A CurrentBatchTimestamp is non-deterministic during 
optimization, so with it the start's predicate pushdown keeps a current-time 
conjunct where a micro-batch keeps it and lookup planning offers no range whose 
parameter reads it; the start therefore reaches the same 
MISSING_JOIN_CONDITION, NO_LOOKUP_CANDIDATE or NO_LOOKUP_PREDICATE decision as 
the first micro-batch, while date and timestamp conversions keep folding as 
before.
   
   **Scope:** Represent the current time at start() as micro-batches do, so the 
startup check reaches their lookup planning decision for comparisons with the 
current time.
   
   **Compatibility:** Micro-batch planning, and the start-time folding of date 
and timestamp conversions that withStartupValues = false keeps, stay unchanged.
   
   **Risks:** A query whose lookup planning depends on a comparison with the 
current time now fails start() with the error its first micro-batch would 
raise, instead of starting and failing later; the internal 
spark.sql.join.externalLookup.startupCheck.enabled turns the check off, and 
reverting the rewrite restores the earlier behavior.
   
   **Constraints:** The start must rewrite the same expressions as a 
micro-batch, with the same data types and time zones, so the two cannot drift. 
Micro-batch planning must not change.
   
   **Exclusions:**
   - Moving comparisons with the current time below lookup joins in 
micro-batches, which would need predicate pushdown to treat the batch timestamp 
as deterministic.
   
   **Success:** A streaming query whose only lookup key compares a lookup 
column with the current time in WHERE fails start() with 
MISSING_JOIN_CONDITION, as its first micro-batch does. A query whose connector 
needs a comparison with the current time next to a stream-side key, written in 
WHERE or as a range in ON, fails start() with NO_LOOKUP_PREDICATE, as its first 
micro-batch does. Queries whose lookup planning does not depend on the current 
time start and plan as before, and a comparison with the current time written 
on the lookup side itself, or as an equality in ON, is still offered at start, 
as in the micro-batches. The comment on the startup optimization describes how 
it represents the current time and date and timestamp conversions.
   
   **Verification:**
   - **Regression:** Starting a query whose only possible lookup keys are 
comparisons of a lookup column with current_timestamp() in a WHERE clause above 
an inner lookup join fails start() with MISSING_JOIN_CONDITION, and starting a 
query with a stream-side key whose connector also needs a comparison of a 
lookup column with current_date() or current_timestamp(), once written in WHERE 
above the join and once as a range in ON, fails start() with 
NO_LOOKUP_PREDICATE; with the startup check off, each of these queries fails 
its first micro-batch with the same error.
   - **Compatibility:** A query with a lookup key and a comparison with the 
current time that the connector does not need starts, and its micro-batches 
select the same lookup predicates and return the same rows as before the 
change, and a comparison of a lookup column with the current time written on 
the lookup side itself, or as an equality in ON, is still offered at start.
   - **Behavior:** A lookup-side filter that compares with a date conversion of 
a constant string still plans at start as it does in the micro-batches.



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