HeartSaVioR commented on code in PR #59909:
URL: https://github.com/apache/spark/pull/59909#discussion_r4507865899


##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -2855,6 +2898,64 @@
     ],
     "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, with no other operator 
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."
+        ]
+      },
+      "MISSING_JOIN_CONDITION" : {
+        "message" : [
+          "The join has no join condition. Write the lookup condition in the 
join itself, such as in its `ON` clause or the condition argument of `join()`, 
rather than in a later `WHERE` clause or filter."
+        ]
+      },
+      "NO_LOOKUP_CANDIDATE" : {
+        "message" : [
+          "The join condition has no lookup predicate that Spark can offer to 
table <table>. Spark offers only an equality `=` between a lookup column, with 
no cast or other expression applied to it, and an expression over the streaming 
side. If the lookup column is cast to match the streaming side, cast the 
streaming-side expression to the lookup column's type instead. Spark offers it 
only on lookup columns whose type a store compares as Spark does: integral 
types, BOOLEAN, DECIMAL, DATE, TIMESTAMP, TIMESTAMP_NTZ, BINARY, and strings 
with a binary collation such as UTF8_BINARY. It never offers one on FLOAT, 
DOUBLE, CHAR, VARCHAR, a string with another collation, a complex type or any 
other type."

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Fixed in 
[2b3a34f2eda](https://github.com/apache/spark/commit/2b3a34f2eda1bcbebcbd19247e57674edc5044ad).
 The message now says that casting the streaming-side expression keeps the 
join's meaning only when every streaming-side value is exactly representable in 
the lookup column's type. Otherwise the rows that match change, for example 
when a value overflows, a decimal is rounded or a TIMESTAMP becomes a DATE. 
#60055 keeps the same sentence in its version of the message.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PrepareExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,296 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import org.apache.spark.SparkException
+import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.catalyst.analysis.FormExternalLookupJoin
+import org.apache.spark.sql.catalyst.dsl.expressions._
+import org.apache.spark.sql.catalyst.expressions.{Attribute, 
AttributeReference, Expression,
+  Literal}
+import org.apache.spark.sql.catalyst.optimizer.ColumnPruning
+import org.apache.spark.sql.catalyst.plans.{FullOuter, Inner, JoinType, 
LeftOuter, PlanTest}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, Join, 
JoinHint,
+  LocalRelation, LogicalPlan, PreparedExternalLookupJoin, Project}
+import org.apache.spark.sql.connector.catalog.{SupportsRead, Table, 
TableCapability}
+import org.apache.spark.sql.connector.catalog.TableCapability.EXTERNAL_LOOKUP
+import org.apache.spark.sql.connector.expressions.FieldReference
+import org.apache.spark.sql.connector.expressions.filter.Predicate
+import org.apache.spark.sql.connector.read.{ExternalLookup, 
ExternalLookupReaderFactory, Scan,
+  ScanBuilder, SupportsExternalLookup}
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation,
+  ExternalLookupRelation, PrepareExternalLookupJoin}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{IntegerType, LongType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+class PrepareExternalLookupJoinSuite extends PlanTest {
+  private val stream =
+    LocalRelation(Seq($"streamId".int, $"streamLabel".string), isStreaming = 
true)
+  private val QUOTED_TABLE_NAME = "`PlanningExternalLookupTable`"
+
+  private def lookupRelation(table: PlanningExternalLookupTable): 
ExternalLookupRelation =
+    ExternalLookupRelation(
+      DataSourceV2Relation.create(table, None, None, 
CaseInsensitiveStringMap.empty))
+
+  private def lookupJoin(
+      lookup: LogicalPlan,
+      condition: Expression,
+      joinType: JoinType = Inner,
+      left: LogicalPlan = stream): LogicalPlan =
+    FormExternalLookupJoin(Join(left, lookup, joinType, Some(condition), 
JoinHint.NONE))
+
+  private def lookupJoinOnId(lookup: LogicalPlan): LogicalPlan =
+    lookupJoin(lookup, stream.output.head === lookup.output.head)
+
+  private def prepare(plan: LogicalPlan): PreparedExternalLookupJoin =
+    PrepareExternalLookupJoin(plan) match {
+      case lookup: PreparedExternalLookupJoin => lookup
+      case other => fail(s"Expected a prepared external lookup join: $other")
+    }
+
+  private def prepareError(plan: LogicalPlan): AnalysisException =
+    intercept[AnalysisException] { PrepareExternalLookupJoin(plan) }
+
+  test("a lookup-only relation that no lookup join reads is rejected") {
+    val lookup = lookupRelation(PlanningExternalLookupTable())
+    prepare(lookupJoinOnId(lookup))
+    checkError(
+      exception = prepareError(Project(lookup.output, lookup)),
+      condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+      parameters = Map("tableName" -> QUOTED_TABLE_NAME, "operation" -> "batch 
scan"))
+  }
+
+  test("an equality is a lookup candidate only on a type that stores compare 
as Spark does") {
+    val offeredTypes = Seq("TINYINT", "SMALLINT", "INT", "BIGINT", "BOOLEAN", 
"DECIMAL(10, 2)",
+      "DATE", "TIMESTAMP", "TIMESTAMP_NTZ", "BINARY", "STRING", "STRING 
COLLATE UTF8_BINARY")
+    val notOfferedTypes = Seq("FLOAT", "DOUBLE", "CHAR(3)", "VARCHAR(3)",
+      "STRING COLLATE UTF8_LCASE", "STRING COLLATE UNICODE", "STRING COLLATE 
UTF8_BINARY_RTRIM",
+      "STRUCT<a: INT>", "ARRAY<INT>", "INTERVAL DAY TO SECOND")
+    for ((codeType, offered) <- offeredTypes.map(_ -> true) ++ 
notOfferedTypes.map(_ -> false)) {
+      var offeredCandidates = Seq.empty[String]
+      val lookup = lookupRelation(PlanningExternalLookupTable(s"id INT, code 
$codeType", select = {
+        candidates =>
+          offeredCandidates = candidates.map(_.toString).toSeq
+          candidates.take(1)
+      }))
+      val Seq(lookupId, lookupCode) = lookup.output
+      val streamId = stream.output.head
+      val streamCode = AttributeReference("streamCode", lookupCode.dataType)()
+      val codesEqual = streamCode === lookupCode
+      val prepared = prepare(lookupJoin(lookup, streamId === lookupId && 
codesEqual,
+        left = LocalRelation(Seq(streamId, streamCode), isStreaming = true)))
+      val expected = if (offered) Seq("id = ?", "code = ?") else Seq("id = ?")
+      assert(offeredCandidates === expected, codeType)
+      // The connector selects only `id = ?`, so Spark evaluates the code 
equality either way.
+      assert(prepared.residualCondition === Some(codesEqual), codeType)
+    }
+
+    // Without another candidate, the join cannot run.
+    Seq("DOUBLE", "STRING COLLATE UTF8_LCASE").foreach { codeType =>
+      val lookup = lookupRelation(PlanningExternalLookupTable(s"id INT, code 
$codeType"))
+      val lookupCode = lookup.output(1)
+      val streamCode = AttributeReference("streamCode", lookupCode.dataType)()
+      checkError(
+        exception = prepareError(lookupJoin(lookup, streamCode === lookupCode,
+          left = LocalRelation(Seq(streamCode), isStreaming = true))),
+        condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE",
+        parameters = Map("table" -> QUOTED_TABLE_NAME))
+    }
+  }
+
+  test("the residual evaluates key equalities and conjuncts that cannot fail 
first") {
+    val lookup = lookupRelation(PlanningExternalLookupTable("id INT, label 
STRING, value STRING"))
+    val Seq(lookupId, lookupLabel, lookupValue) = lookup.output
+    val Seq(streamId, streamLabel) = stream.output
+    // A cast can fail, so it runs after the equality and the comparison 
written after it, which
+    // keep their written order. The connector selects only `id = ?`.
+    val mayFail = streamLabel.cast(IntegerType) > 0
+    val conjuncts =
+      Seq(lookupId === streamId, mayFail, streamLabel === lookupLabel, 
lookupValue > "a")
+    val prepared = prepare(lookupJoin(lookup, conjuncts.reduce(_ && _)))
+    assert(prepared.residualCondition ===
+      Some(streamLabel === lookupLabel && lookupValue > "a" && mayFail))
+  }
+
+  test("selected predicates bind in the connector's order, and the residual in 
written order") {
+    val Seq(streamId, streamLabel) = stream.output
+    def prepared(select: Array[Predicate] => Array[Predicate])
+        : (PreparedExternalLookupJoin, Seq[Attribute], Seq[Expression]) = {
+      val lookup = lookupRelation(
+        PlanningExternalLookupTable("id INT, label STRING, value STRING", 
select = select))

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Added in 
[2b3a34f2eda](https://github.com/apache/spark/commit/2b3a34f2eda1bcbebcbd19247e57674edc5044ad):
   - a left outer preparation over NOT NULL lookup columns, which checks the 
nullability widening;
   - assertions on `references` and `missingInput`;
   - a plan-string check, with a scan and a reader factory whose names must not 
appear;
   - a selector that reorders the offered array in place, which checks that 
each parameter stays bound to its predicate.
   
   Each test fails without the code it covers.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala:
##########
@@ -0,0 +1,116 @@
+/*
+ * 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, 
Expression}
+import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftOuter}
+import org.apache.spark.sql.catalyst.trees.TreePattern.{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.types.{BinaryType, BooleanType, ByteType, 
CharType, DataType,
+  DateType, DecimalType, IntegerType, LongType, ShortType, StringType, 
TimestampNTZType,
+  TimestampType, VarcharType}
+
+/**
+ * A lookup join retained through ordinary expression and operator 
optimization.
+ *
+ * @param requiredLookupOutput Lookup-side attributes still required above 
this join. They are

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Fixed in 
[2b3a34f2eda](https://github.com/apache/spark/commit/2b3a34f2eda1bcbebcbd19247e57674edc5044ad).
 The doc now says that the field holds every lookup-side attribute, so column 
pruning never puts a projection between the join and the relation that 
preparation needs. In #60055, where `ColumnPruning` starts to narrow this field 
and preparation prunes the scan to it, the doc describes that instead.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PrepareExternalLookupJoinSuite.scala:
##########
@@ -0,0 +1,296 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import org.apache.spark.SparkException
+import org.apache.spark.sql.AnalysisException
+import org.apache.spark.sql.catalyst.analysis.FormExternalLookupJoin
+import org.apache.spark.sql.catalyst.dsl.expressions._
+import org.apache.spark.sql.catalyst.expressions.{Attribute, 
AttributeReference, Expression,
+  Literal}
+import org.apache.spark.sql.catalyst.optimizer.ColumnPruning
+import org.apache.spark.sql.catalyst.plans.{FullOuter, Inner, JoinType, 
LeftOuter, PlanTest}
+import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, Join, 
JoinHint,
+  LocalRelation, LogicalPlan, PreparedExternalLookupJoin, Project}
+import org.apache.spark.sql.connector.catalog.{SupportsRead, Table, 
TableCapability}
+import org.apache.spark.sql.connector.catalog.TableCapability.EXTERNAL_LOOKUP
+import org.apache.spark.sql.connector.expressions.FieldReference
+import org.apache.spark.sql.connector.expressions.filter.Predicate
+import org.apache.spark.sql.connector.read.{ExternalLookup, 
ExternalLookupReaderFactory, Scan,
+  ScanBuilder, SupportsExternalLookup}
+import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation,
+  ExternalLookupRelation, PrepareExternalLookupJoin}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{IntegerType, LongType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+class PrepareExternalLookupJoinSuite extends PlanTest {
+  private val stream =
+    LocalRelation(Seq($"streamId".int, $"streamLabel".string), isStreaming = 
true)
+  private val QUOTED_TABLE_NAME = "`PlanningExternalLookupTable`"
+
+  private def lookupRelation(table: PlanningExternalLookupTable): 
ExternalLookupRelation =
+    ExternalLookupRelation(
+      DataSourceV2Relation.create(table, None, None, 
CaseInsensitiveStringMap.empty))
+
+  private def lookupJoin(
+      lookup: LogicalPlan,
+      condition: Expression,
+      joinType: JoinType = Inner,
+      left: LogicalPlan = stream): LogicalPlan =
+    FormExternalLookupJoin(Join(left, lookup, joinType, Some(condition), 
JoinHint.NONE))
+
+  private def lookupJoinOnId(lookup: LogicalPlan): LogicalPlan =
+    lookupJoin(lookup, stream.output.head === lookup.output.head)
+
+  private def prepare(plan: LogicalPlan): PreparedExternalLookupJoin =
+    PrepareExternalLookupJoin(plan) match {
+      case lookup: PreparedExternalLookupJoin => lookup
+      case other => fail(s"Expected a prepared external lookup join: $other")
+    }
+
+  private def prepareError(plan: LogicalPlan): AnalysisException =
+    intercept[AnalysisException] { PrepareExternalLookupJoin(plan) }
+
+  test("a lookup-only relation that no lookup join reads is rejected") {
+    val lookup = lookupRelation(PlanningExternalLookupTable())
+    prepare(lookupJoinOnId(lookup))
+    checkError(
+      exception = prepareError(Project(lookup.output, lookup)),
+      condition = "UNSUPPORTED_FEATURE.TABLE_OPERATION",
+      parameters = Map("tableName" -> QUOTED_TABLE_NAME, "operation" -> "batch 
scan"))
+  }
+
+  test("an equality is a lookup candidate only on a type that stores compare 
as Spark does") {
+    val offeredTypes = Seq("TINYINT", "SMALLINT", "INT", "BIGINT", "BOOLEAN", 
"DECIMAL(10, 2)",
+      "DATE", "TIMESTAMP", "TIMESTAMP_NTZ", "BINARY", "STRING", "STRING 
COLLATE UTF8_BINARY")
+    val notOfferedTypes = Seq("FLOAT", "DOUBLE", "CHAR(3)", "VARCHAR(3)",
+      "STRING COLLATE UTF8_LCASE", "STRING COLLATE UNICODE", "STRING COLLATE 
UTF8_BINARY_RTRIM",
+      "STRUCT<a: INT>", "ARRAY<INT>", "INTERVAL DAY TO SECOND")
+    for ((codeType, offered) <- offeredTypes.map(_ -> true) ++ 
notOfferedTypes.map(_ -> false)) {
+      var offeredCandidates = Seq.empty[String]
+      val lookup = lookupRelation(PlanningExternalLookupTable(s"id INT, code 
$codeType", select = {
+        candidates =>
+          offeredCandidates = candidates.map(_.toString).toSeq
+          candidates.take(1)
+      }))
+      val Seq(lookupId, lookupCode) = lookup.output
+      val streamId = stream.output.head
+      val streamCode = AttributeReference("streamCode", lookupCode.dataType)()
+      val codesEqual = streamCode === lookupCode
+      val prepared = prepare(lookupJoin(lookup, streamId === lookupId && 
codesEqual,
+        left = LocalRelation(Seq(streamId, streamCode), isStreaming = true)))
+      val expected = if (offered) Seq("id = ?", "code = ?") else Seq("id = ?")
+      assert(offeredCandidates === expected, codeType)
+      // The connector selects only `id = ?`, so Spark evaluates the code 
equality either way.
+      assert(prepared.residualCondition === Some(codesEqual), codeType)
+    }
+
+    // Without another candidate, the join cannot run.
+    Seq("DOUBLE", "STRING COLLATE UTF8_LCASE").foreach { codeType =>
+      val lookup = lookupRelation(PlanningExternalLookupTable(s"id INT, code 
$codeType"))
+      val lookupCode = lookup.output(1)
+      val streamCode = AttributeReference("streamCode", lookupCode.dataType)()
+      checkError(
+        exception = prepareError(lookupJoin(lookup, streamCode === lookupCode,
+          left = LocalRelation(Seq(streamCode), isStreaming = true))),
+        condition = "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED.NO_LOOKUP_CANDIDATE",
+        parameters = Map("table" -> QUOTED_TABLE_NAME))
+    }
+  }
+
+  test("the residual evaluates key equalities and conjuncts that cannot fail 
first") {
+    val lookup = lookupRelation(PlanningExternalLookupTable("id INT, label 
STRING, value STRING"))
+    val Seq(lookupId, lookupLabel, lookupValue) = lookup.output
+    val Seq(streamId, streamLabel) = stream.output
+    // A cast can fail, so it runs after the equality and the comparison 
written after it, which
+    // keep their written order. The connector selects only `id = ?`.
+    val mayFail = streamLabel.cast(IntegerType) > 0
+    val conjuncts =
+      Seq(lookupId === streamId, mayFail, streamLabel === lookupLabel, 
lookupValue > "a")

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
   
   Added in 
[2b3a34f2eda](https://github.com/apache/spark/commit/2b3a34f2eda1bcbebcbd19247e57674edc5044ad).
 A fallible stream-side conjunct is written before `code = CAST(label AS INT)` 
and `alt <=> CAST(label AS INT)`, and the test checks that both equalities come 
first. Making `isJoinKeyEquality` always false, or dropping its `<=>` case, 
fails it.



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