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


##########
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:
   **Nit (P3):** This says that Finish Analysis turns an ASOF join into a join, 
and that each of these operators becomes a join only after the hints are 
attached, but a SQL ASOF join never becomes a `Join`. 
`AsOfJoin.fromMatchCondition` sets `requiresSortMergeAsOfJoin = true`, 
`MaterializedMatchCondition.toJoin` keeps it on the SQL path, `RewriteAsOfJoin` 
matches only `!requiresSortMergeAsOfJoin`, and `AsOfJoinSelection` plans the 
node as `SortMergeAsOfJoinExec`; the doc of 
`spark.sql.join.sortMergeAsOfJoin.enabled` says that SQL AS-OF joins always use 
sort-merge. A `joinAsOf` takes the same operator when that setting is on, and 
otherwise becomes a projection over a correlated scalar subquery in Finish 
Analysis, which operator optimization later decorrelates into a join. Only a 
NEAREST BY join becomes a plan with a join in Finish Analysis. The 
`CheckExternalLookupJoin` Scaladoc repeats the claim.
   
   The reasons the check gives still hold, because none of these operators is a 
`Join` when `EliminateResolvedHint` attaches the hints and none can run as an 
external lookup join. But a maintainer who trusts the stated mechanism could 
expect a later rule or a strategy hint to see a SQL ASOF join as a join. Saying 
that these operators are not `Join` nodes when the hints are attached, and that 
the planner runs a SQL ASOF join with its own sort-merge operator, would keep 
the reason accurate.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60019#discussion_r4539401783).
   
   **Verification:**
   - **Inspection:** The Scaladocs of HintableJoin and CheckExternalLookupJoin 
describe a SQL ASOF join, and a DataFrame joinAsOf when 
spark.sql.join.sortMergeAsOfJoin.enabled is set, as planned by its own 
sort-merge operator, never as becoming a join, and describe any other rewrite 
they name, of a default DataFrame joinAsOf, a NEAREST BY join or a lateral 
join, as Spark performs it.



##########
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:
   **Nit (P3):** Making `relation` lazy lets eligible joins over a table named 
like `./users` run, but every error branch that names the table still forces 
it, and `toSQLId(String)` parses the name with `parseAttributeName`, which 
throws `INVALID_ATTRIBUTE_NAME_SYNTAX` at a leading, trailing or doubled dot or 
a misplaced backtick. From the code, 
`spark.range(3).toDF("id").join(spark.table("<cat>.ns.path_dual").hint("external_lookup"),
 "id")` fails with "Syntax error in the attribute name: ./users" instead of 
`STATIC_LEFT_SIDE`, and a RIGHT OUTER stream-static join over the same hinted 
table fails the same way instead of with `JOIN_TYPE`. Lines 101 and 172 render 
the name the same way.
   
   So do the `TABLE`, `NO_LOOKUP_CANDIDATE`, `SCAN_BUILDER` and 
`NO_LOOKUP_PREDICATE` errors of `PrepareExternalLookupJoin` and both 
`invalidDataSourceExternalLookupError` factories. That code comes from the base 
branch, but the hint and the new look-through now send hinted and aliased 
lookup sides into it. For example, a BIGINT stream key against the hinted 
table's INT `id` leaves no lookup candidate, and building `NO_LOOKUP_CANDIDATE` 
throws the same syntax error. The start check stops a query only on lookup 
error classes, so that query starts and fails only in its first micro-batch. In 
each case the user gets an error about a name they never wrote in place of the 
reason. One helper that returns `toSQLId(name)` when the name parses and 
`toSQLId(Seq(name))` otherwise, used at each of these sites, would fix it and 
keep ordinary and multipart names as they are.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60019#discussion_r4539401680).
   
   **Verification:**
   - **Regression:** A hinted join with a static left side over a 
dual-capability table named './users', and a right outer stream-static join 
over the same hinted table, fail with STATIC_LEFT_SIDE and JOIN_TYPE whose 
relation parameter is the whole quoted name, not with 
INVALID_ATTRIBUTE_NAME_SYNTAX.
   - **Regression:** An ineligible join over a lookup-only table with such a 
name, such as a full outer join, and an ASOF join with the hint on its right 
input over such a table, fail with JOIN_TYPE naming their join type and the 
whole quoted name.
   - **Regression:** A streaming query whose BIGINT key joins the INT id column 
of the hinted './users' table stops when it starts, before any data arrives, 
with NO_LOOKUP_CANDIDATE whose table parameter is the whole quoted name.
   - **Inspection:** Every error of the external lookup join that names the 
lookup table, in the eligibility classifier, in the lookup planning rule and in 
both DATA_SOURCE_INVALID_EXTERNAL_LOOKUP factories, renders the name through 
the helper that cannot fail.
   - **Compatibility:** An ineligible join over a table whose name parses as a 
multipart identifier still reports it as the quoted multipart name, and the 
existing errors over single-part names keep their parameters.



##########
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:
   **Nit (P3):** This is the only removal for a stray marker in a plan that has 
a join, and no test reaches it. The stray case in `FormExternalLookupJoinSuite` 
and the end-to-end hints over a single table, an aggregate or a subquery 
without a join all go through the earlier `stripHints(plan)`, and in every 
tested plan with a join the markers are on lookup sides, which `lookupSide` 
removes. From the code, returning `formed` here would leave every test passing, 
yet `stream.join(dual.hint("external_lookup").union(dual), ...)` would then 
keep its marker: the union hides it from `lookupHints`, the join stays 
ordinary, and `CheckExternalLookupJoin` accepts it because no join is below the 
marker. No optimizer rule removes an `ExternalLookupHint` and no planner 
strategy plans one, so such a query would fail at planning with an internal 
error instead of ignoring the hint. Plan tests that form a lookup join next to 
a stray marker, and that keep an ordinary join with a marker below a union on i
 ts input, each asserting that no `ExternalLookupHint` remains, would pin it.
   
   **Verification:**
   - **Regression:** For a plan with a join, both when the join is formed into 
a lookup join and when it stays ordinary because the marker sits below a union 
on its input, the formation rule returns a plan without an EXTERNAL_LOOKUP 
marker. The test fails when the removal after formation is dropped.



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