Repository navigation
[SPARK-62239][SQL] Fix wrong results and INTERNAL_ERROR in DataFrame as-of joins when spark.sql.optimizer.decorrelateInnerQuery.enabled is false - #60783
Conversation
…as-of joins when `spark.sql.optimizer.decorrelateInnerQuery.enabled` is false
spark-test
left a comment
There was a problem hiding this comment.
Review summary
By the review's reading of the code, when spark.sql.optimizer.decorrelateInnerQuery.enabled is false the forced decorrelation gives batch DataFrame as-of joins the plan the setting true builds, which removes the INTERNAL_ERROR and the extra right rows the PR describes, and the default setting keeps the base branch's plan. The review found two problems in the forced-decorrelation branch of RewriteAsOfJoin. The forced run also applies to stream-static as-of joins, where the domain join it builds aggregates the streaming side, so, with the setting false, queries that run on the base branch can fail or, in the Update output mode, return duplicated rows, and inner joins keyed on a left column that failed loudly before now return duplicated rows instead (RewriteAsOfJoin.scala line 89). Separately, the assertion after the placeholder swap can never fail, yet it walks the whole left plan on every rewrite (RewriteAsOfJoin.scala line 111). One question for the author follows under Decision challenges. The review also covered the excluded-rules check for PullOutNestedDataOuterRefExpressions, the copied session configuration, the stand-in that keeps the left side's own subqueries on the configured decorrelation, the later legacy pass that keeps the decorrelated subquery, and the unchanged default setting, and found no problem in them.
Findings
2 total: 0 P0, 0 P1, 1 P2, 1 P3.
Non-blocking (P2)
- Forced decorrelation breaks stream-static as-of joins when decorrelateInnerQuery is disabled —
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteAsOfJoin.scala:89— see inline.
Nit (P3)
- Assertion after the placeholder swap can never fail —
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteAsOfJoin.scala:111— see inline.
PR description suggestions
- The user-facing-change section covers batch as-of joins only. It should also say what happens to stream-static DataFrame as-of joins with spark.sql.optimizer.decorrelateInnerQuery.enabled false: as written they get the setting-true plan, which aggregates the streaming side, or, if streaming left sides are left out of the forced decorrelation, that they keep their previous behavior.
Decision challenges
Domain join added to constant-key as-of joins the legacy plan already answers correctly
Location: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteAsOfJoin.scala:89
With spark.sql.optimizer.decorrelateInnerQuery.enabled false, a constant-key DataFrame as-of join whose condition equates a left column with an injective expression of right columns, such as l.joinAsOf(r, lit(10), r("t"), l("k") === r("k") + 1, joinType = "left", ...), now reads the left side twice and joins every filtered right row with a domain of distinct left keys before aggregating, work that grows with both sides, although the base branch already returns the right rows for it with a cheaper plan.
On the base branch the legacy decorrelation groups the filtered right side by r.k and joins it to the left side on l.k = r.k + 1, which is correct because r.k + 1 is injective. The forced run in RewriteAsOfJoin.scala lines 89-113 gives these joins the plan the default setting builds: DecorrelateInnerQuery.canPullUpOverAgg rejects outer(l.k) = r.k + 1, so l.k becomes a domain attribute, and the optimized plan adds an aggregate of the distinct l.k values over the left side, joins it with the filtered right rows on k' = r.k + 1, groups by k' and joins the result back to the left side on l.k <=> k'. By the review's reading of the code both plans return the same rows. Constant-key joins with no condition, with attribute or up-cast equalities, or with predicates on left columns only keep the base branch's plan, and pandas-on-Spark merge_asof never builds this shape, because it always keys on a left column. Stream-static queries of this shape are covered by the separate finding on stream-static as-of joins.
The cheaper implementation the review found keeps the legacy decorrelation for constant-key subqueries whose correlated conjuncts that DecorrelateInnerQuery cannot pull up are all equalities between a left column and a right expression proven injective. The trade-off is that such a guard must decide injectivity for every expression it admits, and a mistake, such as r.k % 10 or a wrapping multiplication, sends the legacy path a subquery it answers with duplicate rows.
The review leans toward deferring that guard with a TODO, because extra work beyond what a correction needs is accepted once the author defers a redesign that is a real trade-off.
Any of these settles it:
- Defer the guard: keep the forced decorrelation for these joins and add a TODO at the forced run in RewriteAsOfJoin naming constant-key joins whose condition equates a left column with an injective expression of right columns as joins that could keep the legacy plan;
l.k === r.k + 1keeps the domain-join plan. - Adopt the guard: add it before the forced run with an injectivity check over the right-side expressions it admits, plus tests that
l.k === r.k + 1keeps the legacy plan and its rows whilel.k === r.k % 10still gets the forced decorrelation. - Keep the change as is:
l.k === r.k + 1keeps the plan the default setting builds, and the code does not change.
Generated by Omnigent on Databricks
| val projectWithCorrelatedSubquery = Project( | ||
| left.output :+ Alias(ScalarSubquery(aggregate, left.output), "__right__")(), | ||
| left) | ||
| val projectWithScalarSubquery = if (conf.decorrelateInnerQueryEnabled) { |
There was a problem hiding this 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, whereStateStoreSaveExecrejects 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.
There was a problem hiding this comment.
Thank you. You're right about the regression. With the configuration false, a stream-static as-of join with a constant left as-of key and an equality such as k === qk + 1 returned the matching rows on master, and the forced decorrelation made it fail. I confirmed it with a streaming query.
One correction: in the Update output mode, the inner join doesn't return duplicated rows. It fails with Update output mode is not supported for stream-stream LeftOuter join, because the scalar subquery becomes a left outer join. The same failures happen with the configuration true, so DataFrame stream-static as-of joins on this path fail by default as well. I'll file a new JIRA issue for that.
I applied your recommendation in 084a497. A streaming left side now keeps the correlated subquery for the legacy decorrelation, with a TODO, and a new test in StreamingAsOfJoinSuite runs a stream-static as-of join with the configuration false. I also updated the PR description.
| 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") |
There was a problem hiding this 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.
There was a problem hiding this comment.
Thank you. Right, the assertion could not fail, and it would not catch a copied placeholder either. In 084a497, I removed it and changed the swap to compare with ==, which also replaces a copy. An empty LocalRelation left that equals the placeholder is replaced by itself.
…as-of joins when `spark.sql.optimizer.decorrelateInnerQuery.enabled` is false
|
For the decision challenge in the review summary, on constant-key as-of joins whose condition equates a left column with an injective expression of right columns: I'd like to keep the change as is. With the configuration false, the goal is the plan that the default configuration builds, and such batch joins with a constant left as-of key are rare. A guard would have to prove injectivity, and a mistake there would send the legacy path a subquery that it answers with duplicate rows. |
What changes were proposed in this pull request?
This PR fixes a correctness issue and an
INTERNAL_ERRORin DataFrame as-of joins (Dataset.joinAsOf, PySparkDataFrame._joinAsOfandpyspark.pandas.merge_asof) that are rewritten into a correlated scalar subquery, which is the default (spark.sql.join.sortMergeAsOfJoin.enabledis false), when the internalspark.sql.optimizer.decorrelateInnerQuery.enabledis false.RewriteAsOfJoinrewrites the join into the following subquery for each left row.Its outer references are in the
MIN_BYorder expression and in a non-equality predicate under anAggregate, and onlyDecorrelateInnerQuerycan decorrelate them. When the configuration is false,PullupCorrelatedPredicatesuses the legacypullOutCorrelatedPredicatesinstead, which only pulls correlated predicates out of aFilter:Aggregateand adds their right-side columns to the grouping. The subquery then returns one row per group instead of the nearest right row, and the join returns every matching right row. This shows when the left as-of key is a constant, because then no other outer reference is left.MIN_BYorder expression, so the query fails at execution withINTERNAL_ERROR. This happens for every as-of join whose left as-of key references the left side, with or without a join condition.The analyzer rejects both shapes in user-written subqueries when the configuration is false, but
RewriteAsOfJoinis an optimizer rule and builds them after analysis.With this PR, when the configuration is false,
RewriteAsOfJoindecorrelates its subquery as the optimizer does when the configuration is true. It runs the two rules that do it then,PullOutNestedDataOuterRefExpressionsandPullupCorrelatedPredicates, with the configuration enabled, on theProjectthat holds the subquery alone. A leaf stands in for the left side during these runs, so that other subqueries in it still follow the configuration. The later run ofPullupCorrelatedPredicateskeeps the decorrelated subquery as it is, since it has no outer references left, andRewriteCorrelatedScalarSubquerybuilds the join as usual. The optimized plan is the same as with the configuration enabled. Nothing changes when the configuration is true, which is the default.A streaming left side, as in a stream-static as-of join, keeps the previous plan, with a TODO. The decorrelated plan aggregates the streaming side, which streaming queries reject, as they also do with the configuration enabled, while the legacy plan aggregates only the static side and works for some of these joins, such as one with a constant left as-of key and an equality condition.
Why are the changes needed?
spark.sql.optimizer.decorrelateInnerQuery.enabledis an internal configuration (since 3.2.0) that turns off theDecorrelateInnerQueryframework. Nothing documents turning it off as a supported fallback, but when it is turned off, every non-sort-merge as-of join fails or returns wrong results. This affects all releases since v3.3.0 (2022-06-09), which addedRewriteAsOfJoin. It is confirmed onmaster, v3.5.9 (2026-07-12), v4.0.5 (2026-10-21), v4.1.4 (2026-10-21), v4.2.1 (2026-10-21) and v4.3.0 (2026-10-27).Does this PR introduce any user-facing change?
Yes, only when
spark.sql.optimizer.decorrelateInnerQuery.enabledis false. DataFrame as-of joins return the same results as with the configuration enabled, instead of wrong results orINTERNAL_ERROR. Stream-static as-of joins keep their previous behavior.How was this patch tested?
Pass the CIs with the newly added test cases.
DataFrameAsOfJoinSuitechecks that, with the configuration false, the optimized plans and the results are the same as with it enabled, including a join condition on a map member of the left side. Without this fix, it fails because the optimized plans differ.StreamingAsOfJoinSuitechecks that, with the configuration false, a stream-static as-of join with a constant left as-of key and an equality condition still returns the matching rows. Decorrelating it like a batch join would fail it withUNSUPPORTED_STREAMING_OPERATOR_WITHOUT_WATERMARK.I also checked manually that the results and the optimized plans are the same with the configuration false and true for inner and left outer joins in all three directions, with a tolerance, with
usingColumns, for a self join and for nested as-of joins. A left side with a correlatedEXISTSsubquery also gives the same results.Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5