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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteAsOfJoin.scala:
##########
@@ -81,9 +83,34 @@ object RewriteAsOfJoin extends Rule[LogicalPlan] {
         val aggExpr = Alias(nearestRight, "__nearest_right__")()
         val aggregate = Aggregate(Seq.empty, Seq(aggExpr), filtered)
 
-        val projectWithScalarSubquery = Project(
+        val projectWithCorrelatedSubquery = Project(
           left.output :+ Alias(ScalarSubquery(aggregate, left.output), 
"__right__")(),
           left)
+        val projectWithScalarSubquery = if (conf.decorrelateInnerQueryEnabled) 
{

Review Comment:
   **Non-blocking (P2):** With 
`spark.sql.optimizer.decorrelateInnerQuery.enabled` false, this branch also 
sends stream-static DataFrame as-of joins through the forced decorrelation. 
Each micro-batch then gets the default setting's domain join: an aggregate over 
the streaming left side, a MIN_BY aggregate above it, and a stream-stream join 
back to the left side. The base branch's legacy plan has none of these; it 
aggregates only the static side.
   
   By the review's reading of the streaming planner, that changes what these 
queries do:
   
   - A constant-key join with an equality the legacy path already answers 
correctly, such as `stream.joinAsOf(static, lit(10), static("t"), stream("k") 
=== static("k") + 1, ...)`, runs on the base branch. It now fails in its first 
micro-batch in the Append output mode, where `StateStoreSaveExec` rejects an 
aggregation without a watermark, and as a left join in the Update output mode, 
where a stream-stream left outer join is rejected. As an inner join in the 
Update output mode it runs, but whenever a key comes back in a later 
micro-batch, both aggregates emit that key's row again and the stream-stream 
join matches the re-emitted row against every stored streaming row, so the 
earlier rows with that key are emitted again.
   - An inner stream-static join keyed on a left column, which fails with 
INTERNAL_ERROR on the base branch, now returns those duplicated rows in the 
Update output mode with no error.
   - A query that ran on the base branch fails when it restarts from its 
checkpoint, because the new stateful operators have no state directory.
   
   Setting the decorrelation flag back to true does not help, since that 
setting builds the same plan, and `spark.sql.join.sortMergeAsOfJoin.enabled` is 
no way out for the constant-key form, because the sort-merge as-of join rejects 
a constant left as-of key at analysis. The new test runs only batch queries, so 
nothing covers this. It affects only stream-static queries run with the 
internal setting off its default; batch as-of joins keep the fix.
   
   **Recommended change:** In RewriteAsOfJoin, return the base branch's 
correlated projection whenever the as-of join's left side is streaming, not 
only when spark.sql.optimizer.decorrelateInnerQuery.enabled is true, so that 
with the setting false a stream-static as-of join is decorrelated by the legacy 
path as on the base branch and only batch as-of joins get the forced 
decorrelation. Add a TODO at that condition naming what stays deferred: with 
the setting false, stream-static as-of joins keep the base branch's results, 
including its INTERNAL_ERROR and wrong rows, because the domain join the forced 
run would build aggregates the streaming side, so the query would fail in the 
Append output mode and could duplicate rows in the Update output mode, as it 
also does with the setting true. Add streaming as-of join tests that run with 
the setting false.
   
   **Why this works:** The condition at RewriteAsOfJoin.scala line 89 becomes 
true when the decorrelation setting is on or the join's left side is streaming. 
A streaming left side then gets exactly the base branch's projection, so every 
later rule and the micro-batch planner see the plan they see on the base 
branch, with aggregation over the static side only. A batch left side with the 
setting false still takes the forced run, as the PR does now.
   
   **Compatibility:** Batch as-of joins keep exactly the plans the PR builds. 
With spark.sql.optimizer.decorrelateInnerQuery.enabled true, RewriteAsOfJoin 
builds the base branch's plan for every as-of join, streaming or not.
   
   **Risks:** With the setting false, stream-static as-of joins that the base 
branch fails or answers wrongly, such as an inner one keyed on a left column or 
one on a constant key with a non-equality condition, keep the base branch's 
INTERNAL_ERROR or wrong rows. The fix as written would instead fail them in the 
Append output mode and for left joins in the Update output mode, and for inner 
joins in the Update output mode would return the right rows only until a key 
repeats across micro-batches.
   
   **Constraints:** Batch as-of joins with the decorrelation setting false must 
keep the PR's optimized plans and results, so the existing test that compares 
them with the plan the setting true builds keeps passing. The check reads the 
as-of join's own left side when the join is optimized, so it covers every 
micro-batch of a stream-static query, whose streaming leaves are marked as 
streaming, and no batch query, including one run inside foreachBatch.
   
   **Exclusions:**
   - Keeping the legacy plan for batch constant-key joins whose condition 
equates a left column with an injective right expression, which is the author's 
decision in the separate question about their extra work.
   - Correct results for the stream-static as-of joins that the base branch 
fails or answers wrongly with the setting false; they need a rewrite that does 
not aggregate the streaming side, which the setting true also lacks, and the 
TODO records them.
   
   **Verification:**
   - **Regression:** With spark.sql.optimizer.decorrelateInnerQuery.enabled 
false, a stream-static inner as-of join with a constant left as-of key and the 
condition left.k = right.k + 1, run in the Update output mode over two 
micro-batches that repeat a key, returns exactly one row per streaming row, and 
the left as-of join of the same shape runs in the Append output mode and 
returns for each streaming row the static row the as-of join should match.
   - **Behavior:** With the setting false, the optimized plan of a 
stream-static as-of join keyed on a left column, and of one with a constant key 
and the condition left.k = right.k + 1, contains no aggregate over the 
streaming side.
   - **Inspection:** A TODO at the changed condition in RewriteAsOfJoin names 
the stream-static as-of joins whose base-branch INTERNAL_ERROR or wrong rows 
stay unfixed with the setting false, and the domain aggregation over the 
streaming side that keeps them out of the forced run.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteAsOfJoin.scala:
##########
@@ -81,9 +83,34 @@ object RewriteAsOfJoin extends Rule[LogicalPlan] {
         val aggExpr = Alias(nearestRight, "__nearest_right__")()
         val aggregate = Aggregate(Seq.empty, Seq(aggExpr), filtered)
 
-        val projectWithScalarSubquery = Project(
+        val projectWithCorrelatedSubquery = Project(
           left.output :+ Alias(ScalarSubquery(aggregate, left.output), 
"__right__")(),
           left)
+        val projectWithScalarSubquery = if (conf.decorrelateInnerQueryEnabled) 
{
+          projectWithCorrelatedSubquery
+        } else {
+          // Without DecorrelateInnerQuery, PullupCorrelatedPredicates only 
pulls correlated
+          // predicates out of a Filter. It would leave the outer reference in 
the MIN_BY order
+          // expression, and pull a non-equality predicate such as the as-of 
condition above the
+          // Aggregate, which changes its result. So decorrelate this subquery 
as when it is
+          // enabled: run the rules that do it then, with it enabled, on this 
Project alone. A
+          // leaf stands in for `left`, so that other subqueries follow the 
configuration. The
+          // later run of PullupCorrelatedPredicates keeps the result, as it 
has no outer
+          // references left. Like the optimizer, skip an excluded
+          // PullOutNestedDataOuterRefExpressions; PullupCorrelatedPredicates 
is non-excludable.
+          val leftPlaceholder = LocalRelation(left.output)
+          val host = 
projectWithCorrelatedSubquery.withNewChildren(Seq(leftPlaceholder))
+          val pullOutExcluded = 
conf.optimizerExcludedRules.toSeq.flatMap(Utils.stringToSeq)
+            .contains(PullOutNestedDataOuterRefExpressions.ruleName)
+          val decorrelationEnabled = conf.clone()
+          
decorrelationEnabled.setConf(SQLConf.DECORRELATE_INNER_QUERY_ENABLED, true)
+          val decorrelated = SQLConf.withExistingConf(decorrelationEnabled) {
+            PullupCorrelatedPredicates(
+              if (pullOutExcluded) host else 
PullOutNestedDataOuterRefExpressions(host))
+          }.transformUp { case r: LocalRelation if r eq leftPlaceholder => 
left }
+          assert(!decorrelated.exists(_ eq leftPlaceholder), "The placeholder 
for left is left")

Review Comment:
   **Nit (P3):** This check runs after the `transformUp` on line 110 has 
already replaced every node that is `eq leftPlaceholder` in the same 
children-only tree, so it cannot fail. The only input where a parent would keep 
the placeholder is an empty, non-streaming `LocalRelation` left equal to 
`LocalRelation(left.output)`, and then `withNewChildren` on line 102 never 
installs it, because it keeps children that `fastEquals` the new ones. A rule 
that copied the placeholder would slip past both the swap and this check, since 
both compare by reference. So the assertion guards nothing, while `exists` 
walks every node of the restored left plan for each as-of join rewritten with 
`spark.sql.optimizer.decorrelateInnerQuery.enabled` false, and again for each 
outer join in a chain of nested as-of joins. Dropping it keeps every plan and 
result unchanged; moving it before the swap instead would fail for that empty 
left.
   
   **Verification:**
   - **Inspection:** The forced-decorrelation branch of RewriteAsOfJoin 
performs no traversal of the plan after the placeholder substitution, and 
returns the substituted plan as its result.



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