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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/ExternalLookupJoin.scala:
##########
@@ -0,0 +1,427 @@
+/*
+ * 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}
+
+/**
+ * Marks the plan below it as the lookup side that the `EXTERNAL_LOOKUP` hint 
asks an external
+ * lookup join to read. 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) 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],
+    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.
+   * @param lookupOutput The output of the join's right side, the lookup side.
+   */
+  def lookupComparison(
+      conjunct: Expression,
+      streamOutput: AttributeSet,
+      lookupOutput: AttributeSet): Option[LookupComparison] = {
+    def isLookupComparison(lookupField: Attribute, parameter: Expression): 
Boolean =
+      lookupOutput.contains(lookupField) && 
parameter.references.subsetOf(streamOutput)
+    conjunct match {
+      case written: BinaryComparison =>
+        LookupKeyComparison.of(written).flatMap { comparison =>
+          Seq(
+            (written.left, written.right, comparison),
+            (written.right, written.left, comparison.swapped)).collectFirst {
+            case (lookupField: Attribute, parameter, comparison)
+                if isLookupComparison(lookupField, parameter) &&
+                  isOfferedOn(comparison, lookupField, parameter) =>
+              LookupComparison(lookupField, parameter, comparison)
+          }
+        }
+      case _ => None
+    }
+  }
+
+  /**
+   * Whether Spark offers the comparison on this lookup column, with this 
parameter.
+   *
+   * Spark evaluates every parameter on every stream row, before the other 
join conditions. That
+   * is safe for an equality, as a hash join evaluates its keys on every row 
too. A range is a
+   * join condition, which a join evaluates only after its keys match, so its 
parameter must be
+   * one that cannot fail, as `cannotFail` decides.
+   */
+  private def isOfferedOn(
+      comparison: LookupKeyComparison,
+      lookupField: Attribute,
+      parameter: Expression): Boolean =
+    if (comparison.isRange) {
+      ExternalLookupKeyTypes.supportsRange(lookupField.dataType) && 
cannotFail(parameter)
+    } else {
+      ExternalLookupKeyTypes.supportsEquality(lookupField)
+    }
+
+  /**
+   * Whether a range parameter cannot fail: 
ExprUtils.canEvaluateUnconditionally accepts it, or it
+   * is a widening numeric cast of such a value. Analysis adds such a cast 
when the stream side has
+   * a narrower type than the lookup column, as an INT column compared with a 
BIGINT key.
+   */
+  private def cannotFail(parameter: Expression): Boolean = parameter match {
+    case cast: Cast =>
+      isTotalNumericWidening(cast.child.dataType, cast.dataType) &&
+        ExprUtils.canEvaluateUnconditionally(cast.child)
+    case _ => ExprUtils.canEvaluateUnconditionally(parameter)
+  }
+
+  /**
+   * Whether a cast converts every value of its source type: an integral type 
to a wider one, or
+   * an integral type or DECIMAL to a DECIMAL with room for all of its digits. 
`Cast.canUpCast`
+   * is not enough: it also accepts casts that fail on some values, as a 
far-future DATE overflows
+   * a TIMESTAMP, and 9999999999999999999 as DECIMAL(19, 0) exceeds BIGINT 
under ANSI.
+   */
+  private def isTotalNumericWidening(from: DataType, to: DataType): Boolean = 
(from, to) match {
+    case (from: IntegralType, to: IntegralType) => from.defaultSize < 
to.defaultSize
+    case (from: IntegralType, to: DecimalType) => to.isWiderThan(from)

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 
[3bb2bc96d1f](https://github.com/apache/spark/commit/3bb2bc96d1fbd8324b1121353de04c3490f478fb):
 tests for both DECIMAL branches of the range widening rule.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteWithExpression.scala:
##########
@@ -108,6 +108,12 @@ object RewriteWithExpression extends Rule[LogicalPlan] {
       // fold, so a definition there worth memoizing keeps its `With`.
       case c @ (_: Command | _: Call) =>
         c.mapExpressions(inlineCommandWiths)
+      // No definition is evaluated in a projection below an external lookup 
join. One over its
+      // lookup side would become a lookup-side stage, which cannot hold every 
expression that the

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 
[3bb2bc96d1f](https://github.com/apache/spark/commit/3bb2bc96d1fbd8324b1121353de04c3490f478fb):
 a rule test for RewriteWithExpression's lookup-join case. A mutation run shows 
that the test pins 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