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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala:
##########
@@ -35,80 +41,338 @@ import 
org.apache.spark.sql.execution.datasources.v2.ExternalLookupRelations
  * 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. 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-only
- * table is on the right side.
+ * 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 and views only, 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: the classifier recognizes no lookup-only 
relation as either
-   * of its sides. A lookup-only relation under another operator, such as a 
projection or an
-   * alias, is not recognized yet, and fails later as a batch scan.
+   * 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 reads a lookup-only table, with a supported join type, but has 
no condition. */
+  /**
+   * 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 reads a lookup-only table, which no other join can read, but 
cannot run. */
+  /** 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)
 
-  def apply(join: Join): Eligibility = {
-    // The lookup-only table must be on the right side; the sides are never 
swapped.
-    // TODO: look through projections, filters and aliases above the lookup 
relation.
-    // TODO: allow the EXTERNAL_LOOKUP hint once it is introduced, and 
classify the joins it opts
-    //   in.
-    (ExternalLookupRelations.lookupOnlyTable(join.left), 
lookupOnlyTableOnRight(join)) match {
-      case (Some(table), _) => ineligible("LOOKUP_TABLE_ON_LEFT", table)
-      case (None, Some(table)) => lookupJoinEligibility(join, table)
-      case (None, None) => NotLookupJoin
-    }
-  }
-
   /**
-   * The lookup-only table on the join's right side, also under a strategy 
hint, which is where a
-   * broadcast hint usually goes in a stream-static join. The hint is then 
reported as conflicting.
+   * An operator that the `EXTERNAL_LOOKUP` hint treats as a join: a [[Join]], 
an ASOF or NEAREST BY
+   * join, which Finish Analysis turns into a join, and a lateral join that 
the query writes, which

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 
[3f43f51963d](https://github.com/apache/spark/commit/3f43f51963dfcdbfdf1123050879d134318960f8).
 HintableJoin's Scaladoc now says that none of these operators is a `Join` when 
`EliminateResolvedHint` attaches the hints. It also says how each one runs:
   - **A SQL ASOF join,** or a `joinAsOf` with 
`spark.sql.join.sortMergeAsOfJoin.enabled` set, is planned with its own 
sort-merge operator.
   - **Any other `joinAsOf`** becomes a projection over a correlated scalar 
subquery in Finish Analysis, which operator optimization later rewrites into a 
join.
   - **A NEAREST BY join** becomes a plan with a join in Finish Analysis.
   - **A lateral join** becomes a join in operator optimization.
   
   CheckExternalLookupJoin's Scaladoc says this in short and points to 
HintableJoin.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala:
##########
@@ -35,80 +41,338 @@ import 
org.apache.spark.sql.execution.datasources.v2.ExternalLookupRelations
  * 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. 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-only
- * table is on the right side.
+ * 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 and views only, 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: the classifier recognizes no lookup-only 
relation as either
-   * of its sides. A lookup-only relation under another operator, such as a 
projection or an
-   * alias, is not recognized yet, and fails later as a batch scan.
+   * 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 reads a lookup-only table, with a supported join type, but has 
no condition. */
+  /**
+   * 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 reads a lookup-only table, which no other join can read, but 
cannot run. */
+  /** 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)
 
-  def apply(join: Join): Eligibility = {
-    // The lookup-only table must be on the right side; the sides are never 
swapped.
-    // TODO: look through projections, filters and aliases above the lookup 
relation.
-    // TODO: allow the EXTERNAL_LOOKUP hint once it is introduced, and 
classify the joins it opts
-    //   in.
-    (ExternalLookupRelations.lookupOnlyTable(join.left), 
lookupOnlyTableOnRight(join)) match {
-      case (Some(table), _) => ineligible("LOOKUP_TABLE_ON_LEFT", table)
-      case (None, Some(table)) => lookupJoinEligibility(join, table)
-      case (None, None) => NotLookupJoin
-    }
-  }
-
   /**
-   * The lookup-only table on the join's right side, also under a strategy 
hint, which is where a
-   * broadcast hint usually goes in a stream-static join. The hint is then 
reported as conflicting.
+   * An operator that the `EXTERNAL_LOOKUP` hint treats as a join: a [[Join]], 
an ASOF or NEAREST BY
+   * join, which Finish Analysis turns into a join, and a lateral join that 
the query writes, which
+   * operator optimization turns into a join. Each of the last three becomes a 
join only after the
+   * hints are attached, so a join strategy hint on one is dropped. None of 
them can run as an
+   * external lookup join, so the `EXTERNAL_LOOKUP` hint on one is misplaced 
and fails, rather than
+   * being dropped like a hint that attaches to no join. A lateral join that 
analysis adds for a
+   * table argument of a table function is not written by the query, so it is 
a unary operator for
+   * the hint, as for any other analysis check.
    */
-  private def lookupOnlyTableOnRight(join: Join): Option[Table] = {
-    def underStrategyHints(plan: LogicalPlan): LogicalPlan = plan match {
-      case ResolvedHint(child, hint) if hint.strategy.isDefined => 
underStrategyHints(child)
-      case other => other
+  object HintableJoin {
+    def unapply(plan: LogicalPlan): Boolean = plan match {
+      case _: Join | _: AsOfJoin | _: NearestByJoin => true
+      case lateral: LateralJoin => 
!lateral.containsTag(LateralJoin.BY_TABLE_ARGUMENT)
+      case _ => false
     }
-    ExternalLookupRelations.lookupOnlyTable(underStrategyHints(join.right))
+
+    /** The tree patterns of these operators. */
+    val patterns: Seq[TreePattern] = Seq(JOIN, AS_OF_JOIN, NEAREST_BY_JOIN, 
LATERAL_JOIN)
   }
 
-  private def lookupJoinEligibility(join: Join, table: Table): Eligibility = {
-    if (!join.left.isStreaming) return ineligible("STATIC_LEFT_SIDE", table)
+  def apply(join: Join): Eligibility = {
+    // Every other outcome needs the hint or a lookup-only relation on an 
input of the join.
+    if (!join.containsAnyPattern(EXTERNAL_LOOKUP_HINT, LOOKUP_ONLY_RELATION)) 
return NotLookupJoin
+    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"))
+    }
+    val (tableRelation, table) = lookupTable(join.right) match {
+      case Right(found) => found
+      case Left(rejection) => return rejection
+    }
+    // Rendered only for an error: Table.name() is free-form, such as the path 
of the table's
+    // files, and need not parse as an identifier.
+    lazy val relation = toSQLId(table.name())

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 
[3f43f51963d](https://github.com/apache/spark/commit/3f43f51963dfcdbfdf1123050879d134318960f8),
 as you suggest. A new helper, `toSQLFreeFormId` in `DataTypeErrorsBase`, 
returns `toSQLId(name)` when the name parses, and `toSQLId(Seq(name))` 
otherwise. Every lookup join error that names the lookup table uses it:
   - the eligibility classifier;
   - `PrepareExternalLookupJoin`'s `TABLE`, `NO_LOOKUP_CANDIDATE`, 
`SCAN_BUILDER` and `NO_LOOKUP_PREDICATE`;
   - both `invalidDataSourceExternalLookupError` factories.
   
   #60198 rewrites the `NO_LOOKUP_CANDIDATE` line and keeps the helper.
   
   Tests over tables named `./users`:
   - **When the DataFrame is built:** a hinted join with a static left side 
fails with `STATIC_LEFT_SIDE`. A right outer stream-static join, a full outer 
join over a lookup-only table, and a SQL ASOF join with the hint on its right 
input each fail with `JOIN_TYPE`. Each error names the table as one quoted part.
   - **At start:** a BIGINT stream key against the hinted table's INT `id` 
stops the query when it starts, with `NO_LOOKUP_CANDIDATE`.
   - **Ordinary names:** a multipart name still renders as `` `ns`.`users` ``.
   
   Reverting the helper at any of these sites fails the tests.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FormExternalLookupJoin.scala:
##########
@@ -183,4 +505,15 @@ object FormExternalLookupJoin extends Rule[LogicalPlan] {
           case NotLookupJoin => join
         }
     }
+    stripHints(formed)

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 
[3f43f51963d](https://github.com/apache/spark/commit/3f43f51963dfcdbfdf1123050879d134318960f8).
 A new test in `FormExternalLookupJoinSuite` covers two plans:
   - a union of a formed lookup join with a hinted table;
   - an ordinary join whose input has the marker below a union.
   
   Both pass `CheckExternalLookupJoin`, and neither keeps an 
`ExternalLookupHint` after the rule. The second must equal the same plan 
without the hint. Returning `formed` instead of removing its markers fails the 
test, for either 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