Skip to content

perf(sql): support safe shuffle MARK joins - #26147

Merged
XuPeng-SH merged 10 commits into
mainfrom
fix/shuffle-mark-join
Jul 28, 2026
Merged

XuPeng-SH merged 10 commits into
mainfrom
fix/shuffle-mark-join

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

What changed

  • Enable shuffle hash execution for MARK joins only when every join predicate is an equi-condition and both key expressions are effectively non-null after child materialization.
  • Account for null extension introduced by LEFT/RIGHT/FULL/SINGLE joins and OUTER APPLY instead of trusting bind-time Expr.Typ.NotNullable metadata.
  • Derive outer-join output nullability without mutating reusable child projection metadata.
  • Add independent planner remap and compiler eligibility guards; stale unsafe shuffle decisions fall back to broadcast instead of surfacing a query error.
  • Support both local shared-pool and distributed shuffle topologies.
  • Support the latest planner post-remap RelPos 0/1 shuffle pass while retaining binding-tag validation in the normal optimizer pass.
  • Add planner/compiler coverage plus a real Multi-CN spill BVT for projected IN result semantics.

Correctness boundary

Nullable MARK joins need global build-side empty/null facts to preserve three-valued SQL semantics. Those facts are available on the broadcast path but are not shared across shuffle buckets. Nullable or null-extended MARK keys therefore remain on broadcast. Residual predicates and mixed-side expressions also fall back conservatively.

Standard TPCH Q18 still plans as a SEMI join, so this PR does not claim a Q18 improvement. This is a follow-up to #25822 for MARK joins used in value-producing contexts.

Validation

  • Targeted planner/compiler tests: pass
  • Targeted planner/compiler tests with -race: pass
  • Full ./pkg/sql/plan ./pkg/sql/compile UT: pass
  • go build ./pkg/sql/plan ./pkg/sql/compile: pass
  • go vet ./pkg/sql/plan ./pkg/sql/compile: pass
  • Regression coverage for bind-time NOT NULL keys made nullable by LEFT/FULL join output, pre-remap planning, post-remap validation, and compiler broadcast fallback
  • Multi-CN spill BVT added for 4,000,000 TRUE / 1,000,000 FALSE / 0 NULL projected IN results
  • Real TPCH SF10 data on a two-CN local deployment: a MARK query over 15,000,000 orders and 59,986,052 lineitems improved from 0.77-0.89s on the parent commit to 0.47-0.60s with this change (about 25-42%). Both CNs share one host in this validation, so this establishes execution-path value but is not a substitute for network-separated cluster benchmarking.

@XuPeng-SH
XuPeng-SH requested a review from aunjgr as a code owner July 24, 2026 09:21
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

I found one blocking issue in this pass.

  • pkg/sql/compile/compile.go:3781-3785
    The new compiler-side MARK shuffle guard panics when a stale/unsafe HashmapStats.Shuffle flag reaches compileJoin. That turns a recoverable planner mismatch into a user-visible query failure, even though compileJoin already has a correct broadcast fallback immediately below. A nullable or residual MARK join that still arrives here with Shuffle=true will now fail with shuffle MARK join requires pure equality predicates with statically non-null keys instead of clearing the stale shuffle choice and compiling to the existing broadcast MARK path.

    Suggestion: treat this guard as a safety fallback, not a hard failure. Clear the shuffle decision here and continue with the broadcast join path, so an unsafe planner flag cannot select shuffle MARK execution and does not regress a previously-correct query into an error.

I did not find another high-confidence blocking correctness issue beyond this one.

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes for one reachable MARK-join three-valued correctness bug. The new planner/compiler tests pass and CI is green, but the eligibility check only covers directly non-null scan keys and misses NULL-extension by an upstream outer join.

Comment thread pkg/sql/plan/shuffle.go Outdated
for _, condition := range node.OnList {
fn := condition.GetF()
if fn == nil || len(fn.Args) != 2 ||
!fn.Args[0].Typ.NotNullable || !fn.Args[1].Typ.NotNullable {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Do not rely on Expr.Typ.NotNullable alone here. A column from the null-generating side of an upstream outer join can still carry the base table's NotNullable=true metadata after final remap. For example, SELECT r.r_regionkey IN (SELECT l.l_partkey FROM lineitem l) FROM nation n LEFT JOIN region r ON n.n_regionkey=r.r_regionkey produces a MARK key whose type remains non-nullable although unmatched rows contain NULL; with production-sized build/NDV stats this function enables shuffle. Shuffle routes those NULL probes to bucket 0, and if that bucket has no build rows while another bucket does, appendMarkForEmptyBuildBucket sees a local row count of zero and emits FALSE, whereas NULL IN (nonempty non-null set) must be NULL. The compiler guard repeats the same type check, so it does not catch this. Please derive eligibility from the child output's effective nullability (including outer-join null extension), or conservatively keep such keys on broadcast, and add a regression covering this plan shape.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

最新 head 已修复 LEFT/FULL OUTER 的这条路径,但 SINGLE 的 NULL 扩展仍遗漏,仍可触发同类 P1 correctness bug。

可复现的真实计划形状:

select d.regionkey in (select l.l_partkey from tpch.lineitem l)
from (
  select (
    select r.r_regionkey
    from tpch.region r
    where r.r_regionkey = n.n_regionkey
  ) regionkey
  from tpch.nation n
) d;

runOneStmt 产生 SINGLE -> MARK。scalar subquery 0 行时,LEFT SINGLE 的 build 输出运行时为 NULL,但 remapAllColRefs 当前只把 LEFT/OUTER 的右输出、RIGHT/OUTER 的左输出设 nullable,导致 SINGLE build output 仍是 NotNullable=true。随后 irregular-index INSERT/LOAD 的 determineShuffleForDMLSteps() 会对完整、已 remap 的 source graph 再跑 determineShuffleMethodAfterRemap;把该 MARK 的 build/NDV stats 调到 production 阈值后,实测 Shuffle 被重新开启。compiler guard 又读取同一份错误的 child ProjectList,因此不会 fallback。

这会让 scalar subquery 产生的 NULL probe 在某些空 bucket 上得到 FALSE,而 NULL IN (nonempty non-null set) 应为 NULL。最小修正是同时传播 SINGLE 的 NULL 扩展:left output 包含 (SINGLE && IsRightJoin),right output 包含 (SINGLE && !IsRightJoin);加入这两处后上述回归通过。请补真实 SINGLE -> MARK post-remap 回归。

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Blocking P1 on the latest head: a row-shaping aggregate can still erase outer-join NULL extension and re-enable an unsafe shuffle MARK join.

A reachable example is:

select d.regionkey in (
  select l.l_partkey from tpch.lineitem l
)
from (
  select r.r_regionkey as regionkey
  from tpch.nation n
  left join tpch.region r on n.n_regionkey = r.r_regionkey
  group by r.r_regionkey
  limit 10
) d;

The LEFT JOIN correctly materializes its right key as nullable, but the AGG remap rewrites node.GroupBy through the child and then emits ProjectList with the old bind-time expr.Typ; it never calls refreshExprNullabilityFromInputs on the group expression. The PROJECT above it therefore also sees a stale NotNullable=true. The pre-remap path has the same gap because colRefEffectivelyNotNullableBeforeRemap trusts the AGG's own binding tag instead of resolving the referenced GroupBy expression against its child.

This is not only stale metadata. With left/right output counts 10M/3M, a 3M build hashmap, and NDV 100K, I verified on c7e9e8a794 that determineShuffleForJoinWithColRefMode(..., true) leaves Shuffle=true. The LIMIT/PROJECT layer means the existing direct-AGG dontShuffle check does not protect this shape, and the compiler guard reads the same stale child ProjectList. An unmatched outer row forms the NULL group; if that probe is sent to a locally empty bucket while the global build is nonempty, MARK returns FALSE although NULL IN (nonempty non-NULL set) must be UNKNOWN.

The same root cause is independently reachable through SAMPLE(... GROUP BY nullable_outer_key) -> LIMIT -> MARK; it also enables shuffle under the same forced production-scale stats. TIME_WINDOW partition output can inherit the stale AGG group-key type as well.

Please fix the type contract at the materialization boundary instead of adding another LIMIT/dontShuffle shape check:

  • after remapping AGG/SAMPLE group expressions, recompute their nullability from the materialized child before building ProjectList;
  • in the pre-remap resolver, resolve AGG/SAMPLE group binding slots through the corresponding GroupBy expression and child rather than trusting the binding tag;
  • add real-plan AGG and SAMPLE regressions with a row-shaping node above them, force shuffle-eligible stats, and assert both planner rejection and compiler fallback.

All full pkg/sql/plan and pkg/sql/compile tests, focused -race tests, and hashjoin/hashbuild tests pass locally, so current coverage does not exercise this unhappy path.

@matrix-meow matrix-meow added size/XXL Denotes a PR that changes 2000+ lines and removed size/XL Denotes a PR that changes [1000, 1999] lines labels Jul 28, 2026

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

还有 1 个可达的数据正确性 blocker:WINDOW 物化输出没有进入 effective-nullability 闭包。真实 planner SQL 已验证 LAG(NOT NULL column) 在 pre-remap 和 remap 后都会被判为可 shuffle,compiler fallback 也读取同一份错误的 child ProjectList,无法拦截。PR 自带的 targeted UT 与三个相关包全量 UT 均通过,但没有覆盖这条路径。

Comment thread pkg/sql/plan/shuffle.go
}
}
return nil, -1, true
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 这里仍漏掉了 WINDOW 这个物化边界。可复现 SQL:

select d.k in (select l.l_partkey from tpch.lineitem l)
from (
  select lag(n.n_regionkey) over (order by n.n_nationkey) k
  from tpch.nation n
) d;

n_regionkey 是 NOT NULL,因此 binder 把 lag(...) 标成 NotNullable=true;但没有 default 的 LAG 在每个 partition 首行必然返回 NULL。当前 helper 遇到 WINDOW 会落到下面的 binding-tag 快路径直接返回 true,而 remap 的 WINDOW 分支又原样复制 expr.Typ,所以我用真实 plan 分别调用 pre-remap 和 after-remap 的 determineShuffleForJoinWithColRefMode,两处都错误地开启了 shuffle。compiler guard 继续读取相同的 WINDOW ProjectList,也不会 fallback。这样 NULL probe 落到局部 build 为空、但全局 build 非空的 bucket 时会得到 FALSE,而 NULL IN (nonempty non-null set) 应为 NULL。请让 WINDOW 输出 fail closed 或传播其真实运行时 nullability,并补 pre-remap + remap/compiler 回归。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已在 adc05a87bd 系统性修复并补回归。

这次没有只加一个 Node_WINDOW 枚举:

  • 修正 value-window 的真实类型契约:无 default 的 LAG/LEAD、可遇到空 frame 的 FIRST_VALUE/LAST_VALUE/NTH_VALUE 不再继承输入的 NOT NULL;
  • pre-remap 从 WINDOW 的 WinSpecList 证明实际输出,能穿过 stacked WINDOW/PARTITION,不能再被复用的 binding tag 快路径绕过;
  • remap 后用同一套保守证明生成 WINDOW ProjectList,测试会刻意把 MARK condition 恢复成陈旧的 NotNullable=true,确认 planner 和 compiler guard 仍从 child materialized contract 拒绝 shuffle;
  • 自审时沿同一闭包又复现了 scalar aggregate output(空输入上的 MAX(NOT NULL))以及 TIME_WINDOW materialization 的同类缺口,因此一并把 AGG/SAMPLE/TIME_WINDOW/FILL 的 value-output 证明闭合;非空 SAMPLE 的正向 shuffle case 保持可用。

验证:focused -race -count=100(window/materializer planner、window nullability、compiler fallback)全部通过;pkg/sql/plan/function、pkg/sql/plan、pkg/sql/compile 全包 -race -count=1 通过;三包 build/vet 通过。

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep re-review completed on exact head adc05a87bd80d7ed1487590c4a62112cac069987.

I found no new merge-blocking correctness or performance issue.

This pass re-derived the full safety chain instead of checking only the last WINDOW fix:

  • planner admission before remap: every MARK predicate must remain pure equi-join and both materialized operands must have a strong non-NULL proof;
  • materialization closure: outer JOIN/SINGLE/APPLY null extension, PROJECT/MATERIAL, UNION variants, AGG/SAMPLE, TIME_WINDOW/FILL, WINDOW/PARTITION, SINK/SINK_SCAN, and recursive CTE fixed-point contracts;
  • post-remap and late-DML re-planning: unsafe/stale shuffle state is cleared, local RelPos 0/1 inputs are checked against child output contracts, and shuffle runtime-filter prerequisites remain present;
  • compiler defense: stale unsafe MARK plans fail closed to the existing broadcast implementation instead of erroring or selecting bucket-local semantics;
  • execution theorem: with all equality operands effectively non-null, exact matches co-locate and every miss is FALSE, so local/shared and distributed buckets do not need global empty/NULL facts;
  • unhappy paths: this diff introduces no new goroutine, lock, channel, FD, or unbounded ownership edge.

Focused current-head regressions for planner nullability/shuffle admission, compiler fallback/topologies, and window-function contracts pass. git diff --check is clean.

GitHub does not allow the PR author to approve their own PR; on code, this pass is approve-equivalent. The existing external CHANGES_REQUESTED state is still visible until that reviewer updates/dismisses it, and CI is still the delivery gate.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve-equivalent deep review on exact head adc05a8: no new correctness or production blocker found.

I rebuilt mo-service from this head and started a fresh native 2-CN cluster (cn1:16001, cn2:16002) with isolated storage. Both CNs observed the same 5,000,000-row probe table, and the tested plans were AP QUERY PLAN ON MULTICN.

Cross-CN execution evidence:

  • single NOT NULL key: MARK + range shuffle, result true/false/null = 2,500,000 / 2,500,000 / 0;
  • composite NOT NULL key: two equality predicates plus range shuffle, same exact result;
  • nullable probe/build, including a NULL build row: MARK remained unshuffled, result 2,500,000 / 0 / 2,500,001;
  • LEFT-join NULL extension feeding MARK: the inner LEFT join shuffled, the outer MARK did not, result 2,500,000 / 0 / 2,500,000;
  • LAG(NOT NULL column) without a default: MARK did not shuffle, result 2,499,999 / 2,500,000 / 1;
  • ROW_NUMBER() materialization: MARK still used hash shuffle, result 2,500,000 / 2,500,000 / 0, confirming that the fix does not disable the safe optimization wholesale.

The planner admission, post-remap/late-DML recheck, and compiler fallback therefore agree on the same materialized-nullability contract in both unsafe and safe cases. The bucket-local theorem also holds for the exercised single and composite keys: with every operand proven non-NULL, exact matches co-locate and every miss is FALSE; otherwise execution falls back to broadcast/global facts.

Local validation also passed for pkg/sql/plan, pkg/sql/compile, and pkg/sql/plan/function: full package tests both normal and -race, focused MARK/nullability regressions, and go vet. git diff --check is clean. The temporary 2-CN data and processes were removed after validation.

GitHub does not allow the PR author to approve their own PR, so this COMMENT is the strongest available review action. The remaining CHANGES_REQUESTED state is from the older WINDOW finding; the real LAG reproduction above confirms that blocker is fixed and should be re-reviewed/dismissed by an external reviewer. I did not wait for the still-running CI jobs.

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes for one reachable normal-business performance regression. The previous OUTER/SINGLE/WINDOW three-valued-correctness blockers are fixed on this head, and the targeted/full planner/compiler tests pass, but the strong shuffle-only nullability proof now also controls the existing broadcast composite MARK operator choice.

for i := range rs {
var op vm.Operator
if canUseHashMarkJoin(node) {
if canUseHashMarkJoinWithInputs(node, left, right) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Keep the shuffle-only strong proof out of broadcast MARK selection. This production branch now calls IsJoinExprEffectivelyNotNullable, whose function case rejects every ordinary expression except PRODUCE_NO_NULL and serial{,_full}; remap also clears the operand NotNullable bit. A real planner query such as

select (n.n_nationkey + 0, n.n_regionkey + 0) in (select l.l_orderkey + 0, l.l_partkey + 0 from tpch.lineitem l) from tpch.nation n

used composite broadcast HashJoin on base ad4cd9d (all four equality operands remained NotNullable=true), but on adc05a8 all four become false and this branch selects LoopJoin. On large row-valued IN inputs this changes hash lookup into probe×build evaluation even though these integer expressions over NOT NULL inputs cannot yield SQL NULL. Please retain the strong proof in canUseShuffleHashMarkJoinWithInputs, but preserve the previous effective-nullability behavior for broadcast composite MARKs, and add a real-plan/compiler regression that safe composite expression/cast keys still construct broadcast HashJoin.

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed exact head 5784418. The previous broadcast composite MARK regression is fixed: broadcast eligibility now derives runtime nullability from materialized child outputs, while shuffle retains the stronger bucket-local proof. The real row-valued IN planner/compiler regression selects broadcast HashJoin again without mutating the reusable plan, and stale shuffle state still falls back safely. Outer/SINGLE/WINDOW/aggregate/set/recursive nullable paths remain rejected. No new correctness, production-performance, lifecycle, wait, or unbounded-growth blocker found. Focused regressions and full pkg/sql/plan/function, pkg/sql/plan, and pkg/sql/compile tests pass; build, vet, and diff-check pass.

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants