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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -2530,6 +2530,76 @@ object SQLConf {
     .bytesConf(ByteUnit.BYTE)
     .createWithDefault(8L << 30)
 
+  val JOIN_EXTERNAL_LOOKUP_MAX_BATCH_BYTES =
+    buildConf("spark.sql.join.externalLookup.maxBatchBytes")
+      .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+      .doc("Size in bytes of input rows at which an external lookup join stops 
adding rows to " +
+        "a lookup request. The row that reaches this size stays in the 
request, so a request " +
+        "can exceed it by one row. A request always takes at least one row, 
and never more rows " +
+        "than the source allows, or 1000.")
+      .version("4.4.0")
+      .bytesConf(ByteUnit.BYTE)
+      .checkValue(_ > 0, "External lookup join max batch bytes must be 
positive")
+      .createWithDefaultString("64m")
+
+  val JOIN_EXTERNAL_LOOKUP_STARTUP_CHECK_ENABLED =
+    buildConf("spark.sql.join.externalLookup.startupCheck.enabled")
+      .internal()
+      .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+      .doc("When true, starting a streaming query plans its external lookup 
joins once, " +
+        "including the planning calls to their connectors, so that a join that 
cannot be " +
+        "planned fails the start instead of the first micro-batch. When false, 
such a join " +
+        "fails the first micro-batch that runs.")
+      .version("4.4.0")
+      .booleanConf
+      .createWithDefault(true)
+
+  val JOIN_EXTERNAL_LOOKUP_CACHE_ENABLED =
+    buildConf("spark.sql.join.externalLookup.cache.enabled")
+      .withBindingPolicy(ConfigBindingPolicy.SESSION)
+      .doc("When true, external lookup join caches the complete lookup result 
of each key, " +
+        "including a key with no result, within a task, per input partition (a 
task that reads " +
+        "several input partitions, e.g. after coalesce, has one cache per 
partition). A cached " +
+        "result is reused as it was read. At present, a join whose source 
serves a range " +
+        "comparison (<, <=, >, >=) caches nothing. It can be overridden per 
join with the " +

Review Comment:
   **Nit (P3):** 'It can be overridden per join with the EXTERNAL_LOOKUP hint 
option ...' comes right after 'a join whose source serves a range comparison 
(<, <=, >, >=) caches nothing', so it reads as if `cache_enabled=true` could 
turn caching on for a range lookup. `PrepareExternalLookupJoin` turns the cache 
off whenever a range is selected, whatever the hint says. Naming the subject 
('This configuration can be overridden per join ...') and saying that the hint 
option does not enable the cache for a range lookup would avoid the misreading.
   
   **Verification:**
   - **Inspection:** The published doc of 
spark.sql.join.externalLookup.cache.enabled names the configuration as what the 
hint option overrides and states that no option enables the cache for a range 
lookup.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -0,0 +1,819 @@
+/*
+ * 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.joins
+
+import java.util.concurrent.{ConcurrentHashMap, TimeUnit}
+import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
+import java.util.concurrent.locks.LockSupport
+
+import scala.collection.mutable
+
+import com.google.common.base.Ticker
+import com.google.common.cache.{Cache, CacheBuilder}
+
+import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, 
SparkException,
+  SparkIllegalStateException, TaskContext}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, CollationKey, 
Expression,
+  GenericInternalRow, JoinedRow, Predicate, SpecializedGetters, 
UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.optimizer.NormalizeFloatingNumbers
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftAnti, 
LeftOuter, LeftSemi}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupCacheOptions,
+  ExternalLookupFilter, ExternalLookupProject, ExternalLookupTransform}
+import org.apache.spark.sql.catalyst.util.ArrayData
+import org.apache.spark.sql.connector.metric.CustomTaskMetric
+import org.apache.spark.sql.connector.read.{ExternalLookupReader, 
ExternalLookupReaderFactory,
+  ExternalLookupResultCursor}
+import org.apache.spark.sql.errors.QueryExecutionErrors
+import org.apache.spark.sql.execution.metric.{CustomMetrics, SQLMetric}
+import org.apache.spark.sql.types.{ArrayType, DataType, Decimal, DecimalType, 
MapType,
+  StructType}
+import org.apache.spark.util.Utils
+
+/**
+ * Creates the partition evaluators of an [[ExternalLookupJoinExec]]. The 
factory is sent to the
+ * tasks, so it holds only what they need; the plan node and its scan stay on 
the driver.
+ *
+ * An evaluator joins its partition one batch of up to 
`maxParameterRowsPerRequest` stream rows at
+ * a time. For each batch it sends one request with the distinct parameters 
that can match and
+ * are not cached, and streams the connector's result rows into output rows. 
Parameters are
+ * deduplicated within a batch. With the cache enabled, a key whose complete 
result an earlier
+ * request of the same input partition returned is served from the cache, 
within the cache's
+ * bounds; otherwise a key repeated in a later batch is requested again.
+ *
+ * Spark does not trust the connector with the selected lookup predicates: it 
evaluates
+ * `lookupKeyCheck` on every row that the connector returns, against the 
request row that the row
+ * answers, and drops a row that fails it, before it joins the row. The stream 
rows that share a
+ * request row have Spark-equal parameters, so one check serves all of them.
+ *
+ * The join condition comes in two parts: `streamCondition` reads only stream 
columns and is
+ * evaluated on each stream row before the request, and `residualCondition` is 
evaluated on the
+ * joined rows. A stream row that fails `streamCondition` cannot match, so its 
parameters are not
+ * sent.
+ */
+class ExternalLookupJoinEvaluatorFactory(
+    tableName: String,
+    lookupParameters: Seq[Expression],
+    nullSafeParameters: Seq[Boolean],
+    lookupKeyCheck: Option[Expression],
+    streamOutput: Seq[Attribute],
+    lookupInput: Seq[Attribute],
+    lookupTransforms: Seq[ExternalLookupTransform],
+    transformedLookup: Seq[Attribute],
+    output: Seq[Attribute],
+    joinType: JoinType,
+    streamCondition: Option[Expression],
+    residualCondition: Option[Expression],
+    readerFactory: ExternalLookupReaderFactory,
+    maxParameterRowsPerRequest: Int,
+    maxBatchBytes: Long,
+    cacheOptions: ExternalLookupCacheOptions,
+    metrics: ExternalLookupJoinMetrics,
+    readerMetrics: ExternalLookupReaderMetrics)
+  extends PartitionEvaluatorFactory[InternalRow, InternalRow] {
+
+  require(lookupParameters.length == nullSafeParameters.length,
+    "Every external lookup parameter must define its null semantics")
+
+  override def createEvaluator(): PartitionEvaluator[InternalRow, InternalRow] 
=
+    new ExternalLookupJoinEvaluator
+
+  private class ExternalLookupJoinEvaluator extends 
PartitionEvaluator[InternalRow, InternalRow] {
+    override def eval(
+        partitionIndex: Int,
+        inputs: Iterator[InternalRow]*): Iterator[InternalRow] = {
+      assert(inputs.length == 1)
+      new PartitionJoinIterator(inputs.head, partitionIndex)
+    }
+  }
+
+  /** Joins one partition batch by batch, and closes its reader after the last 
batch. */
+  private class PartitionJoinIterator(input: Iterator[InternalRow], 
partitionIndex: Int)
+    extends Iterator[InternalRow] {
+    private val reader = new LookupReader
+    private val parameters = new LookupParameters(partitionIndex)
+    private val resultRows = new LookupResultRows
+    private val transforms = new LookupTransforms(partitionIndex)
+    private val joinOutput = new JoinOutput(partitionIndex)
+    private val cache = if (cacheOptions.enabled) Some(new LookupCache) else 
None
+    private var batch: Iterator[InternalRow] = Iterator.empty
+    private var inputExhausted = false
+
+    override def hasNext: Boolean = {
+      tryAdvance()
+      batch.hasNext
+    }
+
+    override def next(): InternalRow = {
+      tryAdvance()
+      if (!batch.hasNext) {
+        throw new SparkIllegalStateException(
+          errorClass = "INTERNAL_ERROR",
+          messageParameters = Map("message" -> "External lookup join 
exhausted"))
+      }
+      batch.next()
+    }
+
+    /** Reads more only when nothing is buffered; safe to call repeatedly. */
+    private def tryAdvance(): Unit = {
+      while (!batch.hasNext && !inputExhausted) {
+        val rows = readBatch()
+        if (rows.nonEmpty) {
+          batch = new BatchJoinIterator(
+            rows, parameters, resultRows, transforms, joinOutput, cache, 
reader)
+        }
+        inputExhausted = !input.hasNext
+      }
+      if (inputExhausted && !batch.hasNext) reader.close()
+    }
+
+    private lazy val toUnsafe = UnsafeProjection.create(streamOutput, 
streamOutput)
+
+    // An array, because a batch's rows are read by position for every key, 
match and output row.
+    // The batch holds its rows until its request is read, so it stops once 
their copies reach
+    // maxBatchBytes, keeping the row that reaches it, as well as at 
maxParameterRowsPerRequest
+    // rows. It always takes one row.
+    private def readBatch(): Array[InternalRow] = {
+      val rows = mutable.ArrayBuffer.empty[InternalRow]
+      var bytes = 0L
+      while (rows.length < maxParameterRowsPerRequest && bytes < maxBatchBytes 
&& input.hasNext) {
+        val row = input.next() match {
+          case unsafe: UnsafeRow => unsafe.copy()
+          case other => toUnsafe(other).copy()
+        }
+        bytes += row.getSizeInBytes
+        rows += row
+      }
+      rows.toArray
+    }
+  }
+
+  /** The stream rows that share a key, and the one request row sent for them. 
*/
+  private case class KeyEntry(requestRow: UnsafeRow, rowIndexes: 
mutable.ArrayBuffer[Int])
+
+  /** The stream rows that share a key, and the cached lookup rows that they 
join. */
+  private case class CachedKey(lookupRows: Array[InternalRow], rowIndexes: 
mutable.ArrayBuffer[Int])
+
+  /**
+   * Joins one batch of stream rows. Rows whose parameters are equal under 
Spark equality share
+   * one request row, and every result row for a request row that satisfies 
the selected lookup
+   * predicates joins all the stream rows sharing it. A stream row is 
finished, which may emit its
+   * unmatched output row, once no more result rows can match it.
+   *
+   * Output rows are projected into a reused row on `next()`, so the consumer 
copies the rows it
+   * retains, as with other join iterators.
+   */
+  private class BatchJoinIterator(
+      rows: Array[InternalRow],
+      parameters: LookupParameters,
+      resultRows: LookupResultRows,
+      transforms: LookupTransforms,
+      joinOutput: JoinOutput,
+      cache: Option[LookupCache],
+      reader: LookupReader) extends Iterator[InternalRow] {
+    metrics.inputRows += rows.length
+    metrics.inputBatches += 1
+
+    private val matched = Array.fill(rows.length)(false)
+    private val finished = mutable.BitSet.empty
+    // Output rows not yet returned: a stream row index and the lookup row it 
is joined with.
+    private val pending = mutable.Queue.empty[(Int, InternalRow)]
+
+    // One entry for each distinct key that can match, in the order of first 
occurrence. A row
+    // that can never match, because it fails the stream condition or has a 
null parameter, is
+    // finished right away, and its key is not requested. The stream condition 
is checked before
+    // the key is computed, so that it can guard the parameter expressions. A 
key is classified
+    // once, on its first occurrence, as a cache hit or a key to request: 
every path fans out to
+    // all the rows sharing the key, so a key must not be both, e.g. across a 
TTL boundary.
+    private val keyEntries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry]
+    private val cachedKeys = mutable.LinkedHashMap.empty[UnsafeRow, CachedKey]
+    rows.indices.foreach { index =>
+      lazy val key = parameters.key(rows(index))
+      if (!joinOutput.canMatch(rows(index)) || parameters.matchesNothing(key)) 
{
+        finish(index)
+      } else {
+        
keyEntries.get(key).map(_.rowIndexes).orElse(cachedKeys.get(key).map(_.rowIndexes))
 match {
+          case Some(rowIndexes) => rowIndexes += index
+          case None => cache.flatMap(_.get(key)) match {
+            case Some(lookupRows) =>
+              metrics.cacheHits += 1
+              cachedKeys.put(key.copy(), CachedKey(lookupRows, 
mutable.ArrayBuffer(index)))
+            case None => keyEntries.put(
+              key.copy(),
+              KeyEntry(parameters.requestRow(rows(index)), 
mutable.ArrayBuffer(index)))
+          }
+        }
+      }
+    }
+    private val requestedKeys = keyEntries.keys.toArray
+    cachedKeys.values.foreach { cached =>
+      cached.rowIndexes.foreach { index =>
+        cached.lookupRows.foreach(joinMatch(index, _))
+        finish(index)
+      }
+    }
+
+    private val cacheWriter = cache.map(new CacheWriter(_, requestedKeys))

Review Comment:
   **Non-blocking (P2):** Every batch builds a `CacheWriter` here, the 
partition's last one included: it buffers the requested keys' result rows while 
the cursor is read and writes them all into the cache at the end. The cache is 
read only when a later batch of the same partition classifies its keys, though, 
and nothing follows the last batch. Once the input runs out, 
`PartitionJoinIterator` also keeps `cache` and the drained `batch` referenced, 
typically until the task ends. So on the default path every partition pays the 
last batch's key copies, Guava puts and row buffering for nothing, and holds up 
to `maxEntries` x `maxRowsPerKey` rows outside the task memory manager while 
downstream operators and the sink commit run; a partition whose micro-batch 
input fits in one request gains nothing from the cache at all. Results are 
unaffected. `tryAdvance` sets `inputExhausted` right after it builds a batch 
and before that batch's results are read, so the batch could create its writer 
only 
 once it reads a result and only when input remains, without moving any 
request, and the iterator could drop `cache` and `batch` once the input is 
exhausted.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60087#discussion_r4515369777), 
[2](https://github.com/apache/spark/pull/60087#pullrequestreview-5829323099).
   
   **Verification:**
   - **Regression:** In each join type, a partition whose stream rows fit in 
one request returns the same rows and sends the same request with the cache 
enabled as with it disabled.
   - **Regression:** Across several batches of one partition, results that 
earlier batches wrote are still served to later batches, the last one included, 
with the same requests, requested keys and hit counts as before the change.
   - **Inspection:** The last batch of a partition creates no cache writer and 
writes nothing to the cache, each batch sends its request before the input is 
asked for its next row, and the partition iterator drops its cache and drained 
batch once its input is exhausted.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveExternalLookupHint.scala:
##########
@@ -0,0 +1,193 @@
+/*
+ * 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 java.util.Locale
+
+import scala.collection.mutable
+import scala.util.control.NonFatal
+
+import org.apache.spark.sql.catalyst.expressions.{Expression, Literal, 
StringLiteral}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupCacheOptions,
+  ExternalLookupHint, LogicalPlan, SubqueryAlias, UnresolvedHint, 
UnresolvedWith, View}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.UNRESOLVED_HINT
+import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.util.Utils
+
+/**
+ * Resolves the `EXTERNAL_LOOKUP` hint to [[ExternalLookupHint]] markers. Its 
parameters are
+ * relation names and cache options:
+ *  - A relation name is an identifier, or a string that does not contain `=`. 
As with join
+ *    strategy hints, a hint without relation names marks the plan it is 
attached to, and a hint
+ *    with relation names marks each named relation.
+ *  - A cache option is a string of the form `key=value`, such as 
`'cache_ttl=5s'`. It overrides a
+ *    `spark.sql.join.externalLookup.cache.*` configuration for the joins that 
the hint marks.
+ */
+object ResolveExternalLookupHint extends Rule[LogicalPlan] with 
QueryErrorsBase {
+  private val HINT_NAME = "EXTERNAL_LOOKUP"
+  private val CACHE_ENABLED_OPTION = "cache_enabled"
+  private val CACHE_MAX_ENTRIES_OPTION = "cache_max_entries"
+  private val CACHE_TTL_OPTION = "cache_ttl"
+  private val CACHE_MAX_ROWS_PER_KEY_OPTION = "cache_max_rows_per_key"
+  private val SUPPORTED_OPTIONS = Set(
+    CACHE_ENABLED_OPTION,
+    CACHE_MAX_ENTRIES_OPTION,
+    CACHE_TTL_OPTION,
+    CACHE_MAX_ROWS_PER_KEY_OPTION)
+  private val NON_NEGATIVE_DURATION = "a non-negative duration, such as 500ms, 
5s, or 10m"
+
+  override def apply(plan: LogicalPlan): LogicalPlan =
+    plan.resolveOperatorsUpWithPruning(_.containsPattern(UNRESOLVED_HINT), 
ruleId) {
+      case UnresolvedHint(name, parameters, child)
+          if name.toUpperCase(Locale.ROOT) == HINT_NAME =>
+        resolveHint(parameters, child)
+    }
+
+  private def resolveHint(parameters: Seq[Expression], child: LogicalPlan): 
LogicalPlan = {
+    val relationNames = mutable.ArrayBuffer.empty[Seq[String]]
+    var cacheOptions = defaultCacheOptions
+    val seenOptions = mutable.HashSet.empty[String]
+    // The Dataset API, PySpark and Spark Connect pass a relation name as a 
string, as they do for
+    // join strategy hints. A relation whose name contains `=` is named with 
an identifier.
+    def addString(value: String): Unit =
+      if (value.contains('=')) {
+        cacheOptions = parseOption(value, cacheOptions, seenOptions)
+      } else {
+        relationNames += UnresolvedAttribute.parseAttributeName(value)
+      }
+    parameters.foreach {
+      case StringLiteral(value) => addString(value)
+      case Literal(value: String, _) => addString(value)
+      case attr: UnresolvedAttribute =>
+        relationNames += attr.nameParts
+      case other =>
+        throw QueryCompilationErrors.invalidExternalLookupHintError(
+          "UNSUPPORTED_PARAMETER", Map("parameter" -> toSQLExpr(other)))
+    }
+    relationNames.diff(relationNames.distinct).headOption.foreach { duplicate 
=>
+      throw QueryCompilationErrors.invalidExternalLookupHintError(
+        "DUPLICATE_RELATION", Map("relation" -> toSQLId(duplicate)))
+    }
+
+    if (relationNames.isEmpty) {
+      ExternalLookupHint(child, cacheOptions)
+    } else {
+      // As with join strategy hints, a name marks every relation that it 
matches. `matched` only
+      // tells which names matched nothing.
+      val matched = mutable.HashSet.empty[Seq[String]]
+      def matches(identifier: Seq[String]): Boolean = {
+        val names = relationNames.filter { name =>
+          ResolveHints.matchedIdentifier(name, identifier, conf.resolver)
+        }
+        matched ++= names
+        names.nonEmpty
+      }
+      // Mirrors the target scoping of ResolveHints.ResolveJoinStrategyHints: 
a name matches an
+      // unaliased (possibly multipart) table or an alias, and does not reach 
into a view,
+      // a WITH clause, or an aliased subquery.
+      def applyHint(plan: LogicalPlan): LogicalPlan = plan match {
+        case relation: UnresolvedRelation if 
matches(relation.multipartIdentifier) =>
+          ExternalLookupHint(relation, cacheOptions)
+        case alias: SubqueryAlias
+            if matches(alias.identifier.qualifier :+ alias.identifier.name) =>
+          ExternalLookupHint(alias, cacheOptions)
+        case _: View | _: UnresolvedWith | _: SubqueryAlias => plan
+        case _ => plan.mapChildren(applyHint)
+      }
+      val rewritten = applyHint(child)
+      val missing = relationNames.filterNot(matched.contains)
+      if (missing.nonEmpty) {
+        throw QueryCompilationErrors.invalidExternalLookupHintError(
+          "RELATION_NOT_FOUND", Map("relations" -> 
missing.map(toSQLId).mkString(", ")))
+      }
+      rewritten
+    }
+  }
+
+  private[analysis] def defaultCacheOptions: ExternalLookupCacheOptions = {

Review Comment:
   **Nit (P3):** Tests set only `spark.sql.join.externalLookup.cache.enabled`; 
`maxEntries`, `ttl` and `maxRowsPerKey` reach a join in tests only through the 
hint options, which override every value this method supplies. As far as the 
review can tell from the suite, swapping `maxEntries` and `maxRowsPerKey` here, 
reading the wrong conf for one of them, or ignoring `ttl` would leave every 
test passing: the 1500 distinct keys in 'external lookup caps each inner-join 
request at the engine batch size' never repeat, and the keys with 250 and 2000 
rows sit in single-batch partitions, so no default bound decides an outcome. A 
test that sets each of these confs to a distinct non-default value and checks 
`PreparedExternalLookupJoin.cacheOptions`, as 'SQL external lookup hint accepts 
cache options' does for the hint, would pin how these three public confs bind.
   
   **Verification:**
   - **Behavior:** For each of maxEntries, ttl and maxRowsPerKey set to a 
non-default value, an unhinted lookup join carries that value in its cache 
options and shows the matching eviction, expiry or uncached key.
   - **Compatibility:** With a conf set and a hint that sets a different cache 
option, the join keeps the conf's value for the option the hint leaves out and 
the hint's value for the one it names.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala:
##########
@@ -0,0 +1,364 @@
+/*
+ * 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, 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.streaming.WriteToStream
+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
+
+/**
+ * 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 (markers.length > 1) {
+      return 
Ineligible(QueryCompilationErrors.invalidExternalLookupHintError("MULTIPLE_HINTS"))
+    }
+    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. On a table that
+    // also supports batch reads, the strategy hint conflicts with the 
`EXTERNAL_LOOKUP` hint.
+    joinStrategyHint(join) match {
+      // The user asked for a physical join, which an external lookup join 
cannot run.
+      case Some(strategy) if lookupOnly =>
+        ineligible("CONFLICTING_JOIN_STRATEGY", relation,
+          Map("strategy" -> toSQLStmt(strategy.displayName)))
+      case Some(strategy) =>
+        Ineligible(QueryCompilationErrors.invalidExternalLookupHintError(
+          "CONFLICTING_JOIN_STRATEGY",
+          Map("strategy" -> toSQLStmt(strategy.displayName), "relation" -> 
relation)))
+      // 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) =>
+        ineligible("JOIN_TYPE", relation, Map(
+          "joinType" -> toSQLStmt(join.joinType.sql),
+          "supportedJoinTypes" -> SUPPORTED_JOIN_TYPES.map(t => 
toSQLStmt(t.sql)).mkString(", ")))
+      case None if join.condition.isEmpty => MissingCondition
+      // The optimizer rewrites a subquery in a join condition only for a 
Join, which a lookup join
+      // no longer is by then.
+      case None if join.condition.exists(SubqueryExpression.hasSubquery) =>
+        ineligible("SUBQUERY_IN_JOIN_CONDITION", relation)
+      case None => Eligible
+    }
+  }
+
+  /** The CTE definitions in `plan` by id, which [[inlineCTEs]] inlines. */
+  def cteDefinitions(plan: LogicalPlan): Map[Long, CTERelationDef] =
+    if (plan.containsPattern(CTE)) {
+      plan.collect { case cteDef: CTERelationDef => cteDef.id -> cteDef }.toMap
+    } else {
+      Map.empty
+    }
+
+  /**
+   * `join` with the CTE references on the paths of unary operators of its 
inputs inlined, as
+   * InlineCTE inlines them for the analysis check. Only these paths decide 
how the join is
+   * classified, and the lookup side of an eligible join is its path alone, so 
it has no other CTE
+   * reference left.
+   */
+  def inlineCTEs(join: Join, cteDefs: Map[Long, CTERelationDef]): Join =
+    if (cteDefs.isEmpty) {
+      join
+    } else {
+      join.copy(
+        left = inlinePathCTEs(join.left, cteDefs),
+        right = inlinePathCTEs(join.right, cteDefs))
+    }
+
+  private def inlinePathCTEs(
+      plan: LogicalPlan,
+      cteDefs: Map[Long, CTERelationDef]): LogicalPlan = plan match {
+    case _ if !plan.containsPattern(CTE) => plan
+    case ref: CTERelationRef if cteDefs.contains(ref.cteId) =>
+      val cteDef = cteDefs(ref.cteId)
+      InlineCTE.inlineReference(ref, cteDef, inlinePathCTEs(cteDef.child, 
cteDefs))
+    case WithCTE(child, _) => inlinePathCTEs(child, cteDefs)
+    case unary: UnaryNode => 
unary.withNewChildren(Seq(inlinePathCTEs(unary.child, cteDefs)))
+    case other => other
+  }
+
+  /**
+   * The plans that external lookup joins in `plan` read by lookups: the 
lookup side of each join
+   * that must run as an external lookup join, and the CTE definitions that 
the side reads,
+   * directly or through other CTE definitions. Subqueries are not searched.
+   */
+  def lookupSidePlans(plan: LogicalPlan): Seq[LogicalPlan] =
+    // As in CheckExternalLookupJoin, other plans have no join that must run 
as a lookup join.
+    if (!plan.containsPattern(JOIN) ||
+        !plan.containsAnyPattern(DATA_SOURCE_V2_RELATION, 
EXTERNAL_LOOKUP_HINT)) {
+      Nil
+    } else {
+      val cteDefs = cteDefinitions(plan)
+      val lookupSides = plan.collect {
+        case join: Join if apply(inlineCTEs(join, cteDefs)) != NotLookupJoin 
=> join.right
+      }
+      val readCTEs = mutable.LinkedHashMap.empty[Long, CTERelationDef]
+      def addReadCTEs(plan: LogicalPlan): Unit = plan.foreach {
+        case ref: CTERelationRef if !readCTEs.contains(ref.cteId) =>
+          cteDefs.get(ref.cteId).foreach { cteDef =>
+            readCTEs(ref.cteId) = cteDef
+            addReadCTEs(cteDef)
+          }
+        case _ =>
+      }
+      lookupSides.foreach(addReadCTEs)
+      lookupSides ++ readCTEs.values
+    }
+
+  /**
+   * The lookup side of an eligible join, without its `EXTERNAL_LOOKUP` hint. 
The lookup side of an
+   * eligible join is a chain of hints, aliases, views, projections and 
filters over the table, so
+   * every marker in it is the join's own.
+   */
+  def lookupSide(join: Join): LogicalPlan =
+    join.right.transformUpWithPruning(_.containsPattern(EXTERNAL_LOOKUP_HINT)) 
{
+      case marker: ExternalLookupHint => marker.child
+    }
+
+  /**
+   * The cache options of an eligible join, with its CTEs inlined by 
[[inlineCTEs]]: its hint's, or
+   * the session defaults.
+   */
+  def cacheOptions(join: Join): ExternalLookupCacheOptions =
+    lookupHints(join.right).headOption.map(_.cacheOptions)
+      .getOrElse(ResolveExternalLookupHint.defaultCacheOptions)
+
+  private def ineligible(
+      subClass: String,
+      relation: String,
+      parameters: Map[String, String] = Map.empty): Ineligible =
+    Ineligible(QueryCompilationErrors.unsupportedExternalLookupJoinError(
+      subClass, parameters + ("relation" -> relation)))
+
+  /** The relation that a join input reads: the first operator that has no 
single child. */
+  @tailrec
+  private def input(plan: LogicalPlan): LogicalPlan = plan match {
+    case unary: UnaryNode => input(unary.child)
+    case other => other
+  }
+
+  /**
+   * The first operator below a join input that is not a hint, an alias, a 
view, or a projection or
+   * filter that the lookup join can evaluate on the lookup results. A Python 
or external UDF or a
+   * subquery in one cannot be evaluated there, and the optimizer would 
rewrite some of them into
+   * other operators.
+   */
+  @tailrec
+  private def lookupRelation(plan: LogicalPlan): LogicalPlan = plan match {
+    case node @ (_: ExternalLookupHint | _: ResolvedHint | _: SubqueryAlias | 
_: View) =>
+      lookupRelation(node.children.head)
+    case node @ (_: Project | _: Filter)
+        if 
node.expressions.forall(ExternalLookupJoinShapes.canEvaluateInLookupStage) =>
+      lookupRelation(node.children.head)
+    case other => other
+  }
+
+  /**
+   * The `EXTERNAL_LOOKUP` hints on a join input. Like a join strategy hint, 
the hint applies to the
+   * join that the input feeds, through any unary operator.
+   */
+  @tailrec
+  private def lookupHints(
+      plan: LogicalPlan,
+      found: Seq[ExternalLookupHint] = Nil): Seq[ExternalLookupHint] = plan 
match {
+    case marker: ExternalLookupHint => lookupHints(marker.child, found :+ 
marker)
+    case unary: UnaryNode => lookupHints(unary.child, found)
+    case _ => found
+  }
+
+  /**
+   * The physical join strategy hint, such as `BROADCAST` or `MERGE`, that 
EliminateResolvedHint
+   * would attach to the join, or None if there is none. The `EXTERNAL_LOOKUP` 
hint is never
+   * returned: it is an [[ExternalLookupHint]] marker, not a 
[[JoinStrategyHint]]. A `HintInfo`
+   * without a strategy asks for nothing, so it is skipped.
+   */
+  private def joinStrategyHint(join: Join): Option[JoinStrategyHint] = {
+    // Only the hints that EliminateResolvedHint will attach to this join 
count; a strategy hint
+    // on a nested join belongs to that join.
+    val attached = join.hint.leftHint.toSeq ++ join.hint.rightHint.toSeq ++
+      Seq(join.left, 
join.right).flatMap(EliminateResolvedHint.extractHintsFromPlan(_)._2)
+    attached.flatMap(_.strategy).headOption
+  }
+}
+
+/**
+ * Reports, while a query is analyzed, why a join cannot run as the external 
lookup join it must
+ * be. It does not change the plan: the join stays a [[Join]] until 
[[FormExternalLookupJoin]]
+ * converts it, so the APIs and rules that expect an analyzed join keep 
working. A join that is not
+ * resolved, for example one whose condition is not boolean, is left to the 
analyzer's own join
+ * checks.
+ *
+ * A missing join condition is reported only for the query of a streaming 
write, which is analyzed
+ * in full when the query starts, so that `start()` throws it. Other plans can 
still get their
+ * condition: the classic Dataset API analyzes a USING join first as a join 
without a condition.
+ */
+object CheckExternalLookupJoin extends (LogicalPlan => Unit) {
+  override def apply(plan: LogicalPlan): Unit = {
+    // A join must run as a lookup join only over a lookup-only table, which 
is a DSv2 relation, or
+    // under the hint, so other plans need no walk.
+    if (plan.containsPattern(JOIN) &&
+        plan.containsAnyPattern(DATA_SOURCE_V2_RELATION, 
EXTERNAL_LOOKUP_HINT)) {
+      val complete = plan.isInstanceOf[WriteToStream]
+      plan.foreachUp {
+        case join: Join if join.resolved =>
+          ExternalLookupJoinEligibility(join) match {
+            case ExternalLookupJoinEligibility.Ineligible(error) => throw error
+            case ExternalLookupJoinEligibility.MissingCondition if complete =>
+              throw QueryCompilationErrors.unsupportedExternalLookupJoinError(
+                "MISSING_JOIN_CONDITION")
+            case _ =>
+          }
+        case _ =>
+      }
+    }
+  }
+}
+
+/**
+ * Replaces each join that runs as an external lookup join with an 
[[ExternalLookupJoin]], and
+ * removes the `EXTERNAL_LOOKUP` hints that no join consumed.
+ *
+ * It must run at the start of optimization, before Finish Analysis and 
operator optimization, so
+ * that it sees the join and its lookup side as analysis left them: no hint or 
alias eliminated,
+ * no predicate pushed into the join and no column pruned. These are the 
shapes that
+ * [[CheckExternalLookupJoin]] validated. It also runs before CTEs are 
inlined, so it classifies a
+ * join with the CTEs of its inputs inlined, as the analysis check does, and 
inlines the CTEs of
+ * the lookup side into the lookup join.
+ */
+object FormExternalLookupJoin extends Rule[LogicalPlan] {
+  import ExternalLookupJoinEligibility._
+
+  // As in CheckExternalLookupJoin, a join runs as a lookup join only over a 
lookup-only table,
+  // which is a DSv2 relation, or under the hint, so other plans have no join 
to convert.
+  override def apply(plan: LogicalPlan): LogicalPlan =
+    if (!plan.containsAnyPattern(DATA_SOURCE_V2_RELATION, 
EXTERNAL_LOOKUP_HINT)) plan
+    else formLookupJoins(plan)
+
+  private def formLookupJoins(plan: LogicalPlan): LogicalPlan = {
+    val cteDefs = cteDefinitions(plan)
+    val formed = plan.transformUpWithPruning(_.containsPattern(JOIN)) {
+      case join: Join =>
+        val inlined = inlineCTEs(join, cteDefs)

Review Comment:
   **Nit (P3):** For any plan with a DSv2 relation, this inlines the CTE 
references on both inputs of every join before classifying the join. For a 
reference whose attributes were renewed, such as the second reference in `WITH 
t AS (...) SELECT ... FROM t a JOIN t b ON a.k = b.k`, 
`InlineCTE.inlineReference` runs `DeduplicateRelations.deduplicateRight` over 
the whole CTE body, and when the plan has no `EXTERNAL_LOOKUP` hint and no 
lookup-only table the join is then classified as not a lookup join and the copy 
is thrown away. `lookupSidePlans` repeats the same work in 
`CacheManager.useCachedData` whenever anything is cached, and at streaming 
start. So ordinary batch and streaming queries over DSv2 tables such as Iceberg 
pay an extra CTE copy per renewed reference at each optimization. Plans and 
results are unchanged and the cost is small next to optimization, but those 
queries did not pay it before. A join can be a lookup join only when the plan 
contains the `EXTERNAL_LOOKUP_HINT` pat
 tern or a lookup-only relation, so checking 
`plan.containsPattern(EXTERNAL_LOOKUP_HINT) || 
plan.exists(ExternalLookupRelations.lookupOnlyTable(_).isDefined)` before 
`cteDefinitions` and the per-join inlining, here and in `lookupSidePlans`, 
gives the same plans without the copies. This code comes from the stacked PRs, 
so the fix may belong in the one that owns it.
   
   **Verification:**
   - **Inspection:** The precheck runs before CTE definitions are collected and 
before any per-join inlining, both where lookup joins are formed and where 
lookup sides are searched.
   - **Compatibility:** Lookup joins over lookup-only tables and hinted tables, 
including through WITH clauses and views, and the removal of a hint that marks 
no lookup side behave as before, while an ordinary DSv2 query whose join reads 
a CTE referenced twice keeps its optimized plan.



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