Skip to content

fix(plan): select eligible shuffle key across join predicates - #26565

Merged
XuPeng-SH merged 7 commits into
mainfrom
fix/26556-shuffle-key-selection
Aug 1, 2026
Merged

XuPeng-SH merged 7 commits into
mainfrom
fix/26556-shuffle-key-selection

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

What changed

  • Inspect all equi-join predicates instead of letting the first equality unconditionally choose the shuffle key.
  • Keep the first candidate that can actually survive the existing complete shuffle recheck: supported shape/type, current child-AGG reuse, NDV policy, hash/range gates, and DEDUP restrictions.
  • Evaluate each candidate on generation-clean HashMapStats; rejected keys and earlier planning passes cannot leak Reuse, Range, or Hybrid state into the selected key.
  • Re-prove ShuffleMethod_Reuse against the current child partition after DML column remapping, and make compile skip probe repartitioning only for proven reuse.
  • Preserve pre-remap Range boundaries only when the same OnList condition remains selected after remapping. remapAllColRefs mutates conditions in place without reordering them, so the condition index is stable. Reuse and multi-CN Hybrid are deliberately not restored because both depend on current physical topology.

Why

For a multi-key join such as:

ON l.bucket = r.bucket AND l.id = r.id

the planner previously stopped at low-NDV bucket, disabled shuffle, and never considered high-NDV id. Reversing equivalent predicates changed the plan and bounded spill.

Adversarial testing found the same underlying defect when a high-NDV serial(id) first candidate passed the initial choice but was later rejected: expression shuffle is hash-only and the estimated HashMap was below the existing hash threshold, yet the later range-capable id was never tried.

A second planning-generation issue appeared in the DML path. createQuery first derives Range/reuse state, then remaps columns; tempOptimizeForDML recalculates cardinality before the late shuffle pass. The late pass must preserve stable same-key Range information to avoid degrading a valid Range plan to Hash, but it must never carry physical Reuse/Hybrid state unless the current topology proves it again.

The root cause is not a particular SQL, threshold, or join type: candidate choice, derived key strategy, and physical reuse have different dependencies and lifetimes. This PR aligns those lifetimes without adding a ranking framework or executor policy.

First-principles / unhappy-path audit

Property Result
Correctness The selected key is an existing equality predicate and passes the same final checks as the emitted plan. Equal values use identical Range boundaries on probe/build.
Generation safety Hash/Range choice is candidate-local. Same-condition Range data may cross remap; Reuse and Hybrid must be re-proved from the current graph. Changed keys and expression keys start from Hash/Normal/Simple.
Ownership Planner-only value copies and read-only Range slice reuse; no resource creation, transfer, goroutine, wait, or cleanup path.
Termination/boundedness One bounded synchronous scan, O(number of join predicates), constant candidate state, no cache/list growth.
Compatibility The first candidate already valid under current rules remains selected. Unknown NDV and valid AGG reuse remain supported; all-low/unsupported cases remain broadcast.
Performance Each candidate is planned once and the selected stats are reused. The normal pre-remap path does not snapshot prior strategy. No executor hot-path work was added.

Coverage

White-box coverage includes:

  • low/high-NDV permutations across INNER, ANTI, SEMI, LEFT, RIGHT, FULL, and MARK;
  • pre-remap and post-remap/DML column-reference modes;
  • unsupported type, same-side equality, supported expression, unknown NDV, all-low, and all-unsupported fallbacks;
  • exact NDV and hash threshold boundaries;
  • a candidate rejected by final hash recheck followed by a valid range/reuse candidate;
  • all 24 permutations of unsupported, known-low, final-recheck-rejected, and reusable candidates;
  • real remapAllColRefs plus the tempOptimizeForDML HashMap reset transition;
  • same-key Range preservation while stale Reuse/Hybrid is cleared;
  • changed-key and expression-key non-inheritance;
  • compile verification that both Hash+Normal and Range+Normal repartition the probe, while proven Reuse does not.

Black-box validation on a fresh single-node instance built from this branch:

#26556 SQL, low-NDV first:             3/3 range(id), SpillRows=260000, SpillSize=9.09 MiB
#26556 SQL, high-NDV first:            3/3 range(id), SpillRows=260000, SpillSize=9.09 MiB
both result orders:                    (130000, 130000, 16900130000)
serial(id) first / id first:           both range(id), SpillRows=260000, SpillSize=2.07 MiB
CAST/arithmetic/low-NDV/mixed keys:    later id selected and spilled
INNER/LEFT/RIGHT/FULL/SEMI/ANTI/MARK:  later eligible key selected and spilled
client cancel during physical spill:  canceled; zero spill files; CN healthy
service stop during physical spill:   canceled; zero spill files; restart healthy

Latest repository validation on macOS/arm64 with the deterministic CGo wrapper:

10 affected planner/compiler tests, each -race -count=100  PASS
pkg/sql/plan full package, normal and race                 PASS
pkg/sql/compile full package, normal and race              PASS
go vet ./pkg/sql/plan ./pkg/sql/compile                    PASS
selector: 1 key 45.8 ns; 128 low + eligible 4.73-4.79 us  0 alloc
post-remap same-key Range selection ~50.1 ns               0 alloc

Non-goals / decision log

  • Broadcast/shared JoinMap spill remains [Bug]: HashBuild can bypass spill and trigger system OOM during large hash table growth #25782; all-low or unsupported-key joins intentionally retain the current broadcast decision.
  • No new threshold, ranking model, executor protocol, log, or metric.
  • Hybrid is not restored from the earlier pass: current topology is required to justify it.
  • No per-query planner logging: the chosen key is visible in EXPLAIN, and spill rows/bytes already exist; extra logs here would add volume without better decision evidence.

Closes #26556

Roadmap: #26563

@XuPeng-SH
XuPeng-SH requested a review from aunjgr as a code owner August 1, 2026 13:29
@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 →

@matrix-meow matrix-meow added size/L Denotes a PR that changes [500,999] lines and removed size/M Denotes a PR that changes [100,499] lines labels Aug 1, 2026
@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Follow-up adversarial review found and fixed one blocker in 6a20e8e21fe.

The initial implementation selected a high-NDV serial(id) candidate, but expression shuffle is hash-only. With a HashMap below the existing 2 MiB hash-shuffle threshold, the final recheck disabled shuffle and did not try the later range-capable id condition. Black-box before the follow-up: serial(id) first retained 16.99 MiB; id first spilled 260000 rows / 2.07 MiB.

Selection now evaluates each candidate with the same extracted final recheck on copied stats and reuses the selected plan. Both orders now choose range(id) and spill identically. The original #26556 SQL also passes 3/3 for both predicate orders with SpillRows=260000, SpillSize=9.09 MiB, identical results, and zero residual spill files.

Additional evidence after the final semantic edit:

  • CAST/arithmetic/low-NDV/mixed candidate SQL and INNER/LEFT/RIGHT/FULL/SEMI/ANTI/MARK paths pass.
  • All 24 white-box permutations of unsupported, known-low, final-recheck-rejected, and reusable candidates choose the reusable eligible key.
  • Six exact tests each pass -race -count=100; full pkg/sql/plan passes normal and race.
  • Cancellation during a one-byte-threshold physical spill returns context canceled, leaves zero spill files, and the CN remains queryable.
  • Planner build/vet and downstream compile/hashbuild spill regressions pass.

The PR description now contains the complete decision log and validation matrix.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

REQUEST CHANGES — self-review blocker

GitHub does not allow the PR author to submit a formal Request changes review, so recording the blocking finding here.

planShuffleJoinCandidate copies the complete existing HashMapStats, including ShuffleMethod_Reuse and key-specific range state. This is unsafe on the late DML post-remap shuffle pass:

  1. The pre-remap pass can select a low-NDV key A by reusing an AGG child's shuffle, leaving ShuffleMethod_Reuse on the join.
  2. tempOptimizeForDML calls resetHashMapStats, which does not clear ShuffleMethod; remapping also clears BindingTags.
  3. On determineShuffleMethodAfterRemap, reusableShuffleChild can no longer prove A reusable, so the new selector skips low-NDV A and selects a later eligible key B.
  4. B's copied candidate stats retain A's ShuffleMethod_Reuse. The selected stats are written back with ShuffleColIdx=B but ShuffleMethod=Reuse.
  5. compileLocalShuffleJoin therefore omits the probe-side shuffle for B, while the build side is shuffled on B. The probe remains partitioned by A, so matching rows can land in different buckets and be lost.

Please make candidate-specific shuffle state generation-clean: either re-prove post-remap reuse for the current key, or reset ShuffleMethod to Normal (and clear key-specific range/hybrid fields) so the probe is repartitioned. Do not inherit reuse from a previously selected key.

Add a two-pass regression: pre-remap chooses reusable low-NDV A; after remap a later B is considered. The final plan must either keep proven reuse of A, or select B with ShuffleMethod_Normal and a real probe shuffle. It must never produce ShuffleColIdx=B + Reuse(A).

@ck89119 ck89119 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed exact head 6a20e8e21fe5a8d1f277a0d599a562974f488af3 against base ffad68fdb75f05d7356b4e08a8013e26349a8968.

Blocking finding:

  • planShuffleJoinCandidate starts from a copy of the existing HashMapStats and only overwrites part of the candidate-specific shuffle state. This is unsafe across the pre-remap and post-remap DML planning passes. A pre-remap low-NDV key A can establish ShuffleMethod_Reuse; resetHashMapStats clears Shuffle but leaves ShuffleMethod and range/hybrid state intact. After remapping removes the evidence needed to re-prove A reuse, selection can move to a later eligible key B while the copied candidate still carries Reuse(A). The final plan therefore combines ShuffleColIdx=B with ShuffleMethod_Reuse; compileLocalShuffleJoin then omits the probe-side shuffle for B, although the probe is partitioned by A. Matching rows may land in different buckets and be lost. Expression candidates have the same inheritance hazard because they only force ShuffleType_Hash.

Please initialize every candidate from generation-clean, key-neutral shuffle state, and set Reuse only when reuse is proved for that exact candidate in the current pass. Clear stale range/hybrid fields when selecting hash/normal shuffle. Add a two-pass regression that first establishes reusable key A, performs the same reset/remap transition as DML planning, then selects B and verifies ShuffleMethod_Normal plus a real probe shuffle (or retains A only if reuse is still independently proved).

I completed the rest of the diff/consumer/test audit and found no additional independent blockers. The new focused planner tests pass locally, and current CI is green, but neither covers this cross-pass state transition. The PR is also currently behind main; re-lock and rerun affected validation after updating the head.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Deep re-review update at c29df8c6c58 (rebased by merge onto current main 55398caaa9a):

  • Re-audited planner -> real remap -> DML replan -> compile -> shuffle executor from state ownership and plan-quality angles.
  • Confirmed the previous correctness blocker remains closed: Reuse is candidate-local and is re-proved against the current aggregate partition; changed keys compile with a real probe shuffle.
  • Found a non-correctness plan regression in both the previous PR head and its base: after remapping, a valid same-key Range plan could degrade to Hash because global table tags were no longer available.
  • Fixed this narrowly by preserving only same-condition Range boundaries. Reuse and multi-CN Hybrid are explicitly excluded because they depend on the current physical topology. Changed keys and expression keys remain clean Hash/Normal/Simple.
  • Added a real remapAllColRefs + HashMap reset regression and compile coverage for Range + Normal probe repartitioning.

Final local validation:

  • 10 affected planner/compiler tests: each -race -count=100 passed.
  • full pkg/sql/plan and pkg/sql/compile: normal and race passed.
  • go vet for both packages passed.
  • selector benchmarks remain 0 alloc: 45.8 ns for one key, 4.73-4.79 us for 128 rejected keys plus one eligible; post-remap same-key Range is about 50.1 ns.

No goroutine/resource/wait/logging/metric changes, and no new threshold or SQL-specific rule. GitHub CI has restarted for the new head.

@XuPeng-SH
XuPeng-SH merged commit 0600408 into main Aug 1, 2026
31 checks passed
@XuPeng-SH
XuPeng-SH deleted the fix/26556-shuffle-key-selection branch August 1, 2026 18:30
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…origin#26565)

## What changed

- Inspect all equi-join predicates instead of letting the first equality
unconditionally choose the shuffle key.
- Keep the first candidate that can **actually survive the existing
complete shuffle recheck**: supported shape/type, current child-AGG
reuse, NDV policy, hash/range gates, and DEDUP restrictions.
- Evaluate each candidate on generation-clean `HashMapStats`; rejected
keys and earlier planning passes cannot leak `Reuse`, Range, or Hybrid
state into the selected key.
- Re-prove `ShuffleMethod_Reuse` against the current child partition
after DML column remapping, and make compile skip probe repartitioning
only for proven reuse.
- Preserve pre-remap Range boundaries only when the same `OnList`
condition remains selected after remapping. `remapAllColRefs` mutates
conditions in place without reordering them, so the condition index is
stable. Reuse and multi-CN Hybrid are deliberately not restored because
both depend on current physical topology.

## Why

For a multi-key join such as:

```sql
ON l.bucket = r.bucket AND l.id = r.id
```

the planner previously stopped at low-NDV `bucket`, disabled shuffle,
and never considered high-NDV `id`. Reversing equivalent predicates
changed the plan and bounded spill.

Adversarial testing found the same underlying defect when a high-NDV
`serial(id)` first candidate passed the initial choice but was later
rejected: expression shuffle is hash-only and the estimated HashMap was
below the existing hash threshold, yet the later range-capable `id` was
never tried.

A second planning-generation issue appeared in the DML path.
`createQuery` first derives Range/reuse state, then remaps columns;
`tempOptimizeForDML` recalculates cardinality before the late shuffle
pass. The late pass must preserve stable same-key Range information to
avoid degrading a valid Range plan to Hash, but it must never carry
physical Reuse/Hybrid state unless the current topology proves it again.

The root cause is not a particular SQL, threshold, or join type:
candidate choice, derived key strategy, and physical reuse have
different dependencies and lifetimes. This PR aligns those lifetimes
without adding a ranking framework or executor policy.

## First-principles / unhappy-path audit

| Property | Result |
|---|---|
| Correctness | The selected key is an existing equality predicate and
passes the same final checks as the emitted plan. Equal values use
identical Range boundaries on probe/build. |
| Generation safety | Hash/Range choice is candidate-local.
Same-condition Range data may cross remap; Reuse and Hybrid must be
re-proved from the current graph. Changed keys and expression keys start
from Hash/Normal/Simple. |
| Ownership | Planner-only value copies and read-only Range slice reuse;
no resource creation, transfer, goroutine, wait, or cleanup path. |
| Termination/boundedness | One bounded synchronous scan, `O(number of
join predicates)`, constant candidate state, no cache/list growth. |
| Compatibility | The first candidate already valid under current rules
remains selected. Unknown NDV and valid AGG reuse remain supported;
all-low/unsupported cases remain broadcast. |
| Performance | Each candidate is planned once and the selected stats
are reused. The normal pre-remap path does not snapshot prior strategy.
No executor hot-path work was added. |

## Coverage

White-box coverage includes:

- low/high-NDV permutations across INNER, ANTI, SEMI, LEFT, RIGHT, FULL,
and MARK;
- pre-remap and post-remap/DML column-reference modes;
- unsupported type, same-side equality, supported expression, unknown
NDV, all-low, and all-unsupported fallbacks;
- exact NDV and hash threshold boundaries;
- a candidate rejected by final hash recheck followed by a valid
range/reuse candidate;
- all 24 permutations of unsupported, known-low, final-recheck-rejected,
and reusable candidates;
- real `remapAllColRefs` plus the `tempOptimizeForDML` HashMap reset
transition;
- same-key Range preservation while stale Reuse/Hybrid is cleared;
- changed-key and expression-key non-inheritance;
- compile verification that both Hash+Normal and Range+Normal
repartition the probe, while proven Reuse does not.

Black-box validation on a fresh single-node instance built from this
branch:

```text
matrixorigin#26556 SQL, low-NDV first:             3/3 range(id), SpillRows=260000, SpillSize=9.09 MiB
matrixorigin#26556 SQL, high-NDV first:            3/3 range(id), SpillRows=260000, SpillSize=9.09 MiB
both result orders:                    (130000, 130000, 16900130000)
serial(id) first / id first:           both range(id), SpillRows=260000, SpillSize=2.07 MiB
CAST/arithmetic/low-NDV/mixed keys:    later id selected and spilled
INNER/LEFT/RIGHT/FULL/SEMI/ANTI/MARK:  later eligible key selected and spilled
client cancel during physical spill:  canceled; zero spill files; CN healthy
service stop during physical spill:   canceled; zero spill files; restart healthy
```

Latest repository validation on macOS/arm64 with the deterministic CGo
wrapper:

```text
10 affected planner/compiler tests, each -race -count=100  PASS
pkg/sql/plan full package, normal and race                 PASS
pkg/sql/compile full package, normal and race              PASS
go vet ./pkg/sql/plan ./pkg/sql/compile                    PASS
selector: 1 key 45.8 ns; 128 low + eligible 4.73-4.79 us  0 alloc
post-remap same-key Range selection ~50.1 ns               0 alloc
```

## Non-goals / decision log

- Broadcast/shared JoinMap spill remains matrixorigin#25782; all-low or
unsupported-key joins intentionally retain the current broadcast
decision.
- No new threshold, ranking model, executor protocol, log, or metric.
- Hybrid is not restored from the earlier pass: current topology is
required to justify it.
- No per-query planner logging: the chosen key is visible in `EXPLAIN`,
and spill rows/bytes already exist; extra logs here would add volume
without better decision evidence.

Closes matrixorigin#26556

Roadmap: matrixorigin#26563
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…origin#26565)

## What changed

- Inspect all equi-join predicates instead of letting the first equality
unconditionally choose the shuffle key.
- Keep the first candidate that can **actually survive the existing
complete shuffle recheck**: supported shape/type, current child-AGG
reuse, NDV policy, hash/range gates, and DEDUP restrictions.
- Evaluate each candidate on generation-clean `HashMapStats`; rejected
keys and earlier planning passes cannot leak `Reuse`, Range, or Hybrid
state into the selected key.
- Re-prove `ShuffleMethod_Reuse` against the current child partition
after DML column remapping, and make compile skip probe repartitioning
only for proven reuse.
- Preserve pre-remap Range boundaries only when the same `OnList`
condition remains selected after remapping. `remapAllColRefs` mutates
conditions in place without reordering them, so the condition index is
stable. Reuse and multi-CN Hybrid are deliberately not restored because
both depend on current physical topology.

## Why

For a multi-key join such as:

```sql
ON l.bucket = r.bucket AND l.id = r.id
```

the planner previously stopped at low-NDV `bucket`, disabled shuffle,
and never considered high-NDV `id`. Reversing equivalent predicates
changed the plan and bounded spill.

Adversarial testing found the same underlying defect when a high-NDV
`serial(id)` first candidate passed the initial choice but was later
rejected: expression shuffle is hash-only and the estimated HashMap was
below the existing hash threshold, yet the later range-capable `id` was
never tried.

A second planning-generation issue appeared in the DML path.
`createQuery` first derives Range/reuse state, then remaps columns;
`tempOptimizeForDML` recalculates cardinality before the late shuffle
pass. The late pass must preserve stable same-key Range information to
avoid degrading a valid Range plan to Hash, but it must never carry
physical Reuse/Hybrid state unless the current topology proves it again.

The root cause is not a particular SQL, threshold, or join type:
candidate choice, derived key strategy, and physical reuse have
different dependencies and lifetimes. This PR aligns those lifetimes
without adding a ranking framework or executor policy.

## First-principles / unhappy-path audit

| Property | Result |
|---|---|
| Correctness | The selected key is an existing equality predicate and
passes the same final checks as the emitted plan. Equal values use
identical Range boundaries on probe/build. |
| Generation safety | Hash/Range choice is candidate-local.
Same-condition Range data may cross remap; Reuse and Hybrid must be
re-proved from the current graph. Changed keys and expression keys start
from Hash/Normal/Simple. |
| Ownership | Planner-only value copies and read-only Range slice reuse;
no resource creation, transfer, goroutine, wait, or cleanup path. |
| Termination/boundedness | One bounded synchronous scan, `O(number of
join predicates)`, constant candidate state, no cache/list growth. |
| Compatibility | The first candidate already valid under current rules
remains selected. Unknown NDV and valid AGG reuse remain supported;
all-low/unsupported cases remain broadcast. |
| Performance | Each candidate is planned once and the selected stats
are reused. The normal pre-remap path does not snapshot prior strategy.
No executor hot-path work was added. |

## Coverage

White-box coverage includes:

- low/high-NDV permutations across INNER, ANTI, SEMI, LEFT, RIGHT, FULL,
and MARK;
- pre-remap and post-remap/DML column-reference modes;
- unsupported type, same-side equality, supported expression, unknown
NDV, all-low, and all-unsupported fallbacks;
- exact NDV and hash threshold boundaries;
- a candidate rejected by final hash recheck followed by a valid
range/reuse candidate;
- all 24 permutations of unsupported, known-low, final-recheck-rejected,
and reusable candidates;
- real `remapAllColRefs` plus the `tempOptimizeForDML` HashMap reset
transition;
- same-key Range preservation while stale Reuse/Hybrid is cleared;
- changed-key and expression-key non-inheritance;
- compile verification that both Hash+Normal and Range+Normal
repartition the probe, while proven Reuse does not.

Black-box validation on a fresh single-node instance built from this
branch:

```text
matrixorigin#26556 SQL, low-NDV first:             3/3 range(id), SpillRows=260000, SpillSize=9.09 MiB
matrixorigin#26556 SQL, high-NDV first:            3/3 range(id), SpillRows=260000, SpillSize=9.09 MiB
both result orders:                    (130000, 130000, 16900130000)
serial(id) first / id first:           both range(id), SpillRows=260000, SpillSize=2.07 MiB
CAST/arithmetic/low-NDV/mixed keys:    later id selected and spilled
INNER/LEFT/RIGHT/FULL/SEMI/ANTI/MARK:  later eligible key selected and spilled
client cancel during physical spill:  canceled; zero spill files; CN healthy
service stop during physical spill:   canceled; zero spill files; restart healthy
```

Latest repository validation on macOS/arm64 with the deterministic CGo
wrapper:

```text
10 affected planner/compiler tests, each -race -count=100  PASS
pkg/sql/plan full package, normal and race                 PASS
pkg/sql/compile full package, normal and race              PASS
go vet ./pkg/sql/plan ./pkg/sql/compile                    PASS
selector: 1 key 45.8 ns; 128 low + eligible 4.73-4.79 us  0 alloc
post-remap same-key Range selection ~50.1 ns               0 alloc
```

## Non-goals / decision log

- Broadcast/shared JoinMap spill remains matrixorigin#25782; all-low or
unsupported-key joins intentionally retain the current broadcast
decision.
- No new threshold, ranking model, executor protocol, log, or metric.
- Hybrid is not restored from the earlier pass: current topology is
required to justify it.
- No per-query planner logging: the chosen key is visible in `EXPLAIN`,
and spill rows/bytes already exist; extra logs here would add volume
without better decision evidence.

Closes matrixorigin#26556

Roadmap: matrixorigin#26563
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…origin#26565)

## What changed

- Inspect all equi-join predicates instead of letting the first equality
unconditionally choose the shuffle key.
- Keep the first candidate that can **actually survive the existing
complete shuffle recheck**: supported shape/type, current child-AGG
reuse, NDV policy, hash/range gates, and DEDUP restrictions.
- Evaluate each candidate on generation-clean `HashMapStats`; rejected
keys and earlier planning passes cannot leak `Reuse`, Range, or Hybrid
state into the selected key.
- Re-prove `ShuffleMethod_Reuse` against the current child partition
after DML column remapping, and make compile skip probe repartitioning
only for proven reuse.
- Preserve pre-remap Range boundaries only when the same `OnList`
condition remains selected after remapping. `remapAllColRefs` mutates
conditions in place without reordering them, so the condition index is
stable. Reuse and multi-CN Hybrid are deliberately not restored because
both depend on current physical topology.

## Why

For a multi-key join such as:

```sql
ON l.bucket = r.bucket AND l.id = r.id
```

the planner previously stopped at low-NDV `bucket`, disabled shuffle,
and never considered high-NDV `id`. Reversing equivalent predicates
changed the plan and bounded spill.

Adversarial testing found the same underlying defect when a high-NDV
`serial(id)` first candidate passed the initial choice but was later
rejected: expression shuffle is hash-only and the estimated HashMap was
below the existing hash threshold, yet the later range-capable `id` was
never tried.

A second planning-generation issue appeared in the DML path.
`createQuery` first derives Range/reuse state, then remaps columns;
`tempOptimizeForDML` recalculates cardinality before the late shuffle
pass. The late pass must preserve stable same-key Range information to
avoid degrading a valid Range plan to Hash, but it must never carry
physical Reuse/Hybrid state unless the current topology proves it again.

The root cause is not a particular SQL, threshold, or join type:
candidate choice, derived key strategy, and physical reuse have
different dependencies and lifetimes. This PR aligns those lifetimes
without adding a ranking framework or executor policy.

## First-principles / unhappy-path audit

| Property | Result |
|---|---|
| Correctness | The selected key is an existing equality predicate and
passes the same final checks as the emitted plan. Equal values use
identical Range boundaries on probe/build. |
| Generation safety | Hash/Range choice is candidate-local.
Same-condition Range data may cross remap; Reuse and Hybrid must be
re-proved from the current graph. Changed keys and expression keys start
from Hash/Normal/Simple. |
| Ownership | Planner-only value copies and read-only Range slice reuse;
no resource creation, transfer, goroutine, wait, or cleanup path. |
| Termination/boundedness | One bounded synchronous scan, `O(number of
join predicates)`, constant candidate state, no cache/list growth. |
| Compatibility | The first candidate already valid under current rules
remains selected. Unknown NDV and valid AGG reuse remain supported;
all-low/unsupported cases remain broadcast. |
| Performance | Each candidate is planned once and the selected stats
are reused. The normal pre-remap path does not snapshot prior strategy.
No executor hot-path work was added. |

## Coverage

White-box coverage includes:

- low/high-NDV permutations across INNER, ANTI, SEMI, LEFT, RIGHT, FULL,
and MARK;
- pre-remap and post-remap/DML column-reference modes;
- unsupported type, same-side equality, supported expression, unknown
NDV, all-low, and all-unsupported fallbacks;
- exact NDV and hash threshold boundaries;
- a candidate rejected by final hash recheck followed by a valid
range/reuse candidate;
- all 24 permutations of unsupported, known-low, final-recheck-rejected,
and reusable candidates;
- real `remapAllColRefs` plus the `tempOptimizeForDML` HashMap reset
transition;
- same-key Range preservation while stale Reuse/Hybrid is cleared;
- changed-key and expression-key non-inheritance;
- compile verification that both Hash+Normal and Range+Normal
repartition the probe, while proven Reuse does not.

Black-box validation on a fresh single-node instance built from this
branch:

```text
matrixorigin#26556 SQL, low-NDV first:             3/3 range(id), SpillRows=260000, SpillSize=9.09 MiB
matrixorigin#26556 SQL, high-NDV first:            3/3 range(id), SpillRows=260000, SpillSize=9.09 MiB
both result orders:                    (130000, 130000, 16900130000)
serial(id) first / id first:           both range(id), SpillRows=260000, SpillSize=2.07 MiB
CAST/arithmetic/low-NDV/mixed keys:    later id selected and spilled
INNER/LEFT/RIGHT/FULL/SEMI/ANTI/MARK:  later eligible key selected and spilled
client cancel during physical spill:  canceled; zero spill files; CN healthy
service stop during physical spill:   canceled; zero spill files; restart healthy
```

Latest repository validation on macOS/arm64 with the deterministic CGo
wrapper:

```text
10 affected planner/compiler tests, each -race -count=100  PASS
pkg/sql/plan full package, normal and race                 PASS
pkg/sql/compile full package, normal and race              PASS
go vet ./pkg/sql/plan ./pkg/sql/compile                    PASS
selector: 1 key 45.8 ns; 128 low + eligible 4.73-4.79 us  0 alloc
post-remap same-key Range selection ~50.1 ns               0 alloc
```

## Non-goals / decision log

- Broadcast/shared JoinMap spill remains matrixorigin#25782; all-low or
unsupported-key joins intentionally retain the current broadcast
decision.
- No new threshold, ranking model, executor protocol, log, or metric.
- Hybrid is not restored from the earlier pass: current topology is
required to justify it.
- No per-query planner logging: the chosen key is visible in `EXPLAIN`,
and spill rows/bytes already exist; extra logs here would add volume
without better decision evidence.

Closes matrixorigin#26556

Roadmap: matrixorigin#26563

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/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: multi-key join predicate order can bypass shuffle spill

3 participants