Repository navigation
fix(plan): select eligible shuffle key across join predicates - #26565
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
Follow-up adversarial review found and fixed one blocker in The initial implementation selected a high-NDV Selection now evaluates each candidate with the same extracted final recheck on copied stats and reuses the selected plan. Both orders now choose Additional evidence after the final semantic edit:
The PR description now contains the complete decision log and validation matrix. |
|
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.
Please make candidate-specific shuffle state generation-clean: either re-prove post-remap reuse for the current key, or reset 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 |
ck89119
left a comment
There was a problem hiding this comment.
Reviewed exact head 6a20e8e21fe5a8d1f277a0d599a562974f488af3 against base ffad68fdb75f05d7356b4e08a8013e26349a8968.
Blocking finding:
planShuffleJoinCandidatestarts from a copy of the existingHashMapStatsand 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 establishShuffleMethod_Reuse;resetHashMapStatsclearsShufflebut leavesShuffleMethodand 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 carriesReuse(A). The final plan therefore combinesShuffleColIdx=BwithShuffleMethod_Reuse;compileLocalShuffleJointhen 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 forceShuffleType_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.
|
Deep re-review update at
Final local validation:
No goroutine/resource/wait/logging/metric changes, and no new threshold or SQL-specific rule. GitHub CI has restarted for the new head. |
…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
…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
…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
What changed
HashMapStats; rejected keys and earlier planning passes cannot leakReuse, Range, or Hybrid state into the selected key.ShuffleMethod_Reuseagainst the current child partition after DML column remapping, and make compile skip probe repartitioning only for proven reuse.OnListcondition remains selected after remapping.remapAllColRefsmutates 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:
the planner previously stopped at low-NDV
bucket, disabled shuffle, and never considered high-NDVid. 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-capableidwas never tried.A second planning-generation issue appeared in the DML path.
createQueryfirst derives Range/reuse state, then remaps columns;tempOptimizeForDMLrecalculates 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
O(number of join predicates), constant candidate state, no cache/list growth.Coverage
White-box coverage includes:
remapAllColRefsplus thetempOptimizeForDMLHashMap reset transition;Black-box validation on a fresh single-node instance built from this branch:
Latest repository validation on macOS/arm64 with the deterministic CGo wrapper:
Non-goals / decision log
EXPLAIN, and spill rows/bytes already exist; extra logs here would add volume without better decision evidence.Closes #26556
Roadmap: #26563